Skip to content

Instantly share code, notes, and snippets.

@andyferris
Last active April 15, 2020 11:18
Show Gist options
  • Save andyferris/b4e633ae83f34ff54a31235d694077f8 to your computer and use it in GitHub Desktop.
Save andyferris/b4e633ae83f34ff54a31235d694077f8 to your computer and use it in GitHub Desktop.
function mapreduce(f, op, a::AbstractArray; init)
out = Ref(init)
foreach(a) do x
out[] = op(f(x), out[])
end
return out[]
end
function map(f, a::AbstractArray)
out = similar(a, Core.Compiler.return_type(f, Tuple{eltype(a)}))
map!(f, out, a)
return freeze(out)
end
function map!(f, out::AbstractArray, a::AbstractArray)
foreach(keys(out)) do i
@inbounds out[i] = f(a[i])
end
end
function foreach(f, a::AbstractArray)
for i in a
f(i)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment