Home > Software engineering >  Remove all occurrences of largest item using list comprehension
Remove all occurrences of largest item using list comprehension

Time:10-16

I am trying to use list comprehension to define a Haskell function designated as ted that takes a list of items of type class Ord. The function ted shall remove all occurrences of the largest item in the list. In case the given list is empty, ted shall just return the empty list.

This is my code

import Data. List
import Data.Function

rmax :: Ord a => [a] -> [a]
Prelude> [a | a<- as]
[a | a <- as, a % 2 == 0

CodePudding user response:

module Main where

list :: [Int]
list = [5,8,6,3,8]
--list = []
--list = [8]

ted :: Ord a => [a] -> [a]
ted as = [a | a<-as, a /= (maximum as)]

main :: IO ()
main =  putStrLn $ show $ ted list

Output:

[5,6,3]

CodePudding user response:

You can do this with a single pass over the list:

import Data.List.NonEmpty (NonEmpty (..))

removeMax :: Ord a => NonEmpty a -> [a]
removeMax xs@(hd :| _) =
  let (res, greatest) =
    foldr
      (\x (tl, m) -> (if x == greatest then tl else x : tl, max x m))
      ([], hd)
      xs
   in res

This is called "tying the knot".

  • Related