0

I am going through a practice exam for my programming languages course. One of the problems states:

Define a function named function+ that “adds” two functions together and returns this composition. For example:

((function+ cube double) 3)

should evaluate to 216, assuming reasonable implementations of the functions cube and double.

I am not sure how to approach this problem. I believe you are supposed to use the functionality of lambdas, but I am not entirely sure.

Community
  • 1
  • 1
  • 2
    This operation is called "function composition" and is pretty easy to define. For example, in Haskell, call it`comp :: (b -> c) -> (a -> b) -> (a -> c)` and define it `comp f g x = f(g x)`. – Musa Al-hassy Feb 23 '16 at 07:26

2 Answers2

1

If you need a procedure which allows you two compose to unary procedures (procedure with only 1 parameter), you'll smack yourself in the head after seeing how simple the implementation is

(define (function+ f g)
  (λ (x) (f (g  x))))

(define (cube x)
  (* x x x))

(define (double x)
  (+ x x))

((function+ cube double) 3)
;=> 216
Mulan
  • 129,518
  • 31
  • 228
  • 259
0

Basically if you need to do that you just do (x (y args ...)) so if you need to have a procedure that takes two arguments proc1 and proc2 returns a lambda that takes any number of arguments. You just use apply to give proc1 arguments as a list and pass the result to proc2. It would look something like this:

(define (compose-two proc2 proc1)
  (lambda args
    ...))

The general compose is slightly more complicated as it takes any number of arguments:

#!r6rs
(import (rnrs))

(define my-compose
  (let* ((apply-1
          (lambda (proc value)
            (proc value)))
         (gen
          (lambda (procs)
            (let ((initial (car procs))
                  (additional (cdr procs)))
              (lambda args
                (fold-left apply-1
                           (apply initial args)
                           additional))))))
    (lambda procs
      (cond ((null? procs) values)
            ((null? (cdr procs)) (car procs))
            (else (gen (reverse procs)))))))

(define (add1 x) (+ x 1))
((my-compose) 1) ;==> 1
((my-compose +) 1 2 3) ; ==> 6
((my-compose sqrt add1 +) 9 15) ; ==> 5
Sylwester
  • 47,942
  • 4
  • 47
  • 79