Algebraic data types: Difference between revisions
Content added Content deleted
(→{{header|Perl 6}}: new entry) |
(→{{header|Perl 6}}: random cleanup) |
||
Line 189: | Line 189: | ||
multi balance($col, $a, $x, $b) is default { [$col, $a, $x, $b] } |
multi balance($col, $a, $x, $b) is default { [$col, $a, $x, $b] } |
||
proto |
proto ins ($, @) {*} |
||
multi ins( $x, [] ) { ['R', [], $x, []] } |
multi ins( $x, [] ) { ['R', [], $x, []] } |
||
Line 198: | Line 198: | ||
} |
} |
||
sub insert( $x, $s ) { |
|||
my ([$, $a, $y, $b]) := ins($x, $s); |
my ([$, $a, $y, $b]) := ins($x, $s); |
||
['B', $a, $y, $b]; |
['B', $a, $y, $b]; |
||
Line 205: | Line 205: | ||
It does, however, use the generic comparison operators <tt>before</tt> and <tt>after</tt>, so it should work on any ordered type. |
It does, however, use the generic comparison operators <tt>before</tt> and <tt>after</tt>, so it should work on any ordered type. |
||
Here we test the code by inserting 10 integers in random order: |
|||
<lang perl6>sub MAIN { |
<lang perl6>sub MAIN { |
||
my $t = []; |
my $t = []; |
||
Line 213: | Line 213: | ||
Output: |
Output: |
||
<pre>["B", ["B", ["R", ["B", [], 1, []], 2, ["B", [], 3, []]], 4, ["B", [], 5, []]], 6, ["B", ["B", [], 7, []], 8, ["B", [], 9, ["R", [], 10, []]]]]</pre> |
<pre>["B", ["B", ["R", ["B", [], 1, []], 2, ["B", [], 3, []]], 4, ["B", [], 5, []]], 6, ["B", ["B", [], 7, []], 8, ["B", [], 9, ["R", [], 10, []]]]]</pre> |
||
After we get enums and non-class generic scopes sorted out, we hope to be able to write the proto signatures with better parametric types. It'll look more like this: |
|||
<lang perl6>role Tree[::A] { |
|||
enum Color <R B>; |
|||
proto balance (Color, Tree[A], A, Tree[A]) {*} |
|||
multi balance(B,[R,[R,$a,$x,$b],$y,$c],$z,$d) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] } |
|||
... |
|||
}</lang> |
|||
And we can, if fact, write that and get it to parse currently. It's just the ability to instantiate that role in a non-class scope that is missing. |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |