How to repeat string n times in idiomatic clojure way?
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 idiomatic way of doing it?
How about this?
(apply str (repeat 3 "str"))
Or just
(repeat 3 "str")
if you want a sequence instead of a string.
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)
You could also use the repeat function from clojure.contrib.string. If you add this to your namespace using require such as
(ns myns.core (:require [clojure.contrib.string :as str]))
then
(str/repeat 3 "hello")
will give you
"hellohellohello"
链接地址: http://www.djcxy.com/p/66874.html
上一篇: 按关键字查找地图clojure地图