Skip to content

Instantly share code, notes, and snippets.

@xitology

xitology/it.jl Secret

Last active December 11, 2020 18:08
Show Gist options
  • Save xitology/347e01ed012e9e2a5530c719b7163500 to your computer and use it in GitHub Desktop.
Save xitology/347e01ed012e9e2a5530c719b7163500 to your computer and use it in GitHub Desktop.
struct It{F}
f::F
end
const it = It(identity)
(i::It)(x) = getfield(i, :f)(x)
(i::It)(xs...) = getfield(i, :f)(xs)
Base.getproperty(i::It, name::Symbol) = getproperty.(i, name)
Base.getindex(i::It, key) = getindex.(i, key)
struct ItStyle <: Base.BroadcastStyle
end
Base.BroadcastStyle(::Type{<:It}) = ItStyle()
Base.BroadcastStyle(::ItStyle, ::Base.Broadcast.DefaultArrayStyle{0}) = ItStyle()
Base.broadcastable(i::It) = i
Base.Broadcast.instantiate(bc::Base.Broadcast.Broadcasted{ItStyle}) = bc
Base.copy(bc::Base.Broadcast.Broadcasted{ItStyle}) =
It(x -> bc.f(((arg isa It) ? arg(x) : arg[] for arg in bc.args)...))
Base.filter(f) = xs -> filter(f, xs)
Base.map(f) = xs -> map(f, xs)
Base.foldl(f) = xs -> foldl(f, xs)
@show 1:10 |> filter(isodd.(it)) |> map(it .* 2) |> foldl(it[1] .+ it[2])
#-> 50
@show [(x = 10, y = 20), (x = 30, y = 20)] |> filter(it.x .> it.y) |> map(it.x .+ it.y) |> sum
#-> 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment