Declaring a "subclass" in Haskell -
i have troubles following simple code in haskell:
import prelude hiding (cycle). class icycle cycle :: -> instance icycle [a] cycle [] = [] cycle (x:xs) = xs ++ [x] instance icycle bool cycle true = false cycle false = true instance num => icycle cycle n = n+1 main = print $ cycle $ [1,2,3] print $ cycle $ true print $ cycle $ 42 here first 2 instance declarations work expected, third 1 triggers various sorts of errors depending on flag combinations.
i know num a no shorter icycle a , hence compiler can not finish type checking. in examples, have seen circumvented either making right-hand side bigger term or declaring class of interest subclass of other classes in first place. here, contrary, want declare existing class subclass of new one.
i wonder if there objections against kind of use of type classes. or else, if there natural solution.
for particular example, think you're best off using newtype wrap instance:
{-# language generalizednewtypederiving #-} import prelude hiding (cycle) class icycle cycle :: -> newtype succ = succ { runsucc :: } deriving (num, eq, ord, bounded, enum, show, read) newtype pred = pred { runpred :: } deriving (num, eq, ord, bounded, enum, show, read) instance enum => icycle (succ a) cycle = succ . succ . runsucc instance enum => icycle (pred a) cycle = pred . pred . runpred main = print $ cycle $ (42 :: succ int) print $ cycle $ (42 :: pred int) there multiple ways 1 cycle through numbers - succ, pred, doubling, halving. advantage of using newtype instance (making rhs "bigger", noted in question) lets have of them.
the standard library same trick product , sum monoid.
looking @ way, if possible define new superclass num, adding default implementation instances of num, you'd taking choice away implementations. in possibly way doesn't make sense.
Comments
Post a Comment