I keep getting this error error: Parse error in pattern: x
I am trying to write a function that tells me whether a given position is valid or not. Where x
is ['a'..'h']
and y
is [1..8]
.
The other answers already discussed what is wrong: you used a guard in the clause where there is no bounded x
:
isValid Position(_ y) = y
and furthermore you use quotes instead of backticks with the elem
function:
x 'elem' ['a'..'h']
So a rigorous fix would be:
isValid :: Position -> Bool
isValid (Position x y)
| x `elem` ['a'..'h'] && y `elem` [1..8] = True
| otherwise = False
Since we actually return the result of the guard, we do not need to use guards and can collapse the guards into one expression:
isValid :: Position -> Bool
isValid (Position x y) = x `elem` ['a'..'h'] && y `elem` [1..8]
Nevertheless since we here work with ranges and the second range are integers, we do not have to use elem
on a range, we can use:
isValid :: Position -> Bool
isValid (Position x y) = 'a' <= x && x <= 'h' && 1 <= y && y <= 8
For such small ranges, there will probably not be that much impact on performance, but elem
works in O(n) worst case, whereas the two bounds checks work in O(1).