Skip to content

Commit e589fcf

Browse files
committed
Implemented list::len() based on Container trait
1 parent 197116d commit e589fcf

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

src/libcollections/list.rs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
//! A standard, garbage-collected linked list.
1212
13+
use std::container::Container;
14+
1315
#[deriving(Clone, Eq)]
1416
#[allow(missing_doc)]
1517
pub enum List<T> {
@@ -53,6 +55,11 @@ impl<T> List<T> {
5355
}
5456
}
5557

58+
impl<T> Container for List<T> {
59+
/// Returns the length of a list
60+
fn len(&self) -> uint { self.iter().len() }
61+
}
62+
5663
/// Returns true if a list contains an element with the given value
5764
pub fn has<T:Eq>(list: @List<T>, element: T) -> bool {
5865
let mut found = false;
@@ -70,13 +77,6 @@ pub fn is_empty<T>(list: @List<T>) -> bool {
7077
}
7178
}
7279

73-
/// Returns the length of a list
74-
pub fn len<T>(list: @List<T>) -> uint {
75-
let mut count = 0u;
76-
iter(list, |_e| count += 1u);
77-
count
78-
}
79-
8080
/// Returns all but the first element of a list
8181
pub fn tail<T>(list: @List<T>) -> @List<T> {
8282
match *list {
@@ -252,10 +252,11 @@ mod tests {
252252

253253
#[test]
254254
fn test_len() {
255-
let list = @List::from_vec([0, 1, 2]);
256-
let empty = @list::Nil::<int>;
257-
assert_eq!(list::len(list), 3u);
258-
assert_eq!(list::len(empty), 0u);
255+
let empty = Nil::<int>;
256+
assert_eq!(empty.len(), 0u);
257+
258+
let list = List::from_vec([0, 1, 2]);
259+
assert_eq!(list.len(), 3u);
259260
}
260261

261262
#[test]

0 commit comments

Comments
 (0)