Clojure - 获取序列元素的非循环方式
Clojure - non-looping ways to pick up sequence elements
除了循环遍历一个序列并从中选取每个元素之外,还有什么其他更符合 clojure 习惯的方法?这是我的意思的循环版本:
(def a-seq (list 700 600 500 400 300 200 100))
(loop [s a-seq]
(if (seq s)
(do (instrument (first s)) (recur (rest s)))
"End"))
我将按如下方式将 (first s)
作为频率输入正弦波发生器(在泛音库中):
(use 'overtone.core)
(definst instrument [frequency 0] (sin-osc frequency))
使用doseq
:
(doseq [item a-seq]
(println item))
(println "End")
map
函数就是你要用的。
(map instrument a-seq)
这将按顺序为 a-seq
中的每个元素调用一次 instrument
函数。
请注意 map 是惰性的,因此您需要使用 map 的结果以保证发生任何副作用,或调用 doall
。
除了循环遍历一个序列并从中选取每个元素之外,还有什么其他更符合 clojure 习惯的方法?这是我的意思的循环版本:
(def a-seq (list 700 600 500 400 300 200 100))
(loop [s a-seq]
(if (seq s)
(do (instrument (first s)) (recur (rest s)))
"End"))
我将按如下方式将 (first s)
作为频率输入正弦波发生器(在泛音库中):
(use 'overtone.core)
(definst instrument [frequency 0] (sin-osc frequency))
使用doseq
:
(doseq [item a-seq]
(println item))
(println "End")
map
函数就是你要用的。
(map instrument a-seq)
这将按顺序为 a-seq
中的每个元素调用一次 instrument
函数。
请注意 map 是惰性的,因此您需要使用 map 的结果以保证发生任何副作用,或调用 doall
。