Skip to content

Instantly share code, notes, and snippets.

@googleson78
Created January 30, 2020 17:50
Show Gist options
  • Save googleson78/14f666979f8874508cd0332a7ca476fb to your computer and use it in GitHub Desktop.
Save googleson78/14f666979f8874508cd0332a7ca476fb to your computer and use it in GitHub Desktop.
List as a newtype, using products and sums
{-# LANGUAGE TypeOperators #-}
data (:+:) a b
= Inl a
| Inr b
data (:*:) a b
= a :*: b
data One = One
newtype List a = List (One :+: (a :*: List a))
nil :: List a
nil = List $ Inl One
cons :: a -> List a -> List a
cons x xs = List $ Inr $ (x :*: xs)
sumList :: List Int -> Int
sumList (List (Inl One)) = 0
sumList (List (Inr (n :*: xs))) = n + sumList xs
-- > sumList (cons 1 (cons 2 (cons 3 nil)))
-- 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment