spa*_*rkr 2 string functional-programming scala function-composition for-comprehension
我正在尝试用于理解来构造对象调用,这是我的简单实现:
object FuncA extends (String => Int => String) {
override def apply(str: String): Int => String = i => {
s"${(str.toInt + i).toString}"
}
}
object FuncB extends (String => Int) {
override def apply(str: String): Int = {
str.toInt
}
}
for {
funcAStr <- FuncA("1")(1)
funcBStr <- FuncB(funcAStr) // Fails here
} yield {
println(s"Final String incremented as int is $funcBStr")
}
Run Code Online (Sandbox Code Playgroud)
但是奇怪的是,我有一个问题,其中funcAStr被解释为Char而不是String。任何理想的原因是什么?
尽管包含了for-loop
标签,但for
在Scala中并未定义循环。for
是定义序列的简写方式map
,flatMap
和withFilter
电话。
您的代码转换为:
FuncA("1")(1).flatMap{ funcAStr =>
FuncB(funcAStr).map{ funcBStr =>
println(s"Final String incremented as int is $funcBStr")
}
}
Run Code Online (Sandbox Code Playgroud)
Func("1")(1)
返回String
。该flatMap
方法对String
需要依次字符串的每个字符,所以funcAStr
实际上是Char
没有String
。
andThen
像这样尝试功能组合
(FuncA("1") andThen FuncB)(1)
Run Code Online (Sandbox Code Playgroud)
哪个输出
res0: Int = 2
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
71 次 |
最近记录: |