typestar

Result in F#

Ok or Error, and bind to keep the pipeline on the happy track.

// Result carries Ok or Error; the pipeline stays on the happy track.
let parseWeight (raw: string) =
    match System.Double.TryParse raw with
    | true, kg -> Ok kg
    | false, _ -> Error (sprintf "unreadable: %s" raw)

let classify kg =
    if kg < 15.0 then Error (sprintf "%.1f kg is too light" kg)
    else Ok (sprintf "%.1f kg accepted" kg)

// bind chains Result-returning steps; the first Error short-circuits.
["31.4"; "n/a"; "9.2"]
|> List.map (parseWeight >> Result.bind classify)
|> List.iter (function
    | Ok note -> printfn "OK: %s" note
    | Error why -> printfn "SKIP: %s" why)

How it works

  1. Double.TryParse matches as a bool-and-value tuple.
  2. Result.bind chains steps; the first Error short-circuits.
  3. function matches the piped value without naming it.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
571
Tokens
119
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 119 seconds.

Type this snippet

Step 1 of 3 in Idioms, step 19 of 27 in Language basics.

← Previous Next →

Result in other languages