微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift 柯里化(currying)和反柯里化(uncurrying)

@H_502_1@

// Demo of currying@H_502_1@


@H_502_1@

func addTwoNums(a: Int)(num: Int) -> Int {@H_502_1@

return a + num@H_502_1@

}@H_502_1@


@H_502_1@

let addToFour = addTwoNums(4)@H_502_1@

let result = addToFour(num: 6)@H_502_1@

print("result: \(result)")@H_502_1@


@H_502_1@

func greaterThan(comparor: Int)(input: Int) -> Bool {@H_502_1@

return input > comparor@H_502_1@

}@H_502_1@


@H_502_1@

let greaterThan10 = greaterThan(10)@H_502_1@

let b1 = greaterThan10(input: 10)@H_502_1@

let b2 = greaterThan10(input: 4)@H_502_1@

print("b1: \(b1)")@H_502_1@

print("b2: \(b2)")@H_502_1@


@H_502_1@

// Demo of uncurrying@H_502_1@


@H_502_1@

let foo = {(a: Int) -> (Int) -> Int in@H_502_1@

return {(b: Int) -> Int in@H_502_1@

return a * a + b * b@H_502_1@

}@H_502_1@

}@H_502_1@


@H_502_1@

let interesting = foo(3)(4)@H_502_1@

print("interesting: \(interesting)")@H_502_1@


@H_502_1@

let interestingAgain = (foo(3))(4)@H_502_1@

print("interestingAgain: \(interestingAgain)")@H_502_1@

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐