I have a function constant to its argument, e.g.
let is_prime x = (test)
But it is quite large and slow. Therefore, I want the result to be calculated only once, when I call it as often as I want.
I tried to do it the way I did it in non-working languages:
let _is_prime x = (test)
let mutable _is_prime_primes = []
let mutable _is_prime_tested = []
let is_prime x =
if List.exists (fun el -> el = x) _is_prime_primes then
true
else
if List.exists (fun el -> el = x) _is_prime_tested then
false
else
let result = _is_prime x
if result then _is_prime_primes <- x :: _is_prime_primes
_is_prime_tested <- x :: _is_prime_tested
result
But I think that I am deeply mistaken. Caching such a result should be something very common and simple for functional languages.
source
share