I want the function isValid to return True if the first and second arguments match desPlanet and currPlanet from the 3rd argument. Is there a way I can do this?
Please see -
I want the function isValid to return True if the first and second arguments match desPlanet and currPlanet from the 3rd argument. Is there a way I can do this?
Please see -
Not like that.
Patterns can only consist of 3 things:
Nothing
, Just (Just x)
, or [desPlanet, _, currPlanet]:_
, etc. The pattern will match values that were constructed with the same constructor, if all of the sub-patterns match the corresponding arguments in the value._
is a special, since it doesn't actually make the matched value available, and can thus be used multiple times across the pattern)123
, "foo"
, 'c'
, etc; which will be matched by equality checking. (If the literal is polymorphic, like numeric literals with the Num
class, then you may need an Eq
constraint)Note that there is no option to match anything against an existing variable (or against one bound elsewhere in the same pattern). The template you're trying to check against must be statically known, it can't be referred to by a variable. You either match against a specific concrete literal, or you match against a specific concrete constructor, or you just accept anything and bind it to a variable name.
However guards do allow you to check arbitrary conditions, and if the guard condition fails then the function will fall through to its next equation (just as if a pattern failed to match). So you can still do exactly what you want ("I want the function isValid to return True if the first and second arguments match desPlanet and currPlanet from the 3rd argument"); you just don't do solely with pattern matching.
For example:
isValid currPlanet desPlanet ([desPlanet', _, curPlanet'] : _) solarSys
| curPlanet == curPlanet' && desPlanet = desPlanet'
= True
isValid ... -- other equations