1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
//! Operations on tuples
trait TupleOps<T,U> {
pure fn first() -> T;
pure fn second() -> U;
pure fn swap() -> (U, T);
}
impl<T: copy, U: copy> (T, U): TupleOps<T,U> {
/// Return the first element of self
pure fn first() -> T {
let (t, _) = self;
return t;
}
/// Return the second element of self
pure fn second() -> U {
let (_, u) = self;
return u;
}
/// Return the results of swapping the two elements of self
pure fn swap() -> (U, T) {
let (t, u) = self;
return (u, t);
}
}
trait ExtendedTupleOps<A,B> {
fn zip() -> ~[(A, B)];
fn map<C>(f: fn(A, B) -> C) -> ~[C];
}
impl<A: copy, B: copy> (&[A], &[B]): ExtendedTupleOps<A,B> {
fn zip() -> ~[(A, B)] {
let (a, b) = self;
vec::zip_slice(a, b)
}
fn map<C>(f: fn(A, B) -> C) -> ~[C] {
let (a, b) = self;
vec::map2(a, b, f)
}
}
impl<A: copy, B: copy> (~[A], ~[B]): ExtendedTupleOps<A,B> {
fn zip() -> ~[(A, B)] {
let (a, b) = self;
vec::zip(a, b)
}
fn map<C>(f: fn(A, B) -> C) -> ~[C] {
let (a, b) = self;
vec::map2(a, b, f)
}
}
#[test]
fn test_tuple() {
assert (948, 4039.48).first() == 948;
assert (34.5, ~"foo").second() == ~"foo";
assert ('a', 2).swap() == (2, 'a');
}
|