Should I use typeclasses or not?

后端 未结 2 1274
傲寒
傲寒 2020-12-05 10:35

I have some difficulties to understand when use and when not use typeclass in my code. I mean create my own, and not use already defined typeclasses, of c

相关标签:
2条回答
  • 2020-12-05 10:57

    Why I shouldn't do something simple and only defining functions without defining new data types and typeclasses (with their instances).

    Why indeed? You could just define:

    checkState :: (a -> Bool) -> (a -> b) -> (a -> b) -> a -> b
    checkState is_repairable repairs destroy a
        = if (is_repairable a) then repairs a else destroy a
    

    People misuse type classes all the time. It doesn't mean that it's idiomatic.

    To answer your more general question, here are some rules of thumb for when to use type classes and when not to use them:

    Use type classes if:

    • There is only one correct behavior per given type

    • The type class has associated equations (i.e. "laws") that all instances must satisfy

    Don't use type classes if:

    • You are trying to just namespace things. That's what modules and namespaces are for.

    • A person using your type class cannot reason about how it will behave without looking at the source code of the instances

    • You find that the extensions you have to turn on are getting out of control

    0 讨论(0)
  • 2020-12-05 11:04

    You can often use a data type instead of a type-class, e.g.

    data Repairable a = Repairable 
       { getRepairable :: a
       , isRepairable :: Bool
       , canBeRepairedWith :: [Tool] -> Bool  -- just to give an example of a function
       } 
    

    Of course you need to pass this value explicitly, but this can be a good thing if you have multiple choices (e.g. think of Sum and Product as possible Monoids for numbers). Except that you have more or less the same expressiveness as for a type-class.

    0 讨论(0)
提交回复
热议问题