Memo
Memo

Reputation: 89

Scheme (DrRacket) lambda expression

I do not understand the following program code. Can anyone explain it to me?

(define myFunction
  (lambda (f x y z)
    (f x y z)))

How can I simplify it?

Upvotes: 1

Views: 319

Answers (2)

Will Ness
Will Ness

Reputation: 71070

You can't simplify it much, except for making it look a bit syntactic, as

(define (myFunction f x y z)
        (f x y z))

which is a syntactic shortcut for defining the exact same thing.

This way, you can treat it mentally as a rewriting rule: whenever you see

        (myFunction f x y z)

in your code - whatever those f, x, y and z placeholders are referring to - you can replace it with

        (f x y z)

while substituting the actual values, a.k.a. arguments, for the placeholders, a.k.a. function parameters.

Thus you see that for the new code to make sense, f should be a function capable of accepting three arguments, x, y and z.

So for example, if you define (define (f x y z) (+ x y z)), you can call

(myFunction f 1 2 3)

and get a result back - which is the result of calling the function f you've just defined above, with the values 1, 2 and 3.

f inside myFunction will refer to the global name f which refers to a value - a function named f you've defined. The lambda form defines a value - an anonymous function - and define binds a name f to it, so that any use of that name refers to that value, from now on. In Scheme, functions are values like any other.

That global function f is defined to apply + to the three arguments it receives, when it receives them. It in effect is saying, "give me some three values and I'll sum them up for you", and the call (myFunction f 1 2 3) supplies it with the three values of your choosing.

Upvotes: 4

Alexey Romanov
Alexey Romanov

Reputation: 170713

lambda ... creates a function which expects 4 arguments, the first of which (f) should itself be a function. (f x y z) applies this f to the other 3 arguments.

define gives the name myFunction to the lambda.

Upvotes: 0

Related Questions