Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, your criterion for an unboxed data structure is probably a bit mislead. Unboxed values <em>must</em> be strict, and they have nothing to do with immutability. The solution I'm going to propose is immutable, lazy, and boxed. Also, I'm not sure in what way you are wanting construction and querying to be O(1). The structure I'm proposing is lazily constructed, but because it's potentially unbounded, its full construction would take infinite time. Querying the structure will take O(k) time for any particular key of size k, but of course the value you're looking up may take further time to compute.</p> <p>The data structure is a lazy trie. I'm using Conal Elliott's MemoTrie library in my code. For genericity, it takes functions instead of lists for the weights and values.</p> <pre><code>knapsack :: (Enum a, Num w, Num v, Num a, Ord w, Ord v, HasTrie a, HasTrie w) =&gt; (a -&gt; w) -&gt; (a -&gt; v) -&gt; a -&gt; w -&gt; v knapsack weight value = knapsackMem where knapsackMem = memo2 knapsack' knapsack' 0 w = 0 knapsack' i 0 = 0 knapsack' i w | weight i &gt; w = knapsackMem (pred i) w | otherwise = max (knapsackMem (pred i) w) (knapsackMem (pred i) (w - weight i)) + value i </code></pre> <p>Basically, it's implemented as a trie with a lazy spine and lazy values. It's bounded only by the key type. Because the entire thing is lazy, its construction before forcing it with queries is O(1). Each query forces a single path down the trie and its value, so it's <strike>O(1) for a bounded key size</strike> O(log n). As I already said, it's immutable, but not unboxed.</p> <p>It will share all work in the recursive calls. It doesn't actually allow you to print the trie directly, but something like this should not do any redundant work:</p> <pre><code>mapM_ (print . uncurry (knapsack ws vs)) $ range ((0,0), (i,w)) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload