From 98329e0a3dd4f78b5d815ac3896272ec70904901 Mon Sep 17 00:00:00 2001 From: Eugen Wissner Date: Thu, 11 Dec 2025 10:28:11 +0100 Subject: Add remaining haskell book exercises --- Haskell-book/18/Instance/src/List.hs | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Haskell-book/18/Instance/src/List.hs (limited to 'Haskell-book/18/Instance/src/List.hs') diff --git a/Haskell-book/18/Instance/src/List.hs b/Haskell-book/18/Instance/src/List.hs new file mode 100644 index 0000000..bd3a06b --- /dev/null +++ b/Haskell-book/18/Instance/src/List.hs @@ -0,0 +1,44 @@ +module List where + +import Test.QuickCheck +import Test.QuickCheck.Checkers + +data List a = + Nil + | Cons a (List a) + deriving (Eq, Show) + +instance Functor List where + fmap f Nil = Nil + fmap f (Cons x xs) = Cons (f x) (fmap f xs) + +append :: List a -> List a -> List a +append Nil ys = ys +append (Cons x xs) ys = Cons x $ xs `append` ys + +fold :: (a -> b -> b) -> b -> List a -> b +fold _ b Nil = b +fold f b (Cons h t) = f h (fold f b t) + +concat' :: List (List a) -> List a +concat' = fold append Nil + +flatMap :: (a -> List b) -> List a -> List b +flatMap f as = concat' $ fmap f as + +instance Applicative List where + pure f = Cons f Nil + Nil <*> _ = Nil + _ <*> Nil = Nil + f <*> x = flatMap (\f' -> fmap f' x) f + +instance Monad List where + return = pure + x >>= f = concat' $ fmap f x + +instance Arbitrary a => Arbitrary (List a) where + arbitrary = frequency [(1, pure Nil), + (5, Cons <$> arbitrary <*> arbitrary)] + +instance Eq a => EqProp (List a) where + (=-=) = eq -- cgit v1.2.3