Skip to content

Commit bdadc17

Browse files
paulstansifergraydon
authored andcommitted
---
yaml --- r: 2805 b: refs/heads/master c: 22953f5 h: refs/heads/master i: 2803: 1b1276a v: v3
1 parent e463d77 commit bdadc17

File tree

3 files changed

+41
-5
lines changed

3 files changed

+41
-5
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
---
2-
refs/heads/master: e2bb98001e5946c35952f3e1cd0b8cfbe3915cc1
2+
refs/heads/master: 22953f52faa3afb24c7024c0373a4895d9c5859b

trunk/src/lib/vec.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -220,12 +220,24 @@ fn grow_init_fn_set[T](&array[T] v, uint index, fn()->T init_fn, &T val) {
220220
v.(index) = val;
221221
}
222222

223-
fn map[T, U](&option::operator[T,U] f, &array[T] v) -> vec[U] {
224-
let vec[U] u = alloc[U](len[T](v));
223+
224+
fn map[T, U](&fn(&T) -> U f, &array[T] v) -> vec[U] {
225+
let vec[U] res = alloc[U](len[T](v));
225226
for (T ve in v) {
226-
u += [f(ve)];
227+
res += [f(ve)];
227228
}
228-
ret u;
229+
ret res;
230+
}
231+
232+
fn filter_map[T, U](&fn(&T) -> option::t[U] f, &array[T] v) -> vec[U] {
233+
let vec[U] res = []; //TODO does this work these days?
234+
for(T ve in v) {
235+
alt(f(ve)) {
236+
case (some[U](?elt)) { res += [elt]; }
237+
case (none[U]) {}
238+
}
239+
}
240+
ret res;
229241
}
230242

231243
fn map2[T,U,V](&operator2[T,U,V] f, &array[T] v0, &array[U] v1) -> vec[V] {

trunk/src/test/run-pass/lib-vec.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,35 @@ fn test_map2() {
5656
}
5757
}
5858

59+
fn test_filter_map() {
60+
fn halve(&int i) -> std::option::t[int] {
61+
if(i % 2 == 0) {
62+
ret std::option::some[int](i / 2);
63+
} else {
64+
ret std::option::none[int];
65+
}
66+
}
67+
fn halve_for_sure(&int i) -> int { ret i/2; }
68+
69+
let vec[int] all_even = [0, 2, 8, 6];
70+
let vec[int] all_odd1 = [1, 7, 3];
71+
let vec[int] all_odd2 = [];
72+
let vec[int] mix = [9, 2, 6, 7, 1, 0, 0, 3];
73+
let vec[int] mix_dest = [1, 3, 0, 0];
74+
75+
assert(std::vec::filter_map(halve, all_even) ==
76+
std::vec::map(halve_for_sure, all_even));
77+
assert(std::vec::filter_map(halve, all_odd1) == std::vec::empty[int]());
78+
assert(std::vec::filter_map(halve, all_odd2) == std::vec::empty[int]());
79+
assert(std::vec::filter_map(halve, mix) == mix_dest);
80+
}
81+
5982
fn main() {
6083
test_init_elt();
6184
test_init_fn();
6285
test_slice();
6386
test_map();
6487
test_map2();
88+
test_filter_map();
6589
}
6690

0 commit comments

Comments
 (0)