How to repeat string n times in idiomatic clojure way?

前端 未结 7 2234
无人及你
无人及你 2020-12-15 16:13

In Ruby, \"str\" * 3 will give you \"strstrstr\". In Clojure, the closest I can think of is (map (fn [n] \"str\") (range 3)) Is there a more idioma

7条回答
  •  攒了一身酷
    2020-12-15 16:52

    And one more fun alternative using protocols:

    (defprotocol Multiply (* [this n]))
    

    Next the String class is extended:

    (extend String Multiply {:* (fn [this n] (apply str (repeat n this)))})
    

    So you can now 'conveniently' use:

    (* "foo" 3)
    

提交回复
热议问题