无法匹配预期类型(自定义类型)

时间:2016-12-01 20:38:30

标签: haskell types

这是我目前的代码:

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

Exp应表示多项式表达式,exp2store接受表达式和函数,该函数为表达式中的变量提供值。

示例:

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

有效。我不知道如何提供具有不同值的多个变量,即

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

显然,这引发了一个例外。有人可以帮我吗?

1 个答案:

答案 0 :(得分: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