在Haskell中打印元组内的值

fbcarpbf  于 2022-11-14  发布在  其他
关注(0)|答案(4)|浏览(126)

我有一个元组列表。例如:[("A",100,1),("B",101,2)]。我需要以一种简单的方式显示它。例如:"your name is: A", "Your id is: 100" .
如果有人能找到解决这个问题的方法,那将是一个很大的帮助。提前感谢。

ha5z0ras

ha5z0ras1#

最简单的方法是创建一个函数,用于处理列表中的某个元素。因此,您需要如下所示:

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

然后将此函数应用于列表中的每个元素,这意味着您要使用Map函数:

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

hgqdbh6s2#

对于一个元组,只需模式匹配所有元素,然后对它们做一些事情。如果有一个函数可以做到这一点,你可以使用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
vnzz0bqm

vnzz0bqm3#

快速和肮脏的解决方案

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(作者:@马克谢诺夫)

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

pgvzfuti4#

请尝试:

get1st (a,_,_) = a
get2nd (_,a,_) = a
get3rd (_,_,a) = a

showTuples [] = ""
showTuples (x:xs) = "Your name is:" ++ show(get1st(x)) ++ " Your ID is: " ++ show(get2nd(x)) ++ "\n" ++ showTuples xs

main = do
    let x = [("A",100,1),("B",101,2)]
    putStrLn . showTuples $ x

相关问题