习题笔记
今天解决一下 Higher Order Functions: Map, Filter, Reduce and more – Part 1 中最后的13个练习题,主要是关于闭包的(咦不对啊我明明是想看集合方面内容的。。。)。
Write a function applyTwice(f:(Float -> Float),x:Float) -> Float that takes a function f and a float x and aplies f to x twice i.e. f(f(x))
func applyTwice(f:(Float -> Float),x:Float) -> Float {
return f(f(x))
}
Write a function applyKTimes(f:(Float -> Float),x:Float,k:Int) -> Float that takes a function f and a float x and aplies f to x k times
// recursive version
func applyKTimes(f:(Float -> Float), x:Float, k:Int) -> Float
{
return k > 0 ? applyKTimes(f, f(x), k - 1) : x
}
// unrolled by hand
func applyKTimes(f:(Float -> Float),x:Float,k:Int) -> Float {
var y : Float = x
for _ in 0..<k {
y = f(y)
}
return y
}
Using applyKTimes write a function that raises x to the kth power
func getKthPower(x:Float, k:Int) -> Float{
return applyKTimes( {x * $0}, 1, k) // {x * $0} => {p in return x * p}
}
getKthPower(2.0, 3) // 8.0