4

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?

2
  • 4
    Use show, "LoadC R" ++ show i ++ "\n". Commented Oct 27, 2012 at 20:34
  • thanks, it works! but how do i print a new line? Commented Oct 27, 2012 at 20:38

1 Answer 1

13

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I run the program by "func 5". How do I print a new line?
@user1510412 hope the new edit explains a bit better for you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.