fatal(~"process did not return an error status");
}
- let prefixes = vec::map(expected_errors, |ee| {
+ let prefixes = expected_errors.iter().transform(|ee| {
fmt!("%s:%u:", testfile.to_str(), ee.line)
- });
+ }).collect::<~[~str]>();
// Scan and extract our error/warning messages,
// which look like:
use std::io::ReaderUtil;
use std::io;
use std::os;
-use std::vec;
/**
A summary of the internal state of a `FileInput` object. `line_num`
*/
// XXX: stupid, unclear name
pub fn pathify(vec: &[~str], stdin_hyphen : bool) -> ~[Option<Path>] {
- vec::map(vec, |&str : & ~str| {
- if stdin_hyphen && str == ~"-" {
+ vec.iter().transform(|str| {
+ if stdin_hyphen && "-" == *str {
None
} else {
- Some(Path(str))
+ Some(Path(*str))
}
- })
+ }).collect()
}
/**
*/
pub fn usage(brief: &str, opts: &[OptGroup]) -> ~str {
- let desc_sep = ~"\n" + " ".repeat(24);
+ let desc_sep = "\n" + " ".repeat(24);
- let rows = vec::map(opts, |optref| {
+ let mut rows = opts.iter().transform(|optref| {
let OptGroup{short_name: short_name,
long_name: long_name,
hint: hint,
return str::to_owned(brief) +
"\n\nOptions:\n" +
- rows.connect("\n") +
+ rows.collect::<~[~str]>().connect("\n") +
"\n\n";
}
} // end groups module
if n == 1 { return copy *a; }
let mut carry = 0;
- let prod = do vec::map(a.data) |ai| {
+ let prod = do a.data.iter().transform |ai| {
let (hi, lo) = BigDigit::from_uint(
(*ai as uint) * (n as uint) + (carry as uint)
);
carry = hi;
lo
- };
+ }.collect::<~[BigDigit]>();
if carry == 0 { return BigUint::new(prod) };
return BigUint::new(prod + [carry]);
}
if n_bits == 0 || self.is_zero() { return copy *self; }
let mut carry = 0;
- let shifted = do vec::map(self.data) |elem| {
+ let shifted = do self.data.iter().transform |elem| {
let (hi, lo) = BigDigit::from_uint(
(*elem as uint) << n_bits | (carry as uint)
);
carry = hi;
lo
- };
+ }.collect::<~[BigDigit]>();
if carry == 0 { return BigUint::new(shifted); }
return BigUint::new(shifted + [carry]);
}
#[test]
fn test_cmp() {
- let data = [ &[], &[1], &[2], &[-1], &[0, 1], &[2, 1], &[1, 1, 1] ]
+ let data: ~[BigUint] = [ &[], &[1], &[2], &[-1], &[0, 1], &[2, 1], &[1, 1, 1] ]
.map(|v| BigUint::from_slice(*v));
for data.iter().enumerate().advance |(i, ni)| {
for data.slice(i, data.len()).iter().enumerate().advance |(j0, nj)| {
vec::concat(map_slices(xs, || {
let f = fn_factory();
let result: ~fn(uint, &[A]) -> ~[B] =
- |_, slice| vec::map(slice, |x| f(x));
+ |_, slice| slice.iter().transform(|x| f(x)).collect();
result
}))
}
let slices = map_slices(xs, || {
let f = fn_factory();
let result: ~fn(uint, &[A]) -> ~[B] = |base, slice| {
- vec::mapi(slice, |i, x| {
+ slice.iter().enumerate().transform(|(i, x)| {
f(i + base, x)
- })
+ }).collect()
};
result
});
let s = if self.pre.is_empty() {
s
} else {
- s + "-" + self.pre.map(|i| i.to_str()).connect(".")
+ fmt!("%s-%s", s, self.pre.map(|i| i.to_str()).connect("."))
};
if self.build.is_empty() {
s
} else {
- s + "+" + self.build.map(|i| i.to_str()).connect(".")
+ fmt!("%s+%s", s, self.build.map(|i| i.to_str()).connect("."))
}
}
}
}
pub fn rpaths_to_flags(rpaths: &[Path]) -> ~[~str] {
- vec::map(rpaths, |rpath| fmt!("-Wl,-rpath,%s",rpath.to_str()))
+ rpaths.iter().transform(|rpath| fmt!("-Wl,-rpath,%s",rpath.to_str())).collect()
}
fn get_rpaths(os: session::os,
fn get_rpaths_relative_to_output(os: session::os,
output: &Path,
libs: &[Path]) -> ~[Path] {
- vec::map(libs, |a| {
- get_rpath_relative_to_output(os, output, a)
- })
+ libs.iter().transform(|a| get_rpath_relative_to_output(os, output, a)).collect()
}
pub fn get_rpath_relative_to_output(os: session::os,
}
fn get_absolute_rpaths(libs: &[Path]) -> ~[Path] {
- vec::map(libs, |a| get_absolute_rpath(a) )
+ libs.iter().transform(|a| get_absolute_rpath(a)).collect()
}
pub fn get_absolute_rpath(lib: &Path) -> Path {
ast::foreign_mod {
sort: nm.sort,
abis: nm.abis,
- view_items: vec::map(filtered_view_items, |x| fld.fold_view_item(*x)),
+ view_items: filtered_view_items.iter().transform(|x| fld.fold_view_item(*x)).collect(),
items: filtered_items
}
}
let mod_nomain = ast::_mod {
view_items: /*bad*/copy m.view_items,
- items: vec::map(m.items, |i| nomain(cx, *i)),
+ items: m.items.iter().transform(|i| nomain(cx, *i)).collect(),
};
fold::noop_fold_mod(&mod_nomain, fld)
expected_cnum += 1;
}
- // mut -> immutable hack for vec::map
- deps.slice(0, deps.len()).to_owned()
+ deps
}
// We're just going to write a list of crate 'name-hash-version's, with
ty_to_str(cx.tcx, left_ty)));
}
}
- let args = vec::map(class_fields, |class_field| {
+ let args = class_fields.iter().transform(|class_field| {
match flds.iter().find_(|f|
f.ident == class_field.ident) {
Some(f) => f.pat,
_ => wild()
}
- });
+ }).collect();
Some(vec::append(args, vec::to_owned(r.tail())))
}
}
use std::float;
use std::hashmap::{HashMap, HashSet};
-use std::vec;
//
// This pass classifies expressions by their constant-ness.
}
}
-pub fn join_all(cs: &[constness]) -> constness {
- cs.iter().fold(integral_const, |a, b| join(a, *b))
+pub fn join_all<It: Iterator<constness>>(mut cs: It) -> constness {
+ cs.fold(integral_const, |a, b| join(a, b))
}
pub fn classify(e: &expr,
ast::expr_tup(ref es) |
ast::expr_vec(ref es, ast::m_imm) => {
- join_all(vec::map(*es, |e| classify(*e, tcx)))
+ join_all(es.iter().transform(|e| classify(*e, tcx)))
}
ast::expr_vstore(e, vstore) => {
}
ast::expr_struct(_, ref fs, None) => {
- let cs = do vec::map((*fs)) |f| {
+ let cs = do fs.iter().transform |f| {
classify(f.node.expr, tcx)
};
join_all(cs)
}
fn check_foreign_fn(cx: &Context, decl: &ast::fn_decl) {
- let tys = vec::map(decl.inputs, |a| a.ty );
- let r = vec::append_one(tys, decl.output);
- for r.iter().advance |ty| {
- check_ty(cx, *ty);
+ for decl.inputs.iter().advance |in| {
+ check_ty(cx, in.ty);
}
+ check_ty(cx, decl.output)
}
match it.node {
C_struct(build_const_struct(ccx, nonnull, vals))
} else {
assert_eq!(vals.len(), 0);
- let vals = do nonnull.fields.mapi |i, &ty| {
+ let vals = do nonnull.fields.iter().enumerate().transform |(i, &ty)| {
let llty = type_of::sizing_type_of(ccx, ty);
if i == ptrfield { C_null(llty) } else { C_undef(llty) }
- };
+ }.collect::<~[ValueRef]>();
C_struct(build_const_struct(ccx, nonnull, vals))
}
}
// we care about.
if ixs.len() < 16 {
let mut small_vec = [ C_i32(0), ..16 ];
- for ixs.iter().enumerate().advance |(i, &ix)| {
- small_vec[i] = C_i32(ix as i32)
+ for small_vec.mut_iter().zip(ixs.iter()).advance |(small_vec_e, &ix)| {
+ *small_vec_e = C_i32(ix as i32);
}
InBoundsGEP(cx, base, small_vec.slice(0, ixs.len()))
} else {
- let v = do vec::map(ixs) |i| { C_i32(*i as i32) };
+ let v = do ixs.iter().transform |i| { C_i32(*i as i32) }.collect::<~[ValueRef]>();
count_insn(cx, "gepi");
InBoundsGEP(cx, base, v)
}
use std::libc::c_uint;
use std::option;
-use std::vec;
pub trait ABIInfo {
fn compute_info(&self, atys: &[Type], rty: Type, ret_def: bool) -> FnType;
impl FnType {
pub fn decl_fn(&self, decl: &fn(fnty: Type) -> ValueRef) -> ValueRef {
- let atys = vec::map(self.arg_tys, |t| t.ty);
+ let atys = self.arg_tys.iter().transform(|t| t.ty).collect::<~[Type]>();
let rty = self.ret_ty.ty;
let fnty = Type::func(atys, &rty);
let llfn = decl(fnty);
match bcx.fcx.param_substs {
Some(substs) => {
- do vec::map(params) |t| {
+ do params.iter().transform |t| {
ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
- }
+ }.collect()
}
_ => params
}
param_substs: Option<@param_substs>,
vts: typeck::vtable_res)
-> typeck::vtable_res {
- @vec::map(*vts, |ds|
- @vec::map(**ds, |d|
- resolve_vtable_under_param_substs(tcx, param_substs, copy *d)))
+ @vts.iter().transform(|ds|
+ @ds.iter().transform(
+ |d| resolve_vtable_under_param_substs(tcx, param_substs, copy *d))
+ .collect::<~[typeck::vtable_origin]>())
+ .collect::<~[typeck::vtable_param_res]>()
}
typeck::vtable_static(trait_id, tys, sub) => {
let tys = match param_substs {
Some(substs) => {
- do vec::map(tys) |t| {
+ do tys.iter().transform |t| {
ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
- }
+ }.collect()
}
_ => tys
};
}
ast::expr_tup(ref args) => {
let repr = adt::represent_type(bcx.ccx(), expr_ty(bcx, expr));
- return trans_adt(bcx, repr, 0, args.mapi(|i, arg| (i, *arg)),
- None, dest);
+ let numbered_fields: ~[(uint, @ast::expr)] =
+ args.iter().enumerate().transform(|(i, arg)| (i, *arg)).collect();
+ return trans_adt(bcx, repr, 0, numbered_fields, None, dest);
}
ast::expr_lit(@codemap::spanned {node: ast::lit_str(s), _}) => {
return tvec::trans_lit_str(bcx, expr, s, dest);
use middle::typeck;
use util::ppaux::{Repr,ty_to_str};
-use std::vec;
use syntax::ast;
use syntax::ast_map;
use syntax::ast_map::path_name;
assert!(real_substs.tps.iter().all(|t| !ty::type_needs_infer(*t)));
let _icx = push_ctxt("monomorphic_fn");
let mut must_cast = false;
- let substs = vec::map(real_substs.tps, |t| {
+ let substs = real_substs.tps.iter().transform(|t| {
match normalize_for_monomorphization(ccx.tcx, *t) {
Some(t) => { must_cast = true; t }
None => *t
}
- });
+ }).collect::<~[ty::t]>();
for real_substs.tps.iter().advance |s| { assert!(!ty::type_has_params(*s)); }
for substs.iter().advance |s| { assert!(!ty::type_has_params(*s)); }
vtables: Option<typeck::vtable_res>,
impl_did_opt: Option<ast::def_id>,
param_uses: Option<@~[type_use::type_uses]>) -> mono_id {
- let precise_param_ids = match vtables {
+ // FIXME (possibly #5801): Need a lot of type hints to get
+ // .collect() to work.
+ let precise_param_ids: ~[(ty::t, Option<@~[mono_id]>)] = match vtables {
Some(vts) => {
debug!("make_mono_id vtables=%s substs=%s",
vts.repr(ccx.tcx), substs.repr(ccx.tcx));
- vec::map_zip(*vts, substs, |vtable, subst| {
+ vts.iter().zip(substs.iter()).transform(|(vtable, subst)| {
let v = vtable.map(|vt| meth::vtable_id(ccx, vt));
(*subst, if !v.is_empty() { Some(@v) } else { None })
- })
- }
- None => {
- vec::map(substs, |subst| (*subst, None))
+ }).collect()
}
+ None => substs.iter().transform(|subst| (*subst, None::<@~[mono_id]>)).collect()
};
let param_ids = match param_uses {
Some(ref uses) => {
- vec::map_zip(precise_param_ids, **uses, |id, uses| {
+ precise_param_ids.iter().zip(uses.iter()).transform(|(id, uses)| {
if ccx.sess.no_monomorphic_collapse() {
match copy *id {
(a, b) => mono_precise(a, b)
}
}
}
- })
+ }).collect()
}
None => {
- precise_param_ids.map(|x| {
+ precise_param_ids.iter().transform(|x| {
let (a, b) = copy *x;
mono_precise(a, b)
- })
+ }).collect()
}
};
@mono_id_ {def: item, params: param_ids, impl_did_opt: impl_did_opt}
id: ast::def_id,
substs: &substs)
-> ~[VariantInfo] {
- do vec::map(*enum_variants(cx, id)) |variant_info| {
- let substd_args = vec::map(variant_info.args,
- |aty| subst(cx, substs, *aty));
+ do enum_variants(cx, id).iter().transform |variant_info| {
+ let substd_args = variant_info.args.iter()
+ .transform(|aty| subst(cx, substs, *aty)).collect();
let substd_ctor_ty = subst(cx, substs, variant_info.ctor_ty);
@VariantInfo_{args: substd_args, ctor_ty: substd_ctor_ty,
../*bad*/copy **variant_info}
- }
+ }.collect()
}
pub fn item_path_str(cx: ctxt, id: ast::def_id) -> ~str {
_
}, _) => {
let mut disr_val = -1;
- @vec::map(enum_definition.variants, |variant| {
+ @enum_definition.variants.iter().transform(|variant| {
match variant.node.kind {
ast::tuple_variant_kind(ref args) => {
let ctor_ty = node_id_to_type(cx, variant.node.id);
fail!("struct variant kinds unimpl in enum_variants")
}
}
- })
+ }).collect()
}
_ => cx.sess.bug("tag_variants: id not bound to an enum")
}
let bound_lifetime_names = bound_lifetimes(this, lifetimes);
let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names));
- let input_tys = do decl.inputs.mapi |i, a| {
+ let input_tys = do decl.inputs.iter().enumerate().transform |(i, a)| {
let expected_arg_ty = do expected_sig.chain_ref |e| {
// no guarantee that the correct number of expected args
// were supplied
if i < e.inputs.len() {Some(e.inputs[i])} else {None}
};
ty_of_arg(this, &rb, *a, expected_arg_ty)
- };
+ }.collect();
let expected_ret_ty = expected_sig.map(|e| e.output);
let output_ty = match decl.output.node {
_ => ()
}
- let tps = vec::map(tys, |ty| fcx.to_ty(*ty));
+ let tps = tys.iter().transform(|ty| fcx.to_ty(*ty)).collect::<~[ty::t]>();
match method::lookup(fcx,
expr,
base,
let mut bot_field = false;
let mut err_field = false;
- let elt_ts = do elts.mapi |i, e| {
+ let elt_ts = do elts.iter().enumerate().transform |(i, e)| {
let opt_hint = match flds {
Some(ref fs) if i < fs.len() => Some(fs[i]),
_ => None
err_field = err_field || ty::type_is_error(t);
bot_field = bot_field || ty::type_is_bot(t);
t
- };
+ }.collect();
if bot_field {
fcx.write_bot(id);
} else if err_field {
-> ~[ConvertedMethod]
{
let tcx = ccx.tcx;
- return vec::map(ms, |m| {
+ return ms.iter().transform(|m| {
let num_rcvr_ty_params = rcvr_ty_generics.type_param_defs.len();
let m_ty_generics =
ty_generics(ccx, rcvr_ty_generics.region_param, &m.generics,
tcx.methods.insert(mty.def_id, mty);
ConvertedMethod {mty: mty, id: m.id,
span: m.span, body_id: m.body.node.id}
- });
+ }).collect();
fn ty_of_method(ccx: &CrateCtxt,
m: &ast::method,
// overlapping locations.
let mut dup_vec = graph.nodes.map(|_| uint::max_value);
- graph.nodes.mapi(|idx, node| {
+ graph.nodes.iter().enumerate().transform(|(idx, node)| {
match node.value {
Value(_) => {
/* Inference successful */
}
node.value
- })
+ }).collect()
}
pub fn report_error_for_expanding_node(&mut self,
use fold;
use pass::Pass;
-use std::vec;
use syntax::ast;
use syntax::ast_map;
let doc = fold::default_seq_fold_enum(fold, doc);
doc::EnumDoc {
- variants: do vec::map(doc.variants) |variant| {
+ variants: do doc.variants.iter().transform |variant| {
let variant = copy *variant;
let desc = {
let variant = copy variant;
desc: desc,
.. variant
}
- },
+ }.collect(),
.. doc
}
}
ast_map::node_item(@ast::item {
node: ast::item_trait(_, _, ref methods), _
}, _) => {
- vec::map(*methods, |method| {
+ methods.iter().transform(|method| {
match copy *method {
ast::required(ty_m) => {
(to_str(ty_m.ident),
(to_str(m.ident), attr_parser::parse_desc(copy m.attrs))
}
}
- })
+ }).collect()
}
ast_map::node_item(@ast::item {
node: ast::item_impl(_, _, _, ref methods), _
}, _) => {
- vec::map(*methods, |method| {
+ methods.iter().transform(|method| {
(to_str(method.ident),
attr_parser::parse_desc(copy method.attrs))
- })
+ }).collect()
}
_ => fail!("unexpected item")
}
};
- do vec::map_zip(docs, attrs) |doc, attrs| {
+ do docs.iter().zip(attrs.iter()).transform |(doc, attrs)| {
assert!(doc.name == attrs.first());
let desc = attrs.second();
desc: desc,
.. copy *doc
}
- }
+ }.collect()
}
fn variantdocs_from_variants(
variants: ~[ast::variant]
) -> ~[doc::VariantDoc] {
- vec::map(variants, variantdoc_from_variant)
+ variants.iter().transform(variantdoc_from_variant).collect()
}
fn variantdoc_from_variant(variant: &ast::variant) -> doc::VariantDoc {
) -> doc::TraitDoc {
doc::TraitDoc {
item: itemdoc,
- methods: do vec::map(methods) |method| {
+ methods: do methods.iter().transform |method| {
match copy *method {
ast::required(ty_m) => {
doc::MethodDoc {
}
}
}
- }
+ }.collect()
}
}
bounds_str: None,
trait_types: ~[],
self_ty: None,
- methods: do vec::map(methods) |method| {
+ methods: do methods.iter().transform |method| {
doc::MethodDoc {
name: to_str(method.ident),
brief: None,
sig: None,
implementation: doc::Provided,
}
- }
+ }.collect()
}
}
#[cfg(test)] use extract;
#[cfg(test)] use parse;
-use std::vec;
-
pub struct Fold<T> {
ctxt: T,
fold_doc: FoldDoc<T>,
pub fn default_seq_fold_doc<T>(fold: &Fold<T>, doc: doc::Doc) -> doc::Doc {
doc::Doc {
- pages: do vec::map(doc.pages) |page| {
+ pages: do doc.pages.iter().transform |page| {
match copy *page {
doc::CratePage(doc) => {
doc::CratePage((fold.fold_crate)(fold, doc))
doc::ItemPage(fold_ItemTag(fold, doc))
}
}
- },
+ }.collect(),
.. doc
}
}
) -> doc::ModDoc {
doc::ModDoc {
item: (fold.fold_item)(fold, copy doc.item),
- items: vec::map(doc.items, |ItemTag| {
+ items: doc.items.iter().transform(|ItemTag| {
fold_ItemTag(fold, copy *ItemTag)
- }),
+ }).collect(),
.. doc
}
}
) -> doc::ModDoc {
doc::ModDoc {
item: (fold.fold_item)(fold, copy doc.item),
- items: vec::map(doc.items, |ItemTag| {
+ items: doc.items.iter().transform(|ItemTag| {
fold_ItemTag(fold, copy *ItemTag)
- }),
+ }).collect(),
.. doc
}
}
) -> doc::ModDoc {
doc::ModDoc {
item: (fold.fold_item)(fold, copy doc.item),
- items: vec::map(doc.items, |ItemTag| {
+ items: doc.items.iter().transform(|ItemTag| {
fold_ItemTag(fold, copy *ItemTag)
- }),
+ }).collect(),
.. doc
}
}
) -> doc::NmodDoc {
doc::NmodDoc {
item: (fold.fold_item)(fold, copy doc.item),
- fns: vec::map(doc.fns, |FnDoc| {
+ fns: doc.fns.iter().transform(|FnDoc| {
(fold.fold_fn)(fold, copy *FnDoc)
- }),
+ }).collect(),
.. doc
}
}
) -> doc::NmodDoc {
doc::NmodDoc {
item: (fold.fold_item)(fold, copy doc.item),
- fns: vec::map(doc.fns, |FnDoc| {
+ fns: doc.fns.iter().transform(|FnDoc| {
(fold.fold_fn)(fold, copy *FnDoc)
- }),
+ }).collect(),
.. doc
}
}
) -> doc::NmodDoc {
doc::NmodDoc {
item: (fold.fold_item)(fold, copy doc.item),
- fns: vec::map(doc.fns, |FnDoc| {
+ fns: doc.fns.iter().transform(|FnDoc| {
(fold.fold_fn)(fold, copy *FnDoc)
- }),
+ }).collect(),
.. doc
}
}
use fold;
use pass::Pass;
-use std::vec;
use syntax::ast;
use syntax::print::pprust;
use syntax::parse::token;
let srv = fold.ctxt.clone();
doc::EnumDoc {
- variants: do vec::map(doc.variants) |variant| {
+ variants: do doc.variants.iter().transform |variant| {
let sig = {
let variant = copy *variant;
do astsrv::exec(srv.clone()) |ctxt| {
sig: Some(sig),
.. copy *variant
}
- },
+ }.collect(),
.. doc
}
}
item_id: doc::AstId,
docs: ~[doc::MethodDoc]
) -> ~[doc::MethodDoc] {
- do vec::map(docs) |doc| {
+ do docs.iter().transform |doc| {
doc::MethodDoc {
sig: get_method_sig(srv.clone(), item_id, copy doc.name),
.. copy *doc
}
- }
+ }.collect()
}
fn get_method_sig(
if len <= ivals.len() {
assert_eq!(res.len(), len);
}
- assert!(ivals.slice(0u, res.len()) == vec::map(res, |x| *x as int));
+ for ivals.iter().zip(res.iter()).advance |(iv, c)| {
+ assert!(*iv == *c as int)
+ }
}
}
let mut i = 0;
// FIXME: #5898: should be called map
/// Creates a new iterator which will apply the specified function to each
- /// element returned by the first, yielding the mapped element instead. This
- /// similar to the `vec::map` function.
+ /// element returned by the first, yielding the mapped element instead.
///
/// # Example
///
use kinds::Copy;
use vec;
+use vec::ImmutableVector;
+use iterator::IteratorUtil;
pub use self::inner::*;
fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C] {
match *self {
(ref a, ref b) => {
- vec::map_zip(*a, *b, f)
+ a.iter().zip(b.iter()).transform(|(aa, bb)| f(aa, bb)).collect()
}
}
}
fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C] {
match *self {
(ref a, ref b) => {
- vec::map_zip(*a, *b, f)
+ a.iter().zip(b.iter()).transform(|(aa, bb)| f(aa, bb)).collect()
}
}
}
// Functional utilities
-/// Apply a function to each element of a vector and return the results
-pub fn map<T, U>(v: &[T], f: &fn(t: &T) -> U) -> ~[U] {
- let mut result = with_capacity(v.len());
- for v.iter().advance |elem| {
- result.push(f(elem));
- }
- result
-}
-
/// Consumes a vector, mapping it into a different vector. This function takes
/// ownership of the supplied vector `v`, moving each element into the closure
/// provided to generate a new element. The vector of new elements is then
}
result
}
-
-/// Apply a function to each element of a vector and return the results
-pub fn mapi<T, U>(v: &[T], f: &fn(uint, t: &T) -> U) -> ~[U] {
- let mut i = 0;
- do map(v) |e| {
- i += 1;
- f(i - 1, e)
- }
-}
-
/**
* Apply a function to each element of a vector and return a concatenation
* of each result vector
result
}
-/**
- * Apply a function to each pair of elements and return the results.
- * Equivalent to `map(zip(v0, v1), f)`.
- */
-pub fn map_zip<T:Copy,U:Copy,V>(v0: &[T], v1: &[U],
- f: &fn(t: &T, v: &U) -> V) -> ~[V] {
- let v0_len = v0.len();
- if v0_len != v1.len() { fail!(); }
- let mut u: ~[V] = ~[];
- let mut i = 0u;
- while i < v0_len {
- u.push(f(&v0[i], &v1[i]));
- i += 1u;
- }
- u
-}
-
pub fn filter_map<T, U>(
v: ~[T],
f: &fn(t: T) -> Option<U>) -> ~[U]
fn last(&self) -> &'self T;
fn last_opt(&self) -> Option<&'self T>;
fn rposition(&self, f: &fn(t: &T) -> bool) -> Option<uint>;
- fn map<U>(&self, f: &fn(t: &T) -> U) -> ~[U];
- fn mapi<U>(&self, f: &fn(uint, t: &T) -> U) -> ~[U];
- fn map_r<U>(&self, f: &fn(x: &T) -> U) -> ~[U];
fn flat_map<U>(&self, f: &fn(t: &T) -> ~[U]) -> ~[U];
fn filter_mapped<U:Copy>(&self, f: &fn(t: &T) -> Option<U>) -> ~[U];
unsafe fn unsafe_ref(&self, index: uint) -> *T;
fn bsearch(&self, f: &fn(&T) -> Ordering) -> Option<uint>;
+
+ fn map<U>(&self, &fn(t: &T) -> U) -> ~[U];
}
/// Extension methods for vectors
None
}
- /// Apply a function to each element of a vector and return the results
- #[inline]
- fn map<U>(&self, f: &fn(t: &T) -> U) -> ~[U] { map(*self, f) }
-
- /**
- * Apply a function to the index and value of each element in the vector
- * and return the results
- */
- fn mapi<U>(&self, f: &fn(uint, t: &T) -> U) -> ~[U] {
- mapi(*self, f)
- }
-
- #[inline]
- fn map_r<U>(&self, f: &fn(x: &T) -> U) -> ~[U] {
- let mut r = ~[];
- let mut i = 0;
- while i < self.len() {
- r.push(f(&self[i]));
- i += 1;
- }
- r
- }
-
/**
* Apply a function to each element of a vector and return a concatenation
* of each result vector
}
return None;
}
+
+ /// Deprecated, use iterators where possible
+ /// (`self.iter().transform(f)`). Apply a function to each element
+ /// of a vector and return the results.
+ fn map<U>(&self, f: &fn(t: &T) -> U) -> ~[U] {
+ self.iter().transform(f).collect()
+ }
}
#[allow(missing_doc)]
impl<A:Clone> Clone for ~[A] {
#[inline]
fn clone(&self) -> ~[A] {
- self.map(|item| item.clone())
+ self.iter().transform(|item| item.clone()).collect()
}
}
#[test]
fn test_map() {
// Test on-stack map.
- let mut v = ~[1u, 2u, 3u];
- let mut w = map(v, square_ref);
+ let v = &[1u, 2u, 3u];
+ let mut w = v.map(square_ref);
assert_eq!(w.len(), 3u);
assert_eq!(w[0], 1u);
assert_eq!(w[1], 4u);
assert_eq!(w[2], 9u);
// Test on-heap map.
- v = ~[1u, 2u, 3u, 4u, 5u];
- w = map(v, square_ref);
+ let v = ~[1u, 2u, 3u, 4u, 5u];
+ w = v.map(square_ref);
assert_eq!(w.len(), 5u);
assert_eq!(w[0], 1u);
assert_eq!(w[1], 4u);
assert_eq!(w[4], 25u);
}
- #[test]
- fn test_map_zip() {
- fn times(x: &int, y: &int) -> int { *x * *y }
- let f = times;
- let v0 = ~[1, 2, 3, 4, 5];
- let v1 = ~[5, 4, 3, 2, 1];
- let u = map_zip::<int, int, int>(v0, v1, f);
- let mut i = 0;
- while i < 5 { assert!(v0[i] * v1[i] == u[i]); i += 1; }
- }
-
#[test]
fn test_filter_mapped() {
// Test on-stack filter-map.
let mix: ~[int] = ~[9, 2, 6, 7, 1, 0, 0, 3];
let mix_dest: ~[int] = ~[1, 3, 0, 0];
assert!(filter_mapped(all_even, halve) ==
- map(all_even, halve_for_sure));
+ all_even.map(halve_for_sure));
assert_eq!(filter_mapped(all_odd1, halve), ~[]);
assert_eq!(filter_mapped(all_odd2, halve), ~[]);
assert_eq!(filter_mapped(mix, halve), mix_dest);
let mix: ~[int] = ~[9, 2, 6, 7, 1, 0, 0, 3];
let mix_dest: ~[int] = ~[1, 3, 0, 0];
assert!(filter_map(all_even, halve) ==
- map(all_even0, halve_for_sure));
+ all_even0.map(halve_for_sure));
assert_eq!(filter_map(all_odd1, halve), ~[]);
assert_eq!(filter_map(all_odd2, halve), ~[]);
assert_eq!(filter_map(mix, halve), mix_dest);
fn test_map_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
let mut i = 0;
- do map(v) |_elt| {
+ do v.map |_elt| {
if i == 2 {
fail!()
}
};
}
- #[test]
- #[ignore(windows)]
- #[should_fail]
- fn test_mapi_fail() {
- let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
- let mut i = 0;
- do mapi(v) |_i, _elt| {
- if i == 2 {
- fail!()
- }
- i += 0;
- ~[(~0, @0)]
- };
- }
-
#[test]
#[ignore(windows)]
#[should_fail]
fn test_flat_map_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
let mut i = 0;
- do map(v) |_elt| {
- if i == 2 {
- fail!()
- }
- i += 0;
- ~[(~0, @0)]
- };
- }
-
- #[test]
- #[ignore(windows)]
- #[should_fail]
- #[allow(non_implicitly_copyable_typarams)]
- fn test_map_zip_fail() {
- let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
- let mut i = 0;
- do map_zip(v, v) |_elt1, _elt2| {
+ do flat_map(v) |_elt| {
if i == 2 {
fail!()
}
// convert a list of uints to an @[ident]
// (ignores the interner completely)
fn uints_to_idents (uints: &~[uint]) -> @~[ident] {
- @uints.map(|u|{ ident {name:*u, ctxt: empty_ctxt} })
+ @uints.map(|u| ident {name:*u, ctxt: empty_ctxt})
}
fn id (u : uint, s: SyntaxContext) -> ident {
}
}
Right(ref fields) => {
- let fields = do fields.mapi |i, f| {
+ let fields = do fields.iter().enumerate().transform |(i, f)| {
cx.field_imm(span, *f, getarg(cx.str_of(*f), i))
- };
+ }.collect();
cx.expr_struct_ident(span, substr.type_ident, fields)
}
};
}
}
Right(ref fields) => {
- let fields = do fields.mapi |i, f| {
+ let fields = do fields.iter().enumerate().transform |(i, f)| {
cx.field_imm(span, *f, getarg(i))
- };
+ }.collect();
cx.expr_struct_ident(span, name, fields)
}
};
// transpose raw_fields
let fields = match raw_fields {
[self_arg, .. rest] => {
- do self_arg.mapi |i, &(opt_id, field)| {
+ do self_arg.iter().enumerate().transform |(i, &(opt_id, field))| {
let other_fields = do rest.map |l| {
match &l[i] {
&(_, ex) => ex
}
};
(opt_id, field, other_fields)
- }
+ }.collect()
}
[] => { cx.span_bug(span, "No self arguments to non-static \
method in generic `deriving`") }
}
}
let field_tuples =
- do vec::map_zip(*self_vec,
- enum_matching_fields) |&(id, self_f), &other| {
+ do self_vec.iter()
+ .zip(enum_matching_fields.iter())
+ .transform |(&(id, self_f), &other)| {
(id, self_f, other)
- };
+ }.collect();
substructure = EnumMatching(variant_index, variant, field_tuples);
}
None => {
let rand_variant = cx.expr_binary(span, ast::rem,
rv_call, variant_count);
- let mut arms = do variants.mapi |i, id_sum| {
+ let mut arms = do variants.iter().enumerate().transform |(i, id_sum)| {
let i_expr = cx.expr_uint(span, i);
let pat = cx.pat_lit(span, i_expr);
rand_thing(cx, span, ident, summary, || rand_call()))
}
}
- };
+ }.collect::<~[ast::arm]>();
// _ => {} at the end. Should never occur
arms.push(cx.arm_unreachable(span));
let next = this.proto.get_state(next_state.state);
assert!(next_state.tys.len() ==
next.generics.ty_params.len());
- let arg_names = tys.mapi(|i, _ty| cx.ident_of(~"x_"+i.to_str()));
- let args_ast = vec::map_zip(arg_names, *tys, |n, t| cx.arg(span, *n, *t));
+ let arg_names = vec::from_fn(tys.len(), |i| cx.ident_of("x_"+i.to_str()));
+ let args_ast: ~[ast::arg] = arg_names.iter().zip(tys.iter())
+ .transform(|(n, t)| cx.arg(span, *n, *t)).collect();
let pipe_ty = cx.ty_path(
path(~[this.data_name()], span)
message(ref _id, span, ref tys, this, None) => {
debug!("pipec: no next state");
- let arg_names = tys.mapi(|i, _ty| (~"x_" + i.to_str()));
+ let arg_names = vec::from_fn(tys.len(), |i| "x_" + i.to_str());
- let args_ast = do vec::map_zip(arg_names, *tys) |n, t| {
- cx.arg(span, cx.ident_of(*n), *t)
- };
+ let args_ast: ~[ast::arg] = arg_names.iter().zip(tys.iter())
+ .transform(|(n, t)| cx.arg(span, cx.ident_of(*n), *t)).collect();
let args_ast = vec::append(
~[cx.arg(span,
use std::io;
use std::result;
-use std::vec;
// These macros all relate to the file system; they either return
// the column/row/filename of the expression, or they include
let file = get_single_str_from_tts(cx, sp, tts, "include_bin!");
match io::read_whole_file(&res_rel_file(cx, sp, &Path(file))) {
result::Ok(src) => {
- let u8_exprs = vec::map(src, |char| {
- cx.expr_u8(sp, *char)
- });
+ let u8_exprs: ~[@ast::expr] = src.iter().transform(|char| cx.expr_u8(sp, *char)).collect();
base::MRExpr(cx.expr_vec(sp, u8_exprs))
}
result::Err(ref e) => {
cur_eis.push(new_ei);
}
- let matches = vec::map(ei.matches, // fresh, same size:
- |_m| ~[]);
+ let matches = vec::from_elem(ei.matches.len(), ~[]);
let ei_t = ei;
cur_eis.push(~MatcherPos {
elts: copy *matchers,
// ...nor do modules
pub fn noop_fold_mod(m: &_mod, fld: @ast_fold) -> _mod {
ast::_mod {
- view_items: vec::map(m.view_items, |x| fld.fold_view_item(*x)),
+ view_items: m.view_items.iter().transform(|x| fld.fold_view_item(*x)).collect(),
items: vec::filter_mapped(m.items, |x| fld.fold_item(*x)),
}
}
ast::foreign_mod {
sort: nm.sort,
abis: nm.abis,
- view_items: vec::map(nm.view_items, |x| fld.fold_view_item(*x)),
- items: vec::map(nm.items, |x| fld.fold_foreign_item(*x)),
+ view_items: nm.view_items.iter().transform(|x| fld.fold_view_item(*x)).collect(),
+ items: nm.items.iter().transform(|x| fld.fold_foreign_item(*x)).collect(),
}
}
}
struct_variant_kind(struct_def) => {
kind = struct_variant_kind(@ast::struct_def {
- fields: vec::map(struct_def.fields,
- |f| fld.fold_struct_field(*f)),
+ fields: struct_def.fields.iter()
+ .transform(|f| fld.fold_struct_field(*f)).collect(),
ctor_id: struct_def.ctor_id.map(|c| fld.new_id(*c))
})
}
@view_item {
@ast::view_item {
node: (self.fold_view_item)(&x.node, self as @ast_fold),
- attrs: vec::map(x.attrs, |a|
- fold_attribute_(*a, self as @ast_fold)),
+ attrs: x.attrs.iter().transform(|a| fold_attribute_(*a, self as @ast_fold)).collect(),
vis: x.vis,
span: (self.new_span)(x.span),
}
// Do the BFS.
info!("PBFS iteration %?", i);
i += 1;
- colors = do colors.mapi() |i, c| {
+ colors = do colors.iter().enumerate().transform |(i, c)| {
let c : color = *c;
match c {
white => {
let i = i as node_id;
- let neighbors = copy graph[i];
+ let neighbors = &graph[i];
let mut color = white;
gray(parent) => { black(parent) }
black(parent) => { black(parent) }
}
- }
+ }.collect()
}
// Convert the results.
- do vec::map(colors) |c| {
+ do colors.iter().transform |c| {
match *c {
white => { -1i64 }
black(parent) => { parent }
_ => { fail!("Found remaining gray nodes in BFS") }
}
- }
+ }.collect()
}
/// A parallel version of the bfs function.
// these channels will allow us to talk to each creature by 'name'/index
let to_creature: ~[Chan<Option<CreatureInfo>>] =
- vec::mapi(set, |ii, col| {
+ set.iter().enumerate().transform(|(ii, col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let ii = ii;
to_rendezvous_log.clone());
}
to_creature
- });
+ }).collect();
let mut creatures_met = 0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// xfail-pretty (extra blank line is inserted in vec::mapi call)
+// xfail-pretty the `let to_child` line gets an extra newline
// multi tasking k-nucleotide
extern mod extra;
- // initialize each sequence sorter
- let sizes = ~[1,2,3,4,6,12,18];
- let streams = vec::map(sizes, |_sz| Some(stream()));
- let mut streams = streams;
+ // initialize each sequence sorter
+ let sizes = ~[1u,2,3,4,6,12,18];
+ let mut streams = vec::from_fn(sizes.len(), |_| Some(stream::<~str>()));
let mut from_child = ~[];
- let to_child = vec::mapi(sizes, |ii, sz| {
+ let to_child = do sizes.iter().zip(streams.mut_iter()).transform |(sz, stream_ref)| {
let sz = *sz;
- let stream = util::replace(&mut streams[ii], None);
+ let stream = util::replace(stream_ref, None);
let (from_child_, to_parent_) = stream.unwrap();
from_child.push(from_child_);
};
to_child
- });
+ }.collect::<~[Chan<~[u8]>]>();
// latch stores true after we've started
// Make sure this import is warned about when at least one of its imported names
// is unused
-use std::vec::{filter, map}; //~ ERROR unused import
+use std::vec::{filter, from_elem}; //~ ERROR unused import
mod foo {
pub struct Point{x: int, y: int}
let a = 3;
ignore(a);
io::stdout().write_str("a");
- let _a = do map([2]) |&x| {
- x + 2
- };
+ let _a = from_elem(0, 0);
}
assert!(any_negative);
// Higher precedence than unary operations:
- let abs_v = do vec::map(v) |e| { e.abs() };
+ let abs_v = do v.iter().transform |e| { e.abs() }.collect::<~[float]>();
assert!(do abs_v.iter().all |e| { e.is_positive() });
assert!(!do abs_v.iter().any_ |e| { e.is_negative() });
+++ /dev/null
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use std::vec;
-
-pub fn main() {
- let v =
- vec::map_zip(~[1, 2, 3, 4, 5],
- ~[true, false, false, true, true],
- |i, b| if *b { -(*i) } else { *i } );
- error!(v.clone());
- assert_eq!(v, ~[-1, 2, 3, -4, -5]);
-}
extern mod std;
use std::str::StrVector;
-use std::{int, vec};
+use std::vec::ImmutableVector;
+use std::iterator::IteratorUtil;
+use std::int;
trait to_str {
fn to_str(&self) -> ~str;
impl<T:to_str> to_str for ~[T] {
fn to_str(&self) -> ~str {
- ~"[" + vec::map(*self, |e| e.to_str()).connect(", ") + "]"
+ fmt!("[%s]", self.iter().transform(|e| e.to_str()).collect::<~[~str]>().connect(", "))
}
}