Functional is a term used to denote a language where functions are first class, whereby they can be used in the same ways as a more primitive data type.
Functional languages also evaluate expressions rather than execute instructions
plus1 x = x + 1 plus2 x = x + 2 add x g h = g x + h x main = print ( show ( add 2 plus1 plus 2))
Here you can see we define two functions plus1
and plus2
which take a single (integer) parameter. We then define add
which takes a value x
along with 2 parameters which are functions. We then pass our functions plus1
and plus2
as parameters into this expression which evaluates to 7.
A functional language is said to be pure when it cannot have side effects.
Haskell is widely considered to be pure whereas OCaml is not.
Pure programs are easier to debug, maintain and reason about. They also handle concurrency better in most cases.
A programming language can be said to be lazy or eager. This distinction refers to their evaluation strategy.
Lazy languages do not evaluate expressions until they are needed, whereas eager languages evaluate them beforehand.
Haskell is an example of a lazy language and OCaml is eager by default.
For example the following code terminates in Haskell:
but does not in OCaml
This happens due to their differing evaluation strategies. When we apply loop
, which will never terminate in either language, to unit
in Haskell, Haskell realises that f
is never used and does not need to be evaluated. OCaml however, eagerly tries to evaluate loop
and in so doing gets stuck infinitely.
In statically typed languages, expression have types that are checked at compile-time. Programs with type errors will fail at compile-time (rather than runtime).
Both Haskell and OCaml are statically typed. Lisp is dynamically typed
add1 :: Integer -> Integer add1 x = x + 1
is accepted by the haskell compiler but:
addT x = x + True
is not, as Haskell realises that we are trying to use +
on an x
of type T and a boolean when the addition operator is defined on integers.
Haskell is a "mostly pure" lazy functional programming language
see h2.hl
We will also be looking at the -Calculus, a very simple functional programming language.
Like turing machines, the -Calculus is a model of computation.
There are only 3 constructs in the -Calculus:
It allows for the creation and application of (anonymous) functions.