aboutsummaryrefslogtreecommitdiff
path: root/Haskell-book/22/ReaderPractice.hs
blob: e530d20a3f192b21cf6f0753c1ddf19e0340710c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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'