使用Haskell中的元组列表

时间:2013-03-21 22:13:54

标签: list haskell tuples

我在Haskell中有一个10元组列表,我希望从元组列表中获得第n个元组。但正如我所看到的,只有长度功能与该列表一起使用。 !! 功能无效。你能告诉我该怎么办?元组由整数和字符串组成。 例如,当我尝试这个时:

tail [(3,5,"String1","String2","String3","String4","String5","String6","String7","String8"),(3,5,"String1","String2","String3","String4","String5","String6","String7","String8"),(3,5,"String1","String2","String3","String4","String5","String6","String7","String8")]

我从拥抱中收到此错误消息:

ERROR - Cannot find "show" function for:
*** Expression : tail [(3,5,"String1","String2","String3","String4","String5","String6","String7","String8"),(3,5,"String1","String2","String3","String4","String5","String6","String7","String8"),(3,5,"String1","String2","String3","String4","String5","String6","String7","String8")]
*** Of type    : [(Integer,Integer,[Char],[Char],[Char],[Char],[Char],[Char],[Char],[Char])]

1 个答案:

答案 0 :(得分:5)

以下是如何为3元组声明Show实例。希望这说明了这个想法,你可以将它扩展到更多元素:

import Data.List (intercalate)

instance (Show a, Show b, Show c) => Show (a, b, c) where
  show (a, b, c) = "(" ++ (intercalate "," ([show a, show b, show c])) ++ ")"

您可以像逻辑含义一样阅读实例声明: if 我可以显示类型a,b和c的值,然后我可以显示类型的元组(a,b,c),这是如何。

GHC为一个15元组的所有内容定义了一个Show实例,所以你可能不需要在你的情况下定义它。