Hi please explain how this can be equal or the same.

MyList.map [1,2,3,4], fn (n) -> n+1 end

MyList.map [1,2,3,4], &(&1 + 1)

the shortcut is confusing.

Hi please explain how this can be equal or the same.

MyList.map [1,2,3,4], fn (n) -> n+1 end

MyList.map [1,2,3,4], &(&1 + 1)

the shortcut is confusing.

`fn(n) -> n + 1`

is an anonymous function

`&(&1 + 1)`

is a short cut or alternative way to write an anonymous function

The outer code of it, `&( )`

indicate that it’s an anonymous function.

The inside is `&1 + 1`

is the body of the function, which is suppose to do `n+1`

. The problem is how do you indicate that `n`

is a parameter? The solution is that `&1`

means first parameter. So `&1 + 1`

just means take the first parameter of the anonymous function and add one to it. The shortcut here is you don’t have to write the `fn(n)`

, the function signature, you indicate it in the body instead which makes it shorter.

IIRC `&(&1 + &2)`

is equivalent to `fn(n,m) -> n + m`

4 Likes