Hi,

In the sample code below, I'd like to rerun the first value that returns a 
non-nil result upon the application of a function (foo in the code sample 
below). In the real use case , the computation of the function is 
expensive, so I'd only like to run foo until I find the first non-nil value.

Looking at the documentation for map indicates that it is lazy and does 
what I need.
user> (doc map)
-------------------------
clojure.core/map
([f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3 & colls])
 Returns a lazy sequence consisting of the result of applying f to the
 set of first items of each coll, followed by applying f to the set
 of second items in each coll, until any one of the colls is
 exhausted.  Any remaining items in other colls are ignored. Function
 f should accept number-of-colls arguments.
nil

I believe the idiomatic way to write this in clojure would be:
user> (clojure-version)
"1.5.0"
user> (defn foo [x] (println "Exeuting for..." x) (when (even? x) x))
#'user/foo
user> (foo 10)
Exeuting for... 10
10
user> (foo 1)
Exeuting for... 1
nil
user> (first (remove nil? (map foo '(1 3 5 2 7 6))))
Exeuting for... 1
Exeuting for... 3
Exeuting for... 5
Exeuting for... 2
2
user> (first (remove nil? (map foo #{1 3 5 2 7 6})))
Exeuting for... 1
Exeuting for... 2
2

This works as expected, however when the collection is a vector, the 
mapping is no longer lazy.

user> (first (remove nil? (map foo [1 3 5 2 7 6])))
Exeuting for... 1
Exeuting for... 3
Exeuting for... 5
Exeuting for... 2
Exeuting for... 7
Exeuting for... 6
2

I would have expected map's behaviour to be agnostic of the collection type 
passed in, but it appears not to be the case.

Insight into this would be greatly appreciated.

Thank you.

Cheers,
Achint

-- 
-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to