A question about run-time errors when class members are undefined

Ben Franksen ben.franksen at online.de
Wed Oct 24 08:26:05 UTC 2018


Am 06.10.2018 um 05:18 schrieb Anthony Clayden:
> On Sat, 6 Oct 2018 at 9:47 AM, Petr Pudlák <redirect at vodafone.co.nz> wrote:
> such as the important laws between `return` and `>>=`. And then for example
>> a class with just `return` doesn't give any information what `return x`
>> means or what should be its properties.
>>
> 
> Then make Bind a superclass constraint on `return` (or vice versa, or both
> ways).
> 
> Just as the laws for Num's methods are defined in terms of equality
> 
> x + negate x == fromInteger 0          -- for example
> 
> Talking about laws is a red herring: you can't declare the laws/the
> compiler doesn't enforce them or rely on them in any way. Indeed the
> Lensaholics seem to take pleasure in building lenses that break the (van
> Laarhoven) laws.

I strongly disagree with this. Class laws are absolutely essential. They
are the main distinguishing feature of Haskell classes versus the usual
ad-hoc overloading found in most mainstream (e.g. OO) languages. Using
'+' for string concatenation? That's just a poor work-around for
languages that only support a fixed set of traditional operators. And if
you have a Monoid or Semigroup class that doesn't require or even
suggest commutativity of the operator, but clearly states that
associativity is required, then I see absolutely no reason to use '+'
for that.

That the compiler can't enforce the laws is irrelevant. Laws are a
contract and violating it is a bug. Non law-abiding lenses like
'filtered' are clearly documented with severe warnings attached. To cite
them as proof that people take pleasure in violating class laws is
ridiculous.

Granted, classes that combine multiple methods are not /required/ to
state laws. But they offer a convenient place where to put them.

>  For example, in Haskell we could have
>>
>> class (Return m, Bind m) => Monad m where
>>
>> without any methods specified. But instances of `Monad` should be only
>> such types for which `return` and `>>=` satisfy the monad laws.
>>
> 
> First: what does "satisfy the xxx laws" mean? The Haskell report and GHC's
> Prelude documentation state a bunch of laws; and it's a good discipline to
> write down laws if you're creating a class; but it's only documentation.

Why you say "only"? Documentation is essential and documentation in the
form of laws (properties) is the most useful sort of documentation. And
many class laws (though not all) /can/ be formally expressed as Haskell
code and thus tested with e.g. quickcheck.

> Arguably IO, the most commonly used Monad, breaks the Monad laws in rather
> serious ways because it imposes sequence of execution;

I think such a bold statement should be accompanied by an example that
demonstrates it.

Cheers
Ben



More information about the Haskell-prime mailing list