简体   繁体   中英

Clojure - map with unbound function

I'm following a Clojure tutorial in Try Clojure , where we are introduced to defining our functions -

(defn square [x] (* x x))

Then apply it to a list of numbers:

(map square [1 2 3 4])

Which promptly prints out an error: java.lang.IllegalStateException: Attempting to call unbound fn: #'sandbox14750/square

When I try to map for example function inc , that works fine - what's the difference between the built-in function inc and my square ?

I had some trouble the first time I tried to run it though after refreshing the page it went fine.

Give me some Clojure:
> (defn square [x] (* x x))
#'sandbox6361/square
> (square 4)
16
> (map square [1 2 3 4])
(1 4 9 16)

If you want to make sure your functions are still available when you need them you can store your functions in locals instead of vars like so:

> (let [square (fn [x] (* x x))] (map square [1 2 3 4]))
(1 4 9 16)
>  

many sandbpxed environments like Clojurebot on #clojure don't let you define arbitrary state so it's worth knowing that functions can be stored in many ways, not just in vars.

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