study-note

8. FP(関数型プログラミング)

目次


モナド(Monad)

値を安全にラップして、操作をつなげられる型のこと


  1. Option
  2. Either
  3. Future


Option型



参照:サンプルコード

Scala標準ライブラリ(Option)


参照:サンプルコード


Optionの合成

複数のOptionを連続的に使いたいとき、ネストせずに読みやすく書くことができる

def getUser(id: Int): Option[String] = Some("ユーザー")
def getEmail(name: String): Option[String] = Some(s"$name@example.com")

val result: Option[String] = for {
  name  <- getUser(1)
  email <- getEmail(name)
} yield s"Send to: $email"

println(result.getOrElse("No email found"))

参照:サンプルコード

Either

val result: Either[String, Int] = Right(42)
val error: Either[String, Int] = Left("Error occurred")


活用例

val res: Either[String, Int] = Right(42)

res match {
  case Right(v) => println(s"Success: $v")
  case Left(e)  => println(s"Error: $e")
}

参照:サンプルコード

Scala標準ライブラリ(Either)

Eitherの合成

複数のEitherを連続的に使いたいときに、ネストせずに読みやすく書くことができる

def getUser(id: Int): Either[String, String] = Right("ユーザー")
def getEmail(name: String): Either[String, String] = Right(s"$name@example.com")

val result: Either[String, String] = for {
  name  <- getUser(1)
  email <- getEmail(name)
} yield s"Send to: $email"

println(result) // Right(Send to: ユーザー@example.com)

参照:サンプルコード


Future(非同期処理)

import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.util.{Success, Failure}

val f: Future[Int] = Future {
  // 重い計算やI/O処理を非同期に実行
  Thread.sleep(1000)
  42
}

f.onComplete {
  case Success(value) => println(s"Got the result: $value")
  case Failure(e) => println(s"Failed with $e")
}


参照:サンプルコード

Scala標準ライブラリ(Future)