简体   繁体   English

Clojure矢量作为函数参数

[英]Clojure vector as function parameter

Being completely inexperienced in clojure, and without any functional programming practice since college, I'm trying to interpret some example code to figure out the clojure syntax. 由于完全缺乏clojure经验,并且自大学以来没有任何函数式编程实践,我试图解释一些示例代码来找出clojure语法。

I started by coding several versions of Fibonacci ( https://gist.github.com/pcalcao/ea4176719d778ea3ab9e ), but I still can't say I fully understand the more complex forms. 我开始编写几个版本的Fibonacci( https://gist.github.com/pcalcao/ea4176719d778ea3ab9e ),但我仍然不能说我完全理解更复杂的形式。

For instance, this: 例如,这个:

(defn fib_map [n]
  (last (take (+ n 1)
    (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))))   

I'm struggling to really understand the innermost part of this code: 我很难真正理解这段代码的最内层部分:

fn [[a b]] [b (+ a b)] 

Now, from my understanding, we're creating an anonymous function that receives one parameter, a vector with two values (this is destructuring, right?), and returns another vector. 现在,根据我的理解,我们正在创建一个匿名函数,它接收一个参数,一个带有两个值的向量(这是解构,对吧?),然后返回另一个向量。

Now, what is the reason we would do this, instead of: 现在,我们这样做的原因是什么,而不是:

fn [a b] [b (+ a b)]

Are these equivalent? 这些是等价的吗? Or are we simply making our anonymous function receive a single parameter as a "gimmick" to use in iterate ? 或者我们只是让我们的匿名函数接收一个参数作为iterate使用的“噱头”?

Sorry if this is totally obvious, but like I said, Lisp-like languages aren't my strong point yet. 对不起,如果这是非常明显的,但就像我说的那样,类似Lisp的语言还不是我的强项。

You already figured it out correctly yourself. 你已经自己弄清楚了。

Function of the form (fn [[ab]] ...) is using destructuring. 形式(fn [[ab]] ...)正在使用解构。 It takes a single parameter that should be a vector or another type of object that supports clojure's nth function. 它需要一个参数,它应该是一个矢量或支持clojure的nth函数的另一种类型的对象。 Using destructuring, it "pulls" the first two values out of the vector and assigns them to local variables a and b . 使用解构,它将前两个值“拉”出向量并将它们分配给局部变量ab

Function of the form (fn [ab] ...) is a function of two parameters. 形式的函数(fn [ab] ...)是两个参数的函数。 The two are not equivalent. 这两者并不相同。

The reason you have to use the (fn [[ab]] ...) form with iterate is that iterate only works with single-parameter functions. 你必须在iterate使用(fn [[ab]] ...)形式的原因是iterate仅适用于单参数函数。

It's because iterate only takes two parameters, ie one function and one parameter. 这是因为迭代只需要两个参数,即一个函数和一个参数。 cf. 比照 the docs 文档

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

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