繁体   English   中英

Haskell字符串的int元组列表

[英]Haskell list of int tuples to string

我正在尝试从以下位置写出我的元组列表:

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

至:

8 7 5 6 3 3 9 4 5 4

这是我走了多远:(更新)

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

我知道我想将此函数映射到列表中的所有元素,但似乎无法正确执行。

(更新)它有效,但是引号仍然存在问题

董事会的类型还有:

type Board = [(Int,Int)]

使用模式匹配:

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

这也可以通过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"

如果您不希望前面的空格,那么就像tail $ foldl (\\r (x,y) -> ...

暂无
暂无

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

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