Anish
Anish

Reputation: 2927

Higher Order Function in Swift

Recently, I came across the following higher order function example in Wiki: https://en.wikipedia.org/wiki/Higher-order_function#Swift

But I am unable to understand the function. Can anyone explain the code?

// generic function
func twice<T>(_ v: @escaping (T) -> T) -> (T) -> T {
    return { v(v($0)) }
}

// inferred closure
let f = { $0 + 3 }

twice(f)(10) // 16

Upvotes: 3

Views: 253

Answers (1)

Jake
Jake

Reputation: 13771

twice takes a function v, and returns a new function that compounds v's functionality. Basically, if you have a function v, calling twice(v)(someValue) is the same as calling v(v(someValue)).

// inferred closure
let f = { $0 + 3 }

twice(f)(10)
//=> f(f(10)) 
//=> { $0 + 3 }(f(10)) 
//=> { $0 + 3 }({ $0 + 3 }(10)) 
//=> { $0 + 3 }(10 + 3)
//=> { $0 + 3 }(13)
//=> 13 + 3
//=> 16

Upvotes: 6

Related Questions