我正在尝试构造一个MyData
类型的新值,这是我定义的个人数据类型,但是我收到了一个错误。 MyData
有一个构造函数List
,它接收MyData
个值的列表。我试图从MyData
类型中提取List
的两个元素,并使用Two And
构造函数创建一个新元素。解析器工作得很好,我查了一下。
data MyData = Var String | Con Bool | Two TwoOp MyData MyData | List [MyData]
deriving Show
data Final= F MyData MyData deriving Show
data TwoOp = And | Or deriving Show
add_and (Right (F (List e1) (List e2))) i1 i2 = do
a<-e1!!i1
b<-e1!!i2
return (Two And a b)
val (Right (F e1 e2))=add_and (Right (F e1 e2)) 0 1
parse_value string_expression= val (parse getfinal "" string_expression)
如果不清楚,请询问。我花了很多时间试图解决它,但不知道如何。
以下是我遇到的错误:
Couldn't match type `MyData' with `m MyData'
Expected type: [m MyData]
Actual type: [MyData]
Relevant bindings include
add_and :: Either t Final -> Int -> Int -> m MyData
(bound at D:\PF\final.hs:53:1)
In the first argument of `(!!)', namely `e1'
In a stmt of a 'do' block: a <- e1 !! i1
D:\PF\final.hs:55:5:
Couldn't match type `MyData' with `m MyData'
Expected type: [m MyData]
Actual type: [MyData]
Relevant bindings include
add_and :: Either t Final -> Int -> Int -> MyData
(bound at D:\PF\final.hs:53:1)
In the first argument of `(!!)', namely `e1'
In a stmt of a 'do' block: b <- e1 !! i2
Failed, modules loaded: none.
答案 0 :(得分:3)
您不想使用<-
从列表中提取值。
在这种情况下,您只想使用模式匹配:
add_and :: Final -> MyData
add_and (F (List (a:_)) (List (b:_))) = Two And a b
add_and _ = error "I don't know what to do here."
list1 :: MyData
list1 = List [ Var "abc" ]
list2 :: MyData
list2 = List [ Con False ]
final :: Final
final = F list1 list2
main = print $ add_and final
在ghci中运行时:
*Main> main
Two And (Var "abc") (Con False)