[Haskell-beginners] Netwire fromRational

Chaddaï Fouché chaddai.fouche at gmail.com
Wed Oct 3 22:18:03 CEST 2012


On Wed, Oct 3, 2012 at 6:12 PM, Nathan Hüsken <nathan.huesken at posteo.de> wrote:
> On 10/03/2012 02:04 PM, Ertugrul Söylemez wrote:
>> When you write 'pure 1.0', then you're using,
>> say, Double's Fractional instance directly.  If you write just '1.0',
>> then you're using Wire's Fractional instance, which is just defined as:
>>
>>     fromRational = pure . fromRational
>>
>> So it's the same thing.
>
> Let me simplify the example:
>
> testW1 :: WireP () Double
> testW1 = pure 1.0
>
> testW2 :: WireP () Double
> testW2 = 1.0
>
> main = do
>   let (res, _) = stepWire 1.0 () testW
>   putStrLn $ show res
>
> (set testW to testW1 or testW2).
> When I test this with testW=testW2 I see that "fromRational" is called
> which converts a Rational (=Ration Integer) to a WireP () Double (I
> tested this by adding a "trace" to the fromRational
> Control/Wire/Classes.hs).
> This means the "1.0" is converted to a Rational and then back to a WireP
> () Double, correct?

1.0 _is_ a Rational in the first place, it's a number literal that is
not integral, so it is translated to a fraction (Rational) by the
parser then converted at runtime (only once so no worry about
efficiency) to the proper type in the Fractional type class by
fromRational, like Double, Float, Ratio, ... Here it's a WireP ()
Double.

This is how this code works :

> let
>   x :: (Fractional a) => a
>   x = 1.23
>   y = (3.5 :: Double) + x
>   z = (2.7 :: Float) + x

Note : Does GHC optimize the case were the final type is monomorphic
and standard (Double, Float) if -O2 is given ? Sure one fromRational
by literal shouldn't hurt much but...
-- 
Jedaï



More information about the Beginners mailing list