2

私は継続渡しスタイル (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の方法で書き直す方法を教えてもらえますか?

4

3 に答える 3

3

簡単な方法:

let resistance_cps c1 c2 c3 = 
    let reciprocal_cps r k = k (checkedDiv 1.0 r)
    reciprocal_cps c1 <| 
        function
        | Some rc1 -> 
            reciprocal_cps c2 <| 
                function
                | Some rc2 -> 
                    reciprocal_cps c3 <|
                        function 
                        | Some rc3 -> Some (rc1 + rc2 + rc3)
                        | _ -> None
                | _ -> None
        | _ -> None

または Option.bind で少し短く

let resistance_cps2 c1 c2 c3 = 
    let reciprocal_cps r k = k (checkedDiv 1.0 r)
    reciprocal_cps c1 <|
        Option.bind(fun rc1 -> 
            reciprocal_cps c2 <| 
                Option.bind(fun rc2 ->
                    reciprocal_cps c3 <| 
                        Option.bind(fun rc3 -> Some (rc1 + rc2 + rc3))
                )
        )
于 2011-12-16T17:43:36.907 に答える
2

ここで定義された多分モナドを使用する

let resistance r1 r2 r3 =
  maybe {
    let! r1 = reciprocal r1
    let! r2 = reciprocal r2
    let! r3 = reciprocal r3
    return r1 + r2 + r3
  }
于 2011-12-16T17:48:04.877 に答える
2

これは、Chris Smith による本「Programming F#」の既知のタスクです。CPS スタイルのソリューション コードは、244 ページに記載されています。

let let_with_check result restOfComputation =
    match result with
    | DivByZero -> DivByZero
    | Success(x) -> restOfComputation x

let totalResistance r1 r2 r3 =
    let_with_check (divide 1.0 r1) (fun x ->
    let_with_check (divide 1.0 r2) (fun y ->
    let_with_check (divide 1.0 r3) (fun z ->
    divide 1.0 (x + y + z) ) ) )
于 2011-12-16T17:45:22.867 に答える