简体   繁体   中英

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.

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.

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 ?

Sorry if this is totally obvious, but like I said, Lisp-like languages aren't my strong point yet.

You already figured it out correctly yourself.

Function of the form (fn [[ab]] ...) is using destructuring. It takes a single parameter that should be a vector or another type of object that supports clojure's nth function. Using destructuring, it "pulls" the first two values out of the vector and assigns them to local variables a and b .

Function of the form (fn [ab] ...) is a function of two parameters. 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.

It's because iterate only takes two parameters, ie one function and one parameter. cf. the docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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