[plt-scheme] Newbie Lambda( ) (???????????)

From: Marco Morazan (morazanm at gmail.com)
Date: Fri Feb 13 17:03:56 EST 2009

On Fri, Feb 13, 2009 at 1:35 PM, Jesus Boadas <jboadas at gmail.com> wrote:
> Thanks I understand now, this is new to me. My usual functions only return
> values, never could imagine that a function could return a function, I was
> doing some research and this is called higher order functions or I am in a
> mistake?.
>

No, you are not. You are quite right. It is quite elegant, no? :-)

Consider, now, a function, f, that returns a function as its value
after being applied to a set of arguments. A nice way to think of such
a function is as specialized-function generator. For example, consider
the problem of creating functions (i.e. what you do when you write
functions) that return a list with the results of adding a constant to
every element of a list of numbers. You would like to write a function
that takes as input a number (i.e. the constant to add) and that
returns a function that takes as input a list of numbers and that
returns a list by adding the given constant to every element of the
list. The code for this could look something like this:

; make-list-adder: number --> (list-of-numbers --> list-of-numbers)
(define (make-list-adder n)
    ; add: number --> number
    (define (add m) (+ n m))

    ; add-n-to-list: list-of-numbers --> list-of-numbers
    (define (add-n-to-list lon) (map add lon))

 add-n-to-list)

Every time make-list-adder is applied to an argument it returns a
function for which n is fixed. We can now, for example, define
functions to add 1 and to add 5 to every element of a list of numbers
without having to explicitly write code (in the conventional sense):

(define add-1-to-list (make-list-adder 1))

(define add-5-to-list (make-list-adder 5))

The above definitions should illustrate that we have not written the
code for neither add-1-to-list nor add-5-to-list in the conventional
sense, but yet we have functions we can use!

(add-1-to-list (list 1 2 3)) = (list 2 3 4)

(add-5-to-list (list 1 2 3)) = (list 6 7 8)

By writing one abstract function, we have the power to define a whole
class of functions. I hope this gives you an appetite to learn more
about HOFs.

-- 

Cheers,

Marco


Posted on the users mailing list.