[Haskell-cafe] Overloading

Anthony Cowley acowley at seas.upenn.edu
Sat Mar 9 23:04:01 CET 2013


On Mar 9, 2013, at 3:33 PM, Peter Caspers <pcaspers1973 at gmail.com> wrote:

> 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).
> 
> 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) ?

Take a look at affine spaces and additive groups in the vector-space package. There may be other treatments of torsors on hackage, but vector-space has a fairly straightforward approach.

> 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 ?

This approach -- hiding data constructors and exporting functions that perform validation -- is called "smart constructors," and is accepted practice. It isn't entirely satisfying due to interfering with pattern matching in client code, so you either need to work with projection functions for your data type, or use ViewPatterns to provide a more transparent record type at use sites.

Anthony


> 
> Thanks a lot
> Peter
> 
> 
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list