简体   繁体   English

Haskell字符串的int元组列表

[英]Haskell list of int tuples to string

I'm trying to write out my list of tuples from: 我正在尝试从以下位置写出我的元组列表:

[(8,7),(5,6),(3,3),(9,4),(5,4)]

to: 至:

8 7 5 6 3 3 9 4 5 4

this is how far i've come: (Updated) 这是我走了多远:(更新)

showTuples :: Board -> String
showTuples = unwords . fmap show . concatMap (\(x,y) -> [x,y])

I know i'm suppose to map this function to all elements of my list but i can't seem to get it right. 我知道我想将此函数映射到列表中的所有元素,但似乎无法正确执行。

(UPDATE) It worked, still having problems with the quotation marks though (更新)它有效,但是引号仍然存在问题

also type of Board is: 董事会的类型还有:

type Board = [(Int,Int)]

Using pattern matching: 使用模式匹配:

type Board = [(Int, Int)]

showTuples :: Board -> String
showTuples [] = ""
showTuples (x:[]) = show(fst(x)) ++ " " ++ show(snd(x))
showTuples (x:xs) = show(fst(x)) ++ " " ++ show(snd(x)) ++ " " ++ showTuples xs

main :: IO ()
main = putStrLn . showTuples $ [(8, 7), (5, 6), (3, 3), (9, 4), (5, 4)] -- 8 7 5 6 3 3 9 4 5 4

This can be done by a foldl too. 这也可以通过foldl来完成。

Prelude> foldl (\r (x,y) -> r ++ " " ++ show x ++ " " ++ show y) "" [(8,7),(5,6),(3,3),(9,4),(5,4)]
" 8 7 5 6 3 3 9 4 5 4"

If you don't want the preceding whitespace then just do like tail $ foldl (\\r (x,y) -> ... 如果您不希望前面的空格,那么就像tail $ foldl (\\r (x,y) -> ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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