Pattern matching as a library
Jacob Carlborg via Digitalmars-d
digitalmars-d at puremagic.com
Sun Mar 13 13:26:27 PDT 2016
On 13/03/16 03:33, Simen Kjaeraas wrote:
> The match function goes through the list of patterns and for each one
> asks the tuple if opMatch returns true for that pattern. If it does, the
> function assigned that pattern is called with the values assigned to args.
>
> opMatch here is checking for each element of the pattern if it matches
> the corresponding element of the tuple. Since the pattern is available
> at compile-time, opMatch can deny patterns it doesn't like (e.g. trying
> to match a Tuple!(int, string) with a string).
>
> The match function is really only a framework for having similar
> matching syntax for dissimilar types.
>
> If the capability of matching patterns to types were in the match
> function, how could a user type override it? Matching on a
> Tuple!(string, string) is different from matching on an
> Algebraic!(int[], Foo*) is different from matching on a specialized user
> type that wants to do something real weird (I'm not sure what that'd be,
> but I'm sure there are people who will want to).
I misinterpreted the code.
> That works. I feel the grouping is looser than in my example, and that
> the pattern doesn't stand out from the rest of the expression, but it
> certainly works, and there are some benefits to that syntax.
Yeah, that's the downside.
>> If the pull request for inspecting templates ever will be merged it
>> won't be necessary to have typed lambdas:
>>
>> auto b = match!(a,
>> int, "foo", (i) => 1,
>> _, _, () => 0,
>> );
>
> There's a problem using that syntax? It works for me in a toy example:
I've not actually tried that particular syntax. I came to think of it
when I saw your syntax. I've mostly been experimenting with the syntax
later in my post.
--
/Jacob Carlborg
More information about the Digitalmars-d
mailing list