PPaste!

Home - All the pastes - Authored by Thooms

Raw version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package problems

import scala.annotation.tailrec

/**
  * Created by t.papillon on 22/12/2016.
  */
object Solutions {
  @tailrec
  def last[A](l: List[A]): Option[A] = l match {
    case List() => None
    case List(x) => Some(x)
    case _ :: xs => last(xs)
  }

  @tailrec
  def penultimate[A](l: List[A]): Option[A] = l match {
    case List() | List(_) => None
    case List(x, _) => Some(x)
    case _ :: xs => penultimate(xs)
  }

  @tailrec
  def nth[A](n: Int, l: List[A]): Option[A] = l match {
    case _ if n < 0 => None
    case List() if n >= 0 => None
    case x :: xs if n == 0 => Some(x)
    case _ :: xs => nth(n - 1, xs)
  }

  def length[A](l: List[A]): Int = {
    @tailrec
    def aux(acc: Int, l: List[A]): Int = l match {
      case List() => acc
      case _ :: xs => aux(acc + 1, xs)
    }
    aux(0, l)
  }

  def reverse[A](l: List[A]): List[A] = {
    @tailrec
    def aux(acc: List[A], l: List[A]): List[A] = l match {
      case List() => acc
      case x :: xs => aux(x :: acc, xs)
    }

    aux(List(), l)
  }
}