1

私は現在、関数型プログラミングに関するプレゼンテーションに取り組んでおり、次の問題に遭遇しました。

関数型プログラミングは、「何」を「どのように」から分離するか、より正確には、計算の宣言をその解釈から分離することを意図しています。これが、このパラダイムの主な焦点の 1 つは、計算がどのように実行されるかについて何の仮定もせずに、構成可能なデータ構造を使用して計算を表すことである理由です。例えば:

// 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ますか?

4

2 に答える 2