Home > Mobile >  Is it possible to work with Maybe more expressively?
Is it possible to work with Maybe more expressively?

Time:12-19

Happy New Year to everyone! I would like to write something like this, but I know that find can return Nothing, is there any better way to write than through Just and Nothing?

snd (find (\t -> fst t == 2) [(1, 2), (2, 3)])

CodePudding user response:

You can make use of lookup :: Eq a => a -> [(a, b)] -> Maybe b which will walk over the list, and will return a Just 3 in this case if it finds the value associated with the given key, or Nothing if there is no such value.

So:

ghci> lookup 1 [(1, 2), (2, 3)]
Just 2
ghci> lookup 2 [(1, 2), (2, 3)]
Just 3
ghci> lookup 3 [(1, 2), (2, 3)]
Nothing

CodePudding user response:

Let's say we define find as:

find _ [] = Nothing
find p (x:xs)
  | p x = Just x
  | otherwise = find p xs

Now:

find (\(x, _) -> x == 2) [(1, 2), (2, 3)]
-- Just (2,3)

If you want to be able to apply a function to the Maybe result without having to explicitly match out the value, you may want something like:

(>>>) (Just x) f = Just (f x)
(>>>) Nothing _ = Nothing

Now:

find (\(x, _) -> x == 2) [(1, 2), (2, 3)] >>> snd
-- Just 3
find (\(x, _) -> x == 2) [(1, 2), (3, 3)] >>> snd >>> (* 2)
-- Nothing

For a Just x result, the function is evaluated with x as it's argument. For Nothing, Nothing is simply propagated along.

  • Related