default instance for IsString
Bas van Dijk
v.dijk.bas at gmail.com
Tue Apr 24 00:30:53 CEST 2012
On 23 April 2012 20:34, J. Garrett Morris <jgmorris at cs.pdx.edu> wrote:
> On Mon, Apr 23, 2012 at 9:58 AM, Yitzchak Gale <gale at sefer.org> wrote:
>> In addition, OverloadedStrings is unsound.
>
> No. OverloadedStrings treats string literals as applications of
> fromString to character list constants. fromString can throw errors,
> just like fromInteger; this is no less sound than any Haskell function
> throwing an exception.
But it would be safer if those errors were moved to compile time by
treating overloaded literals as Template Haskell splices. As in:
1
would be translated to:
$(fromIntegerLit 1)
where:
class FromIntegerLit a where
fromIntegerLit :: Integer -> Q (Exp a)
(this assumes that Exp is parameterized by the type of the value it
splices to which is currently not the case. However you can work
around this by using a Proxy or Tagged value.)
An instance for Integer is trivial:
instance FromIntegerLit Integer where
fromIntegerLit = litE . integerL
The extra safety comes when giving an instance for natural numbers, for example:
newtype Nat = Nat Integer
instance FromIntegerLit Nat where
fromIntegerLit n
| n < 0 = error "Can't have negative Nats"
| otherwise = 'Nat `appE` fromIntegerLit n
Note that the error will be thrown at compile time when the user has
written a negative Nat literal.
Regards,
Bas
More information about the Glasgow-haskell-users
mailing list