Functional Programming

What is Functional Programming?

We are used to imperative programming.

Recall — Imperative Programming:

Remember — All programs transform data into something else.

Functional Programming:

Functions

Example — You can’t do x = 1 + y, instead you have to use functions.

Definition — Mathematical Function: A special type of relation.

Related Notes — CS1300: Relations Properties of Relations: If you cross a set with itself (e.g., int cross int, take a subset), you can define special properties:

Mappings:

Functions are injective. They can be one-to-one or many-to-one.

Functional Equations

This is only a function if you provide domain and codomain.

f(x) = x + 1

Z \to Z

Z: Set of all integers.

This doesn’t change the input variable; it transforms it.

A program, rather than being a list, now just looks like

f_n ( f(_{n-1} ( f_{n-2} ( ... f_2 ( f_1 (\text{input} ) ) ) )

Variables vs. Bindings:

Why do This?

The root of all evil: Destructive updates.

If there are no changes, all computation is local!

Problems

There are parts of a program that need to do destructive updates (e.g., I/O).

Example — Sorting a list instead of an array is quadratic. You need imperative features to be practical.

On Concurrent / Distributed Programming

In modern distributed data and cloud computing, functional languages are emerging as a superior choice because they lack mutable state.

Definitions

1. Concurrent Programming

2. Parallel Programming

Clarification: Taxonomy of Parallelism

The Problem: Shared Memory

Standard programming uses Shared State (e.g., Producer-Consumer models reading/writing the same variable).

The Solution: Message Passing

In functional languages, multithreading is usually done via Message Passing.

SML Specifics: SML has a specific dialect called Concurrent ML (CML) for this.

In CML, instead of locking a variable x, you would have a “Channel”. One thread sends a value into the channel, and another thread receives it. It looks very similar to Go routines or Erlang actors.

Modern Examples: