0

I would like to see how it might be possible to emulate the (curry func) that racket provides. Here is an example of how I'm manually currying a function:

#lang sicp
; convert to a curried function

(define (add1 x y) (+ x y))

(define add2
  (lambda (x)
    (lambda (y)
      (+ x y))))
(add1 2 3)
; 5

((add2 2) 3)
; 5

Where would I start to add a higher-order function such that it converts a 'normal' function into a curried function, something like this:

(((curry add1) 2) 3)
David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

1

You have to make some tradeoffs because it's not easy to tell how many parameters a function accepts. Racket has a procedure-arity function that lets curry tell how many arguments to curry, but the SICP language does not. So you have to choose how to handle this. Some reasonable choices include:

  • Make the caller specify how many arguments to wait for
  • Work only with a fixed number of arguments
  • Curry only the first n calls to a function, and have the n+1th call through the underlying function.
amalloy
  • 89,153
  • 8
  • 140
  • 205
  • I see, so if the caller specified the number of arguments (say, two) or it was fixed at something (also could be two) what might be an example of how that could work? – David542 Jun 17 '21 at 01:02
  • To fix at 2 is pretty simple. Just write it as you wrote `add1`, but instead of hardcoding `+` you use another lambda taking `f` as an argument. – amalloy Jun 17 '21 at 01:04
  • ah I see, yea that one is pretty easy. How would #1 would be? – David542 Jun 17 '21 at 01:13
  • 1
    Try working it out yourself. Obviously the function takes an int and a function as a parameter, and if the int is zero it can just return the function. For a nonzero int, it clearly returns some other function, and that function probably calls curry itself with a smaller int. – amalloy Jun 17 '21 at 03:01
  • thanks for the encouragement and tips, yes I'll try working this one out... – David542 Jun 17 '21 at 03:08
  • FWIW, you probably need to create a helper function that additionally accepts an accumulator, which is a list of arguments to be applied. – Sorawee Porncharoenwase Jun 17 '21 at 03:17
  • @SoraweePorncharoenwase yea, seems a bit over my head...I wrote up what I have and asked a new questions: https://stackoverflow.com/questions/68012640/going-from-curry-0-1-2-to-n – David542 Jun 17 '21 at 03:46