Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain a piece of Smalltalk code?

Tags:

smalltalk

I cannot understand this piece of Smalltalk code:

[(line := self upTo: Character cr) size = 0] whileTrue.

Can anybody help explain it?

like image 471
parsifal Avatar asked Jan 30 '11 03:01

parsifal


People also ask

What is Smalltalk code?

Smalltalk is a fully object-oriented, dynamically typed, reflective programming language with no 'non-object' types. Smalltalk was created as the language to underpin the “new world” of computing exemplified by “human–computer symbiosis.”

What is Smalltalk programming language used for?

Smalltalk was the first language tool to support "live" programming and advanced debugging techniques such as on-the-fly inspection and code changes during execution. Today, live debugging is possible in C# with Visual Studio's "Edit and Continue" and in Java with HotSwap.

What is Smalltalk system?

Smalltalk was a revolutionary system developed by the Learning Research Group (LRG) at Xerox PARC in the 1970s, led by Alan Kay. Smalltalk was comprised of a programming language, a development environment, and a graphical user interface (GUI), running on PARC's groundbreaking Alto computer.

Is Smalltalk a programming language?

Smalltalk is a "pure" object-oriented programming language, meaning that, unlike C++ and Java, there is no difference between values which are objects and values which are primitive types.


1 Answers

One easy thing to do, if you have the image where the code came from, is run a debugger on it and step through.

If you came across the code out of context, like a mailing list post, then you could browse implementers of one of the messages and see what it does. For example, #size and #whileTrue are pretty standard, so we'll skip those for now, but #upTo: sounds interesting. It reminds me of the stream methods, and bringing up implementors on it confirms that (in Pharo 1.1.1), ReadStream defines it. There is no method comment, but OmniBrowser shows a little arrow next to the method name indicating that it is defined in a superclass. If we check the immediate superclass, PositionableStream, there is a good method comment explaining what the method does, which is draw from the stream until reaching the object specified by the argument.

Now, if we parse the code logically, it seems that it:

  • reads a line from the stream (i.e. up to a cr)
    • if it is empty (size = 0), the loop continues
    • if it is not, it is returned

So, the code skips all empty lines and returns the first non-empty one. To confirm, we could pass it a stream on a multi-line string and run it like so:

line := nil.
paragraph := '


this is a line of text.
this is another line
line number three' readStream.
[(line := paragraph upTo: Character cr) size = 0] whileTrue.
line. "Returns 'this is a line of text.'"
like image 123
Sean DeNigris Avatar answered Oct 17 '22 14:10

Sean DeNigris