Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is this wording about typeclasses correct in Chapter3.hs? #505

Open
bitwombat opened this issue Nov 16, 2021 · 1 comment
Open

Is this wording about typeclasses correct in Chapter3.hs? #505

bitwombat opened this issue Nov 16, 2021 · 1 comment
Labels
question Further information is requested

Comments

@bitwombat
Copy link

bitwombat commented Nov 16, 2021

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)?

@chshersh chshersh added the question Further information is requested label Nov 18, 2021
@chshersh
Copy link
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants