F # functional programming – Exercise answers

Time:2021-1-18

original texthttps://fsharpforfunandprofit.com/posts/computation-expressions-bind/

There is an exercise at the end of the original text

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"

The title requires to add the unfinished part of the above code to make the code run correctly.

To do this exercise, you need to learn the previous articles in this series and related original texts.

Here is my answer:

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 >= strAdd "2" >>= strAdd "3" |> printA
strToInt "1" >>= strAdd "xyz" >>= strAdd "3" |> printA