[Haskell-cafe] Begginer question
Jules Bean
jules at jellybean.co.uk
Thu Jan 6 04:04:27 EST 2005
On 6 Jan 2005, at 01:37, Maurício wrote:
> import Complex;
>
> complex_root :: (Float, Float, Float) -> (Complex Float, Complex Float)
> complex_root (a,b,c) = (x1,x2) where {
> delta = b * b - 4 * a * c :: Float;
> sqr_delta = if delta >= 0 then (sqrt delta) :+ 0 else 0 :+ (sqrt
> delta) :: (Complex Float);
> x1 = (b + sqr_delta)/(2 * a);
> x2 = (b - sqr_delta)/(2 * a);
> }
> Couldn't match `Float' against `Complex Float'
> Expected type: Float
> Inferred type: Complex Float
> In the second argument of `(+)', namely `sqr_delta'
> In the definition of `x1': x1 = (b + sqr_delta)
> Can you help me finding what is wrong? Shouldn't "b" be converted to
> Complex Float and be summed to sqr_delta?
>
Haskell will not automatically convert b from Float to Complex Float.
The arguments of (+) should have the same type.
One alternative is to use b :+ 0 instead of b. (and similarly for a).
Another approach is to define a 'cast' function like:
toComplex x = (fromRational.toRational) x :: Complex Float
and then you can use toComplex b instead of b :+ 0. that's more
characters to type, though...
Note that sqr_delta isn't going to be defined as you expect, either.
Since delta has type Float, sqrt delta has type Float. (And sqrt -1 ::
Float is Not A Number). If you want to do it by hand this way, then you
want:
> sqr_delta = if delta >= 0 then (sqrt delta) :+ 0 else 0 :+ (sqrt
> (-delta)) :: (Complex Float);
If delta was itself already Complex, then sqrt would do the right thing
automatically.
Jules
More information about the Haskell-Cafe
mailing list