The Either monad: we can finally get rid of exceptions

Jessica Kerr recently wrote on the very interesting topic: what the best way to get rid of exceptions and of the mess they introduce into the program flow.
Simply put, she's gently introduced the Either monad in Scala language.
Although I find Scala to be a very advanced OO language with reasonably good FP support, I don't think the code Jessica used in her post can force anybody to change the habitual exception handling flow in favor of the Data Flow. This's why: Scala is too verbose.
But this is not the case in a more advanced functional language like OCaml, Haskell or F#. Let's take a look what the latter can offer:

open FSharpx
open FSharpx.Choice
type Error = Error of string
type AuthLevel = Admin | Normal | Guest
let getSetting = function
| "user" -> Choice1Of2 "user1"
| name -> name |> sprintf "setting %s was not found" |> Error |> Choice2Of2
let getAuth = function
| "user1" -> Choice1Of2 Normal
| user -> user |> sprintf "user %s was not found" |> Error |> Choice2Of2
let log = printfn "%s"
let getAuthorizationLevel = getSetting >=> getAuth
let authLevel =
getAuthorizationLevel "user"
|> Choice.choice id (fun (Error error) -> log error; Guest)
view raw either.fs hosted with ❤ by GitHub

The code is much more clear because of using the monadic function composition (>=>) and the amazing type inference.
Conclusion: if you do use monands, use their full power.

Comments

Popular posts from this blog

Regular expressions: Rust vs F# vs Scala

Hash maps: Rust, F#, D, Go, Scala

Haskell: performance