-1

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 -

Error message

j1-lee
  • 13,764
  • 3
  • 14
  • 26
Fuoad
  • 1
  • 1

1 Answers1

3

Not like that.

Patterns can only consist of 3 things:

  1. A constructor, applied to as many sub-patterns as the constructor has arguments. Examples are 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.
  2. A variable, which will simply match anything and make the matched value available under that variable name. (The variable _ is a special, since it doesn't actually make the matched value available, and can thus be used multiple times across the pattern)
  3. A literal like 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
Ben
  • 68,572
  • 20
  • 126
  • 174