Skip to content

Instantly share code, notes, and snippets.

@bradparker
Created December 5, 2018 23:17
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 bradparker/603dc22aa93c7a1aed79a63b1456b5fb to your computer and use it in GitHub Desktop.
Save bradparker/603dc22aa93c7a1aed79a63b1456b5fb to your computer and use it in GitHub Desktop.
Wrong answer ... but fun
data Balance =
Balance !Int
!Int
deriving (Eq, Show)
instance Semigroup Balance where
Balance a b <> Balance c d
| b <= c = Balance (a + c - b) d
| otherwise = Balance a (d + b - c)
instance Monoid Balance where
mempty = Balance 0 0
balanceTotal :: Balance -> Int
balanceTotal (Balance close open) = close + open
balance :: Eq a => a -> a -> a -> Balance
balance open close a
| a == open = Balance 0 1
| a == close = Balance 1 0
| otherwise = Balance 0 0
alphabalance :: NonEmpty (Char -> Balance)
alphabalance = NonEmpty.map (balance <$> id <*> toUpper) ('a' :| ['b' .. 'z'])
runAlphabalance :: Char -> NonEmpty Balance
runAlphabalance = flip NonEmpty.map alphabalance . (&)
stringBalances :: String -> Maybe (NonEmpty (NonEmpty Balance))
stringBalances = (NonEmpty.map runAlphabalance <$>) . NonEmpty.nonEmpty
runStringBalances :: NonEmpty (NonEmpty Balance) -> NonEmpty Balance
runStringBalances = foldr1 (NonEmpty.zipWith (<>))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment