haskell - Extending algebraic data type -
note: if question somehow odd, because exposed haskell , still adapting functional mindset.
considering data type maybe
:
data myownmaybe = myownnothing | myownjust
everyone using data type write functions like
maybetolist :: myownmaybe -> [a] maybetolist myownnothing = [] maybetolist (myownjust x) = [x]
now, suppose that, @ later time, wish extend data type
data myownmaybe = myownnothing | myownjust | superpositionofnothingandjust
how make sure everyone's functions break @ compile-time?
of course, there chance somehow i'm not "getting" algebraic data types , maybe shouldn't doing @ all, considering data type action
data action = reset | send | remove
it seem adding action
add
not uncommon (and wouldn't want risk having these functions around possibly cannot handle new action
)
well, bad news first: can't it. period.
but language-agnostic; in language have break interface. there no way around it.
now, news: can go great length before have that.
you have consider export module. if, instead of exporting internal workings of it, export high-level functions, there chance can rewrite function using new data type, , go smooth.
in particular, careful when exporting data constructors. in case, don't export functions create data; exporting possibility of pattern-matching; , not ties pretty tight.
so, in example, if write functions like
myownnothing :: myownmaybe myownjust :: -> myownmaybe
and
frommyownmaybe :: myownmaybe -> b -> (a -> b) -> b frommyownmaybe myownnothing b _ = b frommyownmaybe (myownjust a) _ f = f
then it's reasonable assume able reimplement updated myownmaybe
data type; so, export functions , data type itself, don't export constructors.
the situation in benefit exporting constructors when absolutely sure data type won't ever change. example, bool
have 2 (fully defined) values: true
, false
, won't extended filenotfound
or (although edward kmett might disagree). ditto maybe
or []
.
but idea more general: stay high-level can.
Comments
Post a Comment