简体   繁体   English

我的清单输入haskell

[英]My list type in haskell

I try to create an own list type in haskell but, my implementation contains errors. 我尝试在haskell中创建自己的列表类型,但是我的实现包含错误。 What is the proper way to do this nice. 什么是做到这一点的正确方法。 Please explain me a bit. 请给我解释一下。 Thank you. 谢谢。

My code: 我的代码:

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

Error code: 错误代码:

[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.

Your composition of show functions is incorrect. 您的show功能组成不正确。 I think you mean to interpolate values. 我认为您的意思是插值。

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

should be something like: 应该是这样的:

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

The type of showString is String -> ShowS . showString的类型为showString String -> ShowS ShowS is a type synonym for String -> String , so the result of showString "[]" is the function that prepends the string "[]" to its argument. ShowSShowS String -> String的类型同义词,因此showString "[]"的结果是将字符串"[]" showString "[]"到其参数的函数。 Since you gave no type signature, that equation determines what type is inferred for the function, but the other equations don't match that type. 由于您未提供类型签名,因此该方程式确定了为该函数推断的类型,但其他方程式与该类型不匹配。

You probably wanted simply 您可能只是想

showList' EmptyList = "[]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM