What's a useful example of a partial function app in Swift?
I can see that Swift offers a convenient syntax for declaring curry functions. The tutorial provides a partial function application as an example of where the function will be used in curry.
Can anyone give me an example where a partial function app might be useful? I know this is a general functional programming concept, but an example in Swift would be most valuable.
source to share
Suppose you often want to check for a number that i
is a multiple of another value. The fact that he can be a multiple can vary, but usually to determine its always the same: i % n == 0
.
You can write a function like this:
func isMultipleOf(#n: Int, #i: Int) -> Bool {
return i % n == 0
}
isMultipleOf(n: 2, i: 3) // false
isMultipleOf(n: 2, i: 4) // true
However, you may often want to use this function with other functions of the "high-order", that is, functions that take other functions as arguments, such as map
, and filter
:
let r = 1...10
// use isMultipleOf to filter out the even numbers
let evens = filter(r) { isMultipleOf(n: 2, i: $0) }
// evens is now [2,4,6,8,10]
This usage isMultipleOf
looks a little awkward and hard to read, so perhaps you define the new function isEven
in terms isMultipleOf
to make it clearer:
let isEven = { isMultipleOf(n: 2, i: $0) }
isEven(2) // true
isEven(3) // false
let evens = filter(r, isEven)
Now, suppose you declare a isMultipleOf
little differently, like a curry function:
func isMultipleOf(#n: Int)(#i: Int) -> Bool {
return i % n == 0
}
isMultipleOf
is now a function that takes a number n
and returns a new function that takes a number and checks if it is a multiple n
.
Now you can use it to declare isEven
like this:
let isEven = isMultipleOf(n: 2)
Or you can use it directly with a filter like this:
let evens = filter(r, isMultipleOf(n: 2))
// just like before, evens is [2,4,6,8,10]
source to share