Avatar of monylad

monylad's solution

to Simple Linked List in the Scala Track

Published at Jul 20 2019 · 0 comments
Instructions
Test suite
Solution

Write a simple linked list implementation that uses Elements and a List.

The linked list is a fundamental data structure in computer science, often used in the implementation of other data structures. They're pervasive in functional programming languages, such as Clojure, Erlang, or Haskell, but far less common in imperative languages such as Ruby or Python.

The simplest kind of linked list is a singly linked list. Each element in the list contains data and a "next" field pointing to the next element in the list of elements.

This variant of linked lists is often used to represent sequences or push-down stacks (also called a LIFO stack; Last In, First Out).

As a first take, lets create a singly linked list to contain the range (1..10), and provide functions to reverse a linked list and convert to and from arrays.

When implementing this in a language with built-in linked lists, implement your own abstract data type.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command sbt test in the exercise directory.

For more detailed info about the Scala track see the help page.

Source

Inspired by 'Data Structures and Algorithms with Object-Oriented Design Patterns in Ruby', singly linked-lists. http://www.brpreiss.com/books/opus8/html/page96.html#SECTION004300000000000000000

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

SimpleLinkedListTest.scala

import org.scalacheck.{Arbitrary}
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FlatSpec, Matchers}

/** @version created manually **/
class SimpleLinkedListTest extends FlatSpec with Matchers with GeneratorDrivenPropertyChecks {

  private implicit def arbitrarySimpleLinkedList[T](implicit arbitraryTs: Arbitrary[Array[T]]): Arbitrary[SimpleLinkedList[T]] =
    Arbitrary {
      arbitraryTs.arbitrary map (SimpleLinkedList(_:_*))
    }

  it should "handle single item list" in {
    val list = SimpleLinkedList().add(1)
    list.isEmpty should be (false)
    list.value should be (1)
  }

  it should "handle single item has no next item" in {
    pending
    val list = SimpleLinkedList().add(1)
    list.next.isEmpty should be (true)
  }

  it should "handle two item list" in {
    pending
    val list = SimpleLinkedList().add(1).add(2)
    list.value should be (1)
    list.next.value should be (2)
  }

  it should "handle two item list has no next value" in {
    pending
    val list = SimpleLinkedList().add(1).add(2)
    list.next.next.isEmpty should be (true)
  }

  it should "allow creation from a Seq" in {
    pending
    val list = SimpleLinkedList.fromSeq(List(3, 2, 1))
    list.value should be (3)
    list.next.value should be (2)
    list.next.next.value should be (1)
  }

  it should "allow conversion to a Seq" in {
    pending
    val list = SimpleLinkedList.fromSeq(List(3, 2, 1))
    val seq = list.toSeq
    seq should be (List(3, 2, 1))
  }

  it should "handle reverse" in {
    pending
    val list = SimpleLinkedList.fromSeq(List(1, 2, 3, 4, 5, 6))
    val reversed = list.reverse
    reversed.value should be (6)
    reversed.next.value should be (5)
    reversed.next.next.value should be (4)
    reversed.next.next.next.value should be (3)
    reversed.next.next.next.next.value should be (2)
    reversed.next.next.next.next.next.value should be (1)
  }

  it should "handle arbitrary list fromSeq toSeq" in {
    pending
    forAll { seq: Seq[Int] =>
      assert(SimpleLinkedList.fromSeq(seq).toSeq == seq)
    }
  }

  it should "handle reverse arbitrary list " in {
    pending
    forAll { seq: Seq[Int] =>
      assert(SimpleLinkedList.fromSeq(seq).reverse.toSeq == seq.reverse)
    }
  }

  it should "reverse arbitrary list back to original" in {
    pending
    forAll { list: SimpleLinkedList[Int] =>
      assert(list.reverse.reverse.toSeq == list.toSeq)
    }
  }

  it should "return correct arbitrary value at index" in {
    pending
    def nthDatum(list: SimpleLinkedList[Int], i: Int): Int = {
      (0 until i).foldLeft(list)((acc, j) => acc.next).value
    }

    forAll { xs: Seq[Int]  =>
      whenever(xs.nonEmpty) {
        val list = SimpleLinkedList.fromSeq(xs)
        xs.indices.foreach {
          i => assert(nthDatum(list, i) == xs(i))
        }
      }
    }
  }

  it should "return original arbitrary list from added list elements" in {
    pending
    forAll { xs: Seq[Int] =>
      val list = xs.foldLeft(SimpleLinkedList[Int]())(_.add(_))
      assert(list.toSeq == xs)
    }
  }

  it should "handle arbitrary generics" in {
    pending
    forAll { xs: Seq[String] =>
      assert(SimpleLinkedList.fromSeq(xs).toSeq == xs)
    }
  }
}
trait SimpleLinkedList[T] {
  def isEmpty: Boolean
  def value: T
  def add(item: T): SimpleLinkedList[T]
  def next: SimpleLinkedList[T]
  def reverse: SimpleLinkedList[T]
  def toSeq: Seq[T]
}

case class Empty[T]() extends SimpleLinkedList[T] {
  override def isEmpty: Boolean = true

  override def value: T = throw new NoSuchElementException

  override def add(item: T): SimpleLinkedList[T] = NonEmpty(item, Empty())

  override def next: SimpleLinkedList[T] = throw new IllegalStateException

  override def reverse: SimpleLinkedList[T] = this

  override def toSeq: Seq[T] = Nil
}

case class NonEmpty[T](value: T, next: SimpleLinkedList[T]) extends SimpleLinkedList[T] {
  override def isEmpty: Boolean = false

  override def add(item: T): SimpleLinkedList[T] = NonEmpty(value, next.add(item))

  override def reverse: SimpleLinkedList[T] = next.reverse.add(value)

  override def toSeq: Seq[T] = value +: next.toSeq
}

object SimpleLinkedList {
  def apply[T](): SimpleLinkedList[T] = Empty[T]()
  def apply[T](elements: T*): SimpleLinkedList[T] = fromSeq(elements)

  def fromSeq[T](seq: Seq[T]): SimpleLinkedList[T] = seq.foldLeft(SimpleLinkedList[T]())((list, el) => list.add(el))
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?