About
The default filter function in prelude, outputs all the elements of the input list, which evaluate to true on applying the function and removes all other elements evaluating to false. Write a modified version of the filter function called limfilt, which can limit the number of items that can be removed from the input list. limfilt function takes a function, f, as its first argument. f in turn takes one argument and returns a Boolean result. The second argument to limfilt will be an integer, limit, which indicates the maximum number of elements that will be removed from the list. The last argument of limfilt will be the list. The value returned by limfilt will be a list of values with limit no of elements (specified by second argument) removed from the original list for which f evaluates to False. Your implementation of limfilt should be applicable to lists of any type. Test cases that you may want to consider include: limfilt (> 0) 10 [-3..3] should return [1,2,3] limfilt (> 0) 0 [-5..5] should return [-5,-4,-3,-2,-1,0,1,2,3,4,5] limfilt (> 0) 3 [-2, 2, -3, 3, -4, 4, -5, 5] should return [2,3,4,-5,5] limfilt (== 0) 3 [] should return [] limfilt (\x -> x
rem
2 == 0) 2 [1..9] should return [2,4,5,6,7,8,9]Write a higher order Scala function that counts the number of times each element appears in a list.
Sol
1)
'''
limfilt :: (a -> Bool) -> Int -> [a] -> [a] limfilt _ _ [] = [] limfilt _ 0 xs = xs limfilt f limit (x:xs) | f x = x : limfilt f limit xs | otherwise = limfilt f (limit - 1) xs
main = do
print $ limfilt (> 0) 10 [-3..3] -- [1,2,3]
print $ limfilt (> 0) 0 [-5..5] -- [-5,-4,-3,-2,-1,0,1,2,3,4,5]
print $ limfilt (> 0) 3 [-2, 2, -3, 3, -4, 4, -5, 5] -- [2,3,4,-5,5]
print $ limfilt (== 0) 3 [] -- []
print $ limfilt (\x -> x rem
2 == 0) 2 [1..9] -- [2,4,5,6,7,8,9]
2)
''' object count{ def countOccurrencesA: Map[A, Int] = { list.foldLeft(Map.empty[A, Int]) { (map, elem) => map + (elem -> (map.getOrElse(elem, 0) + 1)) } }
def main(args: Array[String]): Unit = {
val myList = List(1, 2, 3, 2, 1, 2, 3, 3, 4, 5, 4, 4)
val occurrences = countOccurrences(myList)
println(occurrences)
}
} '''