Swift学习笔记之习题

这篇博客记录了13个关于Swift中闭包应用的练习,涉及applyTwice、applyKTimes函数实现,幂运算,数组操作如map、filter、reduce。还探讨了reduce在并行计算中的问题以及如何正确找到数组中的最大值。
摘要由CSDN通过智能技术生成

习题笔记

今天解决一下 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值