2017-09-14 2 views
1

Ich nehme eine Compiler-Klasse, und ich beschloss, es in Haskell zu tun, aber ich habe eine harte Zeit, die Einrichtung. Mein Problem ist, dass ich eine Atom Klasse und eine Expr Klasse und eine Instanz der Expr kann eine Atom sein, aber wenn die Expr sofort ein Atom ist, hat es ein Problem. Hier ist das Beispiel:Haskell nicht finden "indirekten" Typ

data Atom -- cannot be reduced farther 
    = Const Int -- int is value 
    | Var String -- string is name 
    deriving (Show) -- So we can print it 

data Expr -- add input and the like 
    = Add Expr Expr -- add is two exprs 
    | USub Expr -- negation 
    | Input -- call to input 
    | Atomic Atom -- or an atomic 
    deriving (Show) -- So we can print it 

data Statement 
    = Print Expr 
    | Discard Expr 
    | Assign String Expr 
    deriving (Show) -- So we can print it 


main = do 
    let test5 = Print (Const 2) 
    putStrLn $ show test5 

Der Compiler schlägt fehl am Print (Const 2), weil es eine Expr erwartet. Gibt es eine Lösung dafür, und gibt es ein besseres Vokabular für dieses Problem?

+3

Wie wäre es mit 'Print (Atomic (Const 2))'? –

+0

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ^^^^^^^^^^^^^^^^^^^^^^^^^^ Dann würde "Print (Atomic 2)" funktionieren, und auch "Print (Atomic" hi ")". – Alec

+0

@ BenjaminHodgson Das funktioniert. Willst du antworten, damit ich es annehmen kann und dir die Glaubwürdigkeit gebe? – Hovestar

Antwort

4

Const 2 ist ein Atom, aber Print nimmt eine Expr als ein Argument. Glücklicherweise kann jeder Atom zu einem Expr mit dem Atomic Konstruktor gemacht werden. Also:

main = do 
    let test5 = Print (Atomic (Const 2)) 
    print test5