Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure vector as function parameter

Tags:

clojure

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.

like image 469
pcalcao Avatar asked Jul 04 '26 09:07

pcalcao


2 Answers

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.

like image 140
mtyaka Avatar answered Jul 07 '26 04:07

mtyaka


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

like image 43
Björn Roberg Avatar answered Jul 07 '26 06:07

Björn Roberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!