Converting Data.Text to Int in Haskell
Solution 1
Looking at the text
package, I see a module called Data.Text.Read
. It seems to work:
λ> decimal (T.pack "99 bottles")
Right (99," bottles")
λ> decimal (T.pack "a digit")
Left "input does not start with a digit"
Solution 2
In other words, you want a parser that can consume Text
. There are many parsers on hackage that can consume Text, I suggest you try attoparsec.
import Data.Attoparsec.Text
parseInt = parseOnly (signed decimal)
Ralph
Physician, retired. Retired software engineer/developer (Master of Science in Computer Science). I currently program mostly in Go. I am particularly interested in functional programming. In past lives, I programmed in Java, Scala, Basic, Fortran, Pascal, Forth, C (extensively, at Bell Labs), C++, Groovy, and various assembly languages. Started programming in assembly language in 1976. I started a martial arts school in 1986 (Shojin Cuong Nhu in New Jersey) and currently teach at the Tallest Tree Dojo in Gainesville, Florida. I like to cook. I am an atheist. Email: user: grk, host: usa.net
Updated on July 29, 2022Comments
-
Ralph almost 2 years
In another question, one of the comments says, "
[Data.]Text
is becoming the de-facto textual implementation.String
is still around for legacy reasons and for simple things, but for serious textual manipulation you should be usingText
."What is the easiest way to convert a
Data.Text
to anInt
?read
will not work because theread
function always takes aString
.The best that I can come up with is:
let fortyTwo = Data.Text.pack "42" read $ Data.Text.unpack fortyTwo :: Int
Is there a better way?
-
Ralph over 11 yearsI'm not sure that will be shorter (or better), since I will still have to deal with the
Either
. That might be a reasonable replacement forreads
. -
shachaf over 11 yearsWell, you have to deal with that anyway, for most uses of
read
.read
will crash your program if it sees a malformed string, which is pretty bad (it would probably be better if its type wasRead a => a -> Maybe String
). If you're sure you want to crash your program, you can always definefoo f = fst . either error id . f
, and then usefoo decimal
instead ofdecimal
. -
Ralph over 11 yearsIn my case, I know the string is a number; it comes from a regular expression match (
"\d{2}"
). -
ДМИТРИЙ МАЛИКОВ over 11 yearsWhat is at mean «know the string is a number»? If you know that something is a number, that it is a number. These types are not equal, that why not every
String
could be converted toInt
. Maybe something likeeither (const 0) fst
will be useful, which is kindafromMaybe 0
. -
shachaf over 11 yearsThen feel free to do what I said. Crashing your program shouldn't be the default. :-) An alternative might be to combine the regular expression match and the reading into one function that returns
Either
/Maybe
. It depends on what your code is like. -
Ralph over 11 yearsPlease don't misunderstand. I like your answer.