在不使用 flatten 方法的情况下展平 Scala 中的列表列表,结果不佳
flattening list of lists in Scala with out using flatten method giving bad result
我尝试使用以下代码展平列表列表。当我把它写在纸上时,它应该可以工作,但我认为我误解了或者我不知道列表是如何工作的。谁能告诉我哪里错了。
val a = List(List(1,2,3),List(4,5,6),List(7,8,9))
def flatten(xss : List[List[Any]]) : List[Any] = {
def flat(xs : List[Any]) : List[Any] = xs match {
case Nil => Nil
case head :: Nil=> head :: Nil
case head :: tail => head :: flat(tail)
}
xss match {
case Nil => Nil
case head :: Nil => flat(head)
case head :: tail => flat(head) :: flatten(tail)
}
}
flatten(a)
您的 flat
函数只是重新创建了它的参数列表,因此它可以被删除。
您只需要连接内部列表,使用 :::
:
def flatten(xss : List[List[_]]): List[Any] = xss match {
case Nil => Nil
case head :: tail => head ::: flatten(tail)
}
我对您的示例做了两处小改动以使其正常运行。第一个是使用泛型(不是问题,但稍微清理了代码)。第二种是在输入列表有多个项目的情况下使用 :::
而不是 ::
。 ::
方法将单个项目添加到列表中,该列表是列表中项目的类型。 :::
将两个列表连接在一起。使用类型 List[Any]
,您无法看到该问题。但是一旦我将类型更改为 T
,问题出在哪里就很清楚了。
def flatten[T](xss : List[List[T]]) : List[T] = {
def flat(xs : List[T]) : List[T] = xs match {
case Nil => Nil
case head :: Nil=> head :: Nil
case head :: tail => head :: flat(tail)
}
xss match {
case Nil => Nil
case head :: Nil => flat(head)
case head :: tail => flat(head) ::: flatten(tail)
}
}
您实际上可以深入结构进行模式匹配:
def flatten[T](xss: List[List[T]]): List[T] = xss match {
case Nil => Nil
case Nil :: tail => flatten(tail)
case (innerHead :: innerTail) :: tail => innerHead :: flatten(innerTail :: tail)
}
我尝试使用以下代码展平列表列表。当我把它写在纸上时,它应该可以工作,但我认为我误解了或者我不知道列表是如何工作的。谁能告诉我哪里错了。
val a = List(List(1,2,3),List(4,5,6),List(7,8,9))
def flatten(xss : List[List[Any]]) : List[Any] = {
def flat(xs : List[Any]) : List[Any] = xs match {
case Nil => Nil
case head :: Nil=> head :: Nil
case head :: tail => head :: flat(tail)
}
xss match {
case Nil => Nil
case head :: Nil => flat(head)
case head :: tail => flat(head) :: flatten(tail)
}
}
flatten(a)
您的 flat
函数只是重新创建了它的参数列表,因此它可以被删除。
您只需要连接内部列表,使用 :::
:
def flatten(xss : List[List[_]]): List[Any] = xss match {
case Nil => Nil
case head :: tail => head ::: flatten(tail)
}
我对您的示例做了两处小改动以使其正常运行。第一个是使用泛型(不是问题,但稍微清理了代码)。第二种是在输入列表有多个项目的情况下使用 :::
而不是 ::
。 ::
方法将单个项目添加到列表中,该列表是列表中项目的类型。 :::
将两个列表连接在一起。使用类型 List[Any]
,您无法看到该问题。但是一旦我将类型更改为 T
,问题出在哪里就很清楚了。
def flatten[T](xss : List[List[T]]) : List[T] = {
def flat(xs : List[T]) : List[T] = xs match {
case Nil => Nil
case head :: Nil=> head :: Nil
case head :: tail => head :: flat(tail)
}
xss match {
case Nil => Nil
case head :: Nil => flat(head)
case head :: tail => flat(head) ::: flatten(tail)
}
}
您实际上可以深入结构进行模式匹配:
def flatten[T](xss: List[List[T]]): List[T] = xss match {
case Nil => Nil
case Nil :: tail => flatten(tail)
case (innerHead :: innerTail) :: tail => innerHead :: flatten(innerTail :: tail)
}