Swift subtle difference between curried and higher order function

爱⌒轻易说出口 提交于 2019-12-09 07:18:27

问题


NOTE: This question was asked while Swift 2.1 was the latest.

Given:

class IntWrapper {
    var i: Int = 1
}
func add(inout m: Int, i: Int) {
    m += i
}

And a higher order function

func apply() -> (inout i: Int) -> () -> () {
    return { (inout i: Int) -> () -> () in
        return {
            add(&i, i: 1)
        }
    }
}

Application as so results in the member variable value never changing:

var intW = IntWrapper()
print(intW.i)                             // Prints '1'
apply()(i: &intW.i)()
print(intW.i)                             // Prints '1'

However, when changing the function to curried form

func apply()(inout i: Int)() -> () {
    add(&i, i: 1)
}

Application results in the member variable value changing:

var intW = IntWrapper()
print(intW.i)                             // Prints '1'
apply()(i: &intW.i)()
print(intW.i)                             // Prints '2'

I'm curious to why this is. I always thought that curried syntax was sugar for the higher ordered form of the function, but apparently there are semantic differences.

Additionally this accepted proposal to remove curried syntax from swift seems to state this is merely sugar, and I'm concerned we're losing more than syntax by removing this from the language. Is there a way to get the same functionality from a higher order function?

来源:https://stackoverflow.com/questions/35423428/swift-subtle-difference-between-curried-and-higher-order-function

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