前回
前回の続きで、ズンドコキヨシをやってみた。
# $ crystal zdk.cr # 遅延評価 class Delay(T) def initialize(init_v : T, &block : -> T) @func = block @flag = false @value = init_v end def force unless @flag ret = @func.call @value = ret.nil? ? raise("@func.call is nil. #{@func}") : ret @flag = true end @value end end # Bool 構造体にメソッドを追加 struct Bool def if(t, e) return t.responds_to?(:force) ? t.force : t if self e.responds_to?(:force) ? e.force : e end end # 短縮マクロ macro d_i(x) Delay(Int32).new(0){{{x}}} end macro d_s(x) Delay(String).new(""){{{x}}} end macro d_ai(x) Delay(Array(Int32)).new([0]){{{x}}} end macro d_as(x) Delay(Array(String)).new([""]){{{x}}} end struct Int # zundoko def zdk_base(str_arr) rand.>(0.5).if d_as(self.succ.zdk_base str_arr << "Zun"), d_as((self.>=(4)).if d_as(str_arr << "Doko" << "Ki-Yo-Shi!"), d_as(0.zdk_base str_arr << "Doko")) end end def zdk 0.zdk_base [] of String end # 実行 puts zdk # => ["Doko", "Zun", "Zun", "Zun", "Zun", "Doko", "Ki-Yo-Shi!"]
ズンドコキヨシもほぼワンライナーで書けた。