2

I'm trying to grasp the concept behind curry functions. Below is the code:

class MyHelloWorldClass {

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

I can create a variable that points to the class’s helloWithName function:

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

My new helloWithNameFunc is of type MyHelloWorldClass -> (String) -> String, a function that takes in an instance of my class and returns another function that takes in a string value and returns a string value.

So I can actually call my function like this:

let myHelloWorldClassInstance = MyHelloWorldClass()

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

Credit: I go this code from this site

What is the benefit of using the above curry function? When would there a need to call a function that takes an instance of its class, that takes the subsequent parameter that was passed.

user1107173
  • 10,334
  • 16
  • 72
  • 117
  • possible duplicate of [What is 'Currying'?](http://stackoverflow.com/questions/36314/what-is-currying) – sbooth Feb 19 '15 at 01:58
  • You accepted an answer that doesn't really illustrate currying but instead partial evaluation. And it didn't even use the builtin Swift curry syntax. Okay, up to you. – GoZoner Feb 19 '15 at 04:02
  • Well, my question was marked as a duplicate. I didn't think I would have an answer so I marked it as correct. I unaccepted it. Please feel free to answer. Thanks. – user1107173 Feb 19 '15 at 17:30

1 Answers1

3

The problem is that the example given isn't an example of currying exactly. That's why you don't see any value in it.

This is a better example of 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)
    }
}

This is a better example of how function variables are curried functions in Swift: http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/

Fruity Geek
  • 7,351
  • 1
  • 32
  • 41