Skip to content

Instantly share code, notes, and snippets.

@techtangents
Created January 24, 2013 12:21
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 techtangents/4620869 to your computer and use it in GitHub Desktop.
Save techtangents/4620869 to your computer and use it in GitHub Desktop.
Just learning how to instance Comonad on Non-Empty List
module Nel where
import Control.Comonad
infixr 5 :|
data Nel a = a :| [a]
toList :: Nel a -> [a]
toList (a :| as) = a : as
instance Functor Nel where
f `fmap` (x :| xs) = f x :| (f `fmap` xs)
instance Comonad Nel where
extract (a :| _) = a
duplicate nel@(_ :| []) = nel :| []
duplicate nel@(_ :| (i : t)) = nel :| (toList . duplicate $ (i :| t))
@tonymorris
Copy link

module Nel where

-- ew
-- import Control.Comonad

infixr 5 :|
data Nel a = a :| [a] 

toList :: Nel a -> [a] 
toList (a :| as) = a : as

instance Functor Nel where
  f `fmap` (x :| xs) = f x :| (f `fmap` xs) 

class Functor f => Extend f where
  extend :: (f a -> b) -> f a -> f b
  extend f = fmap f . duplicate 
  duplicate :: f a -> f (f a)
  duplicate = extend id

class Extend f => Comonad f where
  extract :: f a -> a

instance Extend Nel where
  duplicate nel@(_ :| []) = nel :| []  
  duplicate nel@(_ :| (i : t)) = nel :| (toList . duplicate $ (i :| t)) 

instance Comonad Nel where
  extract (a :| _) = a 

@tonymorris
Copy link

instance Show a => Show (Nel a) where
  show = show . toList

λ> duplicate (1 :| [2,3,4]) -- ✔
[[1,2,3,4],[2,3,4],[3,4],[4]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment