简体   繁体   中英

Clojurescript map function behaving unexpectedly

I have two code snippets that I assumed to both result in alerts. However the first results none while the second performs the alerts.

(map #(.alert js/window %) ["hey1" "hey2"])

This slight modification prints (nil nil) as expected, as well as fixing the alert issue. The question being WHY ?

(print (map #(.alert js/window %) ["hey1" "hey2"]))

Another weird observation is that the first snippet works from a browser-repl, but not when typed into code.

Is the map function side effect free, but print is not? Maybe some core code optimization I do not know about?

Work-arounds and answers are both appreciated. If you need more info please let me know in a comment.

[org.clojure/clojurescript "1.8.51"]

BOOT_CLOJURE_VERSION=1.7.0

BOOT_VERSION=2.5.5

java version "1.8.0_101"

Description: Ubuntu 14.04.4 LTS

You don't want to use map for a side-effecty operation like alert. The issue you are seeing is a result of map being lazy, so it won't actually do the work until you consume the elements of the resulting sequence. If you really want to do side-effect sort of things, doseq might be a better option, especially if you don't need a sequence of results:

(doseq [msg ["hey1" "hey2"]]
  (.alert js/window msg))

Or you can use doall to force the evaluation of the whole sequence:

(doall (map #(.alert js/window %) ["hey1" "hey2"]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM