haskell - Is name reuse the only advantage of type classes? -
haskell - Is name reuse the only advantage of type classes? -
i trying understand type classes in haskell.
i pose question using simple example:
lets consider 2 datatypes, a
, b
.
lets assume a1
, a2
of type a
, b1
, b2
of type b
.
now let's assume want define functions check if a1
equals a2
, whether b1
same b2
.
for have 2 options:
option 1:
define 2 equality functions using separate names :
eqa :: -> -> bool eqa = ... eqb :: b -> b -> bool eqb = ...
now if want check if a1
equals a2
write : eqa a1 a2
, b
: eqb b1 b2
.
option 2:
we create a
, b
instances of eq
typeclass. in case can utilize ==
sign checking equality follows.
a1==a2
b1==b2
so, question : far understand sole purpose of existence of type classes can reuse function name ==
equivalence checking function, shown in alternative 2. if utilize type classes not have utilize different function names same purpose ( i.e. checking equality).
is correct? name reuse advantage type classes give? or there more type classes ?
in other words, given programme using type classes, rewrite programme isomorphic programme not utilize type classes giving separate names (i.e. eqa
, eqb
) overloaded function names (i.e. ==
in alternative 2) defined in type class instance declarations.
in simple illustration transformation replace alternative 2 alternative 1.
is such mechanic transformation possible?
is not compiler doing behind scenes?
thank reading.
edit:
thanks illuminating answers !
type classes syntax sugar, there nil cannot without them. question of how hard without them.
my favorite illustration quickcheck, uses type classes recurse on function arguments. (yes, can that.) quickcheck takes function arbitrary number of arguments, , auto-generates random test info each argument, , checks function returns true. uses type classes figure out how "randomly" generate info of each individual type. , uses clever type class tricks back upwards functions number of arguments.
you don't need this; have test1
function, , test2
function, , test3
function, etc. it's nice able have "one function" automatically figures out how many arguments there are. indeed, without type classes you'd end having write like
test_int test_double test_char test_int_int test_int_double test_int_char test_double_int test_double_double test_double_char ...
...for every possible combination of inputs. , annoying. (and luck trying extend within own code.)
really, type classes create code more high-level , declarative. makes easier see code trying do. (most of time.) there advanced cases start think maybe design isn't quite right, vast bulk of stuff, type classes work well.
haskell typeclass
Comments
Post a Comment