2013-03-29 12 views
3

하스켈을 신형으로하며 타입 시스템에 문제가 있습니다.하스켈 어디에서 타입 선언이

threshold price qty categorySize 
    | total < categorySize = "Total: " ++ total ++ " is low" 
    | total < categorySize*2 = "Total: " ++ total ++ " is medium" 
    | otherwise = "Total: " ++ total ++ " is high" 
    where total = price * qty 

하스켈로 응답 : 나는 다음과 같은 기능을 가지고

No instance for (Num [Char]) 
     arising from a use of `*' 
    Possible fix: add an instance declaration for (Num [Char]) 
    In the expression: price * qty 
    In an equation for `total': total = price * qty 
    In an equation for `threshold': 
    ... repeats function definition 

나는 문제가 어떻게 든 하스켈 전체의 종류를 말해, 어쩌면 형 클래스 표시와 연관시킬 필요가 있다고 생각 그러나 나는 그것을 성취 할 방법을 모른다. 어떤 도움을 주셔서 감사합니다.

답변

10

문제는 당신이 그것이 Num a => a로 한 다음 [Char]을 수를 강제로 문자열을 ++에 인수로 사용할 강제로 곱셈의 결과로 total을 정의합니다.

threshold price qty categorySize 
    | total < categorySize = "Total: " ++ totalStr ++ " is low" 
    | total < categorySize*2 = "Total: " ++ totalStr ++ " is medium" 
    | otherwise    = "Total: " ++ totalStr ++ " is high" 
    where total = price * qty 
      totalStr = show total 

자,이 실행되지만 코드는 약간의 반복 같습니다

당신은 String A를 total 변환해야합니다. 나는 다음과 같이 제안 할 것입니다 :

threshold price qty categorySize = "Total: " ++ show total ++ " is " ++ desc 
    where total = price * qty 
      desc | total < categorySize = "low" 
       | total < categorySize*2 = "medium" 
       | otherwise    = "high" 
3

문제는 문자열과 숫자 사이를 명시 적으로 변환해야한다는 것입니다. 하스켈은 문자열을 숫자로 또는 그 반대로 자동으로 강제 변환하지 않습니다.

표시 할 숫자를 문자열로 변환하려면 show을 사용하십시오.

문자열을 숫자로 구문 분석하려면 read을 사용하십시오. read은 실제로 많은 유형에 적용되므로 결과 유형을 지정해야 할 수 있습니다. 예 :

price :: Integer 
price = read price_input_string