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.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,786評論 6 534
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,656評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,697評論 0 379
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,098評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,855評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,254評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,322評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,473評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,014評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,833評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,016評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,568評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,273評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,680評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,946評論 1 288
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,730評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,006評論 2 374

推薦閱讀更多精彩內(nèi)容