mapcat breaking the lazyness

前端 未结 2 1150
孤独总比滥情好
孤独总比滥情好 2021-01-04 13:53

I have a function that produces lazy-sequences called a-function.

If I run the code:

(map a-function a-sequence-of-values) 

it retu

2条回答
  •  太阳男子
    2021-01-04 14:21

    Your premise is wrong. Concat is lazy, apply is lazy if its first argument is, and mapcat is lazy.

    user> (class (mapcat (fn [x y] (println x y) (list x y)) (range) (range)))
    0 0
    1 1
    2 2
    3 3
    clojure.lang.LazySeq
    

    note that some of the initial values are evaluated (more on this below), but clearly the whole thing is still lazy (or the call would never have returned, (range) returns an endless sequence, and will not return when used eagerly).

    The blog you link to is about the danger of recursively using mapcat on a lazy tree, because it is eager on the first few elements (which can add up in a recursive application).

提交回复
热议问题