Reputation: 101
I have simple code
delta a b c = b*b - (4*a*c)
mz1 :: Double -> Double -> Double -> Double
mz1 a b c = (-b - sqrt(delta a b c)) / (2*a)
mz2 :: Double -> Double -> Double -> Double
mz2 a b c = (-b + sqrt(delta a b c)) / (2*a)
mz0 :: Double -> Double -> Double -> Double
mz0 a b c = (-b) / (2*a)
kwad :: (Enum a) => a -> a -> a -> Either Double Bool
kwad a b c
| delta a b c == 0 = Left mz0 a b c
| delta a b c < 0 = Right False
| otherwise = Left mz1 a b c
I'm just starting to learn Haskell and I have no idea how to return either Bool or Double, could anybody help?
Error is:
Couldn't match expected type `a -> a -> a -> Either Double Bool' with actual type `Either (Double -> Double -> Double -> Double) >b0' The function `Left' is applied to four arguments, but its type `(Double -> Double -> Double -> Double) -> Either (Double -> Double -> Double -> Double) b0' has only one
Upvotes: 2
Views: 968
Reputation: 1622
It is not about how to correct your code, but to show what is the main (but not only) purpose of Either a b
.
As a rule it is used as Right answer
, yes, like right answer and Left error_message
- like something is not right.
Sure, this meaning of Either a b
it is only inside the brain, mathematically Left
is the same as Right
. But not every time. For example, standard instance Monad (Either a)
uses Left
as error.
So, more pleasant code would be Either Bool Double
in you example.
But ...
If you want to write something like Left doesn'tMatter
or more simply Left ()
it is another data for this case - Maybe a
.
You could rewrite your example to ... -> Maybe Double
:
| wrong_pattern -> Nothing
| right_pattern -> Just (mz0 a b c)
Upvotes: 3
Reputation: 15028
Your kwad
function has three parameters of type Enum a => a
. In other words, they can take any a
as long as it is enumerable. Your mz
functions expects their values to be of type Double
. I would suggest changing the type signature of kwad
so it takes Double
arguments instead, like so:
kwad :: Double -> Double -> Double -> Either Double Bool
This guarantees that the values you put into kwad
are Double
s, and therefore suitable for your mz
functions as well!
You also need to wrap the argument to Left
in parentheses, like so:
Left (mz0 a b c)
This means that you want to put the entire mz0 a b c
result into a Left
, and not anything else.
Upvotes: 4