<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>3 + 4 &#187; smalltalk</title>
	<atom:link href="http://blog.3plus4.org/category/smalltalk/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.3plus4.org</link>
	<description>The neighbourhood of 7</description>
	<lastBuildDate>Thu, 23 Apr 2009 02:40:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>What&#8217;s a Binary Selector?</title>
		<link>http://blog.3plus4.org/2007/05/06/whats-a-binary-selector/</link>
		<comments>http://blog.3plus4.org/2007/05/06/whats-a-binary-selector/#comments</comments>
		<pubDate>Mon, 07 May 2007 05:35:33 +0000</pubDate>
		<dc:creator>Vassili Bykov</dc:creator>
				<category><![CDATA[smalltalk]]></category>

		<guid isPermaLink="false">http://blog.3plus4.org/2007/05/06/whats-a-binary-selector/</guid>
		<description><![CDATA[Intuitively, binary selectors are obvious&#8212;you string together a few funky characters and you have yourself a binary selector. And binary selectors can useful for making some things easier to read. At least that&#8217;s the theory, and reading the ANSI standard one might assume everything is exactly that clear. The practice in Smalltalk-80 descendants is different. [...]]]></description>
			<content:encoded><![CDATA[<p>Intuitively, binary selectors are obvious&#8212;you string together a few funky characters and you have yourself a binary selector. And binary selectors can useful for making some things easier to read. At least that&#8217;s the theory, and reading the ANSI standard one might assume everything is exactly that clear. The practice in Smalltalk-80 descendants is different.</p>
<p>To begin with, Smalltalk-80 only allowed two characters in a binary selector, ruling out beauties such as &lt;=&gt;, &lt;+&gt; or &gt;&gt;=. Fortunately, the ANSI standard has dropped this limit, and Squeak also allows selectors of more than two characters. VisualWorks, however, still sticks to the old ways.</p>
<p>Then there is the wrench negative number literals throw in the works. Intuitively, <code>3&nbsp;&ndash;&ndash;&nbsp;4</code> is supposed to send the #&#8211; message to 3&#8212;and probably cause an MNU. Indeed, that is what would happen in an ANSI-compliant Smalltalk. Instead, Squeak will happily parse and evaluate the above to 7, while VisualWorks will throw a compiler error saying that an argument is expected following the first minus.</p>
<p>Here is why that is. A negative number literal in Smalltalk-80 is simply a minus token followed by a number token. Squeak still sticks to that interpretation, and so it sees no difference between <code>"-4"</code> and <code>"-&nbsp;&nbsp;4"</code>. Both are valid forms of writing a negative four. ANSI and VisualWorks have since moved to a less quirky behavior treating the minus as part of the literal number token. Interestingly, the cute syntax diagrams at the end of the Blue Book suggest Smalltalk-80 does the same, but evaluating <code>"-&nbsp;&nbsp;4"</code> shows that it doesn&#8217;t.</p>
<p>But wait, before the second minus in <code>"3&nbsp;&ndash;&ndash;&nbsp;4"</code> got attached by Squeak to the number that follows, why did it get detached from the first one to begin with?</p>
<p>And here lurks another feature. This time it is in fact documented by the cute syntax diagrams. A binary selector is made of special characters, but a minus is a special case of a special character. It&#8217;s only allowed once, and only as the first character of a binary selector. So, <code>-</code>, <code>-&gt;</code> or <code>-+</code> are legal, <code>+-</code>, <code>&lt;-</code> or <code>--</code> are not. Clearly, the point of this feature was to have &#8220;3+-4&#8243; or &#8220;3&ndash;&ndash;4&#8243; parse &#8220;sensibly&#8221; as arithmetic expressions rather than exotic message sends.</p>
<p>This also explains why VisualWorks treats &#8220;3&nbsp;&ndash;&ndash;&nbsp;4&#8243; as an error. It switched from the classical treatment of a minus before a literal to a more modern (or at least compliant with the Blue Book syntax diagrams) treatment, so it doesn&#8217;t see the second minus as belonging to the 4 that follows&#8212;but it still refuses to accept &#8220;&ndash;&ndash;&#8221; as a valid binary selector, hence the error. Strange, that.</p>
<p>And that&#8217;s not the end of it. The problem with a minus is that the grammar uses it for two purposes&#8212;as part of a number literal and also as part of a selector. Another character just like that is a vertical bar. &#8220;foo || bar&#8221; doesn&#8217;t work in Squeak and VisualWorks. And it never did, going as far back as Smalltalk-80 again.</p>
<p><img src='http://blog.3plus4.org/wp-content/uploads/2007/05/3barbar4.gif' alt='3 || 4' /></p>
<p>This time the scanner doesn&#8217;t even try to be nice. A vertical bar  always parses as a separate token, so anything like  || or |&gt; is treated by the scanner as a sequence of two tokens and then rejected by the parser as invalid syntax. So in fact the only legal binary selector with a vertical bar is the vertical bar itself. (This again is contrary to what the Blue Book claims Smalltalk-80 recognizes as a binary selector).</p>
<p>All that was perhaps way too much nit-picking as far as any practical programming is concerned, but I find two things interesting about this situation.</p>
<p>One is that the Blue Book misrepresents the grammar of the actual implementation, and not once but twice. The version in the book is probably more of what the authors <em>wanted</em> the grammar to be, rather than an accurate documentation of the ad-hoc implementation in the image. Maybe this was why one of these quirks later got fixed in the ParcPlace branch of the family.</p>
<p>The second interesting point is why is this such a minor issue? How many people in the past 25 years have actually <em>wanted</em> to write &#8220;foo || bar&#8221; or &#8220;foo &lt;- bar&#8221; and discovered they didn&#8217;t work? Do Smalltalkers use binary messages creatively&#8212;that is, outside (semi-)traditional math, concatenation and point creation? And if, as it seems, they do not&#8212;why?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.3plus4.org/2007/05/06/whats-a-binary-selector/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>NotNil, then what?</title>
		<link>http://blog.3plus4.org/2007/04/22/notnil-then-what/</link>
		<comments>http://blog.3plus4.org/2007/04/22/notnil-then-what/#comments</comments>
		<pubDate>Sun, 22 Apr 2007 19:59:46 +0000</pubDate>
		<dc:creator>Vassili Bykov</dc:creator>
				<category><![CDATA[smalltalk]]></category>
		<category><![CDATA[squeak]]></category>

		<guid isPermaLink="false">http://blog.3plus4.org/2007/04/22/notnil-then-what/</guid>
		<description><![CDATA[This is about a fix of a conceptual bug in the current version of Squeak, though it&#8217;s the detailed analysis why this was a bug that I think is worth a blog post. A while ago when ifNil: and ifNotNil: were not standard in the commercial Smalltalks of the day, there was an occasional argument [...]]]></description>
			<content:encoded><![CDATA[<p>This is about a fix of a conceptual bug in the current version of Squeak, though it&#8217;s the detailed analysis why this was a bug that I think is worth a blog post.</p>
<p>A while ago when <code>ifNil:</code> and <code>ifNotNil:</code> were not standard in the commercial Smalltalks of the day, there was an occasional argument on c.l.s now and then whether they were a good thing or superfluous sugar not providing any new functionality. The typical case against <code>ifNil:</code> is something like</p>
<pre class="smalltalk">
foo ifNil: [self doSomething]</pre>
<p>which can trivially be rewritten in &#8220;classic&#8221; Smalltalk. The case that is less trivial, though, is</p>
<pre class="smalltalk">
^self foo ifNil: [self defaultFoo]</pre>
<p>It&#8217;s important that the value being tested is computed and not just fetched from a variable. For a computed value, we cannot in the general case reduce the above to</p>
<pre class="smalltalk">
^self foo isNil ifTrue: [self defaultFoo] ifFalse: [self foo]</pre>
<p>because this would evaluate <code>self foo</code> twice&#8212;something we would want to avoid if <code>self foo</code> had side effects. Avoiding double evaluation would call for a variable to hold onto the result of <code>self foo</code>:</p>
<pre class="smalltalk">
| foo |
foo := self foo.
foo isNil ifTrue: [self defaultFoo] ifFalse: [foo]</pre>
<p>which is significantly more verbose than the ifNil: alternative. So, while ifNil: in this case can still be reduced to &#8220;classic&#8221; Smalltalk, doing so takes us down an abstraction level&#8212;from a single message doing exactly what it says to messing around with variables, tests and branches. While in <a href="http://java.sun.com/">some languages</a> such exposed plumbing is a fact of life, in Smalltalk we like to hide it when we don&#8217;t need to deal with it directly.</p>
<p>Now, looking at <code>ifNotNil:</code>, it&#8217;s important to note that its typical use case is different. In fact, this is what&#8217;s interesting about ifNil: and ifNotNil: in general&#8212;they are asymmetrical. While <code>ifNil:</code> allows us to provide a useful value in the cases when the &#8220;main&#8221; branch of the computation returns nil, it&#8217;s unlikely that we&#8217;d ever use <code>ifNotNil:</code> in a mirrored pattern as</p>
<pre class="smalltalk">
^self foo ifNotNil: [nil]</pre>
<p>This shows that the cause of the asymmetry is the obvious fact that typically <em>nil</em> is used as a token indicating the absence of a value. A non-nil object is interesting in its own right, while <em>nil</em> isn&#8217;t.</p>
<p>So, ifNotNil: is primarily useful not as a value-producing expression, but rather as a control statement that triggers computation when another expression produces a useful result, in the simplest case going as something like</p>
<pre class="smalltalk">
foo ifNotNil: [self doSomethingWith: foo]</pre>
<p>This use of ifNotNil: could again be reduced to <code>isNil ifFalse:</code>. The case when the receiver of ifNotNil: is computed is more interesting because of the same problem of avoiding multiple evaluation, the obvious solution to which would again make the code much bulkier:</p>
<pre class="smalltalk">
| foo |
foo := self computeFoo.
foo ifNotNil: [self doSomethingWith: foo]</pre>
<p>The way to hide the plumbing here is to have ifNotNil: accept a one-argument block and feed the receiver into it, allowing us to fold the above back into a single expression</p>
<pre class="smalltalk">
self computeFoo ifNotNil: [:foo | self doSomethingWith: foo]</pre>
<p>This illustrates another asymmetry of ifNotNil: and ifNil:&#8212;while ifNil: block needs no arguments because nil is not an &#8220;interesting&#8221; object, it&#8217;s often helpful for ifNotNil: to take the non-nil receiver as argument.</p>
<p>A number of years ago Squeak had <code>ifNil:</code> and <code>ifNotNil:</code> implemented exactly this way. The former would take a niladic block as the argument and the latter (as far as I can remember) would only accept a monadic one. When a few years ago Eliot and I were adding the two to VisualWorks we kept almost the same pattern, extending the ifNotNil: case to also accept a niladic block.</p>
<p>In Squeak the two messages have since then been reimplemented as special messages, expanded by the compiler into the equivalent <code>== nil </code><code>ifTrue:/ifFalse:</code> forms. Inexplicably, in the process <code>ifNotNil:</code> was changed to only accept a niladic block&#8212;precisely the case that is less valuable! Also interestingly, the fallback implementation in ProtoObject still allows a monadic block in a &#8220;pure&#8221; <code>ifNotNil:</code> but not as the <code>ifNotNil</code> argument of <code>ifNil:ifNotNil:</code> and <code>ifNotNil:ifNil:</code>! Their classification under the &#8216;testing&#8217; protocol is a minor nit in comparison.</p>
<p>And now for the fix. It is available as a zip file <a href="http://blog.3plus4.org/wp-content/uploads/2007/04/monadicifnotnil.zip" title="MonadicIfNotNil.zip">MonadicIfNotNil.zip</a> with two change sets. One modifies the handling of ifNotNil: and related messages to allow monadic blocks. The second contains the tests and should obviously be filed in after the compiler changes in the first set.</p>
<p>The change was fairly straightforward. Most of the work was dancing around the original error checking code that assumes only niladic blocks are legal as arguments of macroexpanded messages. The expansion simply promotes the block argument into a method temp, expanding</p>
<pre class="smalltalk">
self foo ifNotNil: [:arg | ...]</pre>
<p>into</p>
<pre class="smalltalk">
(arg := self foo) ifNotNil: [...]</pre>
<p>In VisualWorks such treatment would count as incorrect, but this promotion of a block argument into a method temp is in fact the classic Smalltalk-80 trick still surviving in Squeak in the similar treatment of the <code>to:do:</code> message.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.3plus4.org/2007/04/22/notnil-then-what/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Sections Wrap-Up</title>
		<link>http://blog.3plus4.org/2007/04/06/sections-wrap-up/</link>
		<comments>http://blog.3plus4.org/2007/04/06/sections-wrap-up/#comments</comments>
		<pubDate>Sat, 07 Apr 2007 03:55:06 +0000</pubDate>
		<dc:creator>Vassili Bykov</dc:creator>
				<category><![CDATA[smalltalk]]></category>

		<guid isPermaLink="false">http://blog.3plus4.org/2007/04/06/sections-wrap-up/</guid>
		<description><![CDATA[To wrap up for now the thread of functional-like features, here is a very simple implementation of sections that doesn&#8217;t rely on currying: Object&#62;&#62;~ aSymbol aSymbol numArgs = 1 ifFalse: [self error: 'Invalid selector']. ^[:arg &#124; self perform: aSymbol with: arg] Symbol&#62;&#62;~ anObject self numArgs = 1 ifFalse: [self error: 'Invalid selector']. ^[:arg &#124; arg [...]]]></description>
			<content:encoded><![CDATA[<p>To wrap up for now the thread of functional-like features, here is a very simple implementation of sections that doesn&#8217;t rely on currying:</p>
<pre class="smalltalk">
Object&gt;&gt;~ aSymbol
    aSymbol numArgs = 1 ifFalse: [self error: 'Invalid selector'].
    ^[:arg | self perform: aSymbol with: arg]

Symbol&gt;&gt;~ anObject
    self numArgs = 1 ifFalse: [self error: 'Invalid selector'].
    ^[:arg | arg perform: self with: anObject]</pre>
<p>First of all, note the ambiguity of the section operator that we didn&#8217;t discuss in the previous post. What does</p>
<pre class="smalltalk">
#, ~ #,</pre>
<p>mean? Is it a left section prepending a comma to the argument, or a right section appending it?</p>
<p>Considering the implementation, clearly it&#8217;s the latter, but this particular choice of behavior is only a side effect of the implementation. In principle though, the intended meaning is undecidable. There is no difference in Smalltalk between a symbol and a selector&#8212;so there is no way to tell which comma is the operator and which is the section argument. This creates two potential gotchas.</p>
<p>One, it is impossible to create a left section with a Symbol as the fixed argument. We can&#8217;t make a block to check whether the symbol <code>#foobar:</code> includes a given character by writing</p>
<pre class="smalltalk">
#foobar: ~ #includes:</pre>
<p>The second, related, problem is that the behavior of the section operator can vary if the first argument is a variable:</p>
<pre class="smalltalk">
foo ~ #includes:</pre>
<p>creates a left section if the current value of <code>foo</code> is anything but a Symbol, a right section if it is a one-argument selector, or fails otherwise.</p>
<p>In practice, the ambiguity can be avoided by &#8220;downgrading&#8221; the first argument to a string in situations where it might be a symbol we don&#8217;t want to be mistaken for a selector.</p>
<p>A few people asked for some examples how some of the things I talked about could be useful. As I wrote before, I don&#8217;t think currying of blocks can be very useful in practical Smalltalk, simply because the Smalltalk school of expression is different.</p>
<p>I have a slightly different opinion about sections. I use them (the simple currying-independent implementation above) in the framework I&#8217;m working on. I hope to write more about that one day, but for now I&#8217;ll adapt the example to my past project,<a href="http://www.cincomsmalltalk.com/CincomSmalltalkWiki/Announcements+Framework"> VisualWorks Announcements</a>.</p>
<p>Remember that it&#8217;s possible to subscribe for announcements by using either a block</p>
<pre class="smalltalk">
anObject
    when: SomethingHappened
    do: [:ann | ...do something with ann...]</pre>
<p>or a receiver-selector pair</p>
<pre class="smalltalk">
anObject
    when: SomethingHappened
    send: #processAnnouncement:
    to: self</pre>
<p>Given sections, we could handle the receiver-selector case using the same message we use for blocks:</p>
<pre class="smalltalk">anObject
    when: SomethingHappened
    do: self ~ #processAnnouncement:</pre>
<p>Of course, we could also simply drop the receiver-selector option and require explicitly writing</p>
<pre class="smalltalk">
[:ann | self processAnnouncement: ann]</pre>
<p>but arguably the block isn&#8217;t quite as succinct as the equivalent section. So, what does this buy us?</p>
<p>Of course, we simplify the API. There is now only one subscription message instead of two. What was a separate case becomes part of the same mechanism.</p>
<p>The implementation is also simpler. In the original we needed to remember the receiver and the selector to send to it. (The block case is handled by remembering the block as the receiver and setting the selector to <code>#value:</code>&#8212;granted, I&#8217;m simplifying the Announcements picture a little, but as I said my example is only an adaptation). Once we throw out separate support for the receiver-selector case, all we do is remember the block and evaluate it when needed.</p>
<p>There even is a potential performance improvement. The receiver-selector implementation always sends <code>#perform:with:</code> to the receiver to deliver an announcement, even for those subscriptions that use a block. The simplified implementation instead evaluates the block to set things in motion, and <code>#perform:with:</code> only enters the picture together with sections in those cases where we specifically want a receiver-selector option.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.3plus4.org/2007/04/06/sections-wrap-up/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sections</title>
		<link>http://blog.3plus4.org/2007/03/31/sections/</link>
		<comments>http://blog.3plus4.org/2007/03/31/sections/#comments</comments>
		<pubDate>Sun, 01 Apr 2007 06:03:03 +0000</pubDate>
		<dc:creator>Vassili Bykov</dc:creator>
				<category><![CDATA[smalltalk]]></category>

		<guid isPermaLink="false">http://blog.3plus4.org/2007/03/31/sections/</guid>
		<description><![CDATA[Today we are bringing together selectors as blocks from the last post and currying discussed before, to produce something pretty neat: sections. We begin with an example. Using asBlock from the last post, we can write #&#62; asBlock to mean a block comparing two arguments. If we curry it with a number, say 42: #&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>Today we are bringing together selectors as blocks from the last post and currying discussed before, to produce something pretty neat: sections.</p>
<p>We begin with an example. Using <code>asBlock</code> from the last post, we can write</p>
<pre class="smalltalk">
#&gt; asBlock</pre>
<p>to mean a block comparing two arguments. If we curry it with a number, say 42:</p>
<pre class="smalltalk">
#&gt; asBlock curried value: 42</pre>
<p>we get a one-argument block which, when invoked, tells whether 42 is greater than the argument. We could use it as a regular one-argument block, for example, with <code>select:</code></p>
<pre class="smalltalk">
#(1 20 50 43 11) select: (#&gt; asBlock curried value: 42)</pre>
<p>Of course, this by itself isn&#8217;t particularly exciting. <code>[:each | 42 &gt; each]</code> would have done the same, and without excessive mental acrobatics.</p>
<p>Without being too concerned about the form for now, let&#8217;s consider what we have just done by writing that expression. We took an operator (a binary selector) and produced a function (a block) which is an application of that selector to 42 on the left and the function argument on the right. In Haskell such a construct is called a <em>left section</em> of an operator. Similarly, a block applying #&gt; with 42 on the right and the argument on the left would be a <em>right section</em>. This is an interesting concept&#8212;apart from the unwieldy shape it had in our code. Let&#8217;s fix that.</p>
<p>We add two methods to the system, one to the Symbol class, the other to Object.</p>
<pre class="smalltalk">
Object&gt;&gt;~ mustBeSymbol
	| block |
	block := mustBeSymbol asBlock.
	block numArgs ~= 2 ifTrue: [self error: 'invalid selector'].
	^block curried value: self

Symbol&gt;&gt;~ anObject
	| block |
	block := self asBlock.
	block numArgs ~= 2 ifTrue: [self error: 'invalid selector'].
	^[:a :b | block value: b value: a] curried value: anObject</pre>
<p>This defines <code>~</code> as a section operator. Sent to a symbol, it produces a right section, sent to anything else with a symbol as the argument&#8212;a left section. We can now rewrite the example as</p>
<pre class="smalltalk">
#(1 20 50 43 11) select: #&gt; ~ 42</pre>
<p>or to select the opposite</p>
<pre class="smalltalk">
#(1 20 50 43 11) select: 42 ~ #&gt;</pre>
<p>This is more interesting than just currying (and can if fact be rewritten to not rely on currying). It will work for any binary or one-argument keyword message:</p>
<pre class="smalltalk">
Transcript ~ #show:</pre>
<p>is a block that writes its argument to the transcript.</p>
<pre class="smalltalk">
#print: ~ foo</pre>
<p>produces a block writing the printString of whatever was in the variable foo to the argument, which must be a stream-like object.</p>
<pre class="smalltalk">
#, ~ ', hello!'</pre>
<p>is a block that appends &#8216;, hello!&#8217; to the argument, and</p>
<pre class="smalltalk">
'Hello ' ~ #,</pre>
<p>prepends &#8216;Hello &#8216; to it. In general, we can think of a tilda as &#8220;stick the selector and the object together, and the object missing for this to be a complete message send will be provided when the block we create is called&#8221;.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.3plus4.org/2007/03/31/sections/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Selectors as Blocks</title>
		<link>http://blog.3plus4.org/2007/03/27/selectors-as-blocks/</link>
		<comments>http://blog.3plus4.org/2007/03/27/selectors-as-blocks/#comments</comments>
		<pubDate>Wed, 28 Mar 2007 04:30:13 +0000</pubDate>
		<dc:creator>Vassili Bykov</dc:creator>
				<category><![CDATA[smalltalk]]></category>

		<guid isPermaLink="false">http://blog.3plus4.org/2007/03/27/selectors-as-blocks/</guid>
		<description><![CDATA[In the previous two posts we implemented currying in Smalltalk, and in no fewer than two different ways. As Travis asked in a comment, what good is that other than being cool? First of all, coolness is a virtue in itself. It says a lot about the Smalltalk system and the principles of its design [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://blog.3plus4.org/2007/03/24/currying-in-smalltalk-part-2/">the previous two posts</a> we implemented currying in Smalltalk, and in no fewer than two different ways. As Travis asked in a comment, what good is that other than being cool?</p>
<p>First of all, coolness is a virtue in itself. It says a lot about the Smalltalk system and the principles of its design that something like this can be added to it in a matter of minutes by changing a method or two (or not changing anything at all).</p>
<p>Coolness aside, I don&#8217;t expect currying to be as useful in Smalltalk as it is elsewhere. The means of expression Smalltalk and Smalltalkers rely on are different from those of functional languages. Higher-order functions are not nearly as pervasive. Blocks in Smalltalk have always been subservient to objects, so much so that they are not real closures in a few implementations (and some Smalltalkers even <a href="http://wiki.cs.uiuc.edu/VisualWorks/How+to+get+rid+of+Objects+in+Smalltalk">proposed to get rid of them</a>). So from a pragmatic viewpoint Smalltalk blocks are good enough as they are. But I&#8217;m not interested in being pragmatic here. This is an exercise in looking at familar things in an unfamiliar perspective, or mixing a new ingredient into the standard mix just to see what happens. Smalltalk is a pretty good chemistry set.</p>
<p>Today we continue our exploration by adding this method to the Symbol class:</p>
<pre class="smalltalk">
asBlock
	| arity |
	arity := self numArgs + 1.
	arity = 1 ifTrue: [^[:r | r perform: self]].
	arity = 2 ifTrue: [^[:r :a | r perform: self with: a]].
	arity = 3 ifTrue: [^[:r :a :b | r perform: self with: a with: b]].
	"... and to keep the example simple..."
	self error: 'too many arguments'</pre>
<p>As advertised by the selector, it turns a symbol into a block. The block sends the symbol as a message to the first argument, passing the remaining arguments as the arguments of the message. Given this method, we can write:</p>
<pre class="smalltalk">
#('Hello' 'world') collect: #size asBlock</pre>
<p>to collect the sizes of the collection elements.</p>
<p>That&#8217;s right, this reminds the (in)famous <code>Symbol&gt;&gt;value:</code> hack, however it avoids the problems the hack has.</p>
<p>Consider the meaning of <code>numArgs</code>. This message can be sent to both blocks and selectors to determine how many arguments they take. Symbol&gt;&gt;value: pretends that symbols are the same as blocks. Unfortunately, considered as a selector <code>#isLower</code> has zero arguments, while considered as a block it has one. The same holds for any other selector: a Symbol&#8217;s <code>numArgs</code> doesn&#8217;t count the receiver as an argument, while the receiver does become an argument of the block the selector pretends it is. (The reason <code>arity</code> in the code above is <code>numArgs + 1</code>).</p>
<p>In practice this means that if we pass a Symbol such as <code>#isLower</code> to code that explicitly checks the arity of a block it receives by doing something like</p>
<pre class="smalltalk">
aBlock numArgs = 1 ifFalse: [self error: 'Invalid block'].
^aBlock value: foo</pre>
<p>the code will reject it, even though <code>#isLower</code> was supposed to pass for a one-argument block.</p>
<p>Furthermore, <code>Symbol&gt;&gt;value:</code> does nothing of value (sorry) for selectors of more than zero arguments. In contrast, <code>asBlock</code> is a uniform mechanism to cross over from the domain of selectors to the domain of blocks equivalent to those selectors sent to the block&#8217;s first argument. In particular, binary and one-argument keyword selectors can mix well with <code>inject:into:</code>, <code>fold:</code> and <code>with:collect:</code>.</p>
<pre class="smalltalk">
#(1 2 3) with: #(4 5 6) collect: #@ asBlock
#(20 20 42 16) inject: 0 into: #max: asBlock
(1 to: 6) fold: #* asBlock  "6 factorial"
#('Hello ' 'world' '!') fold: #, asBlock
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.3plus4.org/2007/03/27/selectors-as-blocks/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Currying in Smalltalk, part 2</title>
		<link>http://blog.3plus4.org/2007/03/24/currying-in-smalltalk-part-2/</link>
		<comments>http://blog.3plus4.org/2007/03/24/currying-in-smalltalk-part-2/#comments</comments>
		<pubDate>Sat, 24 Mar 2007 07:04:31 +0000</pubDate>
		<dc:creator>Vassili Bykov</dc:creator>
				<category><![CDATA[smalltalk]]></category>

		<guid isPermaLink="false">http://blog.3plus4.org/2007/03/24/currying-in-smalltalk-part-2/</guid>
		<description><![CDATA[In the first part we changed the behavior of the value: protocol of blocks to support currying. That changes the existing behavior of the system, making it possible for those messages to answer a block instead of a &#8220;real&#8221; value. Is that a problem? One could argue that the new behavior comes into force only [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://blog.3plus4.org/2007/03/23/currying-in-smalltalk/">the first part</a> we changed the behavior of the <code>value:</code> protocol of blocks to support currying. That changes the existing behavior of the system, making it possible for those messages to answer a block instead of a &#8220;real&#8221; value. Is that a problem?</p>
<p>One could argue that the new behavior comes into force only in the situations where the original system would signal an error anyway, so if it falls over because of getting a block it didn&#8217;t expect, it would still have fallen over in the old system because of the number of arguments mismatch. On the other hand, what if it doesn&#8217;t fall over immediately after it gets that unexpected block? It is possible for the new behavior to mask an error and make it difficult to find its cause later. Also, some might not like this kind of a change on the familiarity grounds.  <a href="http://gbracha.blogspot.com/">Gilad</a> was the one who got me on the track of playing with currying, and for these reasons he suggested that it might be a good idea to keep <code>value:</code> and friends intact and introduce a different evaluation message that would allow currying&#8211;something like <code>curry:curry:</code>.</p>
<p>A similar in spirit approach, but one that gives us the best of both worlds, is to introduce a unary message <code>curried </code>used as a prefix to <code>value:</code> to indicate that currying is allowed. The example from the previous post then becomes</p>
<pre class="smalltalk">
| add inc |
add := [:a :b | a + b].
inc := add curried value: 1.
(inc value: 2) + (inc value: 3)</pre>
<p>This both preserves the familiar evaluation protocol and declares that currying is possible. To implement this, unlike in the Part 1 version, we leave <code>valueWithArguments:</code> unchanged from its standard implementation. Instead, we introduce a new class called <code>Currier</code> with an instance variable <code>block</code> and an initialization method <code>block:</code>, and add the following method to the block class (either BlockContext or BlockClosure, depending on the Smalltalk dialect):</p>
<pre class="smalltalk">
curried
    ^Currier new block: self</pre>
<p>This injects a Currier into the message stream as <code>add curried value: 1</code> is evaluated, so that the <code>value:</code> message is received by the Currier. To process it, the Currier needs to invoke the original block if there are enough arguments to do so immediately, or create a CurriedBlock otherwise:</p>
<pre class="smalltalk">value: anObject
    block numArgs = 1
        ifTrue: [^block value: anObject].
    block numArgs &gt; 1
        ifTrue: [^CurriedBlock new block: block arguments: {anObject}].
    self error: 'Incorrect number of arguments'</pre>
<p>The above assumes that an expression such as {anObject} creates an Array with anObject, as in Squeak or in VisualWorks with my BraceConstructor extension.</p>
<p>Other <code>value:...</code> protocol messages are implemented similarly. Also, the CurriedBlock class should implement the same <code>curried</code> method as &#8220;real&#8221; blocks do&#8211;curried blocks are no different from regular ones, so they can be &#8220;re-curried&#8221;. (In Part 1 we would get such re-currying for free).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.3plus4.org/2007/03/24/currying-in-smalltalk-part-2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Currying in Smalltalk</title>
		<link>http://blog.3plus4.org/2007/03/23/currying-in-smalltalk/</link>
		<comments>http://blog.3plus4.org/2007/03/23/currying-in-smalltalk/#comments</comments>
		<pubDate>Fri, 23 Mar 2007 07:35:14 +0000</pubDate>
		<dc:creator>Vassili Bykov</dc:creator>
				<category><![CDATA[smalltalk]]></category>

		<guid isPermaLink="false">http://blog.3plus4.org/2007/03/23/currying-in-smalltalk/</guid>
		<description><![CDATA[Currying, unless you are into Thai cooking, is partial function application commonly used in functional languages. (Some argue it should be called Schönfinkelisation, but oddly so far the term hasn&#8217;t caught on). Given a function of N arguments, one can invoke it with K arguments, K &#60; N. This produces a new &#8220;curried&#8221; function of [...]]]></description>
			<content:encoded><![CDATA[<p>Currying, unless you are into Thai cooking, is partial function application commonly used in functional languages. (Some argue it should be called Schönfinkelisation, but oddly so far the term hasn&#8217;t caught on). Given a function of N arguments, one can invoke it with K arguments, K &lt; N. This produces a new &#8220;curried&#8221; function of N &#8211; K arguments, with the K arguments of the original call closed over (remembered).</p>
<p>In Smalltalk, currying would allow the example:</p>
<pre class="smalltalk">
| add inc |
add := [:a :b  | a + b].
inc := add value: 1.
(inc value: 2) + (inc value: 3)</pre>
<p>run without errors and produce 7. This feels like a significant change down in the foundations of the universe, but amazingly it is trivial to implement.</p>
<p>Both in VisualWorks and Squeak, when a Block is invoked with a wrong number of arguments, message processing ends with a primitive failure in the <code>valueWithArguments:</code> method. The standard Smalltalk response to that is to complain about the wrong number of arguments. All we need is change that response to curry the receiver when appropriate.</p>
<p>To make the example shorter and nicer (we&#8217;ll see why a little later), we define a class called CurriedBlock, with instance variables <code>block</code> and <code>arguments</code> and an obvious initialization method <code>block:arguments:</code>. We also change the standard <code>valueWithArguments:</code> as follows:</p>
<pre class="smalltalk">
valueWithArguments: anArray
	&lt;primitive: 500&gt;
	(anArray isMemberOf: Array)
		ifTrue: [anArray size &lt; self numArgs
			ifTrue: [^CurriedBlock new block: self arguments: anArray]
			ifFalse: [self error: 'Incorrect number of arguments']]
		ifFalse: [self error: 'valueWithArguments: requires an Array']</pre>
<p>The method above is a simplification of the VisualWorks version, with the horrible UserMessages replaced by readable strings. The Squeak version is nearly identical.</p>
<p>CurriedBlock needs to reproduce the standard block protocol:</p>
<pre class="smalltalk">
valueWithArguments: anArray
	^block valueWithArguments: arguments, anArray

value: anObject
	^block valueWithArguments: (arguments copyWith: anObject)

<em>... other required value:... methods</em>

numArgs
	^block numArgs - arguments size</pre>
<p>This is all that is needed to make the example work.</p>
<p>In fact, we could do without the CurriedBlock class. Our implementation of <code>valueWithArguments:</code> could answer a real block by doing something like:</p>
<pre class="smalltalk">
valueWithArguments: anArray
	...
		ifTrue: [anArray size &lt; self numArgs
			ifTrue: [^self curriedWithArguments: anArray]
	...

curriedWithArguments: anArray
	| arity |
	arity := self numArgs - anArray size.
	arity = 1 ifTrue:
		[^[:arg | self valueWithArguments: (anArray copyWith: arg)]].
	arity = 2 ifTrue:
	...</pre>
<p>However, since Smalltalk blocks don&#8217;t support the equivalent of Lisp &#8220;rest&#8221; arguments,  the <code>curriedWithArguments:</code> method would have to explicitly enumerate and handle all arities we realistically expect to use in block invocations. Using CurriedBlock instead produces a nicer example.</p>
<p>To be continued.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.3plus4.org/2007/03/23/currying-in-smalltalk/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
