F# 函數式編程之 - 習題答案

原文 https://fsharpforfunandprofit.com/posts/computation-expressions-bind/express

原文的末尾有一道練習題:post

let strToInt str = ???

let stringAddWorkflow x y z = 
    yourWorkflow 
        {
        let! a = strToInt x
        let! b = strToInt y
        let! c = strToInt z
        return a + b + c
        }    

// test1
let good = stringAddWorkflow "12" "3" "2"
let bad = stringAddWorkflow "12" "xyz" "2"

let strAdd str i = ???
let (>>=) m f = ???

// test2
let good = strToInt "1" >>= strAdd "2" >>= strAdd "3"
let bad = strToInt "1" >>= strAdd "xyz" >>= strAdd "3"

題目要求補充上面代碼的未完成部分,使代碼正確運行。學習

作這一道練習題,須要先學習本系列前面的文章以及相關原文。ui

如下是個人解答:this

let strToInt str =
    try
        Ok (int str)
    with
    | _ -> Error "not a number"

type MaybeBuilder() =
    member this.Bind(x, f) = Result.bind f x
    member this.Return(x) = Ok x

let maybe = new MaybeBuilder()

let stringAddWorkflow x y z = 
    maybe
        {
        let! a = strToInt x
        let! b = strToInt y
        let! c = strToInt z
        return a + b + c
        }    

let strAdd str i =
    maybe {
        let! a = strToInt str
        return a + i
    }

let (>>=) m f = Result.bind f m

// test
let printA x = x |> printfn "%A"

printA <| stringAddWorkflow "12" "3" "2"
printA <| stringAddWorkflow "12" "xyz" "2"

strToInt "1" >>= strAdd "2" >>= strAdd "3" |> printA
strToInt "1" >>= strAdd "xyz" >>= strAdd "3" |> printA
相關文章
相關標籤/搜索