How to use function currying in Swift 4

穿精又带淫゛_ 提交于 2019-12-14 03:45:32

问题


I try to understand the function currying tutorial but that code seem out of date. And it's still not really clear about function currying.

I try with this function:

 func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
    return { a in { b in f(a, b)} }
}

And it runs ok with Playground (Xcode 9 beta 6). But the problem is I cannot use this function as the tutorial:

let add = curry(+)
let xs = 1...100
let x = xs.map(add(2))

The code above return error:

Playground execution failed:

    error: FunctionsCurrying.playground:31:17: error: ambiguous use of operator '+'
    let add = curry(+)
                    ^

Please correct me and help me to clear about function currying.


回答1:


That problem is not Swift 4 related, you would get the same error message in Swift 3.

There are many overloaded + operators, therefore in

let add = curry(+)

the compiler does not know which one to choose. With an explicit type cast

let add = curry((+) as ((Int, Int) -> Int))

or an explicit type annotation

let op: (Int, Int) -> Int = (+)
let add = curry(op)

the code compiles and runs as expected.



来源:https://stackoverflow.com/questions/46154375/how-to-use-function-currying-in-swift-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!