Supporting functions that take multiple arguments

In practice, we would probably encounter functions that are more complex than this. For example, the function that requires speed-up probably requires multiple arguments and possibly keyword arguments as well. Our memoize function in the previous section assumes a single argument, so it would not work properly.

A simple way to fix this is illustrated as follows:

function memoize(f)
memo = Dict()
(args...; kwargs...) -> begin
x = (args, kwargs)
if haskey(memo, x)
return memo[x]
else
value = f(args...; kwargs...)
memo[x] = value
return value
end
end
end

The anonymous function being returned now covers any number of positional arguments and keyword arguments as specified in the splatted arguments, args... and kwargs.... We can quickly test this with a dummy function as follows:

# Simulate a slow function with positional arguments and keyword arguments
slow_op = (a, b = 2; c = 3, d) -> begin
sleep(2)
a + b + c + d
end

Then, we can create the fast version as follows:

op = memoize(slow_op)

Let's test the memoized function with a few different cases:

It's working great!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.33.41