簡體   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