In most functional languages, functions are not single definitions. A function is defined in terms of the arguments. So, if you wanted a function that could add up to three numbers, you would define:
Code: Select all
function add () = 0
function add (a) = a
function add (a, b) = a + b
function add (a, b, c) = a + b + c
These would be the function add() with four different arities (arity is the number of arguments it accepts. When add is then called against a series of arguments, the arguments are matched against the pattern of arguments named in the series of definitions of add(). In most, there is an infix cons operator (lisp uses prefix operators, so you have (+ 3 4) instead of (3 + 4), which uses infix) that can be used to break apart a list so that you can define something like add recursively:
Code: Select all
function add() = 0
function add(n) = n
function add(first|rest) = first + add(rest)
...assuming that | is the cons operator here, as it is in many functional languages (well, the ones I know at least).
The pattern matching generally uses unify to create variable associations, so that add([1,2,3]) in the first set of definitions would map to (a=1,b=2,c=3).
newLISP has unify and letex, but they don't work so well together without an intermediate step, even though letex *should* accept an argument like ((A 1) (B 2) (C 3)) -- actually, it does accept that if typed directly into the function, but it seems to work like a macro- if you do not send the evaluated list value then it will throw an error.
At any rate, my when definition uses unify to pattern match the arguments passed and then execute different blocks of code based on which pattern matches, substituting the values of those matched variables (the results of unify) for their occurrences in the expr passed as the second argument (so using ((A 1) (B 2) (C 3)) for (map println '(A B C)) expands to (map println '(1 2 3)).
Ok, I'm done. Class, don't forget to read chapters five and six in your books and prepare for the quiz on Friday.