Implement and explain a custom Monad in Scala.

Instruction: Provide an implementation of a custom Monad in Scala, explaining its structure and use-cases.

Context: This question evaluates the candidate's deep understanding of functional programming concepts in Scala, specifically the design and implementation of custom Monads.

Updated

A custom monadic data type needs a way to introduce a value and a lawful way to sequence dependent computations. This Scala 3 Outcome represents success or the first explicit failure:

enum Outcome[+A] {
  case Done(value: A)
  case Failed(reason: String)

  def flatMap[B](f: A => Outcome[B]): Outcome[B] = this match {
    case Done(value) => f(value)
    case Failed(reason) => Failed(reason)
  }
  def map[B](f: A => B): Outcome[B] = flatMap(a => Outcome.pure(f(a)))
}
object Outcome {
  def pure[A](value: A): Outcome[A] = Outcome.Done(value)
}
def validName(raw: String): Outcome[String] =
  Option(raw).filter(_.nonEmpty) match {
    case Some(name) => Outcome.Done(name)
    case None => Outcome.Failed("Name required")
  }
def validAge(raw: String): Outcome[Int] =
  Option(raw).flatMap(_.toIntOption).filter(_ > 0) match {
    case Some(age) => Outcome.Done(age)
    case None => Outcome.Failed("Positive integer age required")
  }
def user(name: String, age: String): Outcome[(String, Int)] = for {
  n <- validName(name)
  a <- validAge(age)
} yield (n, a)

@main def outcomeExample(): Unit = {
  assert(user("Ava", "25") == Outcome.Done(("Ava", 25)))
  assert(user("", "invalid") == Outcome.Failed("Name required"))
  assert(user("Ava", "0") == Outcome.Failed("Positive integer age required"))
  assert(user(null, "25") == Outcome.Failed("Name required"))
}

The comprehension invokes this type's own flatMap and map. A Failed skips subsequent dependent steps, preserving its reason. This example does not trim names, impose an age upper bound or accumulate independent errors; add those policies deliberately.

For pure, total functions, require the monad laws: introducing a value then binding is equivalent to applying the function; binding a value to pure leaves it unchanged; and regrouping successive bindings leaves the result unchanged. Check success and failure branches, including short-circuit behavior. Property tests over many values complement, rather than replace, reasoning about those laws. Monad operations

This is a small educational implementation. Throwing inside a callback still throws; flatMap does not catch exceptions. A comprehension with a guard needs additional filtering support, which this type does not define. It is not a Cats Monad instance and supplies no stack-safe recursive sequencing operation such as tailRecM. In production, an established type such as Either is usually preferable unless a distinct domain model justifies a custom API.

Related Questions