Pages: 1 [2]   Go Down
Print
Author Topic: Possibile soluzione all'esercizio haskell "Definire il Pattern Matching di PICT"  (Read 1897 times)
0 Members e 1 Utente non registrato stanno visualizzando questa discussione.
rondey
Matricola
*
Offline Offline

Posts: 74


« Reply #15 on: 28-04-2016, 14:18:25 »

Versione funzionante con applySubs

Code:
data PicValue = ValNum Int | ValString [Char] | ValBool Bool | ValName Name | Tuple [PicValue]
    deriving (Show, Eq)

data Pattern = PattNum Int | PattString [Char] | PattBool Bool | PattName Name | PattTuple [Pattern]
    deriving (Show, Eq)

 
data Substitution = MkSubstitution [(Name, PicValue)]
    deriving (Show)

concatSubstitution (MkSubstitution ls1) (MkSubstitution ls2) = MkSubstitution (ls1++ls2)
concatTuple (Tuple ls1) (Tuple ls2) = Tuple (ls1++ls2)
concatTuple v (Tuple ls) = Tuple (v:ls)
concatTuple v1 v2 = Tuple [v1, v2]

   
data Name = Name [Char]
    deriving (Show,Eq)
   
mytuplaP=PattTuple [PattTuple [PattName (Name "x"), PattName (Name "y")], PattName (Name "z")]
mytuplaV=Tuple     [Tuple     [ValNum 35          , ValNum 50          ], ValNum 1]

matching :: Pattern -> PicValue ->(Bool, Substitution)
     
matching patt value =
    case (patt,value) of
       
        (PattNum n, ValNum m ) ->  ((n == m), (MkSubstitution []))
       
        (PattString s1, ValString s2 ) ->  ((s1==s2), (MkSubstitution []))
       
        (PattBool b1, ValBool b2) ->   ((b1==b2), (MkSubstitution []))
       
        (PattName a, value) ->   (True, (MkSubstitution [(a, value)]))
       
        (PattTuple [], Tuple []) ->   (True, (MkSubstitution []))
       
        (PattTuple [], value) ->    (False, (MkSubstitution []))
       
        (PattTuple (p:ps), Tuple (v:vs)) | b -> (b0, (concatSubstitution s0 s))
                                         | otherwise -> (False, (MkSubstitution []))
                                            where (b0,s0) =  (matching p v)
                                                  (b,s) = (matching (PattTuple ps) (Tuple vs))
        (patt, value) -> (False, (MkSubstitution []))

applySubs :: Substitution -> Pattern -> PicValue




applySubs (MkSubstitution sub) patt =
    case patt of
        (PattNum n) -> (ValNum n)
        (PattBool b) -> (ValBool b)
       
        (PattName name) -> find name sub
        (PattTuple ps) -> Tuple (map (applySubs (MkSubstitution sub)) ps)
       
find :: Name -> [(Name, PicValue)] -> PicValue
       
find name [] = ValName name

find name ((n, v):ls) | (n == name) = v
                    | otherwise = find name ls
Logged
Franco Barbanera
Moderator
Forumista Eroico
*****
Offline Offline

Posts: 2.777



WWW
« Reply #16 on: 28-04-2016, 14:33:29 »

Ora la versione con
type Substitution :: Name  ->  PicValue

Logged
Pages: 1 [2]   Go Up
Print
Jump to: