About
max-min elements scala
object MinMaxElements { def main(args: Array[String]): Unit = { val numbers = List(5, 3, 9, 1, 7, 2) val (min, max) = findMinMaxElements(numbers)
println(s"Minimum element: $min")
println(s"Maximum element: $max")
}
def findMinMaxElements(numbers: List[Int]): (Int, Int) = { if (numbers.isEmpty) { throw new IllegalArgumentException("The list is empty.") } else { var min = numbers.head var max = numbers.head
for (num <- numbers) {
if (num < min) {
min = num
}
if (num > max) {
max = num
}
}
(min, max)
}
} }
basket scala
object CommonItemsInBaskets { def main(args: Array[String]): Unit = { val basket1 = List("apple", "banana", "orange", "pear") val basket2 = List("banana", "grape", "pear", "mango") val basket3 = List("pear", "kiwi", "banana", "pineapple")
val commonItems = basket1.intersect(basket2).intersect(basket3)
println("Common items in the baskets:")
commonItems.foreach(println)
} } literals in 2 data structures: val set1 = Set(1, 3, 5, 10, 20) val set2 = Set(20, 17, 18, 99, 0)
val set1DiffSet2 = set1.diff(set2) val set2DiffSet1 = set2.diff(set1)
println("Number literals in set one but not in set two:") println(set1DiffSet2) println("Number literals in set two but not in set one:") println(set2DiffSet1)
higher order functions: haskel
function to truncate strings truncateStrings :: [String] -> [String] truncateStrings = foldr (\x acc -> if length x > 5 then take 5 x : acc else x : acc) []
function to applyN applyN :: (a -> a) -> Int -> a -> a applyN f 0 x = x applyN f n x = applyN f (n-1) (f x)
dropUntil haskel function dropUntil :: (a -> Bool) -> [a] -> [a] dropUntil f xs = dropWhile (not . f) xsTail where xsTail = dropWhile (not . f) xs