[英]Is Scala's Try referentially transparent?
我目前正在编写关于功能编程的演示文稿,并遇到了以下问题。
功能编程旨在将“什么”与“如何”分开,或者更确切地说,将计算的声明与其解释分开。 这就是为什么这个范例的主要焦点之一是使用可组合数据结构来表示计算,而不对它们的执行方式做出任何假设。 例如:
// Represents a computation that may fail
case class Unsafe[A,B](run: A => B)
// ...
val readIntFromFile: Unsafe[String, Int] = Unsafe { filePath => /* ... */ }
interpret(readIntFromFile)
// Interpreter
def interpret(u: Unsafe[String, Int]): Unit = {
try {
u.run("path/to/file")
} catch {
case e => /* ... */
}
}
这似乎是有道理的,因为副作用应仅在执行计算期间执行,而不是在其声明期间执行。 问题是,在Scala看来,许多数据结构都违反了这条规则:
object Try {
/** Constructs a `Try` using the by-name parameter. This
* method will ensure any non-fatal exception is caught and a
* `Failure` object is returned.
*/
def apply[T](r: => T): Try[T] =
try Success(r) catch {
case NonFatal(e) => Failure(e)
}
}
Futures
相同:
/** Starts an asynchronous computation and returns a `Future` object with the result of that computation.
*
* The result becomes available once the asynchronous computation is completed.
*
* @tparam T the type of the result
* @param body the asynchronous computation
* @param executor the execution context on which the future is run
* @return the `Future` holding the result of the computation
*/
def apply[T](body: =>T)(implicit @deprecatedName('execctx) executor: ExecutionContext): Future[T] = impl.Future(body)
所以,我现在想知道, Try
和Future
真的具有透明度? 如果没有,那么如何在不依赖Success
和Failure
情况下处理错误情况呢?
只要您不使用副作用,尝试是参考透明的。 Try的目的不是控制副作用,而是处理可能的异常。
如果您需要以纯粹的方式控制副作用,您可以使用Cats和Scalaz等库中的任务或IO类型。
Future
绝对不是RT,因为这两个块不等同:
这两个期货并行执行:
val fa: Future[Int] = service.call val fb: Future[Int] = service.call for { a <- fa; b <- fb } yield a + b
这两个期货按顺序执行:
for { a <- service.call; b <- service.call } yield a + b
另一方面, Try
是。 处理错误的正确功能方法是使用Either[ErrorDescription, A]
作为返回A
但可能失败的方法(您可以使用type ErrorDescription = Throwable
等效于scala.util.Try
!)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.