Lari
Lari

Reputation: 31

How can I work with the data constructors in Haskell?

I have a problem with working with data constructors and would be happy if someone could help. So I have a data type Colors which constructors are numbers from 0 to 3. And now I want to evaluate which color is more severe (has a higher number). I tried this code

data Color = Green | Yellow | Orange | Red

severity :: Color -> Integer
severity Green = 0
severity Yellow = 1
severity Orange = 2
severity Red = 3

moreSevere :: Color -> Integer -> Bool
moreSevere xs ys = if xs > ys then True
  else False

but it doesn't work and gives me an error:

Couldn't match expected type ‘Color’ with actual type ‘Integer’
    • In the second argument of ‘(>)’, namely ‘ys’
      In the expression: xs > ys
      In the expression: if xs > ys then True else False
   |
66 | moreSevere xs ys = if xs > ys then True

does any of you know how to solve this?

Upvotes: 1

Views: 124

Answers (3)

Lari
Lari

Reputation: 31

Thank you all for the answers! I have to admit that i didn't quite understand your suggestions because this is my first semester of computer science and the things you suggested will I probably learn just later on. But I wanted to update you that I found another solution for it:

moreSevere :: Color -> Color -> Bool
moreSevere x y = if severity x > severity y then True
  else False

I think I just had to change the "Integer" for "Color". But thank you all for your help!

Upvotes: 1

chepner
chepner

Reputation: 532538

You are simply reimplementing the existing Enum and Ord type classes. The compiler can derive them for you.

data Color = Green | Yellow | Orange | Red deriving (Enum, Eq, Ord)

severity :: Color -> Integer
severity = fromEnum

moreSevere :: Color -> Color -> Bool
moreSevere = (>)

moreSevere' :: Color -> Integer -> Bool
moreSevere' c n = severity c > n

Upvotes: 3

leftaroundabout
leftaroundabout

Reputation: 120751

So I have a data type "Colors" which constructors are numbers from 0 to 3

no you don't. You have a data type whose constructors are Green, Yellow, Orange and Red – which makes sense as those are colours, whereas in my book 2 is not a colour.

What is indeed “numbers from 0 to 3” are the severities of those colours. In your function, you're apparently trying to compare a given threshold to the severity of a colour. So you need to write that too –

       ... if severity xs > ys then ...

I don't like your choice of parameter names here – we usually use xs for some list (the elements of which would be x then), but you don't have any lists. Why not

moreSevere c threshold = ...

Also, your if statement is superfluous: if cond then True else False is exactly the same as simply cond alone. So,

moreSevere c threshold = severity c > threshold

You can shorten this further, using eta-reduction, to

moreSevere c = (severity c >)

or even

moreSevere = (>) . severity

but that's a matter of taste.

Upvotes: 9

Related Questions