Nota Bene: There can be many machines and many ways of writing the same program.
Can we devise a process to determine in a finite number of operations, whether a first order logic statement is valid?
In an imperative program, we read, write, perform operations, and take decisions based on contents of memory cells that hold the contents of variables like c, res, n, in the following example:
public class Factorial{
public static int compute(int n){
int res = 1;
for(int c=1; c<=n; c++)
res *= c;
return res;
}
}
Alonzo Church also answers Hilbert's question in 1936 with a completely different approach, inventing the lambda calculus.
$(\lambda x.M) N \xrightarrow{\beta} M[x:=N]$
The $\beta$ reduction rule is the one and only computational device in the system.
In a functional programming language we can define (possibly recursive) functions, and compose and apply them to compute the expected results.
Example:
let rec fact =
function n -> if n=0 then 1 else n*(fact(n-1))
In a truly functional programming language, functions are first clas citizens. They can be:
Using Church's original notation one could write the same example as:
lambda n. if n=0 then 1 else n(fact(n-1))
In [7]:
List.map(fun x -> x+1) [1; 2; 3; 4; 5; 6];;
Out[7]:
[] is the empty lista::l is a list having a as first element,a nd list l as rest.A function to sum all elements in an integer list:
In [16]:
let rec suml =
function
[] -> 0
| a::rest -> a + (suml rest)
;;
suml [1; 2; 3; 4; 5];;
Out[16]:
Out[16]:
All types are computed, and enforced at compile time.
In [14]:
suml [1; 2; 3];;
suml ["1"; "2"; "3"];; (* Error *)
Out[14]:
Out[14]:
In [28]:
let rec fold op e =
function
[] -> e
| a::rest -> op a (fold op e rest)
;;
fold (+) 0 [1; 2; 3; 4; 5];;
fold (^) "" ["1"; "2"; "3"; "4"; "5"];;
fold (fun(x, y) a-> x+a) 0 [(2, 4); (3, 5); (6, 7)];;
Out[28]:
Out[28]:
Out[28]:
Out[28]:
In [33]:
let rec destutter =
function
| [] -> []
| x::[] -> x::[]
| x::y::rest ->
if x=y then destutter(y::rest)
else x::destutter(y::rest)
;;
destutter [1; 1; 2; 2; 2; 3; 1; 4; 2; 2];;
Out[33]:
Out[33]: