How to define default implementation in subclass definition in Haskell? -
i new comer of haskell , following question:
given class:
class myclass foo :: -> [a]
then have subclass more specific:
class (myclass a) => subclass foo param = [bar param] bar :: ->
but doesn't work expected. expecting default implementation setup in definition of subclass
doesn't. need define instance myclass
seperately, sounds stupid. how can achieve default implementation when know subclass satisfies property definitely?
more specifically, want express in haskell, when class satisfies properties, functions parent can have default implementation
. in example, subclass
has property bar
such know foo
defined in such way.
a more general form of question is, idea reuse using classes , instances?
i found post: inclusion of typeclasses default implementation in haskell
it's quite close, still not answering question totally , forms little bit different.
elaborating on daniel's answer:
suppose have new datatype mydata
, defined as
data mydata = d1 | d2
you want make mydata
instance of subclass
. try obvious solution first.
instance subclass mydata bar x = case x of { d1 -> d2 ; d2 -> d1 }
a quick examination of type signatures, though, reveals won't work, because type has instance of myclass
before can instance of subclass
. make mydata
instance of myclass
.
instance myclass mydata
again, raises error, because foo
included in minimal complete definition of myclass
. instance work, have manually define foo
, defeating purpose of default declaration.
in short, there no way in basic haskell98 (or haskell2010, matter). thankfully, however, ghc provides useful extension called defaultsignatures
. so, using daniel's example:
{-# language defaultsignatures #-} class myclass foo :: -> [a] default foo :: subclass => -> [a] foo param = [param] class myclass => subclass bar :: ->
and now, can define instances , work expect. downside solution default definition has defined in myclass
, necessary. definition of foo
belongs definition of myclass
(or 1 of instance declarations), if able define default declaration of foo
within definition of subclass
, haskell's type isolation broken.
Comments
Post a Comment