bag24
bag24

Reputation: 1

Why is the hash map get returning nil after passing through the hash map as a function argument?

I am very new to clojure so this may have a simple fix. I have two examples of code that I can't seem to find the difference in why one works and the other doesn't. The first is:

(defn example []
  (def demokeys (hash-map "z" 1 "b" 2 "a" 3))
  (println demokeys)
  (println (get demokeys "b")))
(example)

which is from https://www.tutorialspoint.com/clojure/clojure_maps_get.htm. This works the way I expect it to, with it printing the hash map and then a 2 on the next line. The second example is:

(defn bill-total [bill]
  (println bill) 
  (println (get bill "b"))
  (println "sometext")
  )


(bill-total[(hash-map "z" 1 "b" 2 "a" 3)]) 

which prints the hashmap, then nil, then sometext. Why does it not correctly print the 2 as it does in the previous example?

Upvotes: 0

Views: 111

Answers (1)

Eugene Pakhomov
Eugene Pakhomov

Reputation: 10652

First of all, don't use def within defn unless you need dynamic runtime declarations (and even then, you should probably reconsider). Instead, use let for local bindings.

As to your main question, you have wrapped the map in a vector, with those [] here: (bill-total [...]). When calling a function, you don't need to repeat its arguments vector's brackets - call it just like you call println or hash-map, because they're also just regular functions.

So in the end, it should be (bill-total (hash-map "z" 1 "b" 2 "a" 3)).

As a final note, there's rarely a need to explicitly use hash-map, especially when you already know the keys and values. So, instead of (hash-map ...) you can use the map literal and write {...}, just like in {"z" 1, "b" 2, "a" 3} (I used commas here just for readability since Clojure ignores them).

Upvotes: 3

Related Questions