お釈迦様の伝説
昨日の夜中にこんな意味の分からないコードが頭のなかに降ってきて
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var shaka = AsyncShaka() | |
shaka.born{ i => | |
i.walk(7) | |
i.raiseRightHandToHeaven() | |
i.lowerLeftHandToEarth() | |
i.say("天上天下唯我独尊") | |
} | |
それをちゃんとnodeで動くように書きなおしたものが下のものである。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Shaka = { | |
walk: function(step) { | |
console.log(step + '歩歩く') | |
}, | |
raiseRightHandToHeaven: function() { | |
console.log('右手で天を指す'); | |
}, | |
lowerLeftHandToEarth: function() { | |
console.log('左手で地を指す'); | |
}, | |
say: function(msg) { | |
console.log(msg + 'と話す'); | |
} | |
}; | |
var e = require('events'); | |
var shakaEmitter = new e.EventEmitter(); | |
shakaEmitter.on('born', function(err, i) { | |
if(err) throw err; | |
i.walk(7); | |
i.raiseRightHandToHeaven(); | |
i.lowerLeftHandToEarth(); | |
i.say("天上天下唯我独尊"); | |
}); | |
shakaEmitter.emit('born', null, Shaka); |
Scalaで書いたらこんな感じになった。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class Shaka(whenBorn: Shaka => Unit) { | |
def born() = whenBorn(this) | |
def walk(step: Int) = println(s"${step}歩歩いた") | |
def raiseRightHandToHeaven() = println("右手で天を指す") | |
def lowerLeftHandToEarth() = println("左手で地を指す") | |
def say(msg: String) = println(s"${msg}と話す") | |
} | |
val shaka = Shaka { i => | |
i.walk(7) | |
i.raiseRightHandToHeaven() | |
i.lowerLeftHandToEarth() | |
i.say("天上天下唯我独尊") | |
} | |
shaka born() |
こういう風に書いたほうがわかりやすいのか・・・?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class WhenBornAction(action: Shaka => Unit) | |
case class Shaka(action: WhenBornAction) { | |
def born() = action.action(this) | |
def walk(step: Int) = println(s"${step}歩歩いた") | |
def raiseRightHandToHeaven() = println("右手で天を指す") | |
def lowerLeftHandToEarth() = println("左手で地を指す") | |
def say(msg: String) = println(s"${msg}と話す") | |
} | |
val shaka = Shaka { | |
WhenBornAction { i => | |
i.walk(7) | |
i.raiseRightHandToHeaven() | |
i.lowerLeftHandToEarth() | |
i.say("天上天下唯我独尊") | |
} | |
} | |
shaka born() |
なんというか、こう… 疲れてたんすよ。
Scalaは引数一つだと()の代わりに{}で書けるので、新しい制御構造みたいにかけていいですね。
実行結果は全部こんな感じです。
7歩歩いた
右手で天を指す
左手で地を指す
天上天下唯我独尊と話す
0 件のコメント:
コメントを投稿