diff --git a/ch07/ex10.hs b/ch07/ex10.hs index dcd533d..8d3a6c4 100644 --- a/ch07/ex10.hs +++ b/ch07/ex10.hs @@ -9,4 +9,4 @@ luhnDouble x = else x * 2 luhn :: [Int] -> Bool -luhn xs = sum (altMap luhnDouble id xs) `mod` 10 == 0 +luhn xs = sum (altMap id luhnDouble $ reverse xs) `mod` 10 == 0 diff --git a/ch12/ex7.hs b/ch12/ex7.hs index f3baa15..0b4c848 100644 --- a/ch12/ex7.hs +++ b/ch12/ex7.hs @@ -4,22 +4,20 @@ data Expr a | Add (Expr a) (Expr a) deriving (Show) -instance Functor Expr +instance Functor Expr where -- fmap :: (a -> b) -> Expr a -> Expr b - where fmap _ (Val x) = Val x fmap g (Var x) = Var (g x) fmap g (Add a b) = Add (fmap g a) (fmap g b) -instance Applicative Expr +instance Applicative Expr where -- pure :: a -> Expr a - where pure = Var + -- (<*>) :: Expr (a -> b) -> Expr a -> Expr b - _ <*> Val x = Val x - Val x <*> _ = Val x - Var f <*> Var x = Var (f x) - Var f <*> Add x y = Add (fmap f x) (fmap f y) + Val x <*> _ = error "Cannot apply a non-function value" + _ <*> Val x = error "Cannot apply a non-function value" + Var f <*> x = fmap f x Add f g <*> x = Add (f <*> x) (g <*> x) instance Monad Expr where @@ -28,6 +26,7 @@ instance Monad Expr where Val x >>= _ = Val x Var x >>= f = f x Add a b >>= f = Add (a >>= f) (b >>= f) + --examples -- Var 5 >>= \x -> Var (x*3) -- result: Var 15