2017-02-25 1 views
0

하스켈을 praticing하고 있습니다. 전자 영화 상점을 만들려고합니다. 오류 : 리터럴에서 발생하는 (Num Price) 인스턴스가 없습니다.

나는 유형 Code, Name, GenrePrice, 튜플 Movie과 튜플 목록 Movies 등을 만들어 나는 tableMovies 메시지 표시에 영화를 추가하려고하면

Prelude> :l movies 
[1 of 1] Compiling Main    (movies.hs, interpreted) 

movies.hs:11:45: 
    No instance for (Num Price) arising from the literal `50' 
    Possible fix: add an instance declaration for (Num Price) 
    In the expression: 50 
    In the expression: (1, "Movie 1", "Adventure", 50) 
    In the expression: 
     [(1, "Movie 1", "Adventure", 50), (2, "Movie 2", "Horror", 30)] 
Failed, modules loaded: none. 
Prelude> 

내 코드 :

type Code = Integer 
type Name = String 
type Genre = String 
data Price = Integer | Float 

type Movie = (Code, Name, Genre,Price) 

type Movies = [(Movie)] 

tableMovies :: Movies 
tableMovies = [ (001,"Movie 1", "Adventure",50) 
      , (002,"Movie 2", "Horror", 30)] 

이 문제에 대한 답변을 찾았지만 코드가 매우 복잡하기 때문에 이해할 수 없었습니다. 유형 Price 및 상수 IntegerFloat : 만이 줄은 세 가지를 생성 하스켈

답변

4
data Price = Integer | Float 

에 시작 해요. 당신이 Integer과 (유형 Price의) Float (유형 Price의) 새로운 값이 귀하의 경우에는

data Bool = False | True 

: 정확히처럼 작동합니다. 이는 유형IntegerFloat과 관련이 없습니다. 50Price 유형의 값이 아닙니다 (Price에는 가능한 값이 두 개만 있음).

형식과 값이 다른 네임 스페이스에 있기 때문에 모든 것이 혼란 스럽습니다. X 유형과 X 값을 가질 수 있으며 서로 관련이 없습니다 (또는 귀하의 경우 Integer 유형 및 Integer 값). 이제

data Price = PriceInteger Integer | PriceFloat Float 

당신이 PriceInteger 50을 할 수 있으며 유형 Price이있을 것이다 (하지만 여전히 베어를 사용할 수 없습니다 : 정수 또는 부동 소수점 하나를 포함하는 형식을 만들려면

, 당신은이 작업을 수행 할 수 있습니다 50). type Price = Integer을 수행하고 수레를 허용하지 않는 것이 더 쉽습니다.

1

FloatIntegerdata 선언의 오른쪽에 - 그들은 즉, 유형을 가지 생성자이기 때문에 당신은 유형에 비해 다른 우주의 시민으로 그들을 볼 수 있습니다.

당신이

data Price = I Integer | F Float deriving (Eq,Show) 

에있는 합계 Integer의 종류와 Float을 갖고 싶어하지만 경우는 scientific에서 하나 Data.Ratio에서 Rational 또는 Scientific로 화폐 가치를 대표하고에 formatting 패키지를 사용하는 것이 가장 좋은 것입니다 고정 된 정밀도의 문자열 표현을 만든다.

import Data.Ratio (Rational) 
import Formatting 

newtype Price = Price {getPrice :: Rational} 
instance Show Price where 
    show (Price p) = formatToString (fixed 2) p 
관련 문제