简体   繁体   English

Scala递归函数返回

[英]Scala recursive function returning Either

I'm writing a recursive function which returns False or a List of values. 我正在写一个返回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
    }
  }
}

I'm getting error: value head is not a member of Either[List[Char],Boolean] , but head method should only be used after matching the list. 我收到错误消息: value head is not a member of Either[List[Char],Boolean] ,但是head方法仅应在匹配列表之后使用。

The pattern match tail match { ... } doesn't magically change the type of the value you're matching on. 模式匹配tail match { ... }不会神奇地更改您要匹配的值的类型。 tail is still an Either and Either doesn't have a member head . tail仍然是Either并且Either没有成员head But l is a List , so replace tail.head with l.head and so on. 但是l 一个List ,所以用tail.head替换l.head ,依此类推。

You can try inserting explicit type annotation to make things clearer. 您可以尝试插入显式类型注释,以使情况更清晰。

Your return types are also wrong in a few places. 您的退货类型在某些地方也有误。 Here's a version that's closer to compiling: 这是一个更接近编译的版本:

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)
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM