Files
book-exercises/Haskell-book/22/ReaderPractice.hs

95 lines
2.1 KiB
Haskell

{-# 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'