35

I'm taking my first few steps in Haskell, and I'm trying to convert a string to an integer, but I'm not managing. I've looked at similar questions and I'm still not sure.

All I want to do is convert, e.g. '6' or "271" to integers, that is, 6 or 271 respectively. How do I do this?

The analogue would be that in Python, I could do this easily: e.g.int("2723") would get the job done.

2
  • 4
    You're looking for read Commented Dec 18, 2013 at 20:17
  • 3
    The first result if you google "haskell string to int" is a stackoverflow post explaining how to use read. Commented Dec 18, 2013 at 20:20

1 Answer 1

60

If you know that the string is a valid integer, or you don't mind it blowing up if that's not the case, read will work. If you are unfamiliar with Haskell's typeclasses, just know that you might have to tell Haskell what type you want to read it as:

main :: IO ()
main = do
  let x = read "271" :: Integer
  print x

You don't always have to do this, if Haskell has some other way of knowing what type you want, like if you proceed to do arithmetic with it.

If you don't know for sure that the string is a valid number, recent versions of base (not sure since when) include a function readMaybe that will safely return Nothing if it is not a readable integer.

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

3 Comments

Thanks, though my question is a duplicate and the answer has been supplied already. Can you link me to a resource for the other way around? (Int -> String?)
@Newb For that you want show.
@Newb The opposite of read is show. Most tutorials cover these functions pretty early on, what have you looked at so far? it might be best to work through a few before trying to dive right in.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.