1
+ // Example from lkuper's intern talk, August 2012 -- now with static
2
+ // methods!
3
+
4
+ trait Equal {
5
+ static fn isEq( a: self , b: self ) -> bool ;
6
+ }
7
+
8
+ enum Color { cyan, magenta, yellow, black }
9
+
10
+ impl Color : Equal {
11
+ static fn isEq( a : Color , b : Color ) -> bool {
12
+ match ( a , b ) {
13
+ ( cyan , cyan ) => { true }
14
+ ( magenta, magenta) => { true }
15
+ ( yellow, yellow) => { true }
16
+ ( black, black) => { true }
17
+ _ => { false }
18
+ }
19
+ }
20
+ }
21
+
22
+ enum ColorTree {
23
+ leaf( Color ) ,
24
+ branch( @ColorTree , @ColorTree )
25
+ }
26
+
27
+ impl ColorTree : Equal {
28
+ static fn isEq( a: ColorTree , b: ColorTree ) -> bool {
29
+ match ( a , b ) {
30
+ ( leaf ( x ) , leaf ( y ) ) => { isEq( x , y ) }
31
+ ( branch ( l1 , r1 ) , branch ( l2 , r2 ) ) => {
32
+ isEq( * l1 , * l2 ) && isEq ( * r1 , * r2 )
33
+ }
34
+ _ => { false }
35
+ }
36
+ }
37
+ }
38
+
39
+ fn main ( ) {
40
+ assert isEq( cyan, cyan) ;
41
+ assert isEq( magenta, magenta) ;
42
+ assert ! isEq( cyan, yellow) ;
43
+ assert ! isEq( magenta, cyan) ;
44
+
45
+ assert isEq( leaf ( cyan) , leaf ( cyan) ) ;
46
+ assert ! isEq( leaf( cyan) , leaf( yellow) ) ;
47
+
48
+ assert isEq( branch ( @leaf ( magenta) , @leaf ( cyan) ) ,
49
+ branch ( @leaf ( magenta) , @leaf ( cyan) ) ) ;
50
+
51
+ assert ! isEq( branch( @leaf( magenta) , @leaf( cyan) ) ,
52
+ branch( @leaf( magenta) , @leaf( magenta) ) ) ;
53
+
54
+ log ( error, "Assertions all succeeded!" ) ;
55
+ }
0 commit comments