Clojure: The difference between a list and a function that returns a list

I am new to Clojure. I am trying to understand why the second form does not work:

First form:

user=>(def nums(range 3)) (0 1 2) user=>(map #(list %1) nums) ((0) (1) (2)) 

Second form:

 user=> (map #(list %1) (0 1 2)) java.lang.ClassCastException: java.lang.Integer cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0) 
+4
source share
4 answers

The problem is the expression (0 1 2) , which is interpreted as 0 , applied to 1 and 2 ; which is impossible because 0 not a function.

 (map #(list %1) '(0 1 2)) 

works as intended.

+11
source

Because (0 1 2) means the call function 0 with arguments 1 and 2, but 0 is not a function. Therefore, you need to create a list, not an application, using the quote or list function ie '(0 1 2) OR (list 0 1 2)

+5
source

larsmans and Ankur have this. I understand this is a trivial example, but it would probably be more idiomatic to use a vector rather than a list:

 (map #(list %1) [0 1 2]) 

You can also use % instead of %1 when only one argument is passed to an anonymous function.

 (map #(list %) [0 1 2]) 
+4
source
 user=> (map list (range 3)) ((0) (1) (2)) user=> (map list '(0 1 2)) ((0) (1) (2)) user=> (map list [0 1 2]) ((0) (1) (2)) 
+1
source

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


All Articles