私は継続渡しスタイル (CPS) を習得しようとしているので、かなり前に Gary Short によって示された例を作り直しています。私は彼のサンプル ソース コードを持っていないので、彼の例を記憶から作り直そうとしています。次のコードを検討してください。
let checkedDiv m n =
match n with
| 0.0 -> None
| _ -> Some(m/n)
let reciprocal r = checkedDiv 1.0 r
let resistance c1 c2 c3 =
(fun c1 -> if (reciprocal c1).IsSome then
(fun c2 -> if (reciprocal c2).IsSome then
(fun c3 -> if (reciprocal c3).IsSome then
Some((reciprocal c1).Value + (reciprocal c2).Value + (reciprocal c3).Value))));;
私がよく理解できないのは、抵抗関数をどのように構築するかです。私はこれを以前に思いつきました:
let resistance r1 r2 r3 =
if (reciprocal r1).IsSome then
if (reciprocal r2).IsSome then
if (reciprocal r3).IsSome then
Some((reciprocal r1).Value + (reciprocal r2).Value + (reciprocal r3).Value)
else
None
else
None
else
None
しかし、もちろん、それは CPS を使用していません。言うまでもなく、それは本当にハッキーに見えますし、コードの匂いのようにも見えるコードがかなり繰り返されているという事実は言うまでもありません。
誰かが抵抗関数をCPSの方法で書き直す方法を教えてもらえますか?