apply
is a function that applies a function to a list of arguments.
Unfortunately, Swift does not provide any apply
method on arrays. To be able to implement Applicative Functors, we need to develop the apply
function. The following code presents a simple version of the apply
function with only one argument:
func apply<T, V>(fn: ([T]) -> V, args: [T]) -> V { return fn(args) }
The apply
function takes a function and an array of any type and applies the function to the first element of the array. Let's test this function as follows:
let numbers = [1, 3, 5] func incrementValues(a: [Int]) -> [Int] { return a.map { $0 + 1 } } let applied = apply(fn: incrementValues, args: numbers)