2016-12-01 68 views
0

這是我的當前代碼:不能匹配期望的類型(自定義類型)

data Exp x = Con Int | Var x | Sum [Exp x] | Prod [Exp x] 
    | Exp x :- Exp x | Int :* Exp x | Exp x :^ Int 

expression :: Exp String 
expression = Sum [3:*(Var"x":^2), 2:*Var"y", Con 1] 

type Store x = x -> Int 

exp2store :: Exp x -> Store x -> Int 
exp2store (Con i) _  = i 
exp2store (Var x) st = st x 
exp2store (Sum es) st = sum $ map (flip exp2store st) es 
exp2store (Prod es) st = product $ map (flip exp2store st) es 
exp2store (e :- e') st = exp2store e st - exp2store e' st 
exp2store (i :* e) st = i * exp2store e st 
exp2store (e :^ i) st = exp2store e st^i 

精通應該代表一個多項式表達和exp2store需要的表達和其與值提供變量中的表達的功能。

例子:

*Main> exp2store (Var"x") $ \"x" -> 5 
5 

的作品。我不知道如何以不同的值提供多個變量,即

*Main> exp2store (Sum[Var"x",Var"y"]) $ \"x" "y" -> 5 10 

顯然,這會引發異常。有人可以幫助我嗎?

回答

4

如果沒有通用公式,編寫一個將任意輸入映射到輸出的匿名函數是很困難的。首先,您可以使用關聯列表來代替;標準函數lookup允許您獲取給定變量的值。 (這是不是最好的執行方法,但它可以讓你避免任何額外的進口開始。)

-- I lied; one import from the base library 
-- We're going to assume the lookup succeeds; 
import Data.Maybe 

-- A better function would use Maybe Int as the return type, 
-- returning Nothing when the expression contains an undefined variable 
exp2store :: Eq x => Exp x -> [(x,Int)] -> Int 
exp2store (Con i) _  = i 
exp2store (Var x) st = fromJust $ lookup x st 
exp2store (Sum es) st = sum $ map (flip exp2store st) es 
exp2store (Prod es) st = product $ map (flip exp2store st) es 
exp2store (e :- e') st = exp2store e st - exp2store e' st 
exp2store (i :* e) st = i * exp2store e st 
exp2store (e :^ i) st = exp2store e st^i 

調用功能

exp2store (Sum[Var"x",Var"y"]) $ [("x",5), ("y",10)] 

如果你必須保持Store定義,你可以這樣寫你的電話

exp2store (Sum[Var"x",Var"y"]) $ \x -> case x of "x" -> 5; "y" -> 10 
相關問題