pcalcao
pcalcao

Reputation: 15965

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.

Upvotes: 2

Views: 3891

Answers (2)

mtyaka
mtyaka

Reputation: 8850

You already figured it out correctly yourself.

Function of the form (fn [[a b]] ...) 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 [a b] ...) is a function of two parameters. The two are not equivalent.

The reason you have to use the (fn [[a b]] ...) form with iterate is that iterate only works with single-parameter functions.

Upvotes: 11

Björn Roberg
Björn Roberg

Reputation: 2356

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

Upvotes: 2

Related Questions