Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - Printing Multiple Non-String Variables

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?

like image 634
Newb Avatar asked Dec 18 '13 22:12

Newb


1 Answers

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
like image 111
Andy Hayden Avatar answered Oct 23 '22 05:10

Andy Hayden