Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

プログラミング全般 | 継続渡しスタイル(CPS = Continuation Passing Style)

概要

継続渡しスタイル(CPS = Continuation Passing Style)

詳細

プログラムの制御を継続を用いて陽に表すプログラミングスタイル。
通常のプログラムは値を返却するが、CPSでは継続を引数として受け取りその継続に
計算結果を受け渡す。

通常のプログラム

# encoding: utf-8

class NotContinuationPassingStyle
  def hoge(message)
    "#{message}hoge"
  end
end

not_cps = NotContinuationPassingStyle.new
puts not_cps.hoge "message"

結果

messagehoge

CPSのプログラム

# encoding: utf-8
class ContinuationPassingStyle
  def hoge(message, &block)
    block.call "#{message}hoge"
  end
end

cps = ContinuationPassingStyle.new
cps.hoge "message" do |message|
  puts message
end

結果

messagehoge

CPSのプログラム(分岐付き)

# encoding: utf-8
class ConditionalContinuationPassingStyle
  def hoge(message, success, failure)
    if message.nil? || message.empty?
      failure.call "failure-#{message}-hoge"
    else
      success.call "success-#{message}-hoge"
    end
  end
end

['', 'message'].each do |message|
  continuation_cps = ConditionalContinuationPassingStyle.new
  continuation_cps.hoge message,
    Proc.new{|message|puts "#{message}-success"},
    Proc.new{|message|puts "#{message}-failure"}
end

結果

failure--hoge-failure
success-message-hoge-success