> struct ntimes<T>(times: uint, value: T) -> T;
Does this syntax work at the moment? ~Brendan On 29/10/2013, at 9:33 PM, Niko Matsakis <[email protected]> wrote: > Incidentally, my preferred way to "return a closure" is to use > an impl like so: > > struct ntimes<T>(times: uint, value: T) -> T; > impl<T:Clone> ntimes<T> { > fn call(&mut self) -> Option<T> { > if self.times == 0 { > None > } else { > self.times -= 1; > Some(self.value.clone()); > } > } > } > > Now you can "call" it like: > > let foo = ntimes(3, v); > foo.call(); // Some(v) > foo.call(); // Some(v) > foo.call(); // Some(v) > foo.call(); // None > > > Niko > > On Mon, Oct 28, 2013 at 04:06:38PM -0400, Steven Blenkinsop wrote: >> 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 > > _______________________________________________ > Rust-dev mailing list > [email protected] > https://mail.mozilla.org/listinfo/rust-dev _______________________________________________ Rust-dev mailing list [email protected] https://mail.mozilla.org/listinfo/rust-dev
