[Haskell-cafe] Re: [Haskell] Converting Double from String
byorgey at gmail.com
Mon Oct 8 13:14:49 EDT 2007
(moving to haskell-cafe...)
On 10/8/07, Johan Tibell <johan.tibell at gmail.com> wrote:
> 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
> > university course you see. Now I'm having some problems with one of our
> > assignments, we're supposed to write a program handling numeric
> > (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
> > to do. But I'm stuck on the Doubles! How can I solve this in a smooth
> You can use read. Here's a session from GHC's interpreter:
> $ ghci
> 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".
...although if you have something like Num (read x), you don't need the ::
Double since the typechecker can figure it out (the Num constructor has to
take a Double). Note that you would use the 'read' function to read integer
values, too; digitToInt is just for dealing with single Chars, not entire
integral values. The read function takes a String representation of
anything that is "readable" (any type that is an instance of the Read type
class) and converts it into a value of the requested type, so it works for
Doubles, Ints, Integers, lists, and so on...
Also, if I were you I'd use something other than "Num" as the name of the
data constructor for numeric values in your Expr type. Num is already used
for something else (it's the name of the general numeric type class), and
although it's legal to have the same name for both, it might lead to
confusion, especially when dealing with error messages.
Good luck with learning Haskell and with your course! If you need more help
there's also the #haskell IRC channel on
where you'll find lots of friendly people who would be glad to answer your
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe