AJJ
AJJ

Reputation: 2074

Outputting a list in Haskell without the brackets, and over a range?

I have a function that returns a list, call it f n.

If I print the list, it looks like [1,2,3,4] whereas I want it to look like 1 2 3 4.

Also I want to output many lists over a range of n, so f 1 on the first line, f 2 on the second line, ... f n on the nth line.

I have my f n function working but cannot get the output to work for the life of me.

Current attempt:

main = do
    n <- readLn :: IO Int
    mapM_ putStrLn [f i | i <- [1..n]]

Upvotes: 2

Views: 3169

Answers (1)

MathematicalOrchid
MathematicalOrchid

Reputation: 62848

You can do something like

list_to_string = unwords . map show

to get the output format you want. Then instead of doing

print [1, 2, 3, 4]

you can do

putStrLn $ list_to_string $ [1, 2, 3, 4]

which should display how you want.

Edit: As for printing a range, try this:

main = do
  n <- readLn :: IO Int
  mapM_ (putStrLn . list_to_string) [ f i | i <- [1..n] ]

Upvotes: 7

Related Questions