anonymous function as function parameter

瀏覽次數:32 次
跳到第一則未讀訊息

duccio

未讀,
2015年10月17日 下午2:37:382015/10/17
收件者:RapydScript
Hi,
it's my first day with rapydscript.
I'd like to know if there's some way to pass an anonymous function directly as a parameter in another function call.
You have this javascript:


func = function(f){
    f("Hi")
    };
   
func( function(x){
    alert(x)
    });


and want to write with rapydscript something like:


def func(f):
    f("Hi")

func ( def(x):
    alert(x) )

 # (doesn't work)


Thanks a lot !


Alexander Tsepkov

未讀,
2015年10月17日 下午2:51:562015/10/17
收件者:duccio、RapydScript
Yes, I actually warn about this in the manual (https://github.com/atsepkov/RapydScript#leveraging-other-apis). Being indentation-based like Python, RapydScript has no way to know that the block has ended by seeing the second parenthesis. So while your syntax appears correct to a human, from compiler perspective it's a syntax error because it's still parsing the inner function when it encounters a redundant parenthesis. The correct format for this is either:

func(def(x):
    alert(x)
)

Or:

func(def(x):
    alert(x);)

Note the semi-colon, this also works, btw:

func(def(x): alert(x);)

You can even put more args or other functions after the semi-colon if you want:

func(def(x): alert(x);, 'foo', 'bar', 'baz', def(x): return 'qux';, 'quux')

Also, take a look at my puzzles repo, where I solve project-euler puzzles in RapydScript, and take full advantage of its syntax for elegant solutions: https://github.com/atsepkov/puzzles/tree/master/project-euler (problem 11, for example, uses this function nesting to define its product function).

duccio

未讀,
2015年10月17日 下午4:02:122015/10/17
收件者:RapydScript
Thanks for the good and rapyd answer ! I can go on with my work.

All the ways you suggest works fine except this:

func(def(x):
    alert(x);)

that gives:
ERROR: Unexpected token: punc «)» [..\WORK/JS\a.pyj:11,13]

I use rapydscript 0.3.9
with node 0.12.4 on win xp

Alexander Tsepkov

未讀,
2015年10月17日 下午4:07:312015/10/17
收件者:duccio、RapydScript
That sounds like a bug, thanks for the heads up.
回覆所有人
回覆作者
轉寄
0 則新訊息