Automatic memoizing in functional programming languages

前端 未结 6 538
故里飘歌
故里飘歌 2020-12-08 14:59

I always thought that Haskell would do some sort of automatic intelligent memoizing. E.g., the naive Fibonacci implementation

fib 0 = 0
fib 1 = 1
fib n = fib         


        
6条回答
  •  余生分开走
    2020-12-08 15:39

    For example of implementing automatic memoization, you may look at the Factor programming language and its Memoization vocabulary. For example, simple Fibonacci number generator:

    : fib ( n -- n )
        dup 1 > [
            [ 1 - fib ]
            [ 2 - fib ]
            bi +
        ] when ;
    

    may be memoized by replacing ":" word with "MEMO:"

    MEMO: fib ( n -- n )
        dup 1 > [
            [ 1 - fib ]
            [ 2 - fib ]
            bi +
        ] when ;
    

    In that case, fib inputs and corresponding outputs will be transparently stored within in-memory dictionary.

    Factor language syntax may be confusing :). I recommend you to watch video presentation from Google Tech Talks about Factor to understand, how is it possible to implement memoization in that way.

提交回复
热议问题