Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

Working with list of tuples in Haskell

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])]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...