Print List of Lists without brackets

一个人想着一个人 提交于 2021-02-04 17:52:40

问题


I am trying to print Pascals triangle up to some arbitrary row, after some thought I came up with this solution:

next xs = zipWith (+) ([0] ++ xs) (xs ++ [0])
pascal n = take n (iterate next [1])

main = do
   n <- readLn :: IO Int
   mapM_ putStrLn $ map show $ pascal n

Which works quite well, except for the printing. When I apply pascal 4 I get:

[1]
[1,1]
[1,2,1]
[1,3,3,1]

When what I really want is this:

1
1 1
1 2 1
1 3 3 1

Is there any way I can do this?


回答1:


Define your own pretty-printing function:

import Data.List (intercalate)

show' :: Show a => [a] -> String
show' = intercalate " " . map show



回答2:


You could unwords / unlines:

import Data.List
...
putStr $ unlines $ map (unwords . map show) $ pascal n


来源:https://stackoverflow.com/questions/19256244/print-list-of-lists-without-brackets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!