Stupid questions...

John Hughes rjmh@cs.chalmers.se
Thu, 23 Jan 2003 14:26:14 +0100 (MET)


On Thu, 23 Jan 2003, Sarah Thompson wrote:

> I need to convert Ints to Strings and vice-versa. What's the best way to do
> this? I've not found library functions for this.

Use read and show.

Prelude> show 23
"23"
Prelude> read "23" :: Int
23

(Type annotation needed on the second example because read and show are
overloaded. Normally type information from the context is sufficient to
fix the type, but when you call read at the top level like this, there is
no contextual information. You can use read and show for most built-in
types, and also for your own types if you add "deriving (Read,Show)" to
your datatype definitions).

>
> Second question:
>
> Using division over integers. I appreciate that a division operator with
> integers as arguments can not be guaranteed to return an exact integer
> result. However, if I *do* want to do integer division, how should I do it?
> Is floor(a/b) appropriate?

No. There is an operator for this: div.

Prelude> 7 `div` 3
2

John