Haskell Searching
Searching looks through a list or a set of pairs for a value. Some searches give a plain answer, and others give a Maybe in case nothing is found.
find gives the first match
The test keeps numbers above 10. find gives the first one it meets, wrapped in Just.
import Data.List (find)
main :: IO ()
main = print (find (\x -> x > 10) [4, 15, 8, 20])Matching on a find result
A case match unwraps the Just value. The program doubles the found number.
import Data.List (find)
main :: IO ()
main = do
case find (\x -> x > 10) [4, 15, 8, 20] of
Just n -> print (n * 2)
Nothing -> print 0elem, any and all test a list
Three tests run on two lists. The answers are True, True and False in that order.
main :: IO ()
main = do
print (elem 3 [1, 2, 3])
print (any (\x -> x > 8) [1, 9, 2])
print (all (\x -> x > 0) [2, 4, -1])Example
import Data.List (find)
main :: IO ()
main = do
print (find (\x -> x < 0) [3, 7, 9])
case lookup "Ben" [("Ana", 91), ("Ben", 72)] of
Just score -> print score
Nothing -> print 0Key points
- find: a Data.List helper that gives the first item that passes a test, wrapped in a Maybe.
- Maybe result: find gives Just the item when it finds one and Nothing when it does not.
- elem: a helper that says whether a value is in a list.
- any and all: helpers that test whether at least one item, or every item, passes a test.
- lookup: a helper that finds the value paired with a key in a list of pairs.
- lookup result: lookup also gives a Maybe, since the key might not be there.
In this example, find looks for a number below 0 and finds none, so it gives Nothing. The lookup then searches the pairs for the key Ben. It finds the pair, and the case match prints its score, 72.
Note
find stops at the first match, so later matches never change its result.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does lookup "Ana" [("Ana", 91), ("Ben", 72)] give?