Ali Salehi
Ali Salehi

Reputation: 6999

Pass a function as a first argument in a function call in coffeescript

In the following code

x= (f,n) -> f(n)
...
x( (n) -> n+1 , 5) #parse error

How can I fix the parse error above ?

Thanks

Upvotes: 18

Views: 7214

Answers (3)

Ali Salehi
Ali Salehi

Reputation: 6999

A pair of parenthesis would fix this problem, just found the answer on IRC.

x( (n) -> n+1  , 5) #parse error
x ((n) -> n+1) , 5 #fixed

Upvotes: 30

liammclennan
liammclennan

Reputation: 5368

Ali's answer is slightly different to the question he asked. One correct solution is

x = (f,n) -> f(n)

x(( -> n+1), 5)

Upvotes: 2

Alex Wayne
Alex Wayne

Reputation: 187004

I usually do either this:

foo ->
  doStuff('foo')
, 5

or this:

fn = -> doStuff('foo')
foo fn, 5

Wrapping extra parens inside argument lists never sat right with me as it's tough for my brain to parse.

Upvotes: 19

Related Questions