Created
June 17, 2024 07:30
-
-
Save andremw/f415a2b4b9b6205bc1139474e6e12088 to your computer and use it in GitHub Desktop.
Rescript Validation Applicative - just to avoid losing it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Validation = { | |
type t<'s, 'f> = | |
| Success('s) | |
| Failure('f) | |
let pure = v => Success(v) | |
let apply = (selector, source, combine) => | |
switch selector { | |
| Success(map) => | |
switch source { | |
| Success(s) => Success(map(s)) | |
| Failure(f) => Failure(f) | |
} | |
| Failure(f1) => | |
switch source { | |
| Success(_) => Failure(f1) | |
| Failure(f2) => combine(f1, f2)->Failure | |
} | |
} | |
let traverse = (list, fn, combine) => { | |
let cons = (head, tail) => list{head, ...tail} | |
let initState = pure(list{}) | |
let folder = (. head, tail) => { | |
cons->pure->apply(fn(head), combine)->apply(tail, combine) | |
} | |
Js.List.foldRight(folder, list, initState) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment