Skip to content

Instantly share code, notes, and snippets.

@dgendill
Last active January 4, 2018 16:51
Show Gist options
  • Save dgendill/8edc7ff9f3f3bcd347959e9cd2f07376 to your computer and use it in GitHub Desktop.
Save dgendill/8edc7ff9f3f3bcd347959e9cd2f07376 to your computer and use it in GitHub Desktop.
Example of the State and Either Monad used in Purescript
-- http://try.purescript.org/?gist=8edc7ff9f3f3bcd347959e9cd2f07376
module Main where
import Prelude
import Data.Identity
import Control.Monad.State
import Control.Monad.Except
import Control.Monad.Eff.Console (log, logShow)
type FirstName = String
type LastName = String
type RequirementExplaination = String
type Eligibility = StateT Person (ExceptT String Identity)
data Person = PB {
firstname :: FirstName,
lastname :: LastName,
age :: Int
}
data Requirement
= AgeAbove Int RequirementExplaination
| AgeBelow Int RequirementExplaination
instance showPerson :: Show Person where
show (PB p) = p.firstname <> " " <> p.lastname <> ", age:" <> (show p.age)
defaultPerson :: Person
defaultPerson = PB
{ firstname : "Ted"
, lastname : "Johnson"
, age : 65 }
person :: FirstName -> LastName -> Int -> Person
person f l a = PB { firstname : f, lastname : l, age : a }
ineligableMessage :: Requirement -> String
ineligableMessage (AgeAbove i m) = "Person is ineligable because their age is below "
<> (show i) <> ". " <> m
ineligableMessage (AgeBelow i m) = "Person is ineligable because their age is above "
<> (show i) <> ". " <> m
meetsRequirement :: Requirement -> Person -> Boolean
meetsRequirement (AgeAbove i m) (PB person) = person.age >= i
meetsRequirement (AgeBelow i m) (PB person) = person.age <= i
eligableWhen :: Requirement -> Eligibility Person
eligableWhen req = do
pers@(PB person) <- get
case (meetsRequirement req pers) of
true -> do
pure pers
false -> do
lift $ throwError (ineligableMessage req)
runEligability p s = runIdentity $ runExceptT $ runStateT p s
main = do
logShow $
runEligability (do
eligableWhen (AgeAbove 63 "The state requires this.")
eligableWhen (AgeBelow 65 "The state requires this.")
) defaultPerson
@desmondrawls
Copy link

This shows an error: "Unknown value runIdentity"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment