2011-11-11 42 views
1

我有一个元组列表。例如:[("A",100,1),("B",101,2)]。我需要以简单的方式显示它。例如:"your name is: A", "Your id is: 100"在Haskell中打印元组中的值

如果任何人都可以找到解决方案,这将是一个很大的帮助。提前致谢。

回答

6

最简单的方法是创建一个适用于列表中某个元素的函数。所以,你需要这样的东西:

showDetails :: (String, Int, Int) -> String 
showDetails (name, uid, _) = "Your name is:" ++ name ++ " Your ID is: " ++ show uid 

那么你会应用此功能列表中的每个元素,这意味着你要使用的映射功能:

map :: (a -> b) -> [a] -> [b] 

所以,如果您的列表被称为xs,你想是这样的:

map showDetails xs 

这显然给你[String]类型的结果,所以你可能会喜欢unlines功能:

unlines :: [String] -> String 

这简单地取字符串的列表,并创建其中每个元素是由一个新行分开的字符串。

把所有这些组合起来,然后,为您提供:

main :: IO() 
main = putStrLn . unlines . map showDetails $ [("A",100,1),("B",101,2)] 
+0

感谢名单4 d响应 – Roy

1

对于一个元组,只是模式匹配的所有元素,并做一些与他们。具有这样的功能,您可以使用map来转换整个列表。

import Data.List (foldl') 

show_tuple :: (Num a, Num b) => (String, a, b) -> String 
show_tuple (name, id, something) = 
    "Your name is: " ++ name ++ "\n" ++ 
    "Your ID is:  " ++ (show id) ++ "\n" ++ 
    "Your something: " ++ (show something) ++ "\n\n" 

-- transforms the list, and then concatenates it into a single string 
show_tuple_list :: (Num a, Num b) => [(String, a, b)] -> String 
show_tuple_list = (foldl' (++) "") . (map show_tuple) 

输出:

*Main Data.List> putStr $ show_tuple_list [("ab", 2, 3), ("cd", 4, 5)] 
Your name is: ab 
Your ID is:  2 
Your something: 3 

Your name is: cd 
Your ID is:  4 
Your something: 5 
+0

我试图采取文件中的元组列表,并显示它n以上提到的方式。但最终会出现一个错误,说“在最终生成器中输入错误”。 – Roy

+2

如果你使用这个解决方案,我会小心不要使用“id”作为变量名,因为它通常被当作识别函数来读取。 –

0

快速和脏溶液

f (x,y,z) = "your id is " ++ (show y) ++ ", your name is " ++ (show x) ++ "\n" 

main = putStrLn $ foldr (++) "" (map f [("A",100,1),("B",101,2)]) 

OR(由@maksenov)

main = putStrLn $ concatMap f [("A",100,1),("B",101,2)] 
+4

'foldr(++)“”$ map'基本上是'concatMap' –

+0

优秀的答案。感谢您的回应。 – Roy

+0

@maksenov哇!我不知道concatMap。 :d –