Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell how to append integer like ".. ++ Integer ++ ..."

Here is my code:

func :: Integer -> String
func i = "LoadC R" ++ i ++ "\n"

But I got the error:

Couldn't match expected type `[Char]' with actual type `Integer'

How do I convert i to char?

like image 327
user1510412 Avatar asked Oct 27 '25 07:10

user1510412


1 Answers

Use show to turn a number into a string:

func :: Integer -> String
func i = "LoadC R" ++ show i ++ "\n"

show works on lots of things (but not all). To actually print this, you need to do

main = putStr (func 5)

or if you're using ghci (which I would recommend you use a lot while you write your code, testing everything as soon as you've written it), you can just write

putStr (func 5)

and it will work. (I'll explain why below.)

If you use putStrLn instead of putStr it puts an extra newline at the end. If you want a new line in what you're printing, put \n in it wherever you like.

func2 :: Integer -> String
func2 i = "\nLoadC \nR\n" ++ show i ++ "\n"

has lots of newlines in it.

Why does putStr turn \n into newlines? Well, putStr and putStrLn have type String -> IO () meaning they turn the String they're given into an IO program that puts it on the screen. In ghci, if you give it something of type IO (), it'll do it. If you give it something of another type it'll show it and then putStr that. This means that if you type

"Hello\nMum"

it has the same effect as

putStrLn (show "Hello\nMum")

whereas if you wanted the \n to be a newline, you'd need to do

putStrLn "Hello\nMum"

to stop ghci from showing it before putting it on the screen. (If you find yourself doing a lot of putStr (show x), there's a shortcut: print x.)

like image 145
AndrewC Avatar answered Oct 30 '25 08:10

AndrewC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!