functor.hs 870 B

1234567891011121314151617181920212223242526272829
  1. -- Slide 64
  2. data Expr a = Val a | Inc (Expr a) | Dec (Expr a) | Inv (Expr a) | Neg (Expr a)
  3. evaluate::(Fractional a)=>Expr a -> a
  4. evaluate (Val x) = x
  5. evaluate (Inc e) = 1 + evaluate e
  6. evaluate (Dec e) = (evaluate e) - 1
  7. evaluate (Inv e) = 1 / (evaluate e)
  8. evaluate (Neg e) = negate (evaluate e)
  9. -- data Maybe a = Nothing | Just a
  10. isZero::(Num a, Eq a)=>Maybe a -> Bool
  11. isZero m = case m of
  12. Nothing -> True
  13. Just x -> if x == 0 then True else False
  14. mfmap::(Fractional a) => (a -> b) -> Maybe a -> Maybe b
  15. mfmap f m = case m of
  16. Nothing -> Nothing
  17. Just x -> Just (f x)
  18. safeval::(Fractional a, Eq a) => Expr a -> Maybe a
  19. safeval (Val x) = Just x
  20. safeval (Inc e) = mfmap (+ 1) (safeval e)
  21. safeval (Dec e) = mfmap (subtract 1) (safeval e)
  22. safeval (Inv e) = let v = safeval e in if isZero v then Nothing else mfmap (1 /) v
  23. safeval (Neg e) = mfmap negate (safeval e)