Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need help deciphering this clojure code

Tags:

clojure

(map drop '(0 1) '((0 1 2 3) (1 2 3)))

The answer is: ((0 1 2 3) (2 3))

Can someone please explain what is going on? I am unable to decipher this code?!

Thanks!

like image 811
iyerland Avatar asked Dec 21 '22 06:12

iyerland


2 Answers

Clojure map can take multiple seqs after the function operand and it zips one element for each seq. When the first seq is exhausted, the map ends.

In your form you give map two seqs: '(0 1) and '((0 1 2 3) (1 2 3)) which both have two elements. The code thus describes two drop calls:

(drop 0 '(0 1 2 3)) ; => '(0 1 2 3)
(drop 1 '(1 2 3))   ; => '(2 3)

Hopefully this doc helps to clear this up (emphasis mine):

clojure.core/map ([f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3 & colls])

Returns a lazy sequence consisting of the result of applying f to the set of first items of each coll, followed by applying f to the set of second items in each coll, until any one of the colls is exhausted. Any remaining items in other colls are ignored. Function
f should accept number-of-colls arguments.

like image 86
mike3996 Avatar answered Dec 22 '22 20:12

mike3996


Note that Clojure's map is a quite flexible function, as it can do several things where you need different functions in other languages.

For example, it does all of what these three Haskell functions can do:

map :: (a -> b) -> [a] -> [b]
zip :: [a] -> [b] -> [(a, b)]
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

where

zip = zipWith (,)

So in clojure you use map to do two different things:

a) Transform a sequence element-wise into a sequence of the same length. This is what is called 'map' in Haskell and other languages.

b) Zip two or more sequences together into one element-wise, giving a sequence which is as long as the shortest input sequence. This is called 'zipWith' in Haskell.

The supplied function must accept as many parameters as there are input sequences and it returns the elements which shall go into the output sequence.

The code you gave uses map in its second function. It drops 0 elements from (0 1 2 3) and 1 element from (1 2 3). The results, which are (0 1 2 3) and (2 3) go into the result sequence.

like image 26
firefrorefiddle Avatar answered Dec 22 '22 20:12

firefrorefiddle