|
| 1 | +object Test1 with |
| 2 | + def consume(xs: List[Int], limit: Int): List[Int] = xs match |
| 3 | + case x :: xs1 if limit > 0 => consume(xs1, limit - x) |
| 4 | + case _ => xs |
| 5 | + |
| 6 | +object Test2 { |
| 7 | + import scala.math.Numeric |
| 8 | + import scala.math.Numeric.Implicits._ |
| 9 | + import scala.math.Ordering.Implicits._ |
| 10 | + |
| 11 | + def consume[T: Numeric](xs: List[T], limit: T): List[T] = |
| 12 | + val zero = implicitly[Numeric[T]].zero |
| 13 | + xs match { |
| 14 | + case x :: xs1 if limit > zero => consume(xs1, limit - x) |
| 15 | + case _ => xs |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +object math3 with |
| 20 | + trait Ord[T] with |
| 21 | + def (x: T) > (t: T): Boolean = ??? |
| 22 | + def (x: T) <= (t: T): Boolean = ??? |
| 23 | + |
| 24 | + trait Numeric[T] extends Ord[T] with |
| 25 | + def (x: T) + (y: T): T = ??? |
| 26 | + def (x: T) - (y: T): T = ??? |
| 27 | + def (x: Int) numeric: T = ??? |
| 28 | +end math3 |
| 29 | + |
| 30 | +object Test3 with |
| 31 | + import math3.Numeric |
| 32 | + import collection.immutable.Seq |
| 33 | + |
| 34 | + def consume[T: Numeric](xs: List[T], limit: T): List[T] = xs match |
| 35 | + case x :: xs1 if limit > 0.numeric => consume(xs1, limit - x) |
| 36 | + case _ => xs |
| 37 | + |
| 38 | + def consume[T: Numeric](xs: LazyList[T], limit: T): LazyList[T] = xs match |
| 39 | + case x #:: xs1 if limit > 0.numeric => consume(xs1, limit - x) |
| 40 | + case _ => xs |
| 41 | + |
| 42 | + def consume[T: Numeric](xs: Seq[T], limit: T): Seq[T] = |
| 43 | + def dropCount(it: Iterator[T], start: Int, limit: T): Int = |
| 44 | + if limit > 0.numeric && it.hasNext then dropCount(it, start + 1, limit - it.next) |
| 45 | + else start |
| 46 | + xs.drop(dropCount(xs.iterator, 0, limit)) |
| 47 | + |
| 48 | + def consume[T: Numeric](xs: Iterable[T], limit: T): Iterable[T] = |
| 49 | + var sum = 0.numeric |
| 50 | + xs.dropWhile { x => |
| 51 | + try sum <= limit finally sum += x |
| 52 | + } |
| 53 | + |
| 54 | + def consume2[T: Numeric](xs: Iterable[T], limit: T): Iterable[T] = |
| 55 | + consume2(LazyList.from(xs), limit) |
| 56 | +end Test3 |
| 57 | + |
0 commit comments