在Haskell中处理元组列表 [英] Working with list of tuples in Haskell

查看:282
本文介绍了在Haskell中处理元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Haskell中的10元组列表,我想从元组列表中获得第n个元组。但正如我所看到的,只有长度函数适用于该列表。 !! 功能不起作用。你能告诉我该怎么办?元组由整数和字符串组成。
例如,当我尝试这样做时:

$ $ p $ $ $ c $尾巴[(3,5,String1,String2, STRING3, 串,4, STRING5, String6, String7, String8),(3,5, 字符串1, String2的, STRING3, 串,4, STRING5, String6, String7, String8),(3,5, 字符串1, String2的, STRING3, 串,4, STRING5, String6, String7, String8) ]

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

 错误 - 无法找到
***的show函数表达式:tail [(3,5,String1,String2,String3, 串,4, STRING5, String6, String7, String8),(3,5, 字符串1, String2的, STRING3, 串,4, STRING5, String6, String7,String8),(3,5,String1,String2,String3,String4,String5,String6,String7,String8)]
***类型:[(Integer,Integer,[Char],[Char],[Char],[Char],[Char],[Char],[Char],[Char])]


解决方案

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

 
import Data.List(插入)

实例(显示a,显示b,显示c)=>显示(a,b,c)其中
显示(a,b,c)=(++(intercalate,([show a ,show b,show c]))++)

您可以像读取逻辑一样读取实例声明:如果我可以显示类型a,b和c的值,那么然后,我可以显示类型为(a,b,c)的元组,并且以下是方法。



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


I have a list of 10-tuples in Haskell and I want to get nth tuple from that list of tuples. But as I saw, only length function worked with that list. head, tail or !! functions didn't work. Can you tell me what should I do? The tuples are composed of integers and strings. For example when I try this :

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")]

I get this error message from hugs:

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])]

解决方案

Here's how to declare a Show instance for a 3-tuple. Hopefully this illustrates the idea and you can extend it to more elements:

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])) ++ ")"

You can read the instance declaration just like logical implication: if I can show values of type a, b, and c, then I can show a tuple of type (a, b, c), and here's how.

GHC defines a Show instance for everything up to a 15-tuple, so you probably won't need to define this in your case.

这篇关于在Haskell中处理元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆