Construct basic functions used for
high-level functional programming
Provides "glue" for certain functions
Define functions
starting with minimal information structures
then moving to more general information structures
Define a function on a complex information structure by
appealing to the definition of the function on simpler information structures
Recursion Manifesto
A function which computes the length of a list
Define the function on the empty list:
length( [ ] ) => 0;This step is called the basis.
Define the function on a generic non-empty list:
length( [ A | L ] ) => length(L) + 1;
This step is called the induction rule.
this gives us details.
length([2, 3, 5, 7]) => (length([3, 5, 7]) + 1) => ((length([5, 7]) + 1) + 1) => (((length([7]) + 1) + 1) + 1) => ((((length([ ]) + 1) + 1) + 1) + 1) => (((( 0 + 1) + 1) + 1) + 1) => ((( 1 + 1) + 1) + 1) => (( 2 + 1) + 1) => ( 3 + 1) => 4
Another example:
append(L, M)
append([1, 2], [3, 4, 5])
==> [1, 2, 3, 4, 5]
==> designates the result of a series of rewrites, rather than a single rule
append( [ ], M ) => M;
append( [A | L], M ) => [A | append(L, M)];
append([1, 2, 3], [4, 5]) => [1 | append([2, 3], [4, 5]) ] => [1, 2 | append([3], [4, 5]) ] => [1, 2, 3 | append([ ], [4, 5]) ] => [1, 2, 3 | [4, 5] ] => [1, 2, 3, 4, 5]
Try rules in succession, starting at the first, until one matches the arguments.
For each function call, start at the top, from the first rule.
map(F, [ ] ) => [ ]; map(F, [A | L]) => [F(A) | map(F, L)]; reduce( _, Unit, [ ] ) => Unit; reduce( H, Unit, [A | X] ) => H(A, reduce(H, Unit, X));
foo( [ ] ) => [1];
foo( [ A | L] ) => length(L) > 5 ? [ 1 | L ];
----------------
foo(L) => L;
foo( [ ] ) ==> [1] foo( [ 2, 3, 4, 5, 6, 7] ) ==> [1, 2, 3, 4, 5, 6, 7] foo( [2, 3, 4] ) ==> [2, 3, 4]
change_first example from notes, chapter 3:
Captain Nimo applet (http://www.cs.hmc.edu/~keller/Nimo.html)
change_first(P, F, L)
change_first(P, F, []) => []; change_first(P, F, [E | L]) => P(E) ? [F(E) | L]; change_first(P, F, [E | L]) => [E | change_first(P, F, L)];
bar( L ) => length(L) > 5 ? [ 1 | L ] : L;
^
note
----------------------------
conditional expression
f(X) => Y = X*X, g(Y);
--------
equational guard
f(X) => [F | R] = X, g(F*F, R);
-----------
equational guard defining F and R from X
| To Next Slide | To Previous Slide | To Contents |