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
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)); | |
} |
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
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); | |
} |
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
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