[Haskell-cafe] Overloading
Peter Caspers
pcaspers1973 at gmail.com
Sat Mar 9 21:33:24 CET 2013
Hi,
I just started playing around a bit with Haskell, so sorry in advance
for very basic (and maybe stupid) questions. Coming from the C++ world
one thing I would like to do is overloading operators. For example I
want to write (Date 6 6 1973) + (Period 2 Months) for some self defined
types Date and Period. Another example would be (Period 1 Years) +
(Period 3 Months).
Just defining the operator (+) does not work because it collides with
Prelude.+. I assume using fully qualified names would work, but that is
not what I want.
So maybe make the types instances of typeclasses? This would be Num for
(+) I guess. For the first example above it will not work however, alone
for it is not of type a -> a -> a. Also the second example does not fit,
because I would have to make Period an instance of Num, which does not
make sense, because I can not multiply Periods (for example).
Am I missing something or is that what I am trying here just impossible
by the language design (and then probably for a good reason) ?
A second question concerns the constructors in own datatypes like Date
above. Is it possible to restrict the construction of objects to
sensible inputs, i.e. reject something like Date 50 23 2013 ? My
workaround would be to provide a function say
date :: Int->Int->Int->Date
checking the input and returning a Date object or throw an error if the
input does not correspond to a real date. I could then hide the Date
constructor itself (by not exporting it). However this seems not really
elegant. Also again, taking this way I can not provide several
constructors taking inputs of different types, can I ?
Thanks a lot
Peter
More information about the Haskell-Cafe
mailing list