Sunday, February 7, 2016

Implicit Class for List Element Extraction in Scala

Last weekend at the library, I stumbled upon the book "Realm of Racket", and it occurred to me that I should see if I can get my daughter to learn a bit about Lisp-like languages before she dives into Java in high school next year. Of course, I also had to start working through the Racket book myself. Unsurprisingly, it's fun.

One little throwaway thing I learned was that Racket has named list extract methods for first, second, third, up to tenth. Perhaps that's not super-useful, but I wanted it in my Scala toolbox nonetheless.

So I implemented them in a Scala implicit class and put them on Github as well as here for your enjoyment:

 * Implicit methods that add "first" through "tenth"
 * extraction methods to the Scala List.
object ListMethods {
  implicit class Nth[T](lst: List[T]) {
    def first = lst(0)
    def second = lst(1)
    def third = lst(2)
    def fourth = lst(3)
    def fifth = lst(4)
    def sixth = lst(5)
    def seventh = lst(6)
    def eighth = lst(7)
    def ninth = lst(8)
    def tenth = lst(9)

It's just about the simplest possible implicit class implementation I can think of -- ten repetitive one-liners. Nonetheless, if you're having trouble structuring an implicit class, perhaps this helps you.

Also, I took the opportunity to try something new -- FunSuite from ScalaTest -- for unit testing. (Keep in mind that ScalaTest actually supports a few different unit testing styles. Here is a snippet of the test code:

class ListMethodsTest extends FunSuite {
  val lst = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

  test("first method works") {
    assert(1 == lst.first)

  // etc

No comments: