Skip to content

Instantly share code, notes, and snippets.

@louthy
Created February 6, 2024 21:20
Show Gist options
  • Save louthy/0b24479bf42b0c2b5dca01bb40861627 to your computer and use it in GitHub Desktop.
Save louthy/0b24479bf42b0c2b5dca01bb40861627 to your computer and use it in GitHub Desktop.
How to use Validation applicative from F#
module Validation =
open LanguageExt
let successValue (ma : Validation<'f, 'a>) : 'a =
ma.IfFail(fun () -> failwith "Validation monad is in a Fail state")
let apply (mf : Validation<'f, 'a -> 'b>) (ma : Validation<'f, 'a>) : Validation<'f, 'b> =
mf.Disjunction(ma)
.Map(fun _ -> (successValue mf) (successValue ma))
let map (f : 'a -> 'b) (ma : Validation<'f, 'a>) : Validation<'f, 'b> =
ma.Map(f)
let success x : Validation<'f, 'a> =
Validation<'f, 'a>.Success(x)
let fail x : Validation<'f, 'a> =
Validation<'f, 'a>.Fail(Prelude.Seq1(x))
let (<*>) = apply
let ($) = map
let add = fun x y -> x + y
let mf = success add
let ma = success 123
let mb = success 456
let mr = mf <*> ma <*> mb
let mr2 = add $ ma <*> mb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment