在Haskell中在元组中打印值 [英] Printing the values inside a tuple in Haskell
问题描述
我有一个元组列表.例如: [("A",100,1),("B",101,2)]
.我需要以一种简单的方式来显示它.例如:您的名字是:A",您的id是:100"
.
I have a list of tuples. For example: [("A",100,1),("B",101,2)]
. I need to display it in a simple way. For example: "your name is: A", "Your id is: 100"
.
如果任何人都可以找到解决方案,那将是一个很大的帮助.预先感谢.
If anyone can find a solution for this, it would be a great help. Thanks in advance.
推荐答案
最简单的方法是创建一个适用于列表中元素之一的函数.因此,您将需要以下内容:
The easiest way to do this is to create a function that works for one of the elements in your list. So you'll need something like:
showDetails :: (String, Int, Int) -> String
showDetails (name, uid, _) = "Your name is:" ++ name ++ " Your ID is: " ++ show uid
然后您将此功能应用于列表中的每个元素,这意味着您要使用映射功能:
Then you would apply this function to each element in the list, which means you want to use the mapping function:
map :: (a -> b) -> [a] -> [b]
因此,如果您的列表名为 xs
,则可能需要以下内容:
So, if your list is called xs
, you would want something like:
map showDetails xs
这显然为您提供了 [String]
类型的结果,因此您可能对 unlines
函数感兴趣:
This obviously gives you a result of type [String]
, so you might be interested in the unlines
function:
unlines :: [String] -> String
这只是获取一个字符串列表,并创建一个字符串,每个元素之间都用新行分隔.
This simply takes a list of strings, and creates a string where each element is separated by a new line.
将所有内容放在一起,即可为您提供:
Putting this all together, then, gives you:
main :: IO ()
main = putStrLn . unlines . map showDetails $ [("A",100,1),("B",101,2)]
这篇关于在Haskell中在元组中打印值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!