diff options
| author | Eugen Wissner <belka@caraus.de> | 2025-12-11 10:28:11 +0100 |
|---|---|---|
| committer | Eugen Wissner <belka@caraus.de> | 2025-12-11 10:28:11 +0100 |
| commit | 98329e0a3dd4f78b5d815ac3896272ec70904901 (patch) | |
| tree | 80f9c56cfe2ac20232358f236d32e84bd683be1b /Haskell-book/22/ReaderPractice.hs | |
| parent | 3624c712d72d246f21d4e710cec7c11e052e0326 (diff) | |
| download | book-exercises-98329e0a3dd4f78b5d815ac3896272ec70904901.tar.gz | |
Add remaining haskell book exercises
Diffstat (limited to 'Haskell-book/22/ReaderPractice.hs')
| -rw-r--r-- | Haskell-book/22/ReaderPractice.hs | 94 |
1 files changed, 94 insertions, 0 deletions
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' |
