Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala递归函数返回_Scala_Pattern Matching_Either - Fatal编程技术网

Scala递归函数返回

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_

我正在编写一个递归函数,它返回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_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)
    }
  }
}