Compare commits

...

2 Commits

Author SHA1 Message Date
9ad00e6182 corrected / added midterm examples 2025-04-15 13:12:25 +02:00
b53e0677cc fixed minor issue in midterm 2025-04-15 13:08:04 +02:00
2 changed files with 20 additions and 2 deletions

View File

@ -24,6 +24,23 @@ def predicates[T](list: List[T])(preds: List[T => Boolean]): List[T] = {
}) })
} }
val l1 = (1 to 10).toList
val f1 = ((a: Int) => a % 2 == 0)
val f2 = ((a: Int) => a > 5)
predicates(l1)(List(f1, f2)) // List(6, 8, 10)
val l2 = ("Hello Scala Echo").toList
val f4 = ((a: Char) => a == 'a' || a == 'e' || a == 'o')
val f3 = ((a: Char) => !a.isUpper)
predicates(l2)(List(f3, f4)) // List('e', 'o', 'a', 'a', 'o')
/*
// Better solution
def predicates[T](list: List[T])(preds: List[T => Boolean]): List[T] = {
preds.foldLeft(list)((acc, fun) => acc.filter(fun))
}
*/
def fixedPoint(f: Int => Int): Int => Int = { def fixedPoint(f: Int => Int): Int => Int = {
@tailrec @tailrec
def func(x: Int): Int = { def func(x: Int): Int = {
@ -34,4 +51,5 @@ def fixedPoint(f: Int => Int): Int => Int = {
func func
} }
fixedPoint(x => x / 2 + 5)(40) fixedPoint(x => if (x % 10 == 0) x else x + 1)(35) // 40
fixedPoint(x => x / 2 + 5)(20) // 10

View File

@ -16,7 +16,7 @@ abstract class Text {
def tail: Text = { def tail: Text = {
this match { this match {
case Chars(cs) => Chars(cs.tail) case Chars(cs) => Chars(cs.tail)
case Concat(t1, t2) => if (t2.isEmpty) t1.tail else Concat(t1, t2.tail) case Concat(t1, t2) => if (t1.isEmpty) t2.tail else Concat(t1.tail, t2)
} }
} }
def map(f: Char => Char): Text = { def map(f: Char => Char): Text = {