#inject:into: What a Gem!
- From: "Eric Taylor" <estaylor@xxxxxxxxxxx>
- Date: Mon, 3 Jul 2006 21:35:14 -0600
Hello Forum,
I just accomplished something in about ten minutes that has taken me
many times that in other languages, even Eiffel. I decided to create a
method in my ActiveTreeModel class that would build a TreeModel from the
bracketed notation of a tree (as explained in Knuth's AoP, Vol. 1). The
bracketed notation is a very efficient way to represent a tree (in most,
but not all, circumstances).
Given the following array,
#(#a #b #(#c #d #e) #f #g #(#h #i #(#j)))
build a tree. It should look like this:
a
b
c
d
e
f
g
h
i
j
I was able to accomplish this with merely the following code:
ActiveTreeModel>>addFromBracketNotation: anArray asChildOf: parent
anArray inject: nil
into:
[:elementBefore :element |
(element isKindOf: Array)
ifTrue:
[self addFromArray: element asChildOf:
elementBefore]
ifFalse: [self add: element asChildOf: parent]]
This kind of parsing is usually a mess in other languages. Smalltalk
just seems to smile and take it all in stride. I expected to have to
spend hours doing this. I think the only reason it took a whopping ten
minutes, instead of five, was due to the need to change from "(element
countElements > 1)" to "(element isKindOf: Array)". I was bitten by the
following scenario:
#(#b) #countElements returns 1.
#c #countElements also returns 1.
Notationally, however, the two are very different.
Cheers,
Eric
.
- Follow-Ups:
- Re: #inject:into: What a Gem!
- From: Fernando Rodríguez
- Re: #inject:into: What a Gem!
- From: Eric Taylor
- Re: #inject:into: What a Gem!
- Prev by Date: Re: GLORP for Dolphin
- Next by Date: Re: Extra Smalltalk-80 "Blue Book"
- Previous by thread: [Bug] Mutate GroupBox.Static to GroupBox gives a walkback error
- Next by thread: Re: #inject:into: What a Gem!
- Index(es):
Relevant Pages
|