简体   繁体   English

我需要帮助来解密此Clojure代码

[英]I need help deciphering this clojure code

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

The answer is: ((0 1 2 3) (2 3)) 答案是:((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. Clojure map可以在函数操作数之后采用多个序列,并且为每个序列压缩一个元素。 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. 在您的表单中,给map两个序列: '(0 1)'((0 1 2 3) (1 2 3)) ,它们都有两个元素。 The code thus describes two drop calls: 因此,该代码描述了两个drop电话:

(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. 返回一个惰性序列,该序列包括以下结果:将f应用于每个coll的第一项的集合 ,然后将f应用于每个coll的第二项的集合的结果,直到任何一个coll都用尽。 Any remaining items in other colls are ignored. 其他列中的所有剩余项目都将被忽略。 Function 功能
f should accept number-of-colls arguments. f应该接受cols-of-colls参数。

Note that Clojure's map is a quite flexible function, as it can do several things where you need different functions in other languages. 请注意,Clojure的map是一种非常灵活的功能,因为它可以在您需要其他语言的不同功能的情况下完成很多事情。

For example, it does all of what these three Haskell functions can do: 例如,它完成了这三个Haskell函数可以完成的所有工作:

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: 因此,在Clojure中,您可以使用map来做两件事:

a) Transform a sequence element-wise into a sequence of the same length. a)将元素逐个序列转换为相同长度的序列。 This is what is called 'map' in Haskell and other languages. 这就是Haskell和其他语言中所谓的“地图”。

b) Zip two or more sequences together into one element-wise, giving a sequence which is as long as the shortest input sequence. b)将两个或两个以上序列一起按元素顺序压缩,得到的序列与最短的输入序列一样长。 This is called 'zipWith' in Haskell. 在Haskell中,这称为“ zipWith”。

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. 您提供的代码在第二个功能中使用map It drops 0 elements from (0 1 2 3) and 1 element from (1 2 3) . 它从(0 1 2 3)删除0元素,并从(1 2 3)删除1元素。 The results, which are (0 1 2 3) and (2 3) go into the result sequence. 结果为(0 1 2 3)(2 3)进入结果序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM