Skip to content

Instantly share code, notes, and snippets.

@gvdr
Created February 25, 2020 01:03
Show Gist options
  • Save gvdr/1094b1581a06a01bff6e56d08946522a to your computer and use it in GitHub Desktop.
Save gvdr/1094b1581a06a01bff6e56d08946522a to your computer and use it in GitHub Desktop.
# I'd live to use the usual mathematical notations to do summatories and productories
# turns out, in Julia it's pretty easy as long as we keep things simple
# as we can just embellish the already defined sum() and prod() function
# only tweak is choosing a negative step if we want to sum from i = N to M with N>M
# for the summatory:
function ∑(f::T;from::Int, to::Int) where T <: Function
step_sum = from > to ? 1 : -1
sum(safer(f), range(from, stop = to, step = step_sum))
end
# for the productory
function ∏(f::T;from::Int, to::Int) where T <: Function
step_sum = from > to ? 1 : -1
prod(safer(f), range(from, stop = to, step = step_sum))
end
# where we use the safer wrapper (something along the lines of R's purrr::safely()
function safer(my_function)
try
my_function
catch e
missing
end
end
# I was also playing with the idea of summatories where the Nth therm is defined as a function of the (N-1)th term
## this can clearly be done better:
function ∑ₛ(start::N, f::T;from::Int, to::Int) where N<:Number where T <: Function
step_sum = from < to ? 1 : -1
result = start
step_value = start
for i in from:step_sum:to
step_value = f(step_value)
result += step_value
end
return result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment