O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The apply function

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) 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required