Kokaの例: Exception
raise effectを定義
koka(js)effect ctl raise(msg: string): int
effec type名とoperation名を同じにすることで簡潔に書ける

raise effectを持つ関数を定義
koka(ts)fun safe-divide(x: int, y: int): raise int
if y==0 then raise("div-by-zero") else x / y
安全に除算する関数
この時点では、
raise()
を呼んだときに、何を行うのかは定義されていない

handlerを用いて safe-divide
を使用する
koka(ts)fun raise-const(): int
with ctl raise(msg) 42 // ①
8 + safe-divide(1,0) // ②
①で、raiseのhandlerとして定数 42
を返す処理を書く
②で実際に処理が実行されるが、
safe-divide
の中で raise
が呼ばれ、①に到達し、
最終的な結果は 42
になる
resumeしてみる
koka(ts)fun raise-resume()
with ctl raise(msg) resume(42)
8 + safe-divide(1,0)
handlerの中で resume
を呼ぶことで処理を再開し、最終的な結果は 8 + 42
で 50
になる
ちなみに、 with fun
を使って以下のようにも書ける
koka(ts)fun raise-resume()
with fun raise(msg) 42
8 + safe-divide(1,0)
やや簡潔

おしゃれなabstraction handlerを用意しておく
koka(ts)fun catch(hnd: (string) -> e a, action: () -> <raise|e> a): e a
with ctl raise(msg) hnd(msg)
action()
以下のように、親しい例であるerror handlingが書ける
koka(ts)fun use-catch()
with catch fn(msg)
println("error: " ++ msg); 42
safe-divide(1,0)
よく見るやつ

try節とcatch節が逆になっているね
use-catch()を実行しraiseした場合の結果error: div-by-zero
42