Comment detail

変形Fizz-Buzz問題 (Nested Flatten)

完璧に出遅れで題意に従っているかあやしいのですが書いてみました。オブジェクト指向 (笑) という感じです。

言語組みこみの if/else を使わないという解釈です。

else にみえるのは、メソッドの名前なので hoge でも fuga でもよく、名前はこのさいどうでもいいと思ったので else のままにしてあります。

cycle を使っているので ruby1.9 です。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class True
    def then
        yield
        self
    end

    def else
        self
    end
end

class False
    def then
        self
    end

    def else
        yield
    end
end

t = True.new
f = False.new
(1..20).zip([f, f, t].cycle, [f, f, f, f, t].cycle).each do |i, i3, i5|
    t = ""
    i3.then {
        i5.then {
            t = "FizzBuzz"
        }.else {
            t =  "Fizz"
        }
    }.else {
        i5.then {
            t = "Buzz"
        }.else {
            t = "hoge"
        }
    }
    puts "%2d:%s" % [i, t]
end

せっかく Ruby なので、もうすこし踏みこんで 1.8 系でも動くようにしました。

TrueClass/FalseClass は true/false のクラスで、それを拡張しています。.result を付けくわえたのは if 文 (のようにみえるもの) が値を持つようにみせかけたかったからです。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!ruby -Ku
require "pp"

class TrueClass
    def then
        @ret = yield
        self
    end

    def else
        self
    end

    def result
        @ret
    end
end

class FalseClass
    def then
        self
    end

    def else
        @ret = yield
        self
    end

    def result
        @ret
    end
end

(1..20).each do |i|
    puts "%2d:%s" % [i,
        (i % 3 == 0).then {
            (i % 5 == 0).then {
                "FizzBuzz"
            }.else {
                "Fizz"
            }.result
        }.else {
            (i % 5 == 0).then {
                "Buzz"
            }.else {
                "hoge"
            }.result
        }.result
    ]
end

Index

Feed

Other

Link

Pathtraq

loading...