Creating curryable functions with lambdas in D does not work as class \ struct memebers

I played with D trying to mimic the Scala style of curryable functions by chaining lambda expressions.

I came up with this:

immutable foo=function(immutable int x)=>(immutable int y)=>(x+y); struct S { static immutable foo=function(immutable int x)=>(immutable int y)=>(x+y); } class C static immutable foo=function(immutable int x)=>(immutable int y)=>(x+y); } void main() { writefln("global\t%s",foo(1)(2)); writefln("struct\t%s",S.foo(1)(2)); writefln("class\t%s",C.foo(1)(2)); } 

This is what I get when I run it:

 global 3 struct 1528543170 Segmentation fault 

As you can see, my method works well for a global function variable, but the variable of the static function struct gives the result of the garbage, and the variable of the static function of the class completes completely. If I remove x from the returned expression - function(immutable int x)=>(immutable int y)=>(y) - the struct version gives the correct result ( 2 ), but the class version still does not work.

If I use a regular method instead of a function variable:

 immutable foo=function(immutable int x)=>(immutable int y)=>(x+y); struct S { static auto foo(immutable int x) { return (immutable int y)=>(x+y); } } class C { static auto foo(immutable int x) { return (immutable int y)=>(x+y); } } void main() { writefln("global\t%s",foo(1)(2)); writefln("struct\t%s",S.foo(1)(2)); writefln("class\t%s",C.foo(1)(2)); } 

It works fine:

 global 3 struct 3 class 3 

And I also get the advantage of using delegates (the compiler does not allow delegates in the first version), but this style is less elegant.

I am well aware that D has a curry function in the std.functional library for currying functions, but sometimes it is more convenient to make the curryable function by default, and next to it I am curious to find out why my first version does not work.

Any ideas?

UPDATE

OK, I filed an error . I did a few more digging, and it turns out that the argument list foo is shifted, and therefore x gets unnecessary data.

+6
source share
1 answer

Honestly, it looks like you are facing a compiler error. Report this . Since the variables in the structure and class are static, their behavior should be identical to the behavior of the module level variable, and obviously this is not so.

+4
source

Source: https://habr.com/ru/post/917816/


All Articles