Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parentheses inside anonymous function with vector as parameter

Tags:

clojure

I'm still learning clojure and I've a doubt

when I write a anonymous function I do this

fn [parameter] 
 (do something)

ok..the function body is enclosed by a set of parentheses

now I'm reading a fibonacci solution like this

(iterate (fn [[a b]] [b (+ a b)]) [0 1]))

my doubt is why It's not like this

(iterate (fn [[a b]]  (    [b (+ a b)]   ))   [0 1]))

I enclose the function with ()

(iterate (fn [[a b]]   "("    [b (+ a b)]   ")"  )   [0 1]))

it receive a vector and then return the body function than is other vector...

It's different when I call a function with a vector like parameter or I'm making a big mistake.

like image 421
coco Avatar asked Sep 27 '26 01:09

coco


2 Answers

If a function is returning a vector, you don't need to wrap it with anything, just return the vector in its brackets. The body of a function is not necessarily "wrapped" in parentheses, it's just very common because usually functions are doing several things before returning a value, which involves using parentheses.

So if you're just returning a vector from a function, the "body" of the function can be [foo,bar,baz]. If you were returning a map, the body of the function could be {:a foo, :b bar, :c baz}. If you're returning a single value, it could be a single symbol.

The only thing "wrapped" in parenthesis is the entire function definition itself, whether its (fn [] ...), #(...), or (defn [] ...).

A further note: The brackets and braces [, ], { and } are actually just syntactic sugar for the (vector) function and (hash-map) functions respectively, so [1,2,3] is the same as (vector 1 2 3) and {:a foo, :b bar} is the same as (hash-map :a foo :b bar). If it helps you to see function bodies "wrapped" in parentheses, you can use the longer function names to return Clojure's vector and map data types, but using the brackets and braces is much more idiomatic.

like image 159
semperos Avatar answered Sep 28 '26 20:09

semperos


Perhaps in more simple words than Semperos, [1 2 3] is shorthand/equivalent for (vector 1 2 3), so the parenthesis are there! Similar for {:a 1 :b 2}, which is equivalent to (hash-map :a 1 :b 2).

What I haven't looked up, but might be fun to dig in the source code to the clojure reader, and see if it indeed replaces anything in [.. ] with (vector ...), or uses some other trick :-).

like image 42
bOR_ Avatar answered Sep 28 '26 22:09

bOR_