BiGram

ヒビルテ経由でイナモデレーター2の「BiGramの実装」の Ruby zip 版を見ていっしゅん、例によって(^_^;)何をやっているか分からなかったので、直訳気味にして咀嚼。

| dictionary contents |
dictionary := Dictionary new.
contents := 'banana'.
contents allButLast with: contents allButFirst do: [: aa : bb |
   | xx |
   xx := String with: aa with: bb.
   dictionary at: xx put: (dictionary at: xx ifAbsent: [0]) + 1].
World findATranscript: nil.
dictionary keysAndValuesDo: [: key : value |
   Transcript cr; show: value printString, String tab, key printString]

なるほど。

関数的にどう書くかという話の流れみたいなのでナンですが、何も考えないで SqueakSmalltalk で書くとこんなかんじでしょうか。

| bag stream |
bag := Bag new.
stream := 'banana' readStream.
[bag add: (stream next: 2). stream atEnd] whileFalse: [stream back].
^ bag sortedCounts


Bag と言えば、Java Collections Framework で Bag は 「めったに使わないのだから、そのつど組め」的な扱いであるとの引用を、角谷HTML化計画のエントリーにて見かけたのをふと思い出したのでついでにメモ。