Returning function from a function (FP style)

So I'm trying to rewrite this scala function in Rust:

  def highScoringWords(wordScore: String => Int,
    words: List[String]): Int => List[String] = {
      higherThan => words.filter(word => wordScore(word) > higherThan)
  }

so far I have this:

fn high_scoring_words(score: impl Fn(&String) -> usize,
    words: &Vec<String>) -> impl Fn(usize) -> Vec<String> {
    move |higher_than| cloned.clone()
                        .into_iter()
                        .filter(|w| score(w) > higher_than)
                        .collect()
}

and I'm getting this error

error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
  --> ch3.rs:33:29
   |
33 |     words: &Vec<String>) -> impl Fn(usize) -> Vec<String> {
   |            ------------     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |            |
   |            hidden type `[closure@ch3.rs:34:5: 37:35]` captures the anonymous lifetime defined here
   |
help: to declare that the `impl Trait` captures '_, you can add an explicit `'_` lifetime bound
   |
33 |     words: &Vec<String>) -> impl Fn(usize) -> Vec<String> + '_ {
   |    

why do I even need a lifetime specification here if I'm cloning the whole thing?

any help on how I can do it?

Because you're not cloning the reference in the outer function. That's why the inner/returned function need to hold the reference itself. Below is the fix to it, but it would be better to change the function to take the owned vector itself.

fn high_scoring_words(score: impl Fn(&String) -> usize,
    words: &Vec<String>) -> impl Fn(usize) -> Vec<String> {
    let cloned = words.clone();
    move |higher_than| cloned.clone()
                        .into_iter()
                        .filter(|w| score(w) > higher_than)
                        .collect()
}

It's questionable you're already using the variable cloned in the returned closure which doesn't exist anyway..

1 Like

It's questionable you're already using the variable cloned in the returned closure which doesn't exist anyway..

bad copy/paste. Copying twice seems a bit overhead. Taking vector by value seems more reasonable.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.