-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
84 additions
and
57 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
object ScalaList: | ||
sealed abstract class List[+A]: | ||
def :: [B >: A](elem: B): List[B] = Cons(elem, this) | ||
def map[B](f: A => B): List[B] = | ||
this match | ||
case Nil => Nil | ||
case Cons(a, as) => f(a) :: as.map(f) | ||
|
||
def ++[B >: A](that: List[B]): List[B] = | ||
this match | ||
case Nil => that | ||
case Cons(a, as) => a :: (as ++ that) | ||
|
||
def tail: List[A] = | ||
require(this != Nil) | ||
this match | ||
case Cons(a, as) => as | ||
|
||
def head: A = | ||
require(this != Nil) | ||
this match | ||
case Cons(a, as) => a | ||
|
||
def length: Int = { | ||
this match | ||
case Nil => 0 | ||
case Cons(h, t) => | ||
val tLen = t.length | ||
if tLen == Int.MaxValue then tLen | ||
else 1 + tLen | ||
} ensuring(res => 0 <= res && res <= Int.MaxValue) | ||
|
||
end List | ||
|
||
case object Nil extends List[Nothing] | ||
final case class Cons[+A](first: A, next: List[A]) extends List[A] | ||
|
||
end ScalaList |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters