The if ... then ... else ...
expression in safeH
is not well-typed:
safeH l e = if length l == 1 then head l
else e /= safeH(tail l)(head l)
The then
branch is incorrectly returning a numeric type, while the else
branch is returning a boolean type Bool
, as I think you intended.
You should add type signatures to all your top-level functions as a way of documenting what your code does, organizing your thoughts, and making errors easy to understand; the error message here is needlessly confusing because GHC infers that your code is returning some Num
type thing from the first branch, and so when the second branch returns Bool
GHC complains about the wrong thing: there being no instance of Num
for the Bool
type).
You should also read about pattern matching on lists, and take a look at the implementation of length
and think about why it's not the best way to implement your function here.
So instead of using length
and head
, start with this framework:
safeH :: [Int] -> Int -> Bool
safeH [n] e = -- the case for a 1-length list
safeH (n:ns) e = -- ???
When you get something working then try redefining it where the base case is the empty list []
.