“居眠り床屋”を Io language で


id:sumim:20090923:p1 の続き。逆に、アクターだから長くなっているってこともないんじゃないのかな…とも思ったので アクターが組み込みの言語である Io で書いてみました。予想通り、比較的短く書けたのではないかと思います。

ただ、非同期メッセージングに使うメソッドである @@ を再定義して、それに来店時の処理を兼ねさせている点が、もしかしたら反則かもしれません。

//sleepingbarber.io

rand := Random clone

shop := Object clone do(
  setSlot("@@", method(
    id := call argAt(0) argsEvaluatedIn(call sender) first
    writeln ("(s) entering shop ", id)
    if((?actorQueue) not or actorQueue size < 3, resend,
      writeln("(s) turning away customer ", id))))
  visitedBy := method(id, barber cutsHairOf(id)))

barber := Object clone do(
  tally := 0
  cutsHairOf := method(id,
    wait(0.1 + 0.6 * rand value)
    writeln("(b) cutting hair of customer ", id)
    tally = tally + 1))

for(i, 1, 20, shop @@visitedBy(i); wait(0.1 + 0.2 * rand value))
while(yield, nil)
writeln("(!) ", barber tally, " customers got haircuts today")
$ io sleepingbarber.io
(s) entering shop 1
(s) entering shop 2
(b) cutting hair of customer 1
(s) entering shop 3
(b) cutting hair of customer 2
(s) entering shop 4
(s) entering shop 5
(s) entering shop 6
(s) turning away customer 6
(b) cutting hair of customer 3
(s) entering shop 7
(s) entering shop 8
(s) turning away customer 8
(b) cutting hair of customer 4
(s) entering shop 9
(b) cutting hair of customer 5
(b) cutting hair of customer 7
(s) entering shop 10
(s) entering shop 11
(b) cutting hair of customer 9
(b) cutting hair of customer 10
(s) entering shop 12
(s) entering shop 13
(s) entering shop 14
(s) turning away customer 14
(b) cutting hair of customer 11
(s) entering shop 15
(b) cutting hair of customer 12
(s) entering shop 16
(s) entering shop 17
(s) turning away customer 17
(s) entering shop 18
(s) turning away customer 18
(b) cutting hair of customer 13
(s) entering shop 19
(s) entering shop 20
(s) turning away customer 20
(b) cutting hair of customer 15
(b) cutting hair of customer 16
(b) cutting hair of customer 19
(!) 14 customers got haircuts today