Access map inside list in Clojure

Here is the code:

(def entry {:name tempName :num tempNum})

(def tempList '(entry))

(println (get (nth tempList 0) (:name)))

Exception in thread "main" java.lang.IllegalArgumentException: Wrong number of args passed to keyword: :name

In this bit of code, I define a map named entry containing: name and a: num, then put it on the list, then try to print the field: name of the first (and only) element of the list. (or at least this is what I consider my code: o)

I can access the name from the input card before putting it on the list, but as soon as it is on the list, I get this error. What arguments should I give?

+3
source share
4 answers

There are two problems.

-, , , (, ), - (backtick) (); :

(def tempList '(entry))

:

(def tempList `(entry))

( , Clojure):

(def tempList [entry]) ; no quoting needed for vectors

(println (get (nth tempList 0) (:name)))

:

(println (get (nth tempList 0) :name))

:

(println (:name (nth tempList 0)))
+3

nth - , . - , .

"" . , :

(:name (tempList 0))

:

(get (get tempList 0) :name)

:

(get-in tempList [0 :name]))
+2

() (: name) . : - , " ", , .

(get (nth '({: name "asdf"}) 0): name))
+1
source

I would write your code as follows:

(def entry {:name tempName :num tempNum})

(def tempList (list entry))

(println (:name (first tempList)))

Note that this is firstfar ahead of use than that nth, and keywords can act as functions to find yourself on the map. Another equivalent approach is to compile functions and apply them to a list:

((comp println :name first) tempList)
+1
source

Source: https://habr.com/ru/post/1712508/


All Articles