简体   繁体   中英

How to use pattern matching inside a function?

I'm struggling with implementation of an unbounded knapsack problem solver. I want to use recursion and memoization instead of explicit state.

But the problem is that I can't find a way to express my thoughts in valid Haskell. Both versions This gives me

    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)

If anyone could also show how to use Data.Func.Memoize on that I would be also grateful.

EDIT1

Working solution

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)

This isn't syntactically valid:

solution, weight = bestUnbounded items (capacity - i)

I think you meant to pattern match on (,) like this:

(solution, weight) = bestUnbounded items (capacity - i)

The tuple syntax always requires parentheses, for both construction and pattern matching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM