News for hackers. Stuff that matters.
Re:You’re better off using Exceptions by UK-Al05 on Monday February 03, 2020 @12:43PM (#22226663)
Thats not how f# works normally.

Normally you chain option operations with either binds, or you do a match(Which is exhaustive).

Directly accessing the value is normally frowned upon.

This guy either needed to make the option type go away, or filter out the None and pass that into average. List.choose could be used for this

    let average (customers : Customer list) =
        match customers with
        | [] -> Error "list was empty"
        | _ ->
            customers
            |> List.choose(fun c -> c.Credit) # Would remove the option type. Any nones would be filtered out the list
            |> List.average
            |> Ok
This is the best I could think off without a computer
Re:You’re better off using Exceptions by vikestep on Monday February 03, 2020 @01:50PM (#22227504)
In support of the article, your code would still throw an exception if all the customers in the list have missing credit.

https://github.com/dotnet/fsharp/blob/master/src/fsharp/FSha...

You could instead write it as the following to handle that.

  let average (customers : Customer list) =
      customers
      |> List.choose (fun c -> c.Credit)
      |> function 
         | [] -> Error "no customers with credit"
         | xs -> Ok (List.average xs)
Re:You’re better off using Exceptions by UK-Al05 on Monday February 03, 2020 @02:37PM (#22228069)
Indeed. I was remembering the behaviour of average off the top of my head.