Last active
March 29, 2022 18:37
-
-
Save ploeh/aeb3fbec3eef34b6a8e1 to your computer and use it in GitHub Desktop.
Safe head function using Either in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
safeHead [] = Left "The list was empty. No head is available." | |
safeHead xs = Right . head $ xs | |
-- Sample usage from GHCI: | |
-- | |
-- *Safefs> safeHead [1..3] | |
-- Right 1 | |
-- *Safefs> safeHead [7] | |
-- Right 7 | |
-- *Safefs> safeHead [2, 3] | |
-- Right 2 | |
-- *Safefs> safeHead [] | |
-- Left "The list was empty. No head is available." |
@moodmosaic , you're not wrong. I think this already exists in Haskell base: https://hackage.haskell.org/package/base-4.16.1.0/docs/Data-List-NonEmpty.html#v:head
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've landed here while searching something related on Google. I wonder if this would suffice: