[Haskell-cafe] Overloading

MigMit miguelimo38 at yandex.ru
Sat Mar 9 22:58:36 CET 2013


On Mar 10, 2013, at 12:33 AM, 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).
> 
> 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).

If you really want that, you can stop ghc from importing Prelude. I haven't tested it yet, but I think

import Prelude hiding (Num)

should work. Of course, in this case you would lose all predefined instances of Num, including the ability to add integers, but you can get them back through another module.



But I would strongly suggest that you define another operator instead. Unlike C++, Haskell allows you to define as many operators as you like.


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

Well, it's the way it is usually done. This is called a "smart constructor" pattern.

> Also again, taking this way I can not provide several constructors taking inputs of different types, can I ?

Sorry, didn't get what you mean here.


More information about the Haskell-Cafe mailing list