Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 66 lines (55 sloc) 1.462 kb
239a799 push
Derek Wyatt authored
1
2 import scala.annotation.tailrec
3 // Possibly "better" but way less readable
4 //
5 // def last[T](l: List[T]): T = {
6 // if (l.isEmpty) throw new Exception("Can't get 'last' of Nil list")
7 // l.foldLeft((l.size, l.head))((a, b) => if (a._1 == 1) (0, b) else ((a._1 - 1, b)))._2
8 // }
9 //
10 // Better but probably not in the spirit of the question
11 //
12 // def last[T](l: List[T]): T = {
13 // if (l.isEmpty) throw new Exception("Can't get 'last' of Nil list")
14 // l.reverse.head
15 // }
16
17 // P01
18 @tailrec
19 def last[T](l: List[T]): T = {
20 l match {
21 case Nil => throw new Exception("Can't get 'last' of Nil list")
22 case x :: Nil => x
23 case x :: xs => last(xs)
24 }
25 }
26
27 println(last(List(1,1,2,3,5,8)))
28
29 // P02
30 @tailrec
31 def penultimate[T](l: List[T]): T = {
32 l match {
33 case Nil => throw new Exception("Can't get 'penultimate' of Nil list")
34 case x :: Nil => throw new Exception("Can't get 'penultimate' of list of size 1")
35 case x :: y :: Nil => x
36 case x :: y :: xs => penultimate(xs)
37 }
38 }
39
40 println(penultimate(List(1,1,2,3,5,8)))
41
42 // P03
43 @tailrec
44 def nth[T](n: Int, l: Seq[T]): T = {
45 if (n >= l.size) throw new Exception("Index out of bounds")
46 n match {
47 case 0 => l.head
48 case _ => nth(n - 1, l.tail)
49 }
50 }
51
52 println(nth(2, List(1,1,2,3,5,8)))
53
54 // P04
55 def length[T](l: Seq[T]): Int = {
56 @tailrec
57 def len[T](i: Int, s: Seq[T]): Int = {
58 if (s.isEmpty) i
59 else len(i + 1, s.tail)
60 }
61 len(0, l)
62 }
63
64 println(length(List(1,1,2,3,5,8)))
65
Something went wrong with that request. Please try again.