[Newbies] Best way to implement two-dimensional array

Göran Krampe goran at krampe.se
Tue Sep 4 07:39:22 UTC 2007


Hi!

> H'mmm...
>
> The only way I can figure out how to create a nested directory
> literal is to do this:
>
> |t|
> t := { #fs -> ({ #C -> 0. #B -> 1. #R -> 2 } as: Dictionary)  } as:
> Dictionary.
> (t at: #fs) at: #B.  "Gives '1' when evaluated"
>
> The parens are necessary, as far as I can figure.
>
> Is there any simpler syntax than this? This is acceptable. Just
> wondering if there is a better way.

Mmmm, I feel I must ask the "why?" question here. :) What are you actually
trying to implement? The reason I ask is because it looks like you may be
falling into the trap of "data objects" (creating structures of data with
no real behaviors).

> Or, I'm thinking it might be simpler to leave the literal as an
> array, and do the castings as necessary during access, like this:

The word "casting" is not generally used in the Smalltalk context given
that Smalltalk is not statically typed. #as: is a message send and it
creates a new object of the given class. You can see what it does by
looking at Object>>as:.

> |t|
> "Create as simple array"
> 	t := { #fs -> { #C -> 0. #B -> 1. #R -> 0 } }.
> "Access as dictionary"
> 	(((t as: Dictionary) at: #fs) as: Dictionary) at: #B.
>
> The reason being, the actual table will be pretty big, and all those
> parens and :as Dictionary statements will clutter up the data.

You can do it in several ways - it's just "code". If you only need Symbols
and literals as above you could use regular Array syntax (it only
evaluates literals - not expressions - and it is constructed at compile
time):

| result dict |
result := Dictionary new.
#(
	(fs (C 0  B 1  R 0))
	(gs (C 7  B 5  R 4))
	(gs (C 7  B 5  R 4))
) do: [:arr |
	dict := Dictionary new.
	arr second pairsDo: [:a :b | dict at: a put: b].
	result at: arr first put: dict].
result

Do an inspect-it on that to see the resulting dicts-in-dict.

> By the way, I would never have figured this out without the Workspace
> to play in. Obviously I'm not the first to discover this, but Wow!
> Workspace is a great tool!
>
> I have used Ruby's IRB to experiment with Ruby expressions, and
> interactive Perl and PHP a bit, but even IRB is no where near as
> useful as the Workspace. It's so simple... I wonder why other
> languages haven't adopted something like it?

The mystery of Smalltalk *not* ruling the earth. Who knows? :)

regards, Göran



More information about the Beginners mailing list