Skip to content

Instantly share code, notes, and snippets.

@bstrie
Last active January 3, 2016 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bstrie/8443947 to your computer and use it in GitHub Desktop.
Save bstrie/8443947 to your computer and use it in GitHub Desktop.
fn integral(f: &|f32|->f32, p: u32, a: f32, b: f32) -> f32 {
if p == 1 {
(b-a) * ((*f)(a) + 4.0 * (*f)((a+b)/2.0) + (*f)(b))/6.0
}
else {
let mid = (a+b)/2.0;
integral(f, p-1, a, mid) + integral(f, p-1, mid, b)
}
}
fn main() {
println!("{}", integral(&|x| x*x, 10, 1.0, 2.0));
}
fn integral<'a>(f: 'a |f32|->f32, p: u32, a: f32, b: f32) -> (f32, 'a |f32|->f32) {
if p == 1 {
((b-a) * (f(a) + 4.0 * f((a+b)/2.0) + f(b))/6.0, f)
} else {
let mid = (a+b)/2.0;
let (i1, f) = integral(f, p-1, a, mid);
let (i2, f) = integral(f, p-1, mid, b);
(i1+i2, f)
}
}
fn main() {
let (i, _) = integral(|x: f32| x*x, 10, 1.0, 2.0);
println!("{}", i);
}
fn integral(f: |f32|->f32, p: u32, a: f32, b: f32) -> f32 {
match (f, p, a, b) {
(f, 1, a, b) => (b-a) * (f(a) + 4.0 * f((a+b)/2.0) + f(b))/6.0,
(f, p, a, b) => {
let mid = (a+b)/2.0;
integral(f, p-1, a, mid) + // note: `f` moved here because it has type `|f32| -> f32`, which is a non-copyable stack closure (capture it in a new closure, e.g. `|x| f(x)`, to override)
integral(f, p-1, mid, b) // error: use of moved value: `f`
}
}
}
fn main() {
println!("{}", integral(|x: f32| x*x, 10, 1.0, 2.0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment