Skip to content

Instantly share code, notes, and snippets.

@mbloms
Created December 23, 2017 23:27
Show Gist options
  • Save mbloms/beca1d31bbdaf2ea204c1fa52ba400e5 to your computer and use it in GitHub Desktop.
Save mbloms/beca1d31bbdaf2ea204c1fa52ba400e5 to your computer and use it in GitHub Desktop.
Simple problem from advent of code 2017. Solved as complicated as possible in as few lines as possible.
import Data.Monoid
import Data.Char (digitToInt)
import Data.Foldable (foldrM)
--- Part One ---
-- Bind using the reader monad:
-- x >>= k = \w-> k (x w) w
-- head >>= foldrM bar = \w -> foldrM bar (head w) w
foo = head >>= foldrM bar
-- The writer monad will sum the first elements
-- the second element will be fed into bar again in the fold.
bar x y | (x==y) = (x,x)
| otherwise = (mempty,x)
-- Read a line, read out the digits and wrap them in the Sum monoid.
-- Send the list of Sums to foo.
-- Unwrap the Sum from the Writer.
-- Print it.
main =
fmap
(getSum . fst . foo
. map (Sum . digitToInt))
getLine
>>= print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment