Handling mutable data types in the arguments

So far, we did not pay much attention to the arguments or keyword arguments being passed to the function. Care must be taken when any of those arguments are mutable. Why? Because our current implementation uses the arguments as the key of the dictionary cache. If we mutate the key of a dictionary, it could lead to unexpected results.

Suppose that we have a function that takes 2 seconds to run:

# This is a slow implementationslow_sum_abs = (x::AbstractVector{T} where {T <: Real}) -> begin    sleep(2)    sum(abs(v) for v in x)end

Knowing that it's quite slow, we happily memoize it as usual:

sum_abs = memoize(slow_sum_abs)

Initially, it seems to work perfectly, as it has always been:

However, we are shocked ...

Get Hands-On Design Patterns and Best Practices with Julia now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.