【问题标题】:Scala: higher order function to concatenate StringsScala:连接字符串的高阶函数
【发布时间】:2017-04-14 21:14:41
【问题描述】:

我从 Scala 开始,现在我谈论的是高阶函数,但我很难处理这种使用函数作为输入的编程方式。

我必须编写一个高阶函数只使用折叠、扫描和/或减少来连接字符串,如下所示:

concatenate(List("S", "T", "R", " example!") , f)
//> res1: List[String] = List(STR example!, TR example!, R example!, " example!", "")

有谁知道我该如何解决这个问题?

【问题讨论】:

    标签: scala


    【解决方案1】:

    仅使用scan

    List("S", "T", "R", " example!").reverse.scan("")((x, y) => y + x).reverse
    // res72: List[String] = List(STR example!, TR example!, R example!, " example!", "")
    

    使用scanRight:

    List("S", "T", "R", " example!").scanRight("")(_+_)
    // res73: List[String] = List(STR example!, TR example!, R example!, " example!", "")
    

    【讨论】:

    • 非常感谢!你能解释一下这是做什么的吗:“(x, y) => y + x”?
    • 用来保证left + right的粘贴顺序,注意列表一开始是颠倒的,如果使用x + y,那么你最终会得到example! RTS而不是你想要的顺序。
    猜你喜欢
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    相关资源
    最近更新 更多