Created
December 5, 2018 23:17
-
-
Save bradparker/603dc22aa93c7a1aed79a63b1456b5fb to your computer and use it in GitHub Desktop.
Wrong answer ... but fun
This file contains 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
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