2012-07-30 4 views
2

여기 분수 배낭 문제를 해결하려면 코드입니다 받았다, 망치로 깨다에 입력하스켈, 배낭 예상하지 반환 형식 오류가

[("label 1", value, weight), ("label 2", value, weight), ...] 

그리고 출력 형식이어야합니다 형식이어야합니다

[("label 1", value, solution_weight), ("label 2", value, solution_weight), ...] 

코드 : 여기

import Data.List {- Need for the sortBy function -} 
{- Input "how much can the knapsack hole <- x" "Possible items in sack [(label, value, weight), ...] <- y" -} 
{-knap x [([Char], Integer, Integer), ... ] = -} 
knap x [] = [] 
knap x y = if length y == 1 
    then 
     if x > last3 (head y) 
      then y 
      else [(frst3 (head y), scnd3 (head y), x)] 
    else 
     knap2 x y [] 
{- x is the knap max, y is the sorted frac list, z is the solution list -} 
knap2 x y z = if x == 0 
    then z 
    else 
     if thrd4 (head y) > x 
      then [((frst4 (head y)), (scnd4 (head y)), x)] 
      else knap2 (x-(thrd4 (head y))) (tail y) (z++[((frst4 (head y)), (scnd4 (head y)), (thrd4 (head y)))]) 

{- take a list of labels, values, and weights and return list of labels and fractions -} 
fraclist :: (Fractional t1) => [(t, t1, t1)] -> [(t, t1, t1, t1)] 
fraclist xs = [(x, y, z, y/z) | (x, y, z) <- xs] 

{- Sort the list -} 
sortList x = sortBy comparator x 
    where comparator (_,_,_,d) (_,_,_,h) = if d > h then LT else GT 

{- helper func to get values from tuples -} 
frst3 (a,b,c) = a 
scnd3 (a,b,c) = b 
last3 (a,b,c) = c 
frst4 (a,b,c,d) = a 
scnd4 (a,b,c,d) = b 
thrd4 (a,b,c,d) = c 
last4 (a,b,c,d) = d 

내가

무엇입니까 오류입니다
Couldn't match expected type `(t1, t0, t2, t3)' 
      with actual type `(t1, t0, t2)' 
Expected type: [(t1, t0, t2, t3)] 
    Actual type: [(t1, t0, t2)] 
In the second argument of `knap2', namely `y' 
In the expression: knap2 x y [] 

나는 내가 할 수있는 것이 무엇인지 잘 모릅니다. 내가 여기 앉아서 한 시간 동안 벽에 내 머리를 쾅 쾅 쾅쾅 찌그러 뜨리기 전에 누군가 분명히 실수를 지적 할 수 있겠는가? 당신은 오류가 knap2 x y []에 사용되는 인수 y에 있음을 알 수

:

답변

2

내가 knap에서 knap2의 4-튜플과 세 튜플 함께 맞게 생각하는 방법을 말할 수 있지만, 당신이 패턴 일치와 head, tail 드롭 경우 문제의 훨씬 더 명확하게 볼 수있을 것이다, thrd4, thirteenth17

knap _ []  = [] 
knap x [(a,b,c)] = if x > c then [(a,b,c)] else [(a, b, x)] 
knap x abcs  = knap2 x abcs [] 

knap2 0 abcs z = z 
knap2 x abcs z = undefined -- not sure how to do this 

-- but this makes sense, it seems: 
knap3 0 _ zs = zs 
knap3 _ [] _ = [] 
knap3 x ((a,b,c,d):abcds) zs = 
    if c > x then [(a, b, x)] 
      else knap3 (x - c) abcds (zs ++ [(a, b, c)]) 

또는 그런 일. if length y == 1을 쓰는 대신 싱글 톤의 경우 패턴 매치를 할 수 있습니다. 평등 테스트 대신 if x == 0을 사용하면 0 경우에 패턴 일치를 수행하여 다른 경우와 구별 할 수 있습니다.

0

편집, 나는 다시, 엉망. 3 배 (실제 유형)이지만 knap2이 4 배가 될 것으로 예상합니다.

+0

knap2는 int, 쿼드 목록 및 트립 목록을 취합니다. 나는 그 전화를 어떻게 제공하지 않는지 모르겠다. Knap2를 knap2로 호출하는 것이 맞습니까? –

+0

아 맞아, 당신의'y'는 3 배가되지만, knap2의 두번째 인수로 전달합니다. –

+0

내 맙소사. 나는 모든 시간을 정렬과 frac 기능을 쓰는 데 보냈다. 나는 그들을 사용하는 것을 잊었다. ......... 나는 그것을 사랑한다. –