Skip to content

Instantly share code, notes, and snippets.

@ploeh

ploeh/Safefs.hs

Last active Aug 6, 2018
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@moodmosaic moodmosaic commented Nov 22, 2017

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.