Skip to content

Instantly share code, notes, and snippets.

@jballanc
Created July 3, 2012 13:37
Show Gist options
  • Save jballanc/3039745 to your computer and use it in GitHub Desktop.
Save jballanc/3039745 to your computer and use it in GitHub Desktop.
(def foo {:hello "World"})
(def bar (ref {:hello "World"}))
(map :hello [foo bar])
;; => ("World" nil)
(map #(% :hello) [foo bar])
;; => ("World" "World")
@rafmagana
Copy link

Here I go:

(map :hello [foo bar])

Here, you're applying the key :hello (which acts like a function in this case, it's casted to clojure.lang.IFn) to foo and bar, so it's something like this:

(:hello foo) => "World"
(:hello bar) => nil

In the second case we're trying to pass the ref bar as parameter to the :hello function but we aren't dereferencing bar, that's why we don't get World but nil.

In the other case:

(map #(% :hello) [foo bar])

This

#(% :hello)

is the same as

(fn [arg] (arg :hello))

so the map function ends up doing something like:

(foo :hello) => "World"
(bar :hello) => "World"

This is like this because the hash map foo is casted to clojure.lang.IFn, so it acts like a function which receives :hello as argument which in turn returns the value of the :hello key.

bar is a reference, but when used like a function we get the dereferenced value which is {:hello "World"}, so:

({:hello "World"} :hello) => "World"

Then, instead of:

(map :hello [foo bar]) => ("World" nil)

you should do:

(map :hello [foo @bar]) => ("World" "World")

@jballanc
Copy link
Author

jballanc commented Jul 3, 2012

@rafmagana 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment