scala - Scala 中的部分应用程序不是引用透明的?

标签 scala functional-programming

给定两个函数:

def f(a: String, b: Int): Int = a.length + b
val g: Int => String = _.toString

为什么我可以通过中间赋值的方式将部分应用的 fg 组合起来:

val f_ = f(_: String, 42)
f_ andThen g
// String => String = <function1>

但不是直接:

f(_: String, 42) andThen g
// error: value andThen is not a member of Int

这是类型推断器的问题还是预期行为的问题?

最佳答案

这只是一个语法错误,如果您打开 -Xprint:parser 选项,您将看到您的表达式与正确表达式之间的差异,即: (f(_:字符串,42)) 然后 g.

你的表情:

((x$1: String) => f((x$1: String), 42).andThen(g))

正确的是:

((x$1: String) => f((x$1: String), 42)).andThen(g)

你可以看到差异。发生这种情况是因为扩展规则,scalac 首先将语法规范为点形式,然后将其扩展。同样的规则也适用于这种形式的函数应用:func(_),它扩展到最里面的大括号,我不记得它在 SLS 中的哪个位置编写。

关于scala - Scala 中的部分应用程序不是引用透明的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25900707/

相关文章:

haskell - 如何从功能上计算未知大小列表的连续元素之间的差异?

functional-programming - 为什么 OCaml 的线程被认为是 `not enough` ?

Scala 包对象构造器

scala - 有没有更惯用的方法从 Option[IO[Option[A]] 获取 IO[Option[A]] 然后使用序列和映射连接?

scala - 如何使用Scala在Spark中创建SQLContext?

functional-programming - 值得学习erlang吗?

c++ - 关于 C++ 中的 "bind"

c++ - 使用运算符!否定重载的 bool 谓词

scala - 来自标准 IO 的 Iteratee 输入

windows - 运行以 utf-8 保存的 scala 脚本会出错