Haskell字符串的int元组列表

时间:2017-11-15 13:10:18

标签: string haskell tuples

我正在尝试写出我的元组列表:

[(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])

我知道我想把这个功能映射到我列表中的所有元素,但我似乎无法做到正确。

(UPDATE) 它工作,但仍然有引号问题

董事会的类型是:

type Board = [(Int,Int)]

2 个答案:

答案 0 :(得分:4)

使用模式匹配:

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

答案 1 :(得分:2)

这也可以由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) -> ...

一样
相关问题