Created
June 4, 2019 05:14
-
-
Save mortenpi/fb7f26ffc9db56ea424f195288bb5287 to your computer and use it in GitHub Desktop.
Function to partition a set according to a predicate.
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
""" | |
partition(f, xs) | |
Partitions a collection according to a predicate `f`. Similar to `filter`, but returns | |
the both the elements for which `f` is `true` and for which it is `false`, in two different | |
collections. | |
Returns a tuple of vectors, where the first vector contains the elements for which `f` is true | |
and the second the elements for which `f` is false. | |
""" | |
function partition(f, xs) | |
T = eltype(xs) | |
xs_true, xs_false = T[], T[] | |
for x in xs | |
f(x) ? push!(xs_true, x) : push!(xs_false, x) | |
end | |
return xs_true, xs_false | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment