2016-12-01 83 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