2012-05-21 100 views
0

我尝试在haskell中创建自己的列表类型,但是,我的实现包含错误。 什么是正确的方法来做到这一点很好。请给我解释一下。 谢谢。我的列表输入haskell

我的代码:

data List a = EmptyList | ListElement a (List a) 

instance (Show a) => Show (List a) where 
     show = showList' 

showList' EmptyList = showString "[]" 
showList' (ListElement a EmptyList) = show a 
showList' (ListElement a b) = show a ++ show " " ++ showList' b 

错误代码:

[1 of 1] Compiling Main    (tipusok.hs, interpreted) 

tipusok.hs:12:39: 
    Couldn't match expected type `Prelude.String -> Prelude.String' 
       with actual type `[Char]' 
    Expected type: ShowS 
     Actual type: Prelude.String 
    In the return type of a call of `show' 
    In the expression: show a 
Failed, modules loaded: none. 

回答

3
showList' EmptyList = showString "[]" 

类型的showStringString -> ShowSShowSString -> String的一个类型的同义词,因此showString "[]"的结果是将字符串"[]"加到其参数的前面的函数。既然你没有给出类型签名,那么这个等式就决定了函数的推断类型,但其他方程不匹配那个类型。

你可能想简单地

showList' EmptyList = "[]" 
+0

:)它的工作,谢谢你 – flatronka

4

你的show功能成分是不正确。我认为你的意思是插值。

showList' (ListElement a b) = show a . showChar ' ' . show b 

应该是这样的:

showList' (ListElement a b) = show a ++ " " ++ showList' b 
+0

感谢,这个递归调用是强制性的,我做了新的错误消息 – flatronka

+1

编辑'showChar'不返回'String'。我认为你的意思是使用空格字符? –

+0

谢谢,我再次做了一个编辑,但它仍然不起作用 – flatronka