Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.1 kB
0
Indexable
Never
module Ficha7 where


--1
data ExpInt = Const Int
            | Simetrico ExpInt
            | Mais ExpInt ExpInt
            | Menos ExpInt ExpInt
            | Mult ExpInt ExpInt


e :: ExpInt
e = Mais (Const 3) (Mult (Const 4) (Const 5))

--a)
calcula :: ExpInt -> Int
calcula (Const x) = x
calcula (Simetrico x) = - (calcula x)
calcula (Mais e1 e2)  = calcula e1 + calcula e2
calcula (Menos e1 e2) = calcula e1 - calcula e2
calcula (Mult e1 e2)  = calcula e1 * calcula e2

--b)
infixa :: ExpInt -> String
infixa (Const x) = show x
infixa (Simetrico x)  = "(-" ++ infixa x ++ ")"
infixa (Mais e1 e2)  = "(" ++ infixa e1 ++ "+" ++ infixa e2 ++ ")"
infixa (Menos e1 e2) = "(" ++ infixa e1 ++ "-" ++ infixa e2 ++ ")"
infixa (Mult e1 e2)  = "(" ++ infixa e1 ++ "*" ++ infixa e2 ++ ")"

--c)
posfixa :: ExpInt -> String
posfixa (Const x) = show x
posfixa (Simetrico x)  = "(-" ++ posfixa x ++ ")"
posfixa (Mais e1 e2)  = posfixa e1 ++ posfixa e2 ++ "+ "
posfixa (Menos e1 e2) = posfixa e1 ++ posfixa e2 ++ "- "
posfixa (Mult e1 e2)  = posfixa e1 ++ posfixa e2 ++ "* "


--2
data RTree a = R a [RTree a]
                deriving Show

rt :: RTree Int
rt = R 7 [ R 3 [ R 1 []
               , R 2 []]
         , R 10 []
         , R 4 [ R 1 [ R 5 []
                     , R 8 []
                     , R 12 []]
                ]
         ]

--a)
soma :: Num a => RTree a -> a
soma (R i l) = i + sum (map soma l)

--com foldr
soma' :: Num a => RTree a -> a
soma' (R i l) = i + foldr (\ t r -> soma t + r) 0 l

--c)
prune :: Int -> RTree a -> RTree a
prune 1 (R i _) = R i []
prune n (R i l) = R i (map (prune (n-1)) l)


prune' :: RTree a -> Int -> RTree a
prune' (R i _) 1 = R i []
prune' (R i l) n = R i (map (\ t -> (prune' t (n-1))) l )

prune'' :: RTree a -> Int -> RTree a
prune'' (R i _) 1 = R i []
prune'' (R i l) n = R i (map ((flip prune'') (n-1)) l)

--c)
mirror :: RTree a -> RTree a
mirror (R i l) = R i (reverse (map mirror l))

--3
data LTree a = Tip a
             | Fork (LTree a) (LTree a)
                    deriving Show

--b)
listaLT :: LTree a -> [a]
lsitaLT (Tip i) = [i]
listaLT (Fork l r) = listaLT l ++ listaLT r
Leave a Comment