Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ryohji
Created December 12, 2019 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryohji/8ccb5204f042c4fd5c6079fb4cf49ec6 to your computer and use it in GitHub Desktop.
Save ryohji/8ccb5204f042c4fd5c6079fb4cf49ec6 to your computer and use it in GitHub Desktop.
Partial recursive function (#1 to #3) (from "アンダースタンディング コンピュテーション")

P.211 ~ 212 の部分再帰関数の実装。名前づけで混乱したので整理しなおしてみた。

# 部品1
def zero
    0
end

# 部品2
def increment(n)
    n + 1
end

# 部品3
def recurse(f, g, *args)
    *xs, y = args
    
    if y.zero?
        send(f, *xs)
    else
        args_updated = xs + [y-1] # args の末尾の値をひとつ減じたリスト
        accumulated = recurse(f, g, *args_updated)
        send(g, *args_updated, accumulated)
    end
end

そして

def add(x, y)
    def base(x)
        puts x
        x
    end
    
    def rec(x, y, acc)
        puts "#{x}; #{y}; #{acc}"
        increment(acc)
    end
    
    recurse(:base, :rec, x, y)
end

add(increment(increment(zero)), increment(increment(increment(zero))))

これを実行すると

2 2; 0; 2 2; 1; 3 2; 2; 4

がプリントされ、結果 5 が得られる。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment