Created
June 24, 2013 15:15
-
-
Save Thiez/5850798 to your computer and use it in GitHub Desktop.
Cute 'findBest' with iter and fold and without evil copies.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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