0
votes

I am getting an error while running my Scala Code on IntelliJ (using Scala 2.11.8):

package week4

/**
  * Created by BigB on 15/08/17.
  */
trait List[T] {
  def isEmpty: Boolean
  def head: T
  def tail: List[T]
}

class Cons[T](val head: T, val tail: List[T]) extends List[T] {
  override def isEmpty: Boolean = false
}

class Nil[T] extends List[T] {
  override def isEmpty: Boolean = true

  override def head: T = throw new NoSuchElementException("Nil.head")

  override def tail: List[T] =throw new NoSuchElementException("Nil.tail")
}

My Scala Worksheet has:

import week4._

object nth {
  def nth[T](n: T, l: List[T]): T = {
    if (l.isEmpty) throw new IndexOutOfBoundsException
    else if (n==0) l.head
    else nth(n-1, l.tail)
  }

  val l1 = new Cons(1, new Cons(2, new Cons(2, new Nil)))

  nth(2, l1)
}

Errors:

Error:(9, 20) not found: type Cons lazy val l1 = new Cons(1, new Cons(2, new Cons(2, new Nil))) ^

Error:(6, 16) value - is not a member of type parameter T else nth(n-1, l.tail) ^

1
You have to first compile week4 package, then try to run worksheet. At-least it works for me without any code changedhana

1 Answers

1
votes

Your nth is parameterized with T. Inside it you call it recursively with nth(n-1, ...).

What's the type of n-1? n is of type T, 1 is of type Int the resulting type cannot be inferred to be of type T so it fails.

I suggest passing an extra parameter, perhaps:

object nth {
  def nth[T](n: T, l: List[T], dec: T => T): T = {
    if (l.isEmpty) throw new IndexOutOfBoundsException
    else if (n==0) l.head
    else nth[T](dec(n), l.tail, dec)
  }

  val l1 = new Cons(1, new Cons(2, new Cons(2, new Nil)))

  nth[Int](2, l1, _ - 1)
}

Edit

Putting my version of your code in a class that extends App works as expected. I've given up using worksheets. Too unreliable or too many hidden secrets.

Edit no.2

Right clicked the worksheet pressed Recompile <ws>.sc and Run.sc` and it worked... Oh well worksheets!

enter image description here