4 ms·
Let's begin with the array. Imagine I have an array of characters: var a = ['a', 'b', 'c'] I'd like instead to have the index of their position in the alphabe
by afthonos 12y ago
Let's begin with the array. Imagine I have an array of characters:
var a = ['a', 'b', 'c']
I'd like instead to have the index of their position in the alphabet. That's another array of the same length that would look like this:
var i = [0, 1, 2]
To each element in a, there corresponds an element i, at the same index. And the operation we use is the same for each element:
f('a') = 0
f('b') = 1
f('c') = 2
But we could also want an array that gives us the next letter in the alphabet, like so:
var n = ['b', 'c', 'd']
Here the function is:
g('a') = 'b'
g('b') = 'c'
g('c') = 'd'
But we're very much doing the same thing. We call it mapping. So Arrays in Swift have a map function defined that works like this:
var i2 = a.map(f)
We're passing the function to apply to each member, and we get an array back, of the same length, with the result of doing so.
A functor is a generalization of that concept. It takes a type parametrized by another type, say Box<V> and a function from the parametrized type to another type, say f:V -> W. Then, according to rules that are specific to Box, if you map f over Box<V>, you'll get a Box<W> out.
The key is that exactly how a Box<V> becomes a Box<W> is up to Box.