在haskell中附加自定义数据类型

时间:2014-01-19 07:35:43

标签: list haskell append

我正在使用数据类型来模拟异构列表:

data Nested a = Elem a | List [Nested a]
            deriving (Show)

这样我就可以表达List [Elem 1, Elem 2, List [Elem 3, Elem 4], List [Elem 5], Elem 6]等数据。

这里我正在编写一个函数,就像普通的追加函数一样,可以连接我的异构列表:

appendn                 :: Nested a -> Nested a -> Either String (Nested a)
appendn (Elem a) (List x)       = Left "error: wrong argument"
appendn (List x) (Elem a)       = Left "error: wrong argument"
appendn (List []) (List x)      = Right (List x)
appendn (List (x:xs)) (List y)  = Right (List (x:appendn (List xs) (List y))

但是我总是在最后一行得到一个解析错误。我想知道我是否可以在这里使用:运算符来追加List。有人可以帮忙吗?感谢。

3 个答案:

答案 0 :(得分:1)

计算左右括号。他们匹配吗?

答案 1 :(得分:1)

有几点:

  1. 您的案例遗失:如果两个参数都在Elem

  2. 您的函数会生成Either String (Nested a),但在最后一种情况下定义为:

    ... appendn(List(x:xs))(List y)= Right(List(x:appendn(List xs)(List y))

  3. 我们试图将(:)值(x :: Nested a)纳入非列表appendn (List xs) (List y) :: Either String (Nested a)

    潜在解决方案

    appendn :: Nested a -> Nested a -> Either String (Nested a)
    
    --  if an `Elem` is given as either argument, the result is
    --  a `Left` error.
    appendn (Elem a) _           = Left "error: wrong argument"
    appendn _ (Elem a)           = Left "error: wrong argument"
    
    --  Otherwise, we must have two `List`; the result of which
    --  can just be `Right` of a new `List`, with the inner list
    --  being the two lists appended together.
    appendn (List xs) (List ys)  = Right (List (xs ++ ys))
    

    以下是一些测试案例:

    $ appendn (Elem 2) (Elem 3)
    = Left "error: wrong argument"
    
    $ appendn (List [Elem 1]) (Elem 2)
    = Left "error: wrong argument"
    
    $ appendn (Elem 2) (List [Elem 1])
    = Left "error: wrong argument"
    
    $ appendn (List [Elem 1, Elem 2]) (List [])
    = Right (List [Elem 1,Elem 2])
    
    $ appendn (List [Elem 1, Elem 2]) (List [Elem 3, Elem 4])
    = Right (List [Elem 1,Elem 2,Elem 3,Elem 4])
    

    这里是否使用了Either,而不是Maybe

    希望这有帮助!

答案 2 :(得分:0)

除了肠胃外不匹配,您还有类型错误。你不能使用(:)函数和“List”参数,你必须解压缩它。

顺便说一句,你为什么不只使用(++)函数?