0
votes

You must use recursion to define rmax2 and you must do so from “scratch”. That is, other than the cons operator, head, tail, and comparisons, you should not use any functions from the Haskell library.

I created a function that removes all instances of the largest item, using list comprehension. How do I remove the last instance of the largest number using recursion?

ved :: Ord a => [a] -> [a] ved [] =[] ved as = [ a | a <- as, m /= a ] where m= maximum as

1

1 Answers

0
votes

If you are strictly required to use recursion, you can use 2 helper functions: One to reverse the list and the second to remove the first largest while reversing the reversed list.

This result in a list where the last occurrence of the largest element is removed.

We also use a boolean flag to make sure we don't remove more than one element.

This is ugly code and I really don't like it. A way to make things cleaner would be to move the reversal of the list to a helper function outside of the current function so that there is only one helper function to the main function. Another way is to use the built-in reverse function and use recursion only for the removal.

removeLastLargest :: Ord a => [a] -> [a]
removeLastLargest xs = go (maximum xs) [] xs where
  go n xs []     = go' n True [] xs
  go n xs (y:ys) = go n (y:xs) ys
  go' n f xs []  = xs
  go' n f xs (y:ys)
    | f && y == n = go' n False xs ys
    | otherwise   = go' n f (y:xs) ys