pawaclawczyk / scalp

Some Scala useful classes ported to PHP.
18 stars 1 forks source link

Patterns for types with variadic constructor like Tuple #20

Closed pawaclawczyk closed 6 years ago

pawaclawczyk commented 7 years ago

Right now when type is matched it is expected that number of provided patterns must be the same as number of arguments used for construction. This behavior is unexpected when discussing types constructed with variadic number of arguments. It could be possible to provide different case pattern for different number of arguments in constructor.

In example below three commented statements will be break by InvalidPatternsNumber exception.

<?php

declare(strict_types=1);

require_once __DIR__.'/../vendor/autoload.php';

use Scalp\Collection\Tuple;
use function Scalp\PatternMatching\match;
use function Scalp\PatternMatching\Type;
use function Scalp\PatternMatching\Any;
use function Scalp\println;

function tupleName(Tuple $tuple): string
{
    return match($tuple)
        ->case(Type(Tuple::class, Any()), function () { return 'Singleton'; })
        ->case(Type(Tuple::class, Any(), Any()), function () { return 'Pair'; })
        ->case(Type(Tuple::class, Any(), Any(), Any()), function () { return 'Triple'; })
        ->case(Type(Tuple::class), function () { return 'Other tuple'; })
        ->done();
}

//println(tupleName(new Tuple(1, 2)));
println(tupleName(new Tuple(1)));
//println(tupleName(new Tuple(1, 2, 3, 4)));
//println(tupleName(new Tuple(1, 2, 3)));