Skip to content

Instantly share code, notes, and snippets.

@robkuz
Created February 23, 2016 10:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robkuz/2f052d6a0a992bfa16ad to your computer and use it in GitHub Desktop.
Save robkuz/2f052d6a0a992bfa16ad to your computer and use it in GitHub Desktop.
How to extract a nested unbalanced structure
-- I was thinking on how to normalize a structure like
-- (Either String (Either String Int)) into
-- Either String Int
-- my first attempt was to pattern match
normalizer :: (Either String (Either String Int)) -> Either String Int
normalizer n = do
case n of
Left l -> Left l
Right r -> r
-- but that somehow liked unhaskellish
-- so I tried this
normalizer' :: (Either String (Either String Int)) -> Either String Int
normalizer' n = either Left id n
-- much better!
-- the empiphany is this
-- a) Data constructors a functions too - Left :: a -> Left a
-- b) if one wants to pipe a value to a function an get the same input back. id is your friend because
-- id :: a -> a
r = normalizer $ Right (Right 10)
l = normalizer $ Left "Oh my"
r' = normalizer' $ Right (Right 10)
l' = normalizer' $ Left "Oh my"
@jstepien
Copy link

You can also use join from Control.Monad.

> join $ Right (Right 10)
Right 10
> join $ Left "oh noes"
Left "oh noes"

@robkuz
Copy link
Author

robkuz commented Feb 23, 2016

@jstepien - nice that join

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