Swift:柯里函数的好处

标签 swift currying

我试图理解柯里函数背后的概念。下面是代码:

class MyHelloWorldClass {

    func helloWithName(name: String) -> String {
        return "hello, \(name)"
    }
}

我可以创建一个指向类的 helloWithName 函数的变量:

let helloWithNameFunc = MyHelloWorldClass.helloWithName
// MyHelloWorldClass -> (String) -> String

我的新 helloWithNameFunc 的类型为 MyHelloWorldClass -> (String) -> String,一个接受我的 实例的 函数 code>classreturns 另一个 function,它接受一个 string 值并返回一个 string 值.

所以我实际上可以像这样调用我的函数:

let myHelloWorldClassInstance = MyHelloWorldClass()

helloWithNameFunc(myHelloWorldClassInstance)("Mr. Roboto") 
// hello, Mr. Roboto

信用:我从这个 site 获取这段代码

使用上面的柯里函数有什么好处?什么时候需要调用一个采用其类实例的函数,该函数采用随后传递的参数。

最佳答案

问题在于给出的示例并不是精确的柯里化(Currying)示例。这就是为什么你看不到它的任何值(value)。

这是柯里化(Currying)的一个更好的例子:

class MyHelloWorldClass {
    //Function that takes two arguments
    func concatenateStrings(string1: String, string2: String) {
        return "\(string1)\(string2)"
    }
    //Curried version of concatenateStrings that takes one argument. 
    func helloWithName(name: String) -> String {
        return concatenateStrings("hello, ", name)
    }
}

这是一个更好的例子,说明函数变量如何在 Swift 中柯里化(Currying)函数: http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/

关于Swift:柯里函数的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28597324/

相关文章:

swift - 如何从 MongoDB 存储和检索 Swift Data 或 NSData?

ios - Swift:如何从字符的开始到最后一个索引获取子字符串

快速运行总和

haskell - 'uncurry' 是否有可能是一个 forall 量词?

javascript - 在 JavaScript 中柯里化(Currying)日期时间

reactjs - curry 函数内的 React hooks(创建 HOC)从 linter 'React Hook "useContext 返回错误“无法在回调内调用”

ios - 使用 uisearchbar 搜索后如何获取索引部分标题

ios - 尝试重用 NSURL 时获取 Nil

F# 参数传递

haskell - 一元谓词检查字符串中的字符