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/22/ReaderPractice.hs | 94 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Haskell-book/22/ReaderPractice.hs (limited to 'Haskell-book/22/ReaderPractice.hs') diff --git a/Haskell-book/22/ReaderPractice.hs b/Haskell-book/22/ReaderPractice.hs new file mode 100644 index 0000000..e530d20 --- /dev/null +++ b/Haskell-book/22/ReaderPractice.hs @@ -0,0 +1,94 @@ +{-# LANGUAGE NoImplicitPrelude #-} +module ReaderPractice where + +import Control.Applicative +import Data.Maybe (Maybe(..)) +import Prelude ( zip + , foldr + , ($) + , flip + , Integer(..) + , (==) + , Eq + , otherwise + , undefined + , (+) + , Num + , (<) + , (>) + , (&&) + , Bool(..) + , print + , sequenceA + , IO(..) + , fmap + , even + , Integral ) + +x = [1, 2, 3] +y = [4, 5, 6] +z = [7, 8, 9] + +lookup :: Eq a => a -> [(a, b)] -> Maybe b +lookup v l = foldr f Nothing l + where f _ (Just x) = Just x + f (x, y) Nothing + | x == v = Just y + | otherwise = Nothing + +-- zip x and y using 3 as the lookup key +xs :: Maybe Integer +xs = lookup 3 (zip x y) + +-- zip y and z using 6 as the lookup key +ys :: Maybe Integer +ys = lookup 6 (zip y z) + +-- zip x and y using 4 as the lookup key +zs :: Maybe Integer +zs = lookup 4 $ zip x y + +z' :: Integer -> Maybe Integer +z' = flip lookup $ zip x z + +x1 :: Maybe (Integer, Integer) +x1 = Just (,) <*> xs <*> ys + +x2 :: Maybe (Integer, Integer) +x2 = Just (,) <*> ys <*> zs + +x3 :: Integer -> (Maybe Integer, Maybe Integer) +x3 n = (z' n, z' n) + +uncurry :: (a -> b -> c) -> (a, b) -> c +uncurry f (x, y) = f x y + +summed :: Num c => (c, c) -> c +summed = uncurry (+) + +bolt :: Integer -> Bool +bolt = (&&) <$> (> 3) <*> (< 8) + +fromMaybe :: a -> Maybe a -> a +fromMaybe x (Just y) = y +fromMaybe x Nothing = x + +sequA :: Integral a => a -> [Bool] +sequA m = sequenceA [(>3), (<8), even] m + +s' :: Maybe Integer +s' = summed <$> ((,) <$> xs <*> ys) + +main :: IO () +main = do + print $ sequenceA [Just 3, Just 2, Just 1] + print $ sequenceA [x, y] + print $ sequenceA [xs, ys] + print $ summed <$> ((,) <$> xs <*> ys) + print $ fmap summed ((,) <$> xs <*> zs) + print $ bolt 7 + print $ fmap bolt z + print $ sequenceA [(> 3), (< 8), even] 7 + print $ foldr (&&) True $ sequA $ fromMaybe 0 s' + print $ sequA $ fromMaybe 0 s' + print $ bolt $ fromMaybe 0 s' -- cgit v1.2.3