Efficient table for Dynamic Programming in Haskell

后端 未结 5 1674
青春惊慌失措
青春惊慌失措 2021-01-31 06:03

I\'ve coded up the 0-1 Knapsack problem in Haskell. I\'m fairly proud about the laziness and level of generality achieved so far.

I start by providing functions for crea

5条回答
  •  死守一世寂寞
    2021-01-31 06:18

    To memoize functions, I recommend a library like Luke Palmer's memo combinators. The library uses tries, which are unbounded and have O(key size) lookup. (In general, you can't do better than O(key size) lookup because you always have to touch every bit of the key.)

    knapsack :: (Int,Int) -> Solution
    knapsack = memo f
        where
        memo    = pair integral integral
        f (i,j) = ... knapsack (i-b,j) ...
    


    Internally, the integral combinator probably builds an infinite data structure

    data IntTrie a = Branch IntTrie a IntTrie
    
    integral f = \n -> lookup n table
         where
         table = Branch (\n -> f (2*n)) (f 0) (\n -> f (2*n+1))
    

    Lookup works like this:

    lookup 0 (Branch l a r) = a
    lookup n (Branch l a r) = if even n then lookup n2 l else lookup n2 r
         where n2 = n `div` 2
    

    There are other ways to build infinite tries, but this one is popular.

提交回复
热议问题