An issue I sometimes encounter when programming in Haskell is sometimes I want to match a pattern against a value, but I'm only interested in a true-false information on whether a value matches a pattern (e.g. a specific data type constructor). For instance:
data Color =
RGB Int Int Int
| Greyscale Int
toHex :: Color -> String
toHex color =
if isGreyscale color then something
else somethingElse
where
isGreyscale :: Color -> Bool
isGreyscale (Greyscale _) = True
isGreyscale _ = False
whereas I'd like to do do the pattern matching without creating an unnecessary auxillary function, something along the lines of:
toHex :: Color -> String
toHex color =
if (color ~~ (Greyscale _)) then something
else somethingElse
Is there a specific syntax allowing something similar to the example above? Or perhaps an idiom that would come in handy in such situations?
ifis often pretty bad, since it forces us to take our rich data and strip everything away until we have a boolean.if conditionis essentially a very limitedcase condition of True -> ... ; False -> ..., which unlike the generalcasenever binds values to variables -- a key part of pattern matching. In your case, to get a boolean you are throwing away thevalueinsideGrayscale value, when acasewould keep it. Don't suffer from boolean blindness! - chiif null [ () | Greyscale _ <- color ] ...- luqui