Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I do not understand why a lambda scheme is working

I'm totally new to scheme, coming from a c# background.

I thought I was getting a handle on lambda, but I don't understand why this example works:

(let ([f (lambda x x)]) (f 1 2 3 4) )

The answer is (1 2 3 4), but how? It's the x x part that I don't get. The lambda takes no parameters so the body is x x, right? But I don't know what that means in this case, can someone explain? Thanks.


2 Answers

In fact, the lambda in your code is receiving parameters, and an aribtrary number of them. The syntax for a lambda with no parameters is different:

(let ([f (lambda () 1)]) (f))
=> 1

The lambda expression in the question is something else:

(lambda x x)

It receives a variable number of arguments as a list, and then returns them. You named it f, and when it's invoked like this:

(f 1 2 3 4) 

All of the arguments get bound to x, a list and then the value of x is returned:

'(1 2 3 4)

So, f is nothing more than an identity function that receives multiple arguments. Perhaps this answer will clarify how variadic functions are defined in Scheme. For completeness' sake, here's an example of a lambda that receives a single argument and returns it:

(let ([f (lambda (x) x)]) (f 1))
=> 1

So there you have it, that's how we define lambdas that receive 0, 1 or many parameters.

like image 167
Óscar López Avatar answered Mar 09 '26 02:03

Óscar López


A lambda syntax is like this:

(lambda argument-list body ...)

Looking at your lambda:

(lambda x x)

Thus the argument list is x and the body of the lambda is x.

A list in Scheme looks like (a b c), but it is really (a . (b . (c . ()))) and in a procedure argument list if the chain ends up in a symbol, like (a b . c) then the procedure takes 2 arguments or more. The "rest" arguments are accumulated in a list called c. In ES6 it's the same as (a, b, ...c) => expression. Now if you have no mandatory argument, eg. you allow 0 or more arguments, the argument list is just a symbol. eg (lambda x x) is the same as (...x) => x.

I believe in C# instead of x one would have written params type[] x. C# doesn't do anonymous lambda + rest argument so I hope you know some ES6.

like image 25
Sylwester Avatar answered Mar 09 '26 04:03

Sylwester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!