Skip to content

Instantly share code, notes, and snippets.

@acfoltzer
Created April 30, 2013 20:00
Show Gist options
  • Select an option

  • Save acfoltzer/5491469 to your computer and use it in GitHub Desktop.

Select an option

Save acfoltzer/5491469 to your computer and use it in GitHub Desktop.
Example of view patterns + typeclasses for polymorphic "constructors"
{-# LANGUAGE ViewPatterns #-}
import Data.Vector (Vector)
import qualified Data.Vector as V
data ConsView a = Nil | Cons a (ConsView a)
deriving (Eq, Ord, Show)
class ConsList l where
viewCons :: l a -> ConsView a
fromCons :: ConsView a -> l a
instance ConsList ConsView where
viewCons = id
fromCons = id
instance ConsList [] where
viewCons [] = Nil
viewCons (x:xs) = Cons x (viewCons xs)
fromCons Nil = []
fromCons (Cons x xs) = x : fromCons xs
instance ConsList Vector where
viewCons v | V.null v = Nil
| otherwise = Cons (V.head v) (viewCons (V.tail v))
fromCons Nil = V.empty
fromCons (Cons x xs) = V.cons x (fromCons xs)
mapCons :: ConsList l => (a -> b) -> l a -> l b
mapCons f (viewCons -> Nil) = fromCons Nil
mapCons f (viewCons -> (Cons x xs)) = fromCons (Cons (f x) (mapCons f xs))
xs = [1..10]
ys = V.fromList [1..10]
test1 = mapCons (+2) xs
test2 = mapCons (+2) ys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment