【问题标题】:How to compose two functions?如何组合两个函数?
【发布时间】:2017-11-27 09:05:37
【问题描述】:

我有两个功能,我正在尝试compose它:

  private def convert(value: String)
  : Path = decode[Path](value) match {


  private def verify(parsed: Path)
  : Path = parsed.os match {

我试过如下:

verify compose convert _

编译器报错:

[error] Unapplied methods are only converted to functions when a function type is expected.
[error] You can make this conversion explicit by writing `verify _` or `verify(_)` instead of `verify`.
[error]     verify compose convert _
[error]     ^
[error] one error found

我正在努力完成以下工作:

  def process(value: String)
  : Path =
    verify(convert(value))

我做错了什么?

【问题讨论】:

    标签: scala


    【解决方案1】:

    问题不在于 scala 中的所有内容都是函数。 convertverify 在您的示例中是方法而不是函数。

    1)如果你想组合函数,定义为函数,如下例,

    函数,

    scala> def convert: String => String = (value: String) => "converted"
    convert: String => String
    
    scala> def verify = (value: String) => if(value == "converted") "valid" else "invalid"
    verify: String => String
    

    撰写 fns

    scala> def vc = verify compose convert
    vc: String => String
    

    将 fn 组合应用于函子

    scala> Some("my-data").map{ vc.apply }
    res29: Option[String] = Some(valid)
    

    2) 另一种方法是将现有方法转换为如下函数,

    scala> def vc = (verify _ compose (convert _))
    vc: String => String
    
    scala> Some("data to convert").map { vc.apply }
    res36: Option[String] = Some(valid)
    

    参考文献

    https://twitter.github.io/scala_school/pattern-matching-and-functional-composition.html

    Chapter 21 - Functions/Function literals

    Function composition of methods, functions, and partially applied functions in Scala

    【讨论】:

    • 如何强制判断def convert = (value: String) => "converted"的返回类型?喜欢def convert(value: String): String = ???
    • @zero_coding 成为一种方法。函数有一个类型A => B,这意味着它是takes A 和returns B。所以,在你的情况下是def convert: String => Path = (value: String) => ???。查看更新的答案
    • 太棒了。 signature 看起来像在 Haskell 中。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多