【问题标题】:Scala recursive function returning EitherScala递归函数返回Either
【发布时间】:2017-03-15 05:19:46
【问题描述】:

我正在编写一个返回 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
    }
  }
}

我收到错误:value head is not a member of Either[List[Char],Boolean],但 head 方法只能在匹配列表后使用。

【问题讨论】:

    标签: scala pattern-matching either


    【解决方案1】:

    模式匹配tail match { ... } 不会神奇地更改您要匹配的值的类型。 tail 仍然是 Either 并且 Either 没有成员 head。但是l List,所以将tail.head 替换为l.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)
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多