5

I am implementing a function with the following signature to solve the 0-1 knapsack problem in Haskell.

knapsack :: [Item] -> Capacity -> [Item]

Where the Item and Capacity files are defined as:

type Value = Int
type Weight = Int

type Capacity = Int

type Item = (Value, Weight)

I'd like to memoize it to have better performances. I tried to use Data.MemoCombinators but I can't get how to have it work.

Can you give me some hints?

2
  • Can you post your Item and Capacity types? This is necessary to define a memoization function for them. Commented Dec 29, 2012 at 21:05
  • Sure, I just edited my question. They're simply an pair of integers and an integer Commented Dec 29, 2012 at 21:11

2 Answers 2

6

I successfully used MemoTrie for tasks like this. Each type that you want to use as a memoization index must implement HasTrie. In your case, you don't have to imlement anything, because the package already provides instances for the primitive data types as well as for pairs and lists.

import Data.MemoTrie

type Value = Int
type Weight = Int

type Capacity = Int

type Item = (Value, Weight)

knapsack :: [Item] -> Capacity -> [Item]
knapsack = memo2 knapsack'
  where
    knapsack' items capacity = ... -- your computation goes here
Sign up to request clarification or add additional context in comments.

Comments

2

If you're looking for performance optimization for operations on lists, I'd suggest to take a look at the strict iteration functions, for example Data.List.foldl':

foldl' :: (a -> b -> a) -> a -> [b] -> a

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.