Multi-line function calls in Coffeescript

Hello everyone: Suppose I have a function foo that should receive two functions as parameters. If I have two lambda functions, I can call "foo" like this:

foo (-> 1),(-> 2) 

In this case, "foo" gets two functions: one that returns 1, and the other that returns 2.

However, as a rule, lambda functions are more complex, therefore both functions on the same line are not practical. Instead, I would like to write two multi-line lambda functions. However, I cannot understand for myself how to do this in coffeescript. Ideally, I would like to write it as follows, but this generates an error:

 foo -> 1 , -> 2 

The best I can think of is very ugly:

 foo.apply [ -> 1 , -> 2 ] 

Can any Coffeescript guru show how I can do this without getting an error? Thanks!

+4
source share
3 answers

That should be enough (you can postpone the second lamda if you want):

 f (-> x = 1 1 + 2 * x), -> y = 2 2 * y 

given the function f:

 f = (a,b) -> a() + b() 

the result should give 3 + 4 = 7

+4
source

I believe this is one of the situations where anonymous functions do not seem to be the answer. They are very practical and idiomatic in many situations, but even they have limitations and may be less readable if used in extreme situations.

I would define two functions in variables and then use them as parameters:

 func1 = -> x = 2 y = 3 z = x+y return z+2*y func2 = -> a = "ok" return a + " if you want this way" foo func1, func2 

But if you decide lambda would be preferable, just use the brackets around the foo options:

 foo ((-> x = 2 y = 3 z = x+y return z+2*y ),(-> a = "ok" return a + " if you want this way" ) ) 

Not because you use CoffeScript to avoid brackets at all costs :)

+6
source

Functions are implicitly called if followed by a variable or function. That's why

 foo -> 2 , -> 3 

will not work; the coffeescript compiler sees only a variable followed by an unexpected indent on the next line. Explicitly call him

 foo( -> 2 , -> 3 ) 

will work.

You can implicitly call a function with several parasites, you just need to align the comma with the start of the function call

 foo -> 2 , -> 3 
0
source

All Articles