From a608a602ad15006a70050433374170c5c48bb110 Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 11 Mar 2025 15:46:02 +0100 Subject: [PATCH] added lesson 4 --- src/Lesson4/Lists.sc | 13 +++++++++++++ src/Lesson4/PatternMatching.sc | 35 ++++++++++++++++++++++++++++++++++ src/Lesson4/Types.sc | 4 ++++ 3 files changed, 52 insertions(+) create mode 100644 src/Lesson4/Lists.sc create mode 100644 src/Lesson4/PatternMatching.sc create mode 100644 src/Lesson4/Types.sc diff --git a/src/Lesson4/Lists.sc b/src/Lesson4/Lists.sc new file mode 100644 index 0000000..89e27a8 --- /dev/null +++ b/src/Lesson4/Lists.sc @@ -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) \ No newline at end of file diff --git a/src/Lesson4/PatternMatching.sc b/src/Lesson4/PatternMatching.sc new file mode 100644 index 0000000..3d8d018 --- /dev/null +++ b/src/Lesson4/PatternMatching.sc @@ -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) \ No newline at end of file diff --git a/src/Lesson4/Types.sc b/src/Lesson4/Types.sc new file mode 100644 index 0000000..5bf9ca0 --- /dev/null +++ b/src/Lesson4/Types.sc @@ -0,0 +1,4 @@ +val a: String = "Hell" + "o" * 50 +def b(s: String): String = "Hell" + s + +a == b("o" * 50) \ No newline at end of file