Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

MyList - step 2

ToString

Add the toString method to MyList

trait MyList[A]:
  ...
  def toString: String
  • Make a recursive version
  • A Tail recursive version
  • A pretty print version that prints MyList(3,2,1)

Exercise

Implement the add method in Cons and Empty And test it in main

Recursive

We have to walk through the linked list get the head and then jump to the tail recursively. The case is the empty node.

override def toString: String =
  def concat(remainder: MyList[A]): String =
    if !remainder.isEmpty then
      current.head.toString + " " + concat(remainder.tail)
    else 
      ""
    concat(this)

Tail Recursive

In the tail recursive version we add a accumulator to the parameters. In every iteration we add the head to the accumulator And the last step in returning the accumulator

override def toString: String =
  def concat(remainder: MyList[A], accumulator: String): String =
    if !remainder.isEmpty then
      concat(remainder.tail, accumulator + " " + remainder.head)
    else
      s"MyList($accumulator)"
  concat(this, "")

Pretty print

To make in pretty print version we add a comma in every iteration. But then we get as many comma's as there are elements and that is one comma too much.

Iterating one less is starting the recursive loop with the tail
And the accumulator start with the head

override def toString: String =
  def concat(remainder: MyList[A], accumulator: String): String =
    if !remainder.isEmpty then
      concat(remainder.tail, accumulator + ", " + remainder.head)
    else
      accumulator
      
  val elements = concat(tail, head.toString)    
  s"MyList($elements)"

main

@main
def main(): Unit =
  val myList: MyList[Int] = Empty() + 1 + 2 + 3
  println(myList)
  
  //  3 2 1
  //  MyList(3, 2, 1)

The order is reversed now.