Getting the first item in a list

2 February 2023

I was writing a parser and got distracted by monads. I came up with the following combinator to get the first item from a list.

ghci> import Control.Monad
ghci> head = foldl mplus Nothing . fmap pure
ghci> head [1, 2, 3]
Just 1
ghci> head []
Nothing
ghci> 

I quite like it.