Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Data.Text to Int in Haskell

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 using Text."

What is the easiest way to convert a Data.Text to an Int? read will not work because the read function always takes a String.

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?

like image 515
Ralph Avatar asked Jan 12 '13 19:01

Ralph


People also ask

How do I convert a String to an integer in Haskell?

int i = int. Parse(s);

How do I convert a String to a float in Haskell?

The unary + operator converts its argument to a double precision floating point. String floatString = "14.5"; float x = Float. parseFloat(floatString); double y = Double. parseFloat(floatString);

How do you use strings in Haskell?

In Haskell a String is just a list of Char s, indeed type String = [Char] . String is just an "alias" for such list. So all functions you define on lists work on strings, given the elements of that list are Char s.

What is text Haskell?

Text is a more efficient alternative to Haskell's standard String type. String is defined as a linked list of characters in the standard Prelude, per the Haskell Report: type String = [Char]


1 Answers

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" 
like image 77
shachaf Avatar answered Oct 14 '22 01:10

shachaf