Josh Chang
Josh Chang

Reputation: 31

Remove all occurrences of largest item using list comprehension

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

Upvotes: 1

Views: 260

Answers (2)

jlwoodwa
jlwoodwa

Reputation: 392

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".

Upvotes: -1

David Lukas
David Lukas

Reputation: 1229

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]

Upvotes: 4

Related Questions