Created
February 11, 2013 02:31
-
-
Save luqui/4752060 to your computer and use it in GitHub Desktop.
zipWith on church lists
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
{-# LANGUAGE RankNTypes #-} | |
import Prelude hiding (zipWith) | |
newtype ChList a = ChList { fold :: forall b. (a -> b -> b) -> b -> b } | |
nil :: ChList a | |
nil = ChList $ \f z -> z | |
cons :: a -> ChList a -> ChList a | |
cons x xs = ChList $ \f z -> f x (fold xs f z) | |
uncons :: ChList a -> Maybe (a, ChList a) | |
uncons xs = fold xs (\x -> Just . (,) x . maybe nil (uncurry cons)) Nothing | |
zipWith :: (a -> b -> c) -> ChList a -> ChList b -> ChList c | |
zipWith f xs ys = ChList $ \g z -> | |
fold xs (\x xsf ys -> | |
maybe z (\(y,ys) -> g (f x y) (xsf ys)) (uncons ys) | |
) (const z) ys | |
toList :: ChList a -> [a] | |
toList xs = fold xs (:) [] | |
fromList :: [a] -> ChList a | |
fromList xs = ChList $ \f z -> foldr f z xs | |
~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment