[plt-scheme] How to apply a multi-argument function to each element of a list

From: Carl Eastlund (carl.eastlund at gmail.com)
Date: Tue Mar 2 18:59:46 EST 2010


There are a few options.

You can have the students write:

(define (encrypt-message m)
  (encrypt 17 40 m))

Then you dodge this problem entirely.

Or you can write:

(map (curry encrypt 17 40) (list ...))

Be careful with the "curry" function.  It can do funny things if the
function you give it accepts a variable number of arguments.  But for
a simple 3-argument function like "encrypt", it should work just fine.

Or you can write any number of variations on your own version of
"curry" and give it to students.  But you probably want the above, to
keep things simple.

Carl Eastlund

On Tue, Mar 2, 2010 at 6:54 PM, Barry Brown <barry at cs.sierracollege.edu> wrote:
> Sorry this is probably a basic question. Other than being familiar with the
> HtDP material, I am kind of a Scheme newbie.
> I'm working on an assignment for my students to implement RSA encryption.
> One of the problems is, naturally, to write a function called encrypt that
> consumes the encryption key pair e and n, along with a message m to encrypt.
> They are using the Pretty Big language.
> encrypt : number number number -> number
> I would then like to use the encrypt function to encrypt a list of numbers.
> Now, if Scheme had implicit currying like Haskell, I could do something like
> this:
> (map (encrypt 17 40) (list 100 115 76))
> How can I do this in Scheme? The students have not seen lambda, nor will
> they be introduced to it. This for a course in discrete structures; I'm
> using Scheme to help illustrate some of the concepts they are learning.
> I think the syntax ought to be similar to the "apply" function, but instead
> of constructing an argument list, it applies the function to each element of
> the list, using the two given arguments:
> (apply-func encrypt 17 40 (list 100 115 76))
> would be equivalent to:
> (list (encrypt 17 40 100) (encrypt 17 40 115) (encrypt 17 40 76))
> Thanks in advance!
> -B

Posted on the users mailing list.