(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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With