Nicolas Joseph

Nicolas Joseph

CTO / Entrepreneur

// ROOT/LOGS/2015-09-15// LOG ENTRY

> Scala School september 2015 Meetups _

The blog post describes my experience at the New York scala school, where I learned about linked list methods and some scala concepts. I highlight the use of sealed traits, which restricts the traits to be extended only within the same file, and provides benefits such as allowing the compiler to check for exhaustive pattern matches. The blog post provides an example implementation of sealed traits and showcases the benefits of using them. The post also provides a skeleton implementation of linked list methods, including length, sum, map, filter, append, and reverse, and asks readers to implement these methods.

// Archived NoteAuthor // Nicolas Joseph

Today I was at the at the New York scala school, we had some fun time implementing linked list methods. The idea was to give some introductions to some of the scala concepts.

The slides of the presentation are available here.

What I mainly got out of this presentation is the existence of sealed traits which are traits that cannot be extended outside of the file. As a result the compiler is able to get all the subtypes and give you a lot of insights at compilation time.

From the presentation was given this example:

sealed trait Answer

case object Yes extends Answer
case object No extends Answer

val x: Answer = Yes
x match {
  case No => println("No")
}

Will give the compiler warning:

<console>:14: warning: match may not be exhaustive.
It would fail on the following input: Yes
              x match {
              ^
scala.MatchError: Yes (of class Yes$)

Finally, we implemented some linked list methods. Here is the skeleton of the project.

case object MNil extends MList
case class MCons(head: Int, tail: MList) extends MList

sealed trait MList {
  def length: Int = this match {
    case MNil => 0
    case MCons(h, t) => 1 + t.length
  }
  def sum: Int = ???
  def map(f: Int => Int): MList = ???
  def filter(f: Int => Boolean): MList = ???
  def append(e: Int): MList = ???
  def reverse: MList = ???
}


val myList: MList = MCons(1, MCons(2, MCons(3, MCons(4, MNil))))
myList.length //4


// Provide implementations for the following methods...
myList.sum // res1: Int = 10
myList.map(_ + 1) // res2: MList = MCons(2,MCons(3,MCons(4,MCons(5,MNil))))
myList.filter(_ % 2 == 0) // res3: MList = MCons(1,MCons(3,MNil))
myList.append(5) // MCons(1,MCons(2,MCons(3,MCons(4,MCons(5,MNil)))))
myList.reverse // MCons(4,MCons(3,MCons(2,MCons(1,MNil))))