fpscala:sequence()函数中的模式匹配错误

时间:2019-07-30 13:31:11

标签: scala

我正在关注《 Scala中的函数编程》一书,并研究问题4.4。

即使我从应答键复制并粘贴了代码,也不确定如何解决。

  def sequence[A](a: List[Option[A]]): Option[List[A]] = a match {
    case Nil => Some(Nil)
    case h :: t => h.flatMap(hh => sequence(t).map(hh :: _))
  }

错误:

Error:(45, 12) constructor cannot be instantiated to expected type;
 found   : scala.collection.immutable.::[A]
 required: List[Option[?A1]] where type ?A1 <: A (this is a GADT skolem)
    case h :: t => h.flatMap(hh => sequence(t).map(hh :: _))

似乎是什么问题?

编辑:看来问题是因为我在同一目录下的另一个文件中定义了List。如何使该文件使用scala.List而不是我定义的List

1 个答案:

答案 0 :(得分:4)

仅隐藏自定义的List类:

import custom.{List => _}

在从List包中导入其他所有内容的同时,隐藏您的custom实现:

import custom.{List => _, _}

或反之亦然-导入类时给它一个新名称(或别名):

import scala.collection.immutable.{List => RenamedList}

并用scala.List引用RenamedList