Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Created September 23, 2021 17:06
Show Gist options
  • Select an option

  • Save carymrobbins/4e175230c7c1b3cf6ea82a60adebdf55 to your computer and use it in GitHub Desktop.

Select an option

Save carymrobbins/4e175230c7c1b3cf6ea82a60adebdf55 to your computer and use it in GitHub Desktop.
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module NEL where
import Data.List.NonEmpty (NonEmpty((:|)))
import qualified Data.List.NonEmpty as NonEmpty
nel :: (NEL a r) => a -> r
nel a = nelgo (a :|)
{-# INLINE nel #-}
class NEL a r where
nelgo :: ([a] -> NonEmpty a) -> r
instance NEL a (NonEmpty a) where
nelgo f = f []
{-# INLINE nelgo #-}
instance (NEL a r) => NEL a (a -> r) where
nelgo f a = nelgo $ f . (a :)
{-# INLINE nelgo #-}
import Data.Foldable (traverse_)
import NEL (nel)
data Foo = Bar | Baz Int | Quux Char Bool deriving (Show)
main :: IO ()
main = do
let nels :: [NonEmpty Foo]
nels =
[ nel Bar
, nel Bar (Baz 1)
, nel Bar (Baz 2) (Quux 'a' True)
]
traverse_ print nels
-- Output:
-- Bar :| []
-- Bar :| [Baz 1]
-- Bar :| [Baz 2,Quux 'a' True]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment