7

I am writing a program that reads two integers from the command line, doubles them, and then prints them back out. So my program reads in the Args, casts them to Ints, and then doubles them. My question is about outputting: in Python, I could just write:

>>>a = 9
>>>b = 10
>>>print a,b
9 10

which gives me satisfactory output. In Haskell, there is a similar print statement to print a given variable - e.g.

Prelude> let a = 10
Prelude> print a
10

I am wondering if there is a Haskell equivalent to python print a,b, so I can print multiple variables at once. Otherwise, I've had to do is convert the doubled Ints back to strings, and then write:
putStrLn (doubledint1 ++ " " ++ doubledint2)

Is there a way to print multiple variables that is more effective than the laborious method of manually converting to strings, and then calling putStrLn on their concatenation?

Newb
  • 2,810
  • 3
  • 21
  • 35

3 Answers3

5

You can use mapM_, either over print or putStr.show:

Prelude> mapM_ print [a, b]
9
10

mapM_ (putStr . show) [a, b]
910Prelude>

See input-output section of learn you a haskell.

You could get the spaces and new line:

Prelude> let pylike_print ints = mapM_ (\x -> putStr $ (show x) ++ " ") ints >> putStr "\n"
Prelude> pylike_print [9, 10]
9 10
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • I have two different types, `Book` and `Creator`. How do I print out `warAndPeace` which is a `Book` and `leoTolstoy` who is a `Creator`? I tried `mapM_ print (warAndPeace, leoTolstoy)` in `main::IO()` but it only prints `leoTolstoy` – mLstudent33 Dec 17 '21 at 02:59
2

You can convert each int in your list to a string using show and create the joined string using intercalate:

import Data.List

let ints = [9, 10]
print $ intercalate " " (map show ints)

As @raymonad points out in the comments, you should use putStrLn instead of print if you don't want the output string to be quoted.

Lee
  • 142,018
  • 20
  • 234
  • 287
2

Alternatively, you could use printf: (from Text.Printf)

printf "%d %d" a b
Justin L.
  • 13,510
  • 5
  • 48
  • 83