[Haskell-cafe] MultiCase alternative

ok at cs.otago.ac.nz ok at cs.otago.ac.nz
Fri Jun 16 06:21:41 UTC 2017

> Hello, Richard.
> As a result I did with "...where f c = ..." :) A way with "which" is
> interesting but duplicates unique constructors (A -> A', B -> B').

Yes, but if you *often* want to group constructors together, it's
still a good idea.  The alternative, which has already been suggested,
is to group them together in the original type, but you might want to
classify the alternatives in more than one way.

> Interesting, is F# can solve this problem with active pattern?

Probably.  See
for details of active patterns in F#.
The syntax is seriously twisted.  You *can* associate
data with the partitions, but it's really not obvious.
If you want to classify something more than 7 ways F# is unhelpful.
F# active patterns are not entirely unlike view patterns
only stranger.

> Pattern matching in Haskell does not seem enought flexible, for
> example, if I have `data D = D a b c d`, how can I match it without
> placeholders for `D` args? Something like `D...`? I need to write
> `D _ _ _ _` if I want to match without to bind args, right?

Yes, but (a) in all seriousness, that's not much of a problem,
surely and (b) there is an alternative.  If you write instead

data D a b c d = D { f1 :: a, f2 :: b, f3 :: c, f4 :: d }

then you can abbreviate patterns like this:

f (D{}) = ()

g (D{f1 = x}) = x

If you have enough fields for counting the placeholders to be a
problem then you have enough fields that you really *ought* to be
naming them anyway.

The problem with making pattern matching overly flexible is that
people have to read and understand this stuff.  It's a bit like
regular expressions:  POSIX regular expressions can be implemented
to take linear time (by simulating an NDFA), but they are a bit
limited, whereas Perl regular expressions are very expressive
indeed, but they can all too easily take exponential time, and it
isn't easy for John and Jane Doe programmers to tell when that is
going to happen.

Generally speaking, before proposing language changes, it's
always a good idea to see if you can solve your problem by
factoring out common stuff into a new function (or type, or
typeclass) first.

More information about the Haskell-Cafe mailing list