Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching function result f#

Tags:

I have a function which is constant to its argument, for example

let is_prime x = (test)

But it's pretty large and slow. So I want the result of it to be calculated only once while I'm calling it as often as I want.

I've tried to do it in a way I did it in not functional 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 I'm deeply wrong. Caching such result must be something very common and simple for functional languages.

like image 679
Valentin Golev Avatar asked Dec 29 '09 20:12

Valentin Golev


1 Answers

Here is the Internet Archive link.

like image 167
Sedat Kapanoglu Avatar answered Oct 03 '22 23:10

Sedat Kapanoglu