I have a guard and the condition is that lookup x list == something i.e. x is in the list. I tried:
| lookup x list == _ = my code here
But when loading the function I get a "pattern syntax in expression context" error?
I have a guard and the condition is that lookup x list == something i.e. x is in the list. I tried:
| lookup x list == _ = my code here
But when loading the function I get a "pattern syntax in expression context" error?
You'd use a guard like
| any ((x ==) . fst) list = ... code ...
The specific error message you get is because _
is not a valid identifier. The token _
is only valid in pattern matches, and pattern matches can only be used in places that explicitly allow them. Patterns are never an expression, so they can't be used any place that expects an arbitrary expression.
If you enable the PatternGuards
extension in GHC, you could also do what you want with syntax like:
| Just _ <- lookup x list = ... code ...
Note that I'm matching on Just
results, rather than all results. Remember that lookup
still produces a value when it doesn't find something, and that the _
pattern matches all values.
Noting that pattern guard syntax works out to be the same amount of typing here, the advantage to using it in this case is that it also lets you bind a name to the value looked up, if you so desire.
| Just y <- lookup x list = ... code that uses y...
Doing this without pattern guards would require a pattern match inside the body, which would possibly be a bit unsatisfying.
Or if you find you want to leave the gratuitous pattern-matching hidden in a library...
import Data.Maybe (fromJust)
...
| isJust (lookup x list) = ...