Last active
December 19, 2017 23:28
-
-
Save emmanueldenloye/4637200f0f9c0afed37fabee9be231d0 to your computer and use it in GitHub Desktop.
collect maximum elements of a list in one pass
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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