Skip to content

Instantly share code, notes, and snippets.

@ploeh
Last active March 29, 2022 18:37
Show Gist options
  • Save ploeh/aeb3fbec3eef34b6a8e1 to your computer and use it in GitHub Desktop.
Save ploeh/aeb3fbec3eef34b6a8e1 to your computer and use it in GitHub Desktop.
Safe head function using Either in Haskell
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
Copy link

I've landed here while searching something related on Google. I wonder if this would suffice:

-- https://hackage.haskell.org/package/semigroups-0.18.1/docs/Data-List-NonEmpty.html
safeHead :: NonEmpty a -> a
safeHead (x :| xs) = x
-- λ safeHead (1 :| [2, 3])
-- 1

-- λ safeHead []
<interactive>:20:10: error:
    * Couldn't match expected type `NonEmpty a' with actual type `[t0]'
    * In the first argument of `safeHead', namely `[]'
      In the expression: safeHead []
      In an equation for `it': it = safeHead []
    * Relevant bindings include it :: a (bound at <interactive>:20:1)

@th3coop
Copy link

th3coop commented Mar 29, 2022

@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