Alex Smith
Alex Smith

Reputation: 51

Currying a sum of squares function in Scheme

I am trying to curry a functions of 4 arguments in Scheme. This is what I have for my curry function. The output should be 30. Please help me with my curry4 function.

(define sum-of-squares
  (lambda (a b c d)
    (+ (* a a) (* b b) (* c c) (* d d))))

(define curry4
  (lambda (a b c d)
    (apply sum-of-squares (a (b (c (d)))))))

(((((curry4 sum-of-squares) 1) 2) 3) 4)

Upvotes: 0

Views: 249

Answers (2)

tjorchrt
tjorchrt

Reputation: 702

In Racket just use curry. You can check definining file in DrRacket.

#lang racket
(define (f n1 n2 n3 n4)
  (apply +
         (map (λ (x) (expt x 2))
              (list n1 n2 n3 n4))))

(((((curry f) 1) 2) 3) 4)

Currying by hand.

#lang racket
(define curry-by-hand-f
  (lambda (x1)
    (lambda (x2)
      (lambda (x3)
        (lambda (x4)
          (f x1 x2 x3 x4))))))

((((curry-by-hand-f 1) 2) 3) 4)

Upvotes: 0

MLavrentyev
MLavrentyev

Reputation: 1969

Here's something you can try:

(define (((((curry-4 func) a) b) c) d)
  (func a b c d))

Note that this is special syntax for expanding it out like:

(define (curry-4 func)
  (λ (a)
    (λ (b)
      (λ (c)
        (λ (d) (func a b c d))))))

What we're doing here is returning a lambda that returns a lambda that ... returns a lambda that returns the result of applying func. Essentially, we're taking one argument at a time, and once we have all of them, we can give back the final value. Until then, we give back a function that's still waiting for the rest of the arguments.

Upvotes: 1

Related Questions