【发布时间】:2017-08-04 05:53:11
【问题描述】:
我在 Haskell 中有以下代码:
module testData where
import SImpL
changeName :: String -> String -> ProgT -> ProgT
...
changeName x y (Seq []) = Seq[]
changeName x y (Seq (oneStatement:moreStatements)) = Seq (changeName x y oneStatement : changeName x y (Seq moreStatements))
ProgT的定义在模块SImpL中定义:
data StmtT = Assign NameT AExprT |
If BExprT StmtT StmtT |
While BExprT StmtT |
Seq [StmtT] -- If the list is empty, this is a statement that does nothing.
deriving (Show,Eq)
type ProgT = StmtT
简单地说,Seq[StmtT] 是一个在构造函数中定义的 Assign、If 或 While 语句的列表。 函数 changeName 检查所有语句中是否有变量等于 x,并将其替换为 y。 当我运行代码时,我收到以下错误: p>
Assignment3.hs:12:89: 错误: • 无法将类型“StmtT”与“[ProgT]”匹配 预期类型:[ProgT] 实际类型:ProgT • 在‘(:)’的第二个参数中,即 ‘changeName x y (Seq moreStatements)’ 在“Seq”的第一个参数中,即 '(changeName x y oneStatement : changeName x y (Seq moreStatements))’ 在表达式中: 序列 (changeName x y oneStatement : changeName x y (Seq moreStatements))
根据错误信息,问题出在最后一行:
changeName x y (Seq (oneStatement:moreStatements)) = Seq(changeName x y oneStatement:changeName x y (Seq moreStatements))
我知道它为什么会抛出错误,但我必须通过每个语句递归来更改语句中的每个变量。抱歉,如果这是微不足道的,但我不知道我可以通过 Seq[StmtT] 类型进行递归而不会出现错误。
注意:我认为其他数据类型是什么(即 BExprT)并不重要,以防万一这里有更多模块:
module SImpL where
data AExprT = ALit ValT -- a literal value (an Int)
| AName NameT -- a variable name (a String)
| Add AExprT AExprT -- one arithmetic expression added to another
| Sub AExprT AExprT -- one arithmetic expression subtracted from another
| Mult AExprT AExprT -- one arithmetic expression multiplied by another
deriving (Show,Eq)
data BExprT = BLit Bool -- a literal value (True or False)
| Eq AExprT AExprT -- an equality test between two arithmetic expressions
| Less AExprT AExprT -- a "less than" test between two arithmetic expressions
| Greater AExprT AExprT -- a "greater than" test between two arithmetic expressions
| Not BExprT -- the negation of a boolean expression
| And BExprT BExprT -- the "and" of two boolean expressions
| Or BExprT BExprT -- the "or" of two boolean expressions
deriving (Show,Eq)
type ValT = Integer
type NameT = String
data StmtT = Assign NameT AExprT |
If BExprT StmtT StmtT |
While BExprT StmtT |
Seq [StmtT] -- If the list is empty, this is a statement that does nothing.
deriving (Show,Eq)
If BExprT StmtT StmtT |
While BExprT StmtT |
Seq [StmtT] -- If the list is empty, this is a statement that does nothing.
deriving (Show,Eq)
type ProgT = StmtT
type StateT = [(NameT, ValT)]
编辑: @Ben 使用 map 帮助解决了错误(因为该函数现在不返回列表)。
【问题讨论】:
标签: haskell