FranGoitia
FranGoitia

Reputation: 1993

Scala recursive function returning Either

I'm writing a recursive function which returns False or a List of values.

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.

Upvotes: 2

Views: 542

Answers (1)

danielnixon
danielnixon

Reputation: 4268

The pattern match tail match { ... } doesn't magically change the type of the value you're matching on. tail is still an Either and Either doesn't have a member head. But l is a List, so replace tail.head with l.head and so on.

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

Upvotes: 4

Related Questions