Element promotion
Sometimes you have a list and you want to "promote" one element toward the front of the list. Essentially, you need to swap the element with its immediate predecessor (if it exists). Write a function promote
that takes a predicate and a list. If the predicate is true, the element should be promoted.
Examples
(promote even? [1 3 5 6]) ;=> (1 3 6 5)
(promote even? []) ;=> ()
(promote even? [2 1]) ;=> (2 1)
(promote even? [0 2 4 6]) ;=> (0 2 4 6)
(promote even? [0 1 2 3 4 5 6]) ;=> (0 2 1 4 3 6 5)
(promote even? [1 2 2 2 2]) ;=> (2 2 2 2 1)
Thanks to Enzzo Cavallo for the challenge idea!
Please submit your solutions as comments on this gist.
To subscribe: https://purelyfunctional.tv/newsletter/
@steffan-westcott Oof, that's what I get for trying to flail a language feature that I stopped using long time ago, only to misrepresent my gang affiliation for some cheap gist cred. I really do like your version and its rather elegant single predicate split. Alas! ;-)
(Let's be honest, IRL I'd just
loop
it. Because of course I'll putlazy-seq
in the wrong place. :P)