added lesson 4

This commit is contained in:
Louis Heredero 2025-03-11 15:46:02 +01:00
parent 966767f58c
commit a608a602ad
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
3 changed files with 52 additions and 0 deletions

13
src/Lesson4/Lists.sc Normal file

@ -0,0 +1,13 @@
def insert(x: Int, xs: List[Int]): List[Int] = {
if (xs.isEmpty) x::Nil
else if (x < xs.head) x::xs
else xs.head::insert(x, xs.tail)
}
def isort(xs: List[Int]): List[Int] = {
if (xs.isEmpty) Nil
else insert(xs.head, isort(xs.tail))
}
isort(7::3::9::2::Nil)

@ -0,0 +1,35 @@
def patFoo(value: Any): Boolean = {
value match {
case a: Int => a % 4 == 0
case c: Char => c.isUpper
case b: Boolean => true
case _ => false
}
}
abstract class Expr
case class Number(n: Int) extends Expr
case class Sum(e1: Expr, e2: Expr) extends Expr
def eval(e: Expr): Int = e match {
case Number(n) => n
case Sum(e1, e2) => eval(e1) + eval(e2)
}
def show(e: Expr): String = e match {
case Number(n) => n.toString
case Sum(e1, e2) => "(" + show(e1) + " + " + show(e2) + ")"
}
patFoo(23)
patFoo(24)
patFoo('a')
patFoo('A')
patFoo(false)
patFoo(true)
patFoo("Hello")
patFoo(null)
val e: Expr = Sum(Number(3), Sum(Number(4), Number(5)))
eval(e)
show(e)

4
src/Lesson4/Types.sc Normal file

@ -0,0 +1,4 @@
val a: String = "Hell" + "o" * 50
def b(s: String): String = "Hell" + s
a == b("o" * 50)