【发布时间】:2012-07-30 17:07:10
【问题描述】:
到目前为止,我正在尝试在 haskell 中解决分数背包问题
代码:
{- 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
输入列表的形式为 [([Char], Integer, Integer), ... ] 列表列表 (list of chars, integer, and integer)。
我的问题是试图找出可能放入背包的每件物品的标签、价值和重量。 (从列表列表中提取值)
在我的前奏中>提示我正在做一些尝试
ghci 输出:
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'
如您所见,我正在尝试做列表!指数 !!索引以尝试从“项目”中拉出重量。这样做的正确语法是什么?
【问题讨论】:
-
您是否忘记了第一个代码块中的
if表达式的其余部分?此外,[([Char], Integer, Integer)]是一个元组列表,这不是您想要实现的目标。您可能正在寻找[[([Char], Integer, Integer)]]。 -
如果我必须允许输入是一个元组列表,我如何获得元组中的值?