我正在努力实现无限背包问题解决方案。我想使用递归和memoization而不是显式状态。
但问题是我找不到在有效的Haskell中表达思想的方法。这两个版本都给了我
parse error on input ‘=’
Perhaps you need a 'let' in a 'do' block?
e.g. 'let x = 5' instead of 'x = 5'
bestUnbounded :: [Integer] -> Integer -> ([Integer], Integer)
bestUnbounded items capacity = if capacity <= 0
then ([], 0)
else maximumBy (comparing snd) solutions
where solutions = filter (\ s -> snd s <= capacity) $ map solve items
solve i = (solution, weight + i)
where solution, weight = bestUnbounded items (capacity - i)
bestUnbounded :: [Integer] -> Integer -> ([Integer], Integer)
bestUnbounded items capacity
| capacity <= 0 = ([], 0)
| otherwise = maximumBy (comparing snd) solutions
where solutions = filter (\ s -> snd s <= capacity) map solve items
solve i = let solution, weight = bestUnbounded items (capacity - i)
in (solution, weight + i)
如果有人也可以展示如何使用Data.Func.Memoize
,我也会感激不尽。
EDIT1
工作解决方案
import Data.List (maximumBy)
import Data.Ord (comparing)
import Data.Function.Memoize (memoize)
bestUnbounded :: [Integer] -> Integer -> ([Integer], Integer)
bestUnbounded items capacity
| capacity <= 0 = ([], 0)
| otherwise = solver' capacity
where solver' = memoize solver
solver capacity = maximumBy (comparing snd) solutions
solutions = filter (\ s -> snd s <= capacity) $ map solve items
solve i = let (solution, weight) = bestUnbounded items (capacity - i)
in (i : solution, weight + i)
答案 0 :(得分:1)
这在语法上无效:
solution, weight = bestUnbounded items (capacity - i)
我认为您打算在(,)
上进行模式匹配,如下所示:
(solution, weight) = bestUnbounded items (capacity - i)
对于构造和模式匹配,元组语法总是需要括号。