AS/A Computer Science: Functional programming

What is functional programming?

Functional programming is a programming paradigm where functions are the building blocks of programs. A function accepts inputs from a set of possible values, known as the domain, and maps these to a set of possible outputs, known as the co-domain.



The domain is a set from which the function's input values are chosen. The co-domain is a set from which the function's output values are chosen. Not all of the co-domain's members need to be outputs. For our example function machine above, f(x) = x/4. Here the domain is the set of integers. Any integer can be passed to the machine. The co-domain would be the set of rational numbers. It is not possible to output all rational numbers e.g. it would never output 1/5.

Function types, types and typeclasses

In functional programming, a function, f, has a function type e.g. f: A → B (where the type is A maps to B, A is the domain, and B is the co-domain). The domain and co-domain are always subsets of objects in some data type.

In the functional programming language Haskell, everything has a type. You can check the type of something in Haskell using the command :t and passing the value or reference to the value you want the type of.



Typeclasses are groups of types e.g. the Num typeclass includes integers, floats, doubles and other numeric types. A type variable is used where a specific type has not been defined to specify as wide a group of elements as possible. In the example below when no type has been defined it uses the type variable a to show it can take any valid numeric class but once it is defined it will only accept integers.



First class objects

First-class objects (or values) are objects which may:

For example integers, floating-point values, characters and strings.

A function is a first-class object in functional programming languages and in imperative programming languages that support such objects. This means that a function can be provided as an argument to another function or returned as the result of a function call.

Knowledge check


Questions:
Correct:

Question text


© All materials created by and copyright S.Goff