#Crusty Noob learns about closures

3 messages · Page 1 of 1 (latest)

spice breach
#

So I have made an adaptive integration method that takes the function to be integrated as arguement. It works fine for simple functions. But I dont know how to pass in a closure function of different "fixed" variables while integrate only with respect to one of the variables. I will attach a MWE below that links to rust playground. Thank u!

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=fceb8cc5590f5880e04e8dc1a6d64aaf

sharp spindle
#

So this error message will give you the info in the issue you're having

closures can only be coerced to `fn` types if they do not capture any variables

What you actually want to take is "something that can be called as if it's a function"....which Rust gives us with the Fn trait: https://doc.rust-lang.org/std/ops/trait.Fn.html

Basically you'll want to change the input type from fn(f32) -> f32 into impl Fn(f32) -> f32

However - Rust then is applying move semantics because you're taking this by value so it can't be shared around, and making just that change alone gives

error[E0382]: use of moved value: `f`
  --> src/main.rs:35:22
   |
24 |     f: impl Fn(f32) -> f32,
   |     - move occurs because `f` has type `impl Fn(f32) -> f32`, which does not implement the `Copy` trait
...
34 |     let sl = simpson(f, a, m, &w);
   |                      - value moved here
35 |     let sr = simpson(f, m, b, &w);
   |                      ^ value used here after move
   |
note: consider changing this parameter type in function `simpson` to borrow instead if owning the value isn't necessary
  --> src/main.rs:16:19
   |
16 | pub fn simpson(f: impl Fn(f32) -> f32, a: f32, b: f32, w: &Array1<f32>) -> f32 {
   |        -------    ^^^^^^^^^^^^^^^^^^^ this parameter takes ownership of the value
   |        |
   |        in this function
help: consider borrowing `f`
   |
34 |     let sl = simpson(&f, a, m, &w);

So what you actually want is to take a reference to it so it can be shared around and called repeatedly - so the input type should be &impl Fn(f32) -> f32

So fixed up here: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=4ecdaee2b5273e82afc6b3d8d244eac6

spice breach
#

thank u