Currying,柯里化

原文地址

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,029评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,395评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,570评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,535评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,650评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,850评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,006评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,747评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,207评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,536评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,683评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,342评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,964评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,772评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,004评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,401评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,566评论 2 349

推荐阅读更多精彩内容