learn4haskell icon indicating copy to clipboard operation
learn4haskell copied to clipboard

Is this wording about typeclasses correct in Chapter3.hs?

Open bitwombat opened this issue 4 years ago • 1 comments

Chapter3 says:

As you can see, both monster and knight have similar characteristics, but they also have some differences. So it is possible to describe their common properties using typeclasses, but they are different data types in the end.

Do typeclasses describe their common properties (e.g. health) or the common actions that can be taken on them (e.g. fight)?

bitwombat avatar Nov 16 '21 23:11 bitwombat

Typeclasses can describe both 🙂

In Haskell, a typeclass for values that have Health:

class HasHealth a where
    getHealth :: a -> Health

and typeclass, describing the fight between two values of the same type:

class Fighter a where
    fight :: a -> a -> FightResult

However, as you can see, this Fighter typeclass allows to fight only values of the same type and not others. If you design the Fighter typeclass differently:

class Fighter a where
    ... something clever here ...

You can implement a top-level function (not a typeclass method) that performs fight between two values of different types:

fight :: (Fighter a, Fighter b) => a -> b -> FightResult

chshersh avatar Nov 18 '21 22:11 chshersh