Functional programming -- 2008-2009 -- info.uvt.ro/Laboratory 6


Functional programming (Spring 2010):

High order functions

edit

References

edit
  • or:
    • Cornel Izbasa's laboratory: [1];
    • the Lisp processing chapter from Practical Common Lisp: [2];
    • the tutorial: [3], with the Mapcar section.

Examples

edit
  • the examples were provided by:
    • Dan Claudiu Codrean;
  • mapcar and reduce usage:
> (defun square(x) 
         (* x x))
SQUARE

> (square 4)
16

> (mapcar #'square '(1 3 4))
(1 9 16)

> (mapcar #'+ '(1 2 3) '(2 3 4))
(3 5 7)

> (reduce #'+ '(1 2 3))
6

> (reduce #'+ '(1 2 3) :initial-value 0)
6
  • summing all the numbers, but ignoring any other object:
> (reduce #'+
    (mapcar #'
        (lambda (x)
            (if (numberp x) x 0))
        '(1 a 2 b 3 c 4)))
10

> (reduce #'+ (remove-if-not #'numberp '(1 a 2 b 3)))
6
  • mapcar implementation:
> (defun map* (f l r) 
    (if (null l) r
        (map* f (rest l)
            (cons (funcall (first l)) r))))
MAP*

> (defun map (f l)
    (reverse (map* f l nil)))
MAP

First class functions

edit

References

edit
  • the Common Lisp Hyperspec references:
  • or:
    • Cornel Izbasa's laboratory: [4];
    • the Functions chapter from Practical Common Lisp: [5];
    • the tutorial: [6], with the Lambda and Closures section;

Examples

edit
  • the examples were provided by:
    • Dan Claudiu, Codrean;
  • a function that takes other two functions and creates a new one that composes the previous two:
> (defun compose (f g) 
    #'(lambda (x)
        (funcall f (funcall g x))))
COMPOSE

> (reduce #'+ (mapcar (compose #'sqrt #'sin) '(2)))
0.9535708819095106
  • curry-ing pattern:
    • instead of:
> (defun my-power (n m)
    (cond
        ((equal m 0) 1)
        ((equal n 0) 0)
        (t (* n (my-power n (1- m))))))
MY-POWER

> (reduce #'+ (mapcar #' (lambda (y) (my-power x y)) '(1 2 3)))
14
    • we could use:
> (defun curry (f x)
    #'(lambda (y) (funcall f x y)))
CURRY

> (reduce #'+ (mapcar (curry #'my-power x) '(1 2 3)))
14