Skip to content

Instantly share code, notes, and snippets.

@TerrorJack
Last active March 30, 2016 14:19
Show Gist options
  • Save TerrorJack/d449c80f8323f0f23de18066461b12af to your computer and use it in GitHub Desktop.
Save TerrorJack/d449c80f8323f0f23de18066461b12af to your computer and use it in GitHub Desktop.
Two different implementations for a same functional sequence with O(1) concat and O(n) fromList/toList.
newtype DList a = DList ([a] -> [a])
fromList :: [a] -> DList a
fromList l = DList (l++)
toList :: DList a -> [a]
toList (DList f) = f []
concat :: DList a -> DList a -> DList a
concat (DList lf) (DList rf) = DList $ lf . rf
data Builder a = Nil | Singleton a | Concat (Builder a) (Builder a)
fromList :: [a] -> Builder a
fromList = foldr (Concat . Singleton) Nil
toList :: Builder a -> [a]
toList = f [] where
f rest Nil = rest
f rest (Singleton a) = a:rest
f rest (Concat l r) = f (f rest r) l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment