Created
January 30, 2020 17:50
-
-
Save googleson78/14f666979f8874508cd0332a7ca476fb to your computer and use it in GitHub Desktop.
List as a newtype, using products and sums
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 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