Skip to content

Instantly share code, notes, and snippets.

@Thiez
Created June 24, 2013 15:15
Show Gist options
  • Save Thiez/5850798 to your computer and use it in GitHub Desktop.
Save Thiez/5850798 to your computer and use it in GitHub Desktop.
Cute 'findBest' with iter and fold and without evil copies.
use std::num::*;
// Given a collection and a score function, find the item with highest score.
fn findBest<'t,T,C:Ord>(src:&'t [T], scoreFunc:&fn(x:&'t T)->C)->Option<(&'t T,uint,C)> {
let mut it = src.iter();
let mut i = 0;
match it.next() {
None => None,
Some(first) => {
let firstScore = scoreFunc(first);
let firstResult = (first,0,firstScore);
Some(do it.fold(firstResult) |old,cur| {
i = i + 1;
let &(_,_,oldScore) = &old;
let newScore = scoreFunc(cur);
if (newScore > oldScore) {
(cur,i,newScore)
} else {
old
}
})
}
}
}
fn main() {
let array=~[1i,4i,3i,10i,-15i];
println(match do findBest(array) |x|{-abs(x-5i)} {
Some((item,_,_)) => fmt!("Closest to 5: =%d ",*item),
None => ~"no inputs"
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment