Enabling Type Classes with a Default Implementation in Haskell

Consider the following definitions:

class Foo a where
    foo :: a -> Int

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

Now, how can I say, "everyone is Fooalso Bar, and Barby default is specified as bar x = [foo x]" in Haskell?

(No matter what I try, the compiler gives me "Invalid instance declaration" or "Limit no less than the head of the instance")

Btw, I can define my classes Fooand Barin some other way, if it will help.

+3
source share
3 answers

Bar Foo - Foo, , - . .

{-# 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]
+4
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
+10

, [*] - , - . Show ​​:

instance (Show a, Show b) => Show (a,b) where

Some of the approaches to Generics allow you to simulate a common base case, and then have special special cases. SYB3 allowed this - perhaps, unfortunately, SYB3 is not a common practice of the Generics library, it is Data.Data/Data.Generics, which I think is SYB1.

[*] In the wild, the story is a little more complicated because Dario says that UndecidableInstances can turn it on.

+4
source

Source: https://habr.com/ru/post/1780843/


All Articles