[plt-scheme] Functions as first class data types.

From: Carl Eastlund (carl.eastlund at gmail.com)
Date: Sat Feb 14 19:33:44 EST 2009

On Sat, Feb 14, 2009 at 7:24 PM, aditya shukla
<adityashukla1983 at gmail.com> wrote:
> Can someone  please explain what's the use of having functions as first
> class data type in scheme .I am a little confused about functions having
> functions as their arguments .

For a thorough introduction to first-class functions, I suggest going
through section IV of How To Design Programs; specifically chapters 19
through 22.

http://www.htdp.org/2003-09-26/Book/curriculum-Z-H-25.html

If you are new to Scheme and functional programming, you may want to
start at the beginning of the book and work up to there at your own
pace.

For a quick answer, higher order functions can save you a lot of
repeated effort.  If there's a frequent programming pattern you use,
like walking down the elements of a list, you can encode that as a
higher order function that walks the list.  The part that's different
each time, the choice of what to do with each list element, you can
then pass in as an argument to the higher order function.  It then
becomes very easy to process lists without writing a new function:

(map sqr xs) ;; square every number in xs
(map - xs) ;; negate every number in xs
(map / xs) ;; take the reciprocal of every number in xs

(foldr + 0 xs) ;; compute the sum of every number in xs
(foldr * 1 xs) ;; compute the product of every number in xs
(foldr string-append "" strs) ;; append all the strings in strs

It may not be immediately clear how each of those examples work, but
once you get used to them it's much easier than writing a new function
each time.

-- 
Carl Eastlund


Posted on the users mailing list.