简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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