Adam
Adam

Reputation: 2398

Scheme, higher order functions, and curried functions

I need to write a Scheme higher-order function that takes a function of two parameters as its parameter and returns a curried version of the function. I understand this much so far in terms of curried functions:

(define curriedFunction (lambda (x) 
        (if (positive? x)
            (lambda (y z) (+ x y z))
            (lambda (y z) (- x y z)))))

(display ((curriedFunction -5) 4 7))
(display "\n")
(display ((curriedFunction 5) 4 7))

If x is negative, it subtracts x y and z. If x is positive, it adds x, y, and z.

In terms of higher order functions I understand this:

(display (map (lambda (x y) (* x y)) '(1 2 3) '(3 4 5)))

And thirdly I understand this much in terms of passing functions in as arguments:

(define (function0 func x y)
        (func x y))

(define myFunction (lambda (x y)
        (* x y)))

(display (function0 myFunction 10 4))

In the code directly above, I understand that the function "myFunction" could have also been written as this:

(define (myFunction x y)
        (* x y))

So now you know where I am at in terms of Scheme programming and syntax. Now back to answering the question of writing a Scheme higher-order function that takes a function of two parameters as its parameter and returns a curried version of the function. How do I connect these concepts together? Thank you in advance, I truly appreciate it.

Upvotes: 1

Views: 266

Answers (1)

Renzo
Renzo

Reputation: 27424

Here is a possible solution:

(define (curry f)
  (lambda (x)
    (lambda (y)
      (f x y))))

The function curry takes the function f and returns a function with a single argument x. That function, given a value for its argument, returns another function that takes an argument y and returns the result of applying the original function f to x and y. So, for instance, (curry +) returns a curried version of +:

(((curry +) 3) 4)  ;  produces 7

Upvotes: 4

Related Questions