美文网首页
Currying,柯里化

Currying,柯里化

作者: 幸运的小强本人 | 来源:发表于2016-03-07 22:20 被阅读21次

    原文地址

    No seriously though, what is currying

    Let's work our way up. Here's a normal function in Swift that takes two Ints as arguments, a and b, then adds them together:

    func add(a: Int, b: Int) ->Int {
        return a + b
    }
    

    So now, if we want to use this function, we can call it:

    let sum = add(2, 3) // sum = 5
    

    This is useful. But what if we wanted to take a list of numbers, and add 2 to each one, getting a new list back. We could create a quick list of numbers using a Range, then use Range.map to iterate through and get a new list. That would give us a chance to apply add to the integer 2 and each number in the range:

    let xs = 1...100
    let x = xs.map {  add($0, 2 } // x = [3, 4, 5, 6, etc]
    

    That's not horrible, but this is also monumentally(知道纪念的) contrived(做作的) example. It feels weird to me to have to create a closure just for the sake of passing add with a default value. It could also get a little hairy if the function was more complicated, and we need to supply more default parameters. Fortunately we can use function currying to help.

    If we just look at types, we can see that add has a type of (Int, Int)->Int. So it takes 2 parameters of the type Int, and returns an Int. However, what we really want is something to pass to map, which takes a function of the type A->B:

    extension Range<A> {
        func map<B>(transform: A->B) -> [B]
    }
    

    Note that the above snippet doesn't compile because you can't create an extension on a generic type. The actual implementation is in the standard lib, and is only here for illustration purpose.

    So, if we had a function that took one argument, and returned one value, we wouldn't need to use a closure for map at all. Instead, we could pass the function to map directly. Well, we could make this work by wrapping add in a new function:

    func addTwo(a: Int) -> Int {
        return add(a, 2)
    }
    let xs = 1...100
    let x = xs.map(addTwo) // x = [3, 4, 5, 6, etc]
    

    But this feels a little too specific. What if we wanted to create addThree or addOneHundred. If we keep going down this road, we'd need to continue to create wrapper function for each integer we want to use. It would be nicer to be able to build something that could be applied more generally for any integer. We can do this by writing our functions to return other functions.

    To illustrate this, let's start by modifying that original method:

    func add(a: Int)->(Int -> Int) {
        return { b in a + b }
    }
    

    We've now redefined our function as one that takes a single argument. The return value is a function that takes a single argument and returns the sum of a(passed by name to the function), and b(passed to, and named by, the closure). This means two things:

    1. If we want to satisfy all of the arguments for the function and call it immediately, we now need to separate the arguments with parenthesis:

      let sum = add(2)(3) // sum = 5

    2. It also lets us "partially apply" the add function. This means that passing one argument to add returns a new function taht accepts the next argument. Once that argument is satisfied, this new unnamed function finally returns the result.

    What's the benefit of this? Well, it allows us to create smaller functions out of larger functions by reducing the number of arguments needed. Our addTwo function definition, for example, can easily become a simple let:

    let addTwo = add(2)
    

    And now addTwo is a function that takes a single Int argument, and returns an Int, which means we can still pass it directly to map:

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

    There's still one more change we can make that will improve our add function. Right now, we're manually creating and returning the closure, and giving our function an unintuitive signature. But Swift actually supports this kind of function out of the box. We can bring our function definition back to something a little closure to what we started with. without losing the currving functionality:

    func add(a: Int)(b: Int)->Int {
        return a + b
    }
    

    This function is equivalent to our earlier implementation that had the closure, with the exception that now you need to name the second parameter:

    let sum = add(2)(b: 3) // sum = 5
    

    In fact, at the time of this writing, there is no way to define the function so that you can omit the external name.

    This is fairly gross, but in this case it doesn't impact us much at all.We can still pass the partially applied function to map as we did before.

    func add(a: Int)(b: Int)->Int {
        return a + b
    }
    
    let addTwo = add(2)
    let xs = 1...100
    let x = xs.map(addTwo)
    

    OK, cool, but what about functions I don't own

    If you don't own the function you're working with (yo what up UIKit) or if you don't want the function to be curried by default (because let's be honest, that calling syntax is funky), you might think you're out of luck. But I have good news: you can implement a function that takes an existing function as a parameter, and returns a curried wrapper around that function. And it uses the same basic technique that we used to create our own curried function in the first place.

    Let's pretend that instead of add, the free function that we defined above, we're dealing with NSNumber.add, a class method that I'm totally making up for the sake of demonstration:

    extension NSNumber {
        class func add(a: NSNumber, b: NSNuber)->NSNumber {
            return NSNumber(integer: a.integerValue + b.integerValue)
        }
    }
    

    So now, if we decide that this function should be curried for some specific use case (like being partially applied for map), we want to be able to do that.

    First thing we need to do is define a function that takes a function of the same type as NSNumber.add as an argument. When you strip away the naming, you end up with (NSNumber, NSNumber)->NSNumber. This will let us pass NSNumber.add into it directly. We'll name this argument localAdd internally to avoid confusion:

    func curry(localAdd:(NSNumber, NSNumber)->NSNumber) {
    
    }
    

    Then we can add the return value, which is a function that takes an NSNumber and returns a new function. That function should take an NSNumber and return an NSNumber. The type we end up with is (NSNumber->(NSNumber->NSNumber))

    func curry(localAdd:(NSNumber, NSNumber)->NSNumber)->(NSNumber->(NSNumber->NSNumber)) {
    
    }
    

    Then we can use the trick from earlier and start returning closures:

    func curry(localAdd:(NSNumber, NSNumber)->NSNumber)->(NSNumber->(NSNumber->NSNumber)) {
        return {a: NSNumber in
                      { b: NSNumber in 
                          {
                              localAdd(a, b)
                          }
        }
    

    So a and b represent the two NSNumber instances that will be passed to localAdd. So now, we could curry our NSNumber.add function with our new curry function:

    let curriedAdd = curry(NSNumber.add)
    let addTwo = curriedAdd(2)
    
    let xs = 1...100
    let x = xs.map(addTwo)
    

    This works really well, but we can actually use Generics to generalize our curry function to take arguments of any type. To start, we should figure out how many types we need. In this case, we want to pass two variables and return a third. These can all be of the same type, but they don't have to be, so we should probably use three generic types in our signature. Generic types are usually shown as uppercase letters, so we'll use A, B, and C. Replacing the explicit NSNumber types with these generic types(and generalizing the function name) leaves us with this:

    func curry<A, B, C>(f: (A, B)->C)->(A->(B->C)) {
        return { a: A in
                      { b: B in
                          return f(a, b) // returns C
                      }
        }
    }
    

    Now, to clean things up, we can take advantage of Swift's type inference to remvoe the inner types:

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

    We can also take advantage of the implicit return values for single line closures and move the whole thing onto one line:

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

    Finally, the parenthesis in the return value are optional, so we can remove them as well:

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

    Interestingly enough, since we've made our function completely generic, this is actually the only way we could have possibly written the implementation in order to get it to compile. So the entire concept is encoded directly into the types. We have no idea that C is, so the only way we know of to create an instance of that type is to use f. We also don't know what A OR B ARE, SO THE ONLY WAY WE CAN GET VALUES to pass to f are to use a and b. That's insanely powerful, since it means we can't mess it up.

    Also, since this function now works with any function that matches the type (A, B)->C, we can use it on any function that matches this type signature. Including the functions that power the standard operators. So, if we really want to get wacky, we can re-write everything we've done so far like so:

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

    This is super long. Wrap it up

    If we take a look of that definition from the first paragraph, it hopefully doesn't sound as much like gibberish anymore

    We have a function that takes multiple arguments. We then change that function so that it only takes one argument, and returns a function that takes the next argument, and so-on and so-forth until all arguments are satisfied. At that point (and only at that point), the calculations are performed, and a value is returned. We handled this for 2 arguments, but it's the same process for as many arguments as you can throw at your functions.

    相关文章

      网友评论

          本文标题:Currying,柯里化

          本文链接:https://www.haomeiwen.com/subject/ywxzkttx.html