I cannot understand this piece of Smalltalk code:
[(line := self upTo: Character cr) size = 0] whileTrue.
Can anybody help explain it?
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.”
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.
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.
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.
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:
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.'"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With