gpt4 book ai didi

clojure - 惰性序列的实现时机

转载 作者:行者123 更新时间:2023-12-02 21:34:24 25 4
gpt4 key购买 nike

(defn square [x]
(do
(println (str "Processing: " x))
(* x x)))

(println (map square '(1 2 3 4 5)))

为什么输出

(Processing: 1 
Processing: 2
1 Processing: 3
4 Processing: 4
9 Processing: 5
16 25)

不是

(Processing: 1
1 Processing: 2
4 Processing: 3
9 Processing: 4
16 Processing: 5
25)

最佳答案

因为 map 很懒。它在幕后使用了lazy-seq,pre-caches the result of rest 。因此,当您的代码获取 map 序列的第一个值时,您会看到两个 println 语句出现。

另请参阅此博文:Lazy Sequences

关于clojure - 惰性序列的实现时机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13455008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com