Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inclusion of typeclasses with default implementation in Haskell

Consider the following definitions:

class Foo a where
    foo :: a -> Int

class Bar a where
    bar :: a -> [Int]

Now, how do I say "every Foo is also a Bar, with bar defined by default as bar x = [foo x]" in Haskell?

(Whatever I try, the compiler gives me "Illegal instance declaration" or "Constraint is no smaller than the instance head")

Btw, I can define my Foo and Bar classes in some other way, if this would help.

like image 305
mik01aj Avatar asked Dec 01 '22 09:12

mik01aj


2 Answers

As the automatic definition of a Bar instance through a Foo instance can lead to undecidable cases for the compiler - i.e. one explicit instance and one through Foo conflicting with each other - , we need some special options to allow the desired behaviour. The rest through is quite straigtforward.

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}

class Foo a where
    foo :: a -> Int

class Bar a where
    bar :: a -> [Int]

instance (Foo a) => Bar a where
    bar x = [foo x]
like image 26
Dario Avatar answered Dec 05 '22 04:12

Dario


class Foo a where
    foo :: a -> Int

-- 'a' belongs to 'Bar' only if it belongs to 'Foo' also
class Foo a => Bar a where
    bar :: a -> [Int]
    bar x = [foo x] -- yes, you can specify default implementation

instance Foo Char where
    foo _ = 0

-- instance with default 'bar' implementation
instance Bar Char
like image 179
max taldykin Avatar answered Dec 05 '22 06:12

max taldykin