#inject:into: What a Gem!



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

.



Relevant Pages

  • Re: GMP vs. straight C arithmetic
    ... They are higher level instructions than ... with complex objects, stacks, autosizeable matrix arrays and tree ... PROSE, one add operation can be used for creating a new ... I'm not interested in type pre-declared languages. ...
    (comp.programming)
  • Re: New Methodology on Analysis of Language Change
    ... Austronesian languages, then applied to the Papuan languages of Island ... linguistics to show statistical evidence for ancient links between ... languages, from which we obtained a consensus tree [tree length, 224 steps; ...
    (sci.lang)
  • Re: Female watchmakers
    ... Frank Adam wrote: ... and do accomplish many things beyond traditional home-maker based ... technical and scientic pursuits is no longer the exception to the rule. ... Go hug a tree. ...
    (alt.horology)
  • Re: Request
    ... >In this case however I think that "how descent works" is ... >of the family tree of primates. ... No one has yet answered the question of why similarity automatically ... >What on earth makes you think that computer languages _aren't_ ...
    (talk.origins)
  • FW: How come Ada isnt more popular?
    ... In one with representation sharing (and that ... When the GC hits it just traverses the tree ... languages in general and general purpose languages. ... I think that it is very important to be able to get high performace ...
    (comp.lang.ada)