I am trying to do the fractional knapsack problem in haskell so far I have
Code:
{- Input "how much can the knapsack hole <- x" "Possible items in sack [(label, value, weight), ...]" -}
knap x [] = []
knap x y = if length y == 1 then
The input list is in the form [([Char], Integer, Integer), … ] a list of lists of (list of chars, integer, and integer).
My problem is trying to pull out the label, value, and weight of each item that could possibly be put in the knapsack. (pulling values out of the list of lists)
In my prelude> prompt I am doing some trying by doing
ghci output:
Prelude> let x = [("label 1", 2, 14), ("label 2", 1, 15)]
Prelude> :t x
x :: [([Char], Integer, Integer)]
Prelude> length x
2
Prelude> x !! 0
("label 1",2,14)
Prelude> x !! 0 !! 1
<interactive>:1:1:
Couldn't match expected type `[a0]'
with actual type `([Char], Integer, Integer)'
Expected type: [[a0]]
Actual type: [([Char], Integer, Integer)]
In the first argument of `(!!)', namely `x'
In the first argument of `(!!)', namely `x !! 0'
As you can see I am trying to do list !! index !! index to try and pull a weight off of a “item”. What is the proper syntax to do this?
Well, the
!!operator only works on lists, as you can see from its type signature:[a] -> Int -> a.If you’d like to stick with tuples, you could define your own functions for 3-tuples in the style of
fstandsnd. You could do this with pattern matching; something like:However, it might be better to design a datatype for an item, and use records to extract the field you need.
Then to make a new item
xyou can uselet x = Item {label = "label 1", value = 2, weight = 14}Now you could model your knapsack as a list of items of type
[Item], and to get the value of the first item, you could usevalue $ knapsack !! 0, whereknapsackis your list of items.