Data.MemoCombinators, where can I find examples?

前端 未结 2 1102
小鲜肉
小鲜肉 2021-02-15 12:38

This package has some functions to turn recursive functions into dynamic programming recursive functions, for better performance:

http://hackage.haskell.org/packages/arc

相关标签:
2条回答
  • 2021-02-15 13:17

    The library defines the type Memo a, which is a "memoizer" for functions taking arguments of type a. The key to understanding how to use this library is to understand how to use and compose these memoizers.

    In the simple case, you have a single argument function and a simple memoizer, for example a Fibonacci function and a memoizer for Integral arguments. In such a case, we obtain the memoized function by applying the memoizer to the function to be memoized:

     fib = Memo.integral fib'
       where
         fib' 0 = 0
         fib' 1 = 1
         fib' x = fib (x-1) + fib (x-2)
    

    Some memoizers take arguments to customize their behavior, for example arrayRange. In the following example, fib n will only be memoized if n is between 1 and 100.

    fib = Memo.arrayRange (1, 100) fib'
      where ...
    

    The library also provides combinators for building more complex memoizers out of simple ones. For example, list, which turns a memoizer for a into a memoizer for [a].

    Finally, to memoize functions of multiple arguments there are the functions memo2 and memo3, which take a memoizer for each argument plus a function and returns a memoized function.

    So to memoize your two-argument function, we will need to use memo2. We can use the integral memoizer for the Int argument, and for the [Int] argument we can use list integral. Putting this together, we get something like this:

    memo2 (list integral) integral foo
    

    However, you can also use more specific memoizers if you know the numbers are in some specified range. For example, if the numbers in the list are between 1 and 10 and the second argument is between 15 and 20:

    memo2 (list $ arrayRange (1, 10)) (arrayRange (15, 20)) foo
    

    Whether this makes sense or not, depends on your application.

    0 讨论(0)
  • 2021-02-15 13:39

    Per types and documentation, I believe

    foo :: [Int] -> Int -> Int
    

    should be memoised per

    memo2 (list integral) integral foo
    

    (disclaimer: I haven't used data-memocombinators).

    0 讨论(0)
提交回复
热议问题