首页 > 解决方案 > 如何在 Scala 中发送通用对象来代替 Type 变量(或 Any)

问题描述

我正在解决此页面上的问题 20 - http://aperiodic.net/phil/scala/s-99/

这是我写的代码

import scala.annotation.tailrec
import scala.collection.immutable.Nil
import scala.collection.immutable.ListSet

object Problem20 extends App {
  def removeAt[A](order: Int, xs: List[A]): (List[A], A) = {
    def removeAtRec(xs: List[A], acc: (List[A], A), i: Int): (List[A], A) =
      (xs, i) match {
        case (Nil, _)                    => (acc._1.reverse, acc._2)
        case (x :: xs_, i) if i == order => removeAtRec(xs_, (acc._1, x), i + 1)
        case (x :: xs_, i)               => removeAtRec(xs_, (x :: acc._1, acc._2), i + 1)
      }
    removeAtRec((xs, (Nil, ### What should I put here ###), 0) 
  }

  println(removeAt(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))
  println(removeAt(0, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))
  println(removeAt(10, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))
  println(removeAt(11, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))
  println(removeAt(12, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))
}

我想在占位符处发送一个对象### What should I put here ###。在 Python、Java 中,我可以发送一个空值。但在斯卡拉它打破了。我想发送一些我知道肯定会被覆盖的对象。

标签: scalafunctional-programming

解决方案


习惯上我们使用Option代替null,例如

def removeAt[A](order: Int, xs: List[A]): (List[A], Option[A]) = {
  @tailrec def removeAtRec(xs: List[A], acc: (List[A], Option[A]), i: Int): (List[A], Option[A]) =
    (xs, i) match {
      case (Nil, _)                    => (acc._1.reverse, acc._2)
      case (x :: xs_, i) if i == order => removeAtRec(xs_, (acc._1, Some(x)), i + 1)
      case (x :: xs_, i)               => removeAtRec(xs_, (x :: acc._1, acc._2), i + 1)
    }
  removeAtRec(xs, (Nil, None), 0)
}

removeAt(42, List('a', 'b')) // res5: (List[Char], Option[Char]) = (List(a, b),None)

推荐阅读