Skip to content

Commit 3375b8f

Browse files
paulstansifergraydon
authored andcommitted
Add list function 'has'.
1 parent 40fe44d commit 3375b8f

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/lib/list.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,19 @@ fn find[T,U](&list[T] ls,
5252
}
5353
}
5454

55+
fn has[T](&list[T] ls, &T elt) -> bool {
56+
alt(ls) {
57+
case (cons[T](?hd, ?tl)) {
58+
if (elt == hd) {
59+
ret true;
60+
} else {
61+
be has(*tl, elt);
62+
}
63+
}
64+
case (nil[T]) { ret false; }
65+
}
66+
}
67+
5568
fn length[T](&list[T] ls) -> uint {
5669
fn count[T](&T t, &uint u) -> uint {
5770
ret u + 1u;

src/test/run-pass/lib-list.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,17 @@ fn test_find_fail() {
4343
assert (res == option::none[int]);
4444
}
4545

46+
fn test_has() {
47+
auto l = from_vec([5, 8 ,6]);
48+
auto empty = list::nil[int];
49+
50+
assert (list::has(l, 5));
51+
assert (!list::has(l, 7));
52+
assert (list::has(l, 8));
53+
54+
assert (!list::has(empty, 5));
55+
}
56+
4657
fn test_length() {
4758
auto l = from_vec([0, 1, 2]);
4859
assert (list::length(l) == 3u);
@@ -54,4 +65,5 @@ fn main() {
5465
test_find_success();
5566
test_find_fail();
5667
test_length();
68+
test_has();
5769
}

0 commit comments

Comments
 (0)