I want to return the preceding element of an element in list. I am intending to get the index of parameter and use it to deprecate list such that parameter is the last element, then reverse it and take the second element of reversed list. I get error: type elemIndex
is Maybe Int
while take
function require Int
. I want to fix it or write code using simple recursion Are there a shorter code using recursion?
precedingElement :: Eq a => a -> [a] -> Maybe a
precedingElement elt lst | lst == [] = error "List is empty"
| elt `notElem` lst = Nothing
| otherwise = Just x where x = snd (reverse (take (elt `elemIndex` lst) lst))
In order to return the preceding element of the given element, you can use some pattern matching and recursion:
precedingElement _ [] = Nothing
precedingElement _ [x] = Nothing
precedingElement elt (x:y:rest)
| y == elt = Just x
| otherwise = precedingElement elt (y:rest)