March 4, 2009, 5:34:15 pm
I had some spare time on my hands for some unknown reason last night, so I knocked up a way to curry blocks in Smalltalk. It follows the same pattern as value:* and cull:* so it should be immediately familiar to fans of blocks.
What is curry? Currying is where you take a function and you prefill some of its arguments to make a new function. This is a pretty common thing to do in functional programming but it's not so common in Smalltalk for some reason. We recently introduced cull:* to the system which does the opposite of currying, it lets you pass in extra parameters to a block closure that are ignored if the block closure doesn't need them.
Culling: [:a :b | a + b ] cull: 1 cull: 2 cull: 3
The third argument in this statement is ignored with the cull selector, while with the value:* selector it would throw an error that there was an arguments mismatch. Sometimes, though, you want to consume one of the arguments. You could do that like this:
originalBlock := [:a :b | a + b ].
curriedBlock := [:b | originalBlock value: 5 value: b]
Because it's sometimes a pain to have to reiterate all the arguments that go in to a block - and because often it's the /first/ argument to a block you want to replace, some of you may find the new BlockCurrying package useful, which in the above example would look like this:
curriedBlock := originalBlock curry: 5
BlockCurrying is by no means necessary and it's not something I'll be pimping for the VisualWorks base anytime soon - not unless we get oodles of people writing in saying "this is something I need all the time" which was the reaction to culling.
BlockCurrying is on the public store now if you're interested in playing with it. It has tests, but if you want something more powerful than the curry:* selector, remember you can always write your own block like in the code above to re-order, replace, add more arguments to the block/function.