The preceding illustration can be generalized to a full matrix/computer algebra system (similar to Matlab for instance) with applications to a full range of domains (e.g. signal/image processing, neural networks, etc.)
To proceed, let's define some other remarkable functions to:
fold
" (e.g. how to use the "sum" template to get the min/max of a list ?).f
to a value x
(what is called the fixpoint of f
, and can be use to solve equations for instance with bissection method).The "sum" function can be written as follow:
let rec sum xs =
match xs with
| [] -> 0
| v::vs -> v+(sum vs)
printfn "%A" (sum [1;2;3])
The elements (0,+)
can be considered as parameters and replaced by (1,*)
, (99,min)
, (-99,max)
, ([],insert)
, etc.
let rec reduce v0 op xs =
match xs with
| [] -> v0
| v::vs -> op v (reduce v0 op vs)
let sum = reduce 0 (+)
let max = reduce (-9) (fun x r -> if x>r then x else r)
printfn "%A" (sum [1;2;3])
printfn "%A" (max [1;2;3])
As an exercice, try to define functions on matrixes (i.e. list of lists).