# Untitled

unknown
plain_text
7 months ago
2.0 kB
1
Indexable
Never
```module Ficha8 where

--2
data Exp a = Const a
| Simetrico (Exp a)
| Mais (Exp a) (Exp a)
| Menos (Exp a) (Exp a)
| Mult (Exp a) (Exp a)
--       deriving Eq

--e = 3 + (4 * 5)
e :: Exp Int
e = (Const 3) `Mais` ((Const 4) `Mult` (Const 5))

e' :: Exp Int
e' = (Const 3) `Mais` (Const 4) `Mult` (Const 5)
--a)
pp :: Show a => Exp a -> String
pp (Const v) = show v
pp (Simetrico e) = "( - " ++ pp e ++ ")"
pp (Mais e1 e2)  = "(" ++ pp e1 ++ " + " ++ pp e2 ++ ")"
pp (Menos e1 e2) = "(" ++ pp e1 ++ " - " ++ pp e2 ++ ")"
pp (Mult e1 e2)  = "(" ++ pp e1 ++ " * " ++ pp e2 ++ ")"

instance Show a => Show (Exp a) where
show e = pp e

--b)
-- Duas expressões são iguais quando o seu valor é igual

calcula :: Num a => Exp a -> a
calcula (Const v) = v
calcula (Simetrico e) = - (calcula e)
calcula (Mais e1 e2)  = calcula e1 + calcula e2
calcula (Menos e1 e2) = calcula e1 - calcula e2
calcula (Mult e1 e2)  = calcula e1 * calcula e2

iguais :: (Num a, Eq a) => Exp a -> Exp a -> Bool
iguais e1 e2 = calcula e1 == calcula e2

instance (Num a, Eq a) => Eq (Exp a) where
(==) = iguais

-- Ord a
menorIgual :: (Num a, Ord a) => Exp a -> Exp a -> Bool
menorIgual e1 e2 = calcula e1 <= calcula e2

instance (Num a, Ord a) => Ord (Exp a) where
(<=) = menorIgual

-- Contas
maisExp :: Num a => Exp a -> Exp a -> Exp a
maisExp e1 e2 = Const (calcula e1 + calcula e2)

menosExp :: Num a => Exp a -> Exp a -> Exp a
menosExp e1 e2 = Const (calcula e1 - calcula e2)

multExp :: Num a => Exp a -> Exp a -> Exp a
multExp e1 e2 = Const (calcula e1 * calcula e2)

absExp :: Num a => Exp a -> Exp a
absExp e = Const \$ abs \$ calcula e

signumExp :: Num a => Exp a -> Exp a
signumExp e = Const \$ signum \$ calcula e

fromIntegerExp :: Num a => Integer -> Exp a
fromIntegerExp i = Const (fromInteger i)

instance Num a => Num (Exp a) where
(+) = maisExp
(-) = menosExp
(*) = multExp
abs = absExp
signum = signumExp
fromInteger = fromIntegerExp

```