Haskell, declaring a function in a class

I am trying to create multiple instances for a polyorph class tree, but I am not getting it,

look, my code is:

data BTree a = BLeaf a | BBranch a (BTree a) (BTree a) deriving(Show)
data TTree a = TLeaf a | TBranch a (TTree a) (TTree a) (TTree a) deriving(Show)

class Tree a where

    getName :: a -> a -- How should i declare this function?

instance Tree (BTree a) where

    getName (BLeaf name) = name
    getName (BBranch name lhs rhs) = name

instance Tree (TTree a) where

    getName (TLeaf name) = name
    getName (TBranch name lhs mhs rhs) = name

test1 = getName (BLeaf 1)
test2 = getName (TLeaf 1)

GHCI says:

Couldn't match expected type `a' with actual type `BTree a'

So how do I declare a getName function?

+4
source share
1 answer

Use the typeclass parameter tfor the type constructor (for example, BTreeor TTree, and unlike BTree aand TTree a):

class Tree t where
    getName :: t a -> a

instance Tree BTree where
    getName (BLeaf name) = name
    getName (BBranch name lhs rhs) = name

If you want instances to change depending on the type of element a, you need multi-parameter classes:

{-# LANGUAGE MultiParamTypeClasses #-}

class Tree t a where
    getName :: t a -> a

instance Tree BTree Int where
    getName (BLeaf name) = name+1
    getName (BBranch name lhs rhs) = name*2

instance Tree BTree Char where
    getName (BLeaf name) = name
    getName (BBranch name lhs rhs) = name

You probably don't need to make this so general.

+5
source

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


All Articles