Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ericgj
Created November 2, 2016 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericgj/6d761e0d5ca26c95d2568541a27ee04d to your computer and use it in GitHub Desktop.
Save ericgj/6d761e0d5ca26c95d2568541a27ee04d to your computer and use it in GitHub Desktop.
module Validation
exposing
( ValidationResult(..)
, map, mapMessage, andThen, andMap, succeed
, withDefault
, fromMaybeInitial, fromMaybe, toMaybe
, fromResultInitial, fromResult
, toString, message, isValid, isInvalid
, validate
)
type ValidationResult a
= Initial
| Succeed a
| Fail String String
map : (a -> b) -> ValidationResult a -> ValidationResult b
map fn r =
case r of
Initial -> Initial
Fail msg input -> Fail msg input
Succeed a -> Succeed (fn a)
mapMessage : (String -> String) -> ValidationResult a -> ValidationResult a
mapMessage fn r =
case r of
Initial -> Initial
Succeed a -> Succeed a
Fail msg input -> Fail (fn msg) input
andThen : ValidationResult a -> (a -> ValidationResult b) -> ValidationResult b
andThen r fn =
case r of
Initial -> Initial
Fail msg input -> Fail msg input
Succeed a -> fn a
andMap : ValidationResult (a -> b) -> ValidationResult a -> ValidationResult b
andMap fn r =
case r of
Initial -> Initial
Fail msg input -> Fail msg input
Succeed a -> andThen r (\r_ -> andThen fn (\f_ -> Succeed (f_ r_)))
succeed : a -> ValidationResult a
succeed a =
Succeed a
withDefault : a -> ValidationResult a -> a
withDefault a r =
case r of
Initial -> a
Fail msg input -> a
Succeed a_ -> a_
fromMaybeInitial : Maybe a -> ValidationResult a
fromMaybeInitial m =
case m of
Nothing -> Initial
Just a -> Succeed a
fromMaybe : String -> String -> Maybe a -> ValidationResult a
fromMaybe msg input m =
case m of
Nothing -> Fail msg input
Just a -> Succeed a
toMaybe : ValidationResult a -> Maybe a
toMaybe r =
case r of
Initial -> Nothing
Fail msg input -> Nothing
Succeed a -> Just a
fromResultInitial : Result e a -> ValidationResult a
fromResultInitial m =
case m of
Ok a -> Succeed a
Err e -> Initial
fromResult : (e -> String) -> String -> Result e a -> ValidationResult a
fromResult fn input m =
case m of
Ok a -> Succeed a
Err e -> Fail (fn e) input
toString : (a -> String) -> ValidationResult a -> String
toString fn r =
case r of
Succeed a -> fn a
Fail _ last -> last
Initial -> ""
message : ValidationResult a -> Maybe String
message r =
case r of
Initial -> Nothing
Succeed _ -> Nothing
Fail msg _ -> Just msg
isValid : ValidationResult a -> Bool
isValid r =
case r of
Succeed _ -> True
_ -> False
isInvalid : ValidationResult a -> Bool
isInvalid r =
case r of
Initial -> False
Succeed _ -> False
Fail msg last -> True
validate : (String -> Result String a) -> String -> ValidationResult a
validate fn input =
fn input |> fromResult identity input
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment