Scala递归函数返回
我正在编写一个递归函数,它返回False或值列表Scala递归函数返回,scala,pattern-matching,either,Scala,Pattern Matching,Either,我正在编写一个递归函数,它返回False或值列表 def parse(chars: List[Char]): Either[List[Char], Boolean] = { if (chars.length == 1) chars else { val head = chars.head val tail = parse(chars.tail) tail match { case Left(l) => { if (are_
def parse(chars: List[Char]): Either[List[Char], Boolean] = {
if (chars.length == 1)
chars
else {
val head = chars.head
val tail = parse(chars.tail)
tail match {
case Left(l) => {
if (are_equal(head, tail.head))
head :: tail
else if (are_cancelled(head, tail.head))
tail.tail
else
false
}
case Right(b) => false
}
}
}
我得到了一个错误:
值head不是[List[Char],Boolean]
的成员,但是head方法只能在匹配列表后使用。模式匹配尾部匹配{…}
不会神奇地改变您匹配的值的类型tail
仍然是other
并且other
没有成员head
。但是l
是一个列表
,所以用l.head
替换tail.head
,依此类推
您可以尝试插入显式类型注释以使事情更清楚
您的退货类型在一些地方也有错误。下面是一个更接近编译的版本:
def parse(chars: List[Char]): Either[List[Char], Boolean] = {
if (chars.length == 1) {
Left(chars)
} else {
val head = chars.head
val tail = parse(chars.tail)
tail match {
case Left(l) =>
if (are_equal(head, l.head))
Left(head :: l)
else if (are_cancelled(head, l.head))
Left(l.tail)
else
Right(false)
case Right(b) => Right(false)
}
}
}