Q&A
Ask and answer questions to make information more available to wider audiences.
Anna Joseph @josephanna85   07, Jun 2023 12:00 AM
Solve the problem
The following functions each take predicate function and a list as input, and remove certain items from the list based on the predicate function. They each have this signature:

(a -> Bool) -> [a] -> [a]
a. ltrim removes all items from the start of the list that satisfy the predicate function.
b. rtrim removes all items from the end of the list that satisfy the predicate function.
c. trim removes all items from both the start and end of the list that satisfy the predicate function.

What's the solution?

answers 1
 
Answer 1
Jose Grimsbro @josegrimsbro   12, Jun 2023 07:41 PM
-- remove all occurrences of values at the start of a list that satisfy the
-- given predicate function
ltrim :: (a -> Bool) -> [a] -> [a]
ltrim _ [] = []
ltrim f (x:xs) = if f x then
                    ltrim f xs
                 else
                    x:xs

-- remove all occurrences of values at the end of a list that satisfy the
-- given predicate function
rtrim :: (a -> Bool) -> [a] -> [a]
rtrim f lst = reverse (ltrim f (reverse lst))

-- remove all occurrences of values at the start/end of a list that satisfy the
-- given predicate function
trim :: (a -> Bool) -> [a] -> [a]
trim f lst = ltrim f (rtrim f lst)