Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何组合两个函数?_Scala - Fatal编程技术网

Scala 如何组合两个函数?

Scala 如何组合两个函数?,scala,Scala,我有两个函数,我正在尝试编写它: private def convert(value: String) : Path = decode[Path](value) match { private def verify(parsed: Path) : Path = parsed.os match { 我尝试了以下方法: verify compose convert _ def process(value: String) : Path = verify(con

我有两个函数,我正在尝试编写它:

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


  private def verify(parsed: Path)
  : Path = parsed.os match {
我尝试了以下方法:

verify compose convert _
  def process(value: String)
  : Path =
    verify(convert(value))
编译器抱怨:

[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
我正在努力实现以下目标:

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

我做错了什么?

问题不在于scala中的一切都是函数<示例中的代码>转换和验证是方法而不是函数

1)如果要组合函数,请定义为函数,如下例所示,

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

scala> Some("data to convert").map { vc.apply }
res36: Option[String] = Some(valid)
功能

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)
scala> def vc = (verify _ compose (convert _))
vc: String => String

scala> Some("data to convert").map { vc.apply }
res36: Option[String] = Some(valid)
2)另一种方法是将现有方法转换为以下函数,

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

scala> Some("data to convert").map { vc.apply }
res36: Option[String] = Some(valid)
工具书类


如何强制确定
def convert=(值:String)=>“converted”
的返回类型?像
def convert(value:String):String=??
@zero\u编码,它成为一种方法。函数有一个类型
a=>B
,这意味着它
接受
a而
返回B
。因此,在您的情况下,它将是
defconvert:String=>Path=(value:String)=>?
。请参阅更新的答案。签名
与Haskell中的签名类似。谢谢。