Skip to content

Instantly share code, notes, and snippets.

@astanin
Created July 17, 2013 15:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astanin/6021448 to your computer and use it in GitHub Desktop.
Save astanin/6021448 to your computer and use it in GitHub Desktop.
Generic `head`-like functions implemented with functional dependency.
{-# LANGUAGE FunctionalDependencies, FlexibleInstances #-}
module HasHeadFD where
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as BSC
class HasHeadFD c e | c -> e where
safeHead :: c -> Maybe (e)
instance HasHeadFD [a] a where
safeHead [] = Nothing
safeHead (x:_) = Just (x)
instance HasHeadFD T.Text Char where
safeHead t | T.null t = Nothing
| otherwise = Just (T.head t)
instance HasHeadFD BSC.ByteString Char where
safeHead s | BSC.null s = Nothing
| otherwise = Just (BSC.head s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment