Last active
February 21, 2025 03:58
-
-
Save abradley2/1a1b01641019a292988d34976c85f1ae to your computer and use it in GitHub Desktop.
Elm Applicative Validation Example
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 Main exposing (..) | |
import List.Nonempty exposing (..) | |
import State exposing (State(..)) | |
type alias Error = | |
String | |
mkCharacter : Model -> Result (List Error) Character | |
mkCharacter m = | |
State.state (Just Character) | |
|> (\s -> State.andMap s (validateName m)) | |
|> (\s -> State.andMap s (validateBio m)) | |
|> (\s -> State.andMap s (validateLore m)) | |
|> State.run [] | |
|> (\( c, errors ) -> Result.fromMaybe errors c) | |
validateName model = | |
case model.validName of | |
Nothing -> | |
State (\errors -> ( always Nothing, errors ++ [ "Name is required" ] )) | |
Just validName -> | |
State (\errors -> ( Maybe.map ((|>) validName), errors )) | |
validateBio model = | |
case model.validBio of | |
Nothing -> | |
State (\errors -> ( always Nothing, errors ++ [ "Bio is required" ] )) | |
Just validBio -> | |
State (\errors -> ( Maybe.map ((|>) validBio), errors )) | |
validateLore model = | |
case model.validLore of | |
Nothing -> | |
State (\errors -> ( always Nothing, errors ++ [ "Lore is required" ] )) | |
Just validLore -> | |
State (\errors -> ( Maybe.map ((|>) validLore), errors )) | |
type alias Model = | |
{ validName : Maybe String | |
, validBio : Maybe (Nonempty String) | |
, validLore : Maybe (Nonempty String) | |
} | |
type alias Character = | |
{ name : String | |
, bio : Nonempty String | |
, lore : Nonempty String | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment