Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell String-> Int Type Conversion [duplicate]

Tags:

haskell

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.

like image 330
Newb Avatar asked Dec 18 '13 20:12

Newb


1 Answers

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.

like image 81
Onyxite Avatar answered Nov 12 '22 14:11

Onyxite