Clojure apply vs map

前端 未结 3 1449
北恋
北恋 2021-01-30 21:48

I have a sequence (foundApps) returned from a function and I want to map a function to all it\'s elements. For some reason, apply and count work for th

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 22:24

    Most likely you're being hit by map's laziness. (map produces a lazy sequence which is only realised when some code actually uses its elements. And even then the realisation happens in chunks, so that you have to walk the whole sequence to make sure it all got realised.) Try wrapping the map expression in a dorun:

    (dorun (map println foundApps))
    

    Also, since you're doing it just for the side effects, it might be cleaner to use doseq instead:

    (doseq [fa foundApps]
      (println fa))
    

    Note that (map println foundApps) should work just fine at the REPL; I'm assuming you've extracted it from somewhere in your code where it's not being forced. There's no such difference with doseq which is strict (i.e. not lazy) and will walk its argument sequences for you under any circumstances. Also note that doseq returns nil as its value; it's only good for side-effects. Finally I've skipped the rest from your code; you might have meant (rest foundApps) (unless it's just a typo).

    Also note that (apply println foundApps) will print all the foundApps on one line, whereas (dorun (map println foundApps)) will print each member of foundApps on its own line.

提交回复
热议问题