Modify

Functions to modify, filter and discard elements of a collection.

Modifying

modify applies a function f to each element of x.

using TidierIteration;

x = [1:4;]
modify!(x, x->x^2)
x
4-element Vector{Int64}:
  1
  4
  9
 16

It also work on dictionaries, keeping the keys intact:

d = Dict(i => i for i in [1:4;])
modify(d, x->x^2)
Dict{Int64, Int64} with 4 entries:
  4 => 16
  2 => 4
  3 => 9
  1 => 1

We can also modify only when a function p is true:

y = [1:6;]
modify_if(y, x->x^2, isodd)
6-element Vector{Int64}:
  1
  2
  9
  4
 25
  6

Filtering

We can discard some elements of x when a function p is false:

using TidierIteration;

x = [1:4;]
keep(x, isodd)
2-element Vector{Int64}:
 1
 3

This is the same as base Julia filter(p, x). It also work on dictionaries:

d = Dict(i => i for i in [1:4;])
keep(x, isodd)
2-element Vector{Int64}:
 1
 3

If we want to apply p to the keys of a dictionary, use

d = Dict(i => i^2 for i in [1:4;])
keep_keys(d, isodd)
Dict{Int64, Int64} with 2 entries:
  3 => 9
  1 => 1

There is also the negation of keep: discard. It’s definition is trivial: discard(x, p) = keep(x, !p).

When we want to throw away “length zero elements”, use compact:

x = [1, [1, 2], nothing, [], ""]
compact(x)
2-element Vector{Any}:
 1
  [1, 2]