Differences between lambda function and regular functions in higher order functions
partypooper
pythonproof at gmail.com
Mon Feb 21 10:39:34 UTC 2022
On Monday, 21 February 2022 at 10:04:16 UTC, steve wrote:
> I am trying to implement a simple map function. I found code to
> do this in another post but it only seems to work with lambda
> functions and I do not understand why. Any help would be
> greatly appreciated
>
> ```
> import std.stdio;
>
> T[] map_vals(T,S)(scope T function(S) f, S[] a){
> auto b = new T[a.length];
> foreach(i,x;a) b[i] = f(x);
> return b;
> }
>
>
> auto timestwo(float x) {
> return 2*x;
> }
>
> void main(){
> float[] my_array = [1., 2., 3.];
> auto ff = (float x)=>2*x;
>
> // This works
> writeln(map_vals(ff, my_array));
>
> // this does not
> // writeln(map_vals(timestwo, my_array));
> }
> ```
I guess because your function parameter is actually a pointer to
a function. ff is a pointer to anonymous function. timestwo is
not. This should work
```d
writeln(map_vals(×two, my_array));
```
More information about the Digitalmars-d-learn
mailing list