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(知道紀(jì)念的) 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)系作者
  • 序言:七十年代末捡多,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子铐炫,更是在濱河造成了極大的恐慌垒手,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件倒信,死亡現(xiàn)場離奇詭異科贬,居然都是意外死亡,警方通過查閱死者的電腦和手機鳖悠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門榜掌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人乘综,你說我怎么就攤上這事憎账。” “怎么了卡辰?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵胞皱,是天一觀的道長邪意。 經(jīng)常有香客問我,道長反砌,這世上最難降的妖魔是什么雾鬼? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮宴树,結(jié)果婚禮上策菜,老公的妹妹穿的比我還像新娘。我一直安慰自己酒贬,他們只是感情好又憨,可當(dāng)我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著锭吨,像睡著了一般蠢莺。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上耐齐,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天浪秘,我揣著相機與錄音蒋情,去河邊找鬼埠况。 笑死,一個胖子當(dāng)著我的面吹牛棵癣,可吹牛的內(nèi)容都是我干的辕翰。 我是一名探鬼主播,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼狈谊,長吁一口氣:“原來是場噩夢啊……” “哼喜命!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起河劝,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤壁榕,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后赎瞎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體牌里,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年务甥,在試婚紗的時候發(fā)現(xiàn)自己被綠了牡辽。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡敞临,死狀恐怖态辛,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情挺尿,我是刑警寧澤奏黑,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布炊邦,位于F島的核電站,受9級特大地震影響攀涵,放射性物質(zhì)發(fā)生泄漏铣耘。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一以故、第九天 我趴在偏房一處隱蔽的房頂上張望蜗细。 院中可真熱鬧,春花似錦怒详、人聲如沸炉媒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽吊骤。三九已至,卻和暖如春静尼,著一層夾襖步出監(jiān)牢的瞬間白粉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工鼠渺, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留鸭巴,地道東北人。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓拦盹,卻偏偏與公主長得像鹃祖,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子普舆,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,573評論 2 359

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

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,572評論 0 23
  • 《月亮是最古老的電視》是1965年韓裔藝術(shù)家白南準(zhǔn)創(chuàng)作的一件藝術(shù)作品恬口,這件作品由12 個黑白電視組成,分別顯示月相...
    白胡椒哇閱讀 2,455評論 0 5
  • 輕塵伏在一棵樹的樹梢上沼侣,盡量把身子隱藏在濃密的葉子里瓷产,快速運功療傷诅挑。 內(nèi)傷本已不輕,大大小小十?dāng)?shù)道傷口中尤其以后背...
    是靜顏呀閱讀 342評論 0 0