Skip to content

Instantly share code, notes, and snippets.

@emmanueldenloye
Last active December 19, 2017 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emmanueldenloye/4637200f0f9c0afed37fabee9be231d0 to your computer and use it in GitHub Desktop.
Save emmanueldenloye/4637200f0f9c0afed37fabee9be231d0 to your computer and use it in GitHub Desktop.
collect maximum elements of a list in one pass
-- Got inspiration from http://izzycecil.com/posts/2015-07-29-circular.html
trace :: (a -> c -> (b, c)) -> a -> b
trace f a = b
where (b, c) = f a c
collect' :: (Ord a) => (a -> a -> a) -> [a] -> a -> ([a],a)
collect' f [x] m = ([m],x)
collect' f (x:xs) m =
let (replaced, m') = collect' f xs m
in ( if compare m x == EQ
then m : replaced
else replaced
, f x m')
collect
:: (Ord a)
=> (a -> a -> a) -> [a] -> [a]
collect f = trace (collect' f)
collectMaxs = collect max
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment