Result of caching function f #

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.

+3
source share
2 answers

Here is a detailed thread on this.

And here is the link to the online archive .

+3
source

FSI, F #.

let cache f =
    let dict = new Dictionary<_,_>()
    fun n ->
        if dict.ContainsKey(n) then dict.[n]
        else
            let r = f n
            dict.[n] <- r
            r

('a->'b) -> ('a->'b) when 'a : equality. . , . . , . :

let slow n = // 'a -> 'a
    System.Threading.Thread.Sleep(1000)
    n

let fast = cache slow // 'a -> 'a

fast 1 . .

+1

Source: https://habr.com/ru/post/1726829/


All Articles