开发者

Parentheses inside anonymous function with vector as parameter

开发者 https://www.devze.com 2023-03-09 15:08 出处:网络
I\'m still learning clojure and I\'ve a doubt when I write a anonymous function I do this fn [parameter]

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

(iter开发者_Go百科ate (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.


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.


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 :-).

0

精彩评论

暂无评论...
验证码 换一张
取 消