Skip to content

Instantly share code, notes, and snippets.

@eborden
Last active March 8, 2017 16:44
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 eborden/2e2735ac769652f5ff212adad088d60d to your computer and use it in GitHub Desktop.
Save eborden/2e2735ac769652f5ff212adad088d60d to your computer and use it in GitHub Desktop.
Lazyness and the duality between Sums and Products
{-# LANGUAGE NoImplicitPrelude #-}
import Data.Foldable
import Control.Applicative
data Either a b = Left a | Right b
data Eithers t a b
= Eithers
{ lefts :: t a
, rights :: t b
}
consEither :: Either a b -> Eithers [] a b -> Eithers [] a b
consEither e (Eithers xs ys) = case e of
Left x -> Eithers (x:xs) ys
Right y -> Eithers xs (y:ys)
eithers :: Foldable t => t (Either a b) -> Eithers [] a b
eithers = foldr consEither (Eithers [] [])
genericEithers :: (Foldable t, Alternative s) => t (Either a b) -> Eithers s a b
genericEithers = foldr f' (Eithers empty empty)
where
f' e (Eithers xs ys) = case e of
Left x -> Eithers (pure x <|> xs) ys
Right y -> Eithers xs (pure y <|> ys)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment