Functional Currying in Scheme
Posted: February 25, 2011 Filed under: Programming | Tags: functional programming, scheme Leave a comment »Back when I was taking a look at Haskell, I saw that the language supports functional currying automatically: if you call a function, not providing all the arguments it requires, what you get is another function that can be called later, that takes the missing arguments, and does the job of the original function as if all the arguments were given all at once in a complete direct call. In other programming languages, if you call a function not giving all the needed arguments, you get an error. As in Scheme.
However, in Scheme, there is a very easy and simple way to implement functional currying; like the one I saw in Haskell.
(define (curry proc . args)
(lambda x
(apply proc (append args x))))
There isn’t much to talk about this, but you can, as I’m still doing, keep staring at it and see how simple it is.
Using this procedure, you can do currying in scheme. It seems that there is a srfi that implements currying with a macro called cut, but I’m unaware of it.
You might want to apply curry giving sequential, but not starting, arguments: giving arguments second, third and fourth for example; and then, the return function will take all the missing arguments and make the first given argument, as the procedure given to it in the first place’s first argument; the second argument would become the procedure’s fifth argument, etc.
Here is curry-middle, which does that.
(define (curry-middle proc start . args)
(define (list-until l n)
(if (zero? n)
'()
(cons (car l) (list-until (cdr l) (sub1 n)))))
(lambda x
(apply proc (append (list-until x start) args (list-tail x start)))))
Curry-middle is also simple, and is also small. It’d be a one liner if I knew some built-in function that could replace list-until.
I didn’t test those functions but their ideas are ok, and they seem to work. The first one (i.e. curry); I can’t see how it’d fail; but the second one may have some flaw I’m not seeing.
Recent Comments