2

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.

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Accepted for the more detailed explanation. Also, first two values of the vector made me realize that if I pass a coll with more elements the rest will be ignored, I didn't know that! Nice.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.