std: remove fold[lr] in favour of iterators

This commit is contained in:
Huon Wilson 2013-06-08 15:12:39 +10:00
parent 65c7c58c8f
commit ed299af625
25 changed files with 72 additions and 193 deletions

View File

@ -354,7 +354,7 @@ a single large vector of floats. Each task needs the full vector to perform its
use extra::arc::ARC;
fn pnorm(nums: &~[float], p: uint) -> float {
(vec::foldl(0.0, *nums, |a,b| a+(*b).pow(p as float) )).pow(1f / (p as float))
nums.iter().fold(0.0, |a,b| a+(*b).pow(p as float) ).pow(1f / (p as float))
}
fn main() {

View File

@ -20,6 +20,7 @@ Do not use ==, !=, <, etc on doubly-linked lists -- it may not terminate.
use core::prelude::*;
use core::iterator::IteratorUtil;
use core::managed;
use core::old_iter;
use core::vec;
@ -110,7 +111,7 @@ pub fn from_elem<T>(data: T) -> @mut DList<T> {
/// Creates a new dlist from a vector of elements, maintaining the same order
pub fn from_vec<T:Copy>(vec: &[T]) -> @mut DList<T> {
do vec::foldl(DList(), vec) |list,data| {
do vec.iter().fold(DList()) |list,data| {
list.push(*data); // Iterating left-to-right -- add newly to the tail.
list
}

View File

@ -12,7 +12,7 @@
use core::prelude::*;
use core::vec;
use core::iterator::IteratorUtil;
#[deriving(Eq)]
pub enum List<T> {
@ -28,7 +28,7 @@ pub enum MutList<T> {
/// Create a list from a vector
pub fn from_vec<T:Copy>(v: &[T]) -> @List<T> {
vec::foldr(v, @Nil::<T>, |h, t| @Cons(*h, t))
v.rev_iter().fold(@Nil::<T>, |t, h| @Cons(*h, t))
}
/**

View File

@ -12,6 +12,7 @@
use core::prelude::*;
use core::iterator::*;
use core::vec;
use core::f64;
use core::cmp;
@ -36,17 +37,17 @@ pub trait Stats {
impl<'self> Stats for &'self [f64] {
fn sum(self) -> f64 {
vec::foldl(0.0, self, |p,q| p + *q)
self.iter().fold(0.0, |p,q| p + *q)
}
fn min(self) -> f64 {
assert!(self.len() != 0);
vec::foldl(self[0], self, |p,q| cmp::min(p, *q))
self.iter().fold(self[0], |p,q| cmp::min(p, *q))
}
fn max(self) -> f64 {
assert!(self.len() != 0);
vec::foldl(self[0], self, |p,q| cmp::max(p, *q))
self.iter().fold(self[0], |p,q| cmp::max(p, *q))
}
fn mean(self) -> f64 {

View File

@ -18,6 +18,7 @@ use middle;
use syntax::{ast, ast_map, ast_util, visit};
use syntax::ast::*;
use core::iterator::IteratorUtil;
use core::float;
use core::hashmap::{HashMap, HashSet};
use core::vec;
@ -72,7 +73,7 @@ pub fn join(a: constness, b: constness) -> constness {
}
pub fn join_all(cs: &[constness]) -> constness {
vec::foldl(integral_const, cs, |a, b| join(a, *b))
cs.iter().fold(integral_const, |a, b| join(a, *b))
}
pub fn classify(e: @expr,

View File

@ -17,6 +17,7 @@ use middle::trans::cabi::{ABIInfo, FnType, LLVMType};
use middle::trans::common::{T_i8, T_i16, T_i32, T_i64};
use middle::trans::common::{T_array, T_ptr, T_void};
use core::iterator::IteratorUtil;
use core::option::{Option, None, Some};
use core::uint;
use core::vec;
@ -43,9 +44,8 @@ fn ty_align(ty: TypeRef) -> uint {
if llvm::LLVMIsPackedStruct(ty) == True {
1
} else {
do vec::foldl(1, struct_tys(ty)) |a, t| {
uint::max(a, ty_align(*t))
}
let str_tys = struct_tys(ty);
str_tys.iter().fold(1, |a, t| uint::max(a, ty_align(*t)))
}
}
Array => {
@ -68,13 +68,11 @@ fn ty_size(ty: TypeRef) -> uint {
Double => 8,
Struct => {
if llvm::LLVMIsPackedStruct(ty) == True {
do vec::foldl(0, struct_tys(ty)) |s, t| {
s + ty_size(*t)
}
let str_tys = struct_tys(ty);
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let size = do vec::foldl(0, struct_tys(ty)) |s, t| {
align(s, *t) + ty_size(*t)
};
let str_tys = struct_tys(ty);
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}

View File

@ -10,6 +10,7 @@
use core::prelude::*;
use core::iterator::IteratorUtil;
use core::libc::c_uint;
use core::ptr;
use core::uint;
@ -56,9 +57,8 @@ fn ty_align(ty: TypeRef) -> uint {
if llvm::LLVMIsPackedStruct(ty) == True {
1
} else {
do vec::foldl(1, struct_tys(ty)) |a, t| {
uint::max(a, ty_align(*t))
}
let str_tys = struct_tys(ty);
str_tys.iter().fold(1, |a, t| uint::max(a, ty_align(*t)))
}
}
Array => {
@ -81,13 +81,11 @@ fn ty_size(ty: TypeRef) -> uint {
Double => 8,
Struct => {
if llvm::LLVMIsPackedStruct(ty) == True {
do vec::foldl(0, struct_tys(ty)) |s, t| {
s + ty_size(*t)
}
let str_tys = struct_tys(ty);
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let size = do vec::foldl(0, struct_tys(ty)) |s, t| {
align(s, *t) + ty_size(*t)
};
let str_tys = struct_tys(ty);
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}

View File

@ -19,6 +19,7 @@ use lib::llvm::True;
use middle::trans::common::*;
use middle::trans::cabi::*;
use core::iterator::IteratorUtil;
use core::libc::c_uint;
use core::option;
use core::option::Option;
@ -80,9 +81,8 @@ fn classify_ty(ty: TypeRef) -> ~[x86_64_reg_class] {
if llvm::LLVMIsPackedStruct(ty) == True {
1
} else {
do vec::foldl(1, struct_tys(ty)) |a, t| {
uint::max(a, ty_align(*t))
}
let str_tys = struct_tys(ty);
str_tys.iter().fold(1, |a, t| uint::max(a, ty_align(*t)))
}
}
Array => {
@ -104,16 +104,14 @@ fn classify_ty(ty: TypeRef) -> ~[x86_64_reg_class] {
Float => 4,
Double => 8,
Struct => {
if llvm::LLVMIsPackedStruct(ty) == True {
do vec::foldl(0, struct_tys(ty)) |s, t| {
s + ty_size(*t)
if llvm::LLVMIsPackedStruct(ty) == True {
let str_tys = struct_tys(ty);
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let str_tys = struct_tys(ty);
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
} else {
let size = do vec::foldl(0, struct_tys(ty)) |s, t| {
align(s, *t) + ty_size(*t)
};
align(size, ty)
}
}
Array => {
let len = llvm::LLVMGetArrayLength(ty) as uint;

View File

@ -24,6 +24,7 @@ use fold::Fold;
use fold;
use pass::Pass;
use core::iterator::IteratorUtil;
use core::str;
use core::util;
use core::vec;
@ -150,7 +151,7 @@ pub fn paragraphs(s: &str) -> ~[~str] {
for str::each_line_any(s) |line| { lines.push(line.to_owned()); }
let mut whitespace_lines = 0;
let mut accum = ~"";
let paras = do vec::foldl(~[], lines) |paras, line| {
let paras = do lines.iter().fold(~[]) |paras, line| {
let mut res = paras;
if str::is_whitespace(*line) {

View File

@ -14,6 +14,7 @@ use core::prelude::*;
use doc;
use core::iterator::IteratorUtil;
use core::vec;
pub type AstId = int;
@ -174,7 +175,7 @@ pub struct IndexEntry {
impl Doc {
pub fn CrateDoc(&self) -> CrateDoc {
vec::foldl(None, self.pages, |_m, page| {
self.pages.iter().fold(None, |_m, page| {
match copy *page {
doc::CratePage(doc) => Some(doc),
_ => None

View File

@ -11,6 +11,7 @@
use core::prelude::*;
use core::vec;
use core::iterator::IteratorUtil;
use astsrv;
use doc;
@ -30,7 +31,7 @@ pub fn run_passes(
passes: ~[Pass]
) -> doc::Doc {
let mut passno = 0;
do vec::foldl(doc, passes) |doc, pass| {
do passes.iter().fold(doc) |doc, pass| {
debug!("pass #%d", passno);
passno += 1;
do time(copy pass.name) {

View File

@ -21,6 +21,7 @@ middle of a line, and each of the following lines is indented.
use core::prelude::*;
use core::iterator::IteratorUtil;
use core::str;
use core::uint;
use core::vec;
@ -36,7 +37,7 @@ fn unindent(s: &str) -> ~str {
for str::each_line_any(s) |line| { lines.push(line.to_owned()); }
let mut saw_first_line = false;
let mut saw_second_line = false;
let min_indent = do vec::foldl(uint::max_value, lines)
let min_indent = do lines.iter().fold(uint::max_value)
|min_indent, line| {
// After we see the first non-whitespace line, look at

View File

@ -1066,64 +1066,6 @@ impl<'self, T:Copy> VectorVector<T> for &'self [&'self [T]] {
}
}
/**
* Reduces a vector from left to right.
*
* # Arguments
* * `z` - initial accumulator value
* * `v` - vector to iterate over
* * `p` - a closure to operate on vector elements
*
* # Examples
*
* Sum all values in the vector [1, 2, 3]:
*
* ~~~ {.rust}
* vec::foldl(0, [1, 2, 3], |a, b| a + *b);
* ~~~
*
*/
pub fn foldl<'a, T, U>(z: T, v: &'a [U], p: &fn(t: T, u: &'a U) -> T) -> T {
let mut accum = z;
let mut i = 0;
let l = v.len();
while i < l {
// Use a while loop so that liveness analysis can handle moving
// the accumulator.
accum = p(accum, &v[i]);
i += 1;
}
accum
}
/**
* Reduces a vector from right to left. Note that the argument order is
* reversed compared to `foldl` to reflect the order they are provided to
* the closure.
*
* # Arguments
* * `v` - vector to iterate over
* * `z` - initial accumulator value
* * `p` - a closure to do operate on vector elements
*
* # Examples
*
* Sum all values in the vector [1, 2, 3]:
*
* ~~~ {.rust}
* vec::foldr([1, 2, 3], 0, |a, b| a + *b);
* ~~~
*
*/
pub fn foldr<'a, T, U>(v: &'a [T], mut z: U, p: &fn(t: &'a T, u: U) -> U) -> U {
let mut i = v.len();
while i > 0 {
i -= 1;
z = p(&v[i], z);
}
return z;
}
/// Return true if a vector contains an element with the given value
pub fn contains<T:Eq>(v: &[T], x: &T) -> bool {
for each(v) |elt| { if *x == *elt { return true; } }
@ -1974,7 +1916,7 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
/// Reduce a vector from right to left
#[inline]
fn foldr<'a, U>(&'a self, z: U, p: &fn(t: &'a T, u: U) -> U) -> U {
foldr(*self, z, p)
self.rev_iter().fold(z, |u, t| p(t, u))
}
/// Apply a function to each element of a vector and return the results
@ -3394,39 +3336,6 @@ mod tests {
assert_eq!(v, ~[1, 3, 5]);
}
#[test]
fn test_foldl() {
// Test on-stack fold.
let mut v = ~[1u, 2u, 3u];
let mut sum = foldl(0u, v, add);
assert_eq!(sum, 6u);
// Test on-heap fold.
v = ~[1u, 2u, 3u, 4u, 5u];
sum = foldl(0u, v, add);
assert_eq!(sum, 15u);
}
#[test]
fn test_foldl2() {
fn sub(a: int, b: &int) -> int {
a - *b
}
let v = ~[1, 2, 3, 4];
let sum = foldl(0, v, sub);
assert_eq!(sum, -10);
}
#[test]
fn test_foldr() {
fn sub(a: &int, b: int) -> int {
*a - b
}
let v = ~[1, 2, 3, 4];
let sum = foldr(v, 0, sub);
assert_eq!(sum, -2);
}
#[test]
fn test_each_empty() {
for each::<int>([]) |_v| {
@ -4234,38 +4143,6 @@ mod tests {
};
}
#[test]
#[ignore(windows)]
#[should_fail]
#[allow(non_implicitly_copyable_typarams)]
fn test_foldl_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
let mut i = 0;
do foldl((~0, @0), v) |_a, _b| {
if i == 2 {
fail!()
}
i += 0;
(~0, @0)
};
}
#[test]
#[ignore(windows)]
#[should_fail]
#[allow(non_implicitly_copyable_typarams)]
fn test_foldr_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
let mut i = 0;
do foldr(v, (~0, @0)) |_a, _b| {
if i == 2 {
fail!()
}
i += 0;
(~0, @0)
};
}
#[test]
#[ignore(windows)]
#[should_fail]

View File

@ -19,6 +19,7 @@ use codemap::BytePos;
use diagnostic::span_handler;
use parse::comments::{doc_comment_style, strip_doc_comment_decoration};
use core::iterator::IteratorUtil;
use core::hashmap::HashSet;
use core::vec;
use extra;
@ -313,7 +314,7 @@ pub enum inline_attr {
/// True if something like #[inline] is found in the list of attrs.
pub fn find_inline_attr(attrs: &[ast::attribute]) -> inline_attr {
// FIXME (#2809)---validate the usage of #[inline] and #[inline(always)]
do vec::foldl(ia_none, attrs) |ia,attr| {
do attrs.iter().fold(ia_none) |ia,attr| {
match attr.node.value.node {
ast::meta_word(@~"inline") => ia_hint,
ast::meta_list(@~"inline", ref items) => {

View File

@ -16,7 +16,7 @@ use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use core::vec;
use core::iterator::IteratorUtil;
pub fn expand_deriving_iter_bytes(cx: @ExtCtxt,
span: span,
@ -85,7 +85,7 @@ fn iter_bytes_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @
cx.span_bug(span, "#[deriving(IterBytes)] needs at least one field");
}
do vec::foldl(exprs[0], exprs.slice(1, exprs.len())) |prev, me| {
do exprs.slice(1, exprs.len()).iter().fold(exprs[0]) |prev, me| {
cx.expr_binary(span, and, prev, *me)
}
}

View File

@ -27,6 +27,7 @@ use parse::token::{ident_to_str, intern, fresh_name};
use visit;
use visit::{Visitor,mk_vt};
use core::iterator::IteratorUtil;
use core::vec;
pub fn expand_expr(extsbox: @mut SyntaxEnv,
@ -128,7 +129,7 @@ pub fn expand_mod_items(extsbox: @mut SyntaxEnv,
// decorated with "item decorators", then use that function to transform
// the item into a new set of items.
let new_items = do vec::flat_map(module_.items) |item| {
do vec::foldr(item.attrs, ~[*item]) |attr, items| {
do item.attrs.rev_iter().fold(~[*item]) |items, attr| {
let mname = attr::get_attr_name(attr);
match (*extsbox).find(&intern(*mname)) {

View File

@ -129,12 +129,12 @@ pub fn copy_up(mpu: &matcher_pos_up) -> ~MatcherPos {
}
pub fn count_names(ms: &[matcher]) -> uint {
vec::foldl(0u, ms, |ct, m| {
do ms.iter().fold(0) |ct, m| {
ct + match m.node {
match_tok(_) => 0u,
match_seq(ref more_ms, _, _, _, _) => count_names((*more_ms)),
match_nonterminal(_,_,_) => 1u
}})
}}
}
pub fn initial_matcher_pos(ms: ~[matcher], sep: Option<Token>, lo: BytePos)

View File

@ -19,9 +19,9 @@ use parse::token::{EOF, INTERPOLATED, IDENT, Token, nt_ident};
use parse::token::{ident_to_str};
use parse::lexer::TokenAndSpan;
use core::iterator::IteratorUtil;
use core::hashmap::HashMap;
use core::option;
use core::vec;
///an unzipping of `token_tree`s
struct TtFrame {
@ -113,9 +113,7 @@ fn lookup_cur_matched_by_matched(r: &mut TtReader,
matched_seq(ref ads, _) => ads[*idx]
}
}
let r = &mut *r;
let repeat_idx = &r.repeat_idx;
vec::foldl(start, *repeat_idx, red)
r.repeat_idx.iter().fold(start, red)
}
fn lookup_cur_matched(r: &mut TtReader, name: ident) -> @named_match {
@ -152,10 +150,10 @@ fn lockstep_iter_size(t: &token_tree, r: &mut TtReader) -> lis {
}
match *t {
tt_delim(ref tts) | tt_seq(_, ref tts, _, _) => {
vec::foldl(lis_unconstrained, *tts, |lis, tt| {
do tts.iter().fold(lis_unconstrained) |lis, tt| {
let lis2 = lockstep_iter_size(tt, r);
lis_merge(lis, lis2)
})
}
}
tt_tok(*) => lis_unconstrained,
tt_nonterminal(_, name) => match *lookup_cur_matched(r, name) {

View File

@ -8,12 +8,12 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::vec;
use std::iterator::IteratorUtil;
fn compute1() -> float {
let v = ~[0f, 1f, 2f, 3f];
do vec::foldl(0f, v) |x, y| { x + *y } - 10f
do v.iter().fold(0f) |x, y| { x + *y } - 10f
//~^ ERROR mismatched types: expected `()`
}

View File

@ -8,13 +8,13 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::vec;
use std::iterator::IteratorUtil;
fn main() {
let needlesArr: ~[char] = ~['a', 'f'];
do vec::foldr(needlesArr) |x, y| {
do needlesArr.iter().fold() |x, y| {
}
//~^ ERROR 2 parameters were supplied (including the closure passed by the `do` keyword)
//~^ ERROR 1 parameter were supplied (including the closure passed by the `do` keyword)
//
// the first error is, um, non-ideal.
}

View File

@ -14,7 +14,7 @@ pub fn main() {
let v = ~[-1f, 0f, 1f, 2f, 3f];
// Trailing expressions don't require parentheses:
let y = do vec::foldl(0f, v) |x, y| { x + *y } + 10f;
let y = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
assert_eq!(y, 15f);
}

View File

@ -13,6 +13,6 @@ use std::vec;
pub fn main() {
fn f(i: &fn() -> uint) -> uint { i() }
let v = ~[-1f, 0f, 1f, 2f, 3f];
let z = do do vec::foldl(f, v) |x, _y| { x } { 22u };
let z = do do v.iter().fold(f) |x, _y| { x } { 22u };
assert_eq!(z, 22u);
}

View File

@ -13,6 +13,6 @@ use std::vec;
pub fn main() {
fn f(i: uint) -> uint { i }
let v = ~[-1f, 0f, 1f, 2f, 3f];
let z = do vec::foldl(f, v) |x, _y| { x } (22u);
let z = do v.iter().fold(f) |x, _y| { x } (22u);
assert_eq!(z, 22u);
}

View File

@ -8,25 +8,26 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::iterator::IteratorUtil;
use std::vec;
fn w_semi(v: ~[int]) -> int {
// the semicolon causes compiler not to
// complain about the ignored return value:
do vec::foldl(0, v) |x,y| { x+*y };
do v.iter().fold(0) |x,y| { x+*y };
-10
}
fn w_paren1(v: ~[int]) -> int {
(do vec::foldl(0, v) |x,y| { x+*y }) - 10
(do v.iter().fold(0) |x,y| { x+*y }) - 10
}
fn w_paren2(v: ~[int]) -> int {
(do vec::foldl(0, v) |x,y| { x+*y} - 10)
(do v.iter().fold(0) |x,y| { x+*y} - 10)
}
fn w_ret(v: ~[int]) -> int {
return do vec::foldl(0, v) |x,y| { x+*y } - 10;
return do v.iter().fold(0) |x,y| { x+*y } - 10;
}
pub fn main() {

View File

@ -51,9 +51,9 @@ pub fn main() {
// Lower precedence than binary operations:
let w = do vec::foldl(0f, v) |x, y| { x + *y } + 10f;
let y = do vec::foldl(0f, v) |x, y| { x + *y } + 10f;
let z = 10f + do vec::foldl(0f, v) |x, y| { x + *y };
let w = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
let y = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
let z = 10f + do v.iter().fold(0f) |x, y| { x + *y };
assert_eq!(w, y);
assert_eq!(y, z);