< 返回版块

WingDust 发表于 2021-12-11 11:35

Tags:函数式

我想用柯里化去实现 为 Vec字符串 之间添加一个字符,如空格、逗号,最后返回这个字符串

// 输入 Vec![ "qq","ww","ee"]  返回 "qq,ww,ee" 或者 “qq ww ee"

自己实现的写法不知道有什么问题,请指出

fn gap_symbols(symbol: &'static str) -> impl Fn(Vec<&str>) -> String{
  move |args:Vec<&str>| args.join(symbol)
}

fn space(args:Vec<&str>)->String{
  let space_gap = gap_symbols(" ");
  space_gap(args)
}
fn comma(args:Vec<&str>)->String{
  let comma_gap = gap_symbols(",");
  comma_gap(args)
}

#[test]
fn curry(){
  let a = vec!["qq","ww","ee"];
  println!("{}",space(a));
}

评论区

写评论
c5soft 2021-12-13 10:14

@Bai-Jinlin 亲的代码技术含量很高! 直接这样写,是不是就有点柯里化的味道:

fn main() {
    let v = vec!["asd", "zxc"];
    println!("{}", curry_what(",")(&v));
}

fn curry_what<'a>(sep: &'a str) -> impl for<'b> Fn(&'b Vec<&str>) -> String + 'a {
    |v: &Vec<&str>| v.join(sep)
}

作者 WingDust 2021-12-12 20:23

觉得你的好一些

Bai-Jinlin 2021-12-11 15:03

这样吗?

fn curry_what<'a>(sep: &'a str) -> impl for<'b> Fn(&'b Vec<&str>) -> String + 'a {
    |v: &Vec<&str>| { v.join(sep) }
}
fn main() {
    let v = vec!["asd", "zxc"];
    let f = curry_what(",");
    println!("{}", f(&v));
}
1 共 3 条评论, 1 页