fpcourse/lessons/functions.md

91 lines
2.9 KiB
Markdown
Raw Permalink Normal View History

2023-04-14 20:36:03 +00:00
# Functions
As you might've guessed, the foundations of functional programming are
_functions_! Yes, exactly in the math sense. If high school math is getting a
bit hazy for you, here's a recap:
- Functions take a single input (or multiple inputs, but we'll get into this a
bit later!) and produce a single output
- f(1) = 2
- f(2) = 4
- f(3) = 6
- Multiple inputs are allowed to produce a single output
- g(1) = 1
- g(2) = 1
- g(3) = 2
- A single output cannot produce two different values!
- h(1) = 1
- h(2) = 2
This isn't a function. Think of functions as being this unchangeable binding
between one input and a certain output. If you evaluate the function again, it
should always produce that same output, so it doesn't make sense for a
function to simultaneously give two outputs for a single input. This property
is called function _purity_.
> There are also impure functions, which have _side effects_. For now, we will
> focus on pure functions.
> Example questions:
>
> - Which of the following are functions? (give a few functions)
## Functions can call other functions
The output of a function is really just like any other expression that you could
write. For example:
- 1, 5+5, log(x) is a valid output. f(x) = 1, g(x) = 5+5, h(x) = log(x)
- Any expression involving the input is valid. f(x) = 2 \* x
- Calling the function again is valid! f(x) = f(x - 1)
- _There are a few restrictions to this. We'll see how this works later_
In general, we can say that function calls are part of what we consider
expressions. Since the right side of functions are also expressions, we can call
functions inside functions!
- See also: Expressions
## Functions are first class
In traditional arithmetic, we think of functions as rather _privileged_.
Functions are these operations that we can _do_ to numbers, which are different
from numbers.
Well, not anymore. Functions themselves are also expressions now! We can talk
about passing them around to other functions, but not much in the realm of
arithmetic.
- Venn diagram:
- Functions
- Can be called
- Both
- Can be passed around as variables
- Numbers
- Can be added / subtracted / multiplied / divided
- Can take square roots and compute lots of functions
If you noticed, all we really added was this middle part. But this gives us a
lot of power to use functions. Say you wanted to write a function called
**repeat**. All it does is repeat a function several times. For example,
- If I have f(x) = 2x, then repeat(f, 5) = f(f(f(f(f(x))))) = 32x
- If I have g(x) = 3x - 1, then repeat(g, 2) = 3(3x - 1) - 1 = 9x - 4
In this case, the function **repeat** is known as a _higher order function_. It
takes a function as its parameter, and can freely call it or pass it around.
There are a few very useful and popular higher order functions:
- map
- filter
- fold
## Recursion
## Currying