[Haskell-beginners] Custom type classes

Chaddaï Fouché chaddai.fouche at gmail.com
Thu Jan 28 20:14:21 UTC 2016


Le mer. 27 janv. 2016 à 14:29, Guillaume Bouchard <
guillaum.bouchard+haskell at gmail.com> a écrit :

> However I discovered the `ConstraintKinds` extension which may improve
> the situation.


It does, it is in fact quite easy in modern Haskell to write a typeclass
analogue to a functor but which may have further constraints on the types
contained. But it won't be the historic "Functor" typeclass which is
ubiquitous in the Haskell packages...

{-# LANGUAGE ConstraintKinds, TypeFamilies #-}
module ConstrainedFunctor where
import GHC.Exts (Constraint)
import qualified Data.Vector.Unboxed as V

class CFunctor f where
   type FConstraint f x :: Constraint
   type instance FConstraint f x = ()
   cfmap :: (FConstraint f a, FConstraint f b) => (a -> b) -> f a -> f b

instance CFunctor V.Vector where
   type FConstraint V.Vector x = V.Unbox x
   cfmap f v = V.map f v

doubleVector :: V.Vector Int -> V.Vector Int
doubleVector = cfmap (*2)

-- 
Jedaï
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20160128/17241342/attachment.html>


More information about the Beginners mailing list