2

I am learning functional programming. A question came to my mind when I read about the lambda section introduction about FP.

In Scheme the syntax for anonymous functions is the following one:

(lambda (arg1...argn) body)

...

We can now easily define the compose function

(define (compose f g)
  (lambda (x) (f (g x))))

I struggle to understand about x, it is not in the argument list of definition of compose function. so how is x passed in?

also, suppose we have function g1 taking argument y, z, how to call compose? compose (f1 g1) y z? If so, then it takes arguments not just two functions, but also the arguments from g1. I'm very confused.

1
  • x is argument of resulting composition. Suppose you have functions f1 and g1 and argument x1, then you can call it like that ((compose f1 g1) x1). Commented Mar 18, 2017 at 21:42

2 Answers 2

3

Since

(define (compose f g)
  (lambda (x) (f (g x))))

we have

             (compose + *) 

evaluates to

             (lambda (x) (+ (* x))).

That is, in

 ((compose + *) 42)

we get

    ((compose + *) 42)
 => ((lambda (x) (+ (* x))) 42)
 => (+ (* 42))
 => (+ 42)
 => 42
Sign up to request clarification or add additional context in comments.

Comments

1

First of having a list around the name and arguments is the syntax sugar. So to understand it completely lets expand it fully:

(define compose
  (lambda (f g)     ; compose
    (lambda (x)     ; body
      (f (g x))))

First off notice that the name compose is given to the result of evaluation of the outer lambda expression and it becomes a two argument closure.

So when you call (compose f2 f1) the arguments bets bound to f and g and the body expression (lambda (x) (f (g x))) is evaluated. It becomes a one argument closure. You could use define here to:

(define special-function (compose f2 f1))

In order to use that function you need to call it again. Thus. (special-function 5) would be the same as evaluating (f2 (f1 5)). It's easy to see using substitution rules.

So why do this then? Well. We have functions that take one function, like map and instead of writing:

(map (lambda (x) (f2 (f1 x))) '(1 2 3 4))

You can write

(map (compose f2 f1) '(1 2 3 4))

Which essentially is the exact same expression a little easier.

A real world compose function actually takes any number of arguments and it's last argument, the function to be applied first, will decide the arity of the resulting function. Thus in racket you can do:

((compose add1 add1 *) 3 7)
; ==> 23

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.