]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/typeclasses-eq-example-static.rs
63a59b6f750ea6490f38f2717bd8881d9dd3d120
[rust.git] / src / test / run-pass / typeclasses-eq-example-static.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 // Example from lkuper's intern talk, August 2012 -- now with static
13 // methods!
14 use Color::{cyan, magenta, yellow, black};
15 use ColorTree::{leaf, branch};
16
17 trait Equal {
18     fn isEq(a: &Self, b: &Self) -> bool;
19 }
20
21 #[derive(Clone)]
22 enum Color { cyan, magenta, yellow, black }
23
24 impl Copy for Color {}
25
26 impl Equal for Color {
27     fn isEq(a: &Color, b: &Color) -> bool {
28         match (*a, *b) {
29           (cyan, cyan)       => { true  }
30           (magenta, magenta) => { true  }
31           (yellow, yellow)   => { true  }
32           (black, black)     => { true  }
33           _                  => { false }
34         }
35     }
36 }
37
38 #[derive(Clone)]
39 enum ColorTree {
40     leaf(Color),
41     branch(Box<ColorTree>, Box<ColorTree>)
42 }
43
44 impl Equal for ColorTree {
45     fn isEq(a: &ColorTree, b: &ColorTree) -> bool {
46         match (a, b) {
47           (&leaf(ref x), &leaf(ref y)) => {
48               Equal::isEq(&(*x).clone(), &(*y).clone())
49           }
50           (&branch(ref l1, ref r1), &branch(ref l2, ref r2)) => {
51             Equal::isEq(&(**l1).clone(), &(**l2).clone()) &&
52                 Equal::isEq(&(**r1).clone(), &(**r2).clone())
53           }
54           _ => { false }
55         }
56     }
57 }
58
59 pub fn main() {
60     assert!(Equal::isEq(&cyan, &cyan));
61     assert!(Equal::isEq(&magenta, &magenta));
62     assert!(!Equal::isEq(&cyan, &yellow));
63     assert!(!Equal::isEq(&magenta, &cyan));
64
65     assert!(Equal::isEq(&leaf(cyan), &leaf(cyan)));
66     assert!(!Equal::isEq(&leaf(cyan), &leaf(yellow)));
67
68     assert!(Equal::isEq(&branch(box leaf(magenta), box leaf(cyan)),
69                 &branch(box leaf(magenta), box leaf(cyan))));
70
71     assert!(!Equal::isEq(&branch(box leaf(magenta), box leaf(cyan)),
72                  &branch(box leaf(magenta), box leaf(magenta))));
73
74     println!("Assertions all succeeded!");
75 }