Find the first element matching a predicate.
find takes a predicate and a foldable structure, returning the first element that satisfies the predicate wrapped in Just, or Nothing if no element matches. Its type signature is Foldable t => (a -> Bool) -> t a -> Maybe a.
find processes elements left to right and stops as soon as a matching element is found, making it efficient for large or infinite lists. It does not examine elements beyond the first match.
find is safer than head . filter p because it returns Maybe instead of potentially crashing on an empty result. For finding the index of the first match, use findIndex from Data.List. find is found in Data.List.
| Name | Description | Optional |
|---|---|---|
p |
A predicate (a -> Bool) to test each element. | No |
xs |
A foldable structure to search. | No |
import Data.List (find)
find even [1, 3, 4, 6] -- Just 4
find (> 10) [1, 2, 3] -- Nothing
find (== 'o') "hello" -- Just 'o'