On Monday, October 28, 2013, Ramakrishnan Muthukrishnan wrote: > On Mon, Oct 28, 2013 at 11:48 AM, Jesse Ruderman > <[email protected]<javascript:;>> > wrote: > > If you don't mind changing ntimes to not return a closure: > > > > fn ntimes<T>(f: &fn(T) -> T, times: uint, x: T) -> T { > > match times { > > 0u => x, > > _ => ntimes(|x| f(x), times - 1u, f(x)) > > } > > } > > > > fn main() { > > println(format!("{:d}", ntimes(|k| k*2, 2u, 3))); > > } > > Thanks. That is very nice. > > No, I am not particular about returning a closure. I was just trying > out some toy programs to learn Rust. > > It would have been nice to return a closure from `ntimes' though. :(
You can *create* a closure from ntimes, doing `|x| ntimes(|k| k*2, 2, x)`. The idea is that closures borrow data from the stack, so passing them up the stack is difficult. If you want to use the stack as your datastructure, you have to ensure everything travels down the stack, which you can do by requiring the caller to pass in their own closure accepting your closure as an argument (a syntax extension abstracting over this pattern would be nice so the code doesn't become ungainly). Otherwise, you have to build up your own datastructure to pass up the stack, and then derive a closure from that somehow. Ultimately, if closures become a special case of trait objects, this should be really straightforward to do.
_______________________________________________ Rust-dev mailing list [email protected] https://mail.mozilla.org/listinfo/rust-dev
