Bob Templ
Bob Templ

Reputation: 241

Print List of Lists without brackets

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?

Upvotes: 6

Views: 2180

Answers (2)

Sassa NF
Sassa NF

Reputation: 5406

You could unwords / unlines:

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

Upvotes: 6

Fixnum
Fixnum

Reputation: 1862

Define your own pretty-printing function:

import Data.List (intercalate)

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

Upvotes: 13

Related Questions