[Haskell-cafe] Associated types for number coercion

Johan Tibell johan.tibell at gmail.com
Wed Mar 20 00:05:14 CET 2013


On Tue, Mar 19, 2013 at 3:58 PM, Christopher Done <chrisdone at gmail.com>wrote:

> From the paper Fun with Type Funs, it's said:
>
> > One compelling use of such type functions is to make type
> > coercions implicit, especially in arithmetic. Suppose we want to be able
> to
> > write add a b to add two numeric values a and b even if one is an Integer
> > and the other is a Double (without writing fromIntegral explicitly).
>
> And then an Add class is defined which can dispatch at the type-level
> to appropriate functions which resolve two types into one, with a
> catch-all case for Num.
>
> Has anyone put this into a package, for all common arithmetic
> operations? I would use it. Doing arithmetic stuff in Haskell always
> feels labored because of having constantly convert between number
> types.
>

I prefer the current way (which is interestingly what Go chose as well).
With implicit casts it's easy to shoot yourself in the foot e.g. when doing
bit-twiddling. These two are different

f :: Word8 -> Int -> Word32
f w8 n = fromIntegral (w8 `shiftL` n)

f' :: Word8 -> Int -> Word32
f' w8 n = (fromIntegral w8) `shiftL` n
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20130319/5d3c9d7b/attachment.htm>


More information about the Haskell-Cafe mailing list