Skip to content

Instantly share code, notes, and snippets.

@mortenpi
Created June 4, 2019 05:14
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 mortenpi/fb7f26ffc9db56ea424f195288bb5287 to your computer and use it in GitHub Desktop.
Save mortenpi/fb7f26ffc9db56ea424f195288bb5287 to your computer and use it in GitHub Desktop.
Function to partition a set according to a predicate.
"""
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