[Haskell] Converting Double from String
johan.tibell at gmail.com
Mon Oct 8 06:01:19 EDT 2007
On 10/8/07, bjornie <bjorn.wikstrom at gmail.com> wrote:
> Hi! I'm kind of new to functional programming with Haskell, I'm reading a
> university course you see. Now I'm having some problems with one of our lab
> assignments, we're supposed to write a program handling numeric operations
> (addition, multiplication, and some functionality like sin and cos).
> I've made a data type;
> data Expr = Num Double | Add Expr Expr | Mul Expr Expr...
> I.e for representing the expression:
> 2.4 * (4.0 + 1.5)
> The Haskell representation is:
> Mul (Num 2.4) (Add (Num 4.0) (Num 1.5))
> My problem is to convert a String to an expression like the one above.
> I.e the String: "2.4*(4.0+1.5)"
> If we would use plain Integers there would not be a problem, since the
> Prelude function 'digitToInt' :: Char -> Int does nearly what I would like
> to do. But I'm stuck on the Doubles! How can I solve this in a smooth way?
You can use read. Here's a session from GHC's interpreter:
Prelude> read "1.0" :: Double
Since read is polymorphic (i.e. works for different types) you need to
specify the type of the result you want using ":: Double".
More information about the Haskell