From 812db1ec0d97217414b4e49962e8da75761b9279 Mon Sep 17 00:00:00 2001 From: Lindsey Kuper Date: Thu, 9 Aug 2012 11:20:15 -0700 Subject: [PATCH] Example from lkuper's intern talk, but now with static methods! --- .../run-pass/typeclasses-eq-example-static.rs | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/test/run-pass/typeclasses-eq-example-static.rs diff --git a/src/test/run-pass/typeclasses-eq-example-static.rs b/src/test/run-pass/typeclasses-eq-example-static.rs new file mode 100644 index 000000000000..ff15036054db --- /dev/null +++ b/src/test/run-pass/typeclasses-eq-example-static.rs @@ -0,0 +1,55 @@ +// Example from lkuper's intern talk, August 2012 -- now with static +// methods! + +trait Equal { + static fn isEq(a: self, b: self) -> bool; +} + +enum Color { cyan, magenta, yellow, black } + +impl Color : Equal { + static fn isEq(a: Color, b: Color) -> bool { + match (a, b) { + (cyan, cyan) => { true } + (magenta, magenta) => { true } + (yellow, yellow) => { true } + (black, black) => { true } + _ => { false } + } + } +} + +enum ColorTree { + leaf(Color), + branch(@ColorTree, @ColorTree) +} + +impl ColorTree : Equal { + static fn isEq(a: ColorTree, b: ColorTree) -> bool { + match (a, b) { + (leaf(x), leaf(y)) => { isEq(x, y) } + (branch(l1, r1), branch(l2, r2)) => { + isEq(*l1, *l2) && isEq(*r1, *r2) + } + _ => { false } + } + } +} + +fn main() { + assert isEq(cyan, cyan); + assert isEq(magenta, magenta); + assert !isEq(cyan, yellow); + assert !isEq(magenta, cyan); + + assert isEq(leaf(cyan), leaf(cyan)); + assert !isEq(leaf(cyan), leaf(yellow)); + + assert isEq(branch(@leaf(magenta), @leaf(cyan)), + branch(@leaf(magenta), @leaf(cyan))); + + assert !isEq(branch(@leaf(magenta), @leaf(cyan)), + branch(@leaf(magenta), @leaf(magenta))); + + log(error, "Assertions all succeeded!"); +} \ No newline at end of file