
Hello! I want to create two data types: a) Purchase, which represents purchase by a customer (two attributes - amount of the purchase and rebate, both Double's) b) Customer, which represents a customer and his/her purchases. This tuple has two attributes - customer ID and a list of all purchases. Customer ID is Int, list of all purchases is a list of instances of Purchase (see above item a)). So, I wrote this code: <code-snippet> data Purchase (price :: Double) (rebate :: Double) = -- error occurs here Purchase price rebate deriving (Show, Eq) data Customer (id :: Int) (purchases :: [Purchase]) = Participant id purchases deriving (Show, Eq) </code-snippet> When I try to load it into GHCi, I'm getting this error message: <error-message> Prelude> :reload Compiling Gs ( Gs.hs, interpreted ) Gs.hs:15: parse error on input `Double' Failed, modules loaded: none. </error-message> Line 15 is the first line of the code snippet above. I have three questions: a) How should I define the types of the attributes correctly? b) Is it possible to impose a constraint on the "constructor" of tuple Purchase, so that the compiler throws an error, if one tries to create a purchase where rebate is greater than price (rebate and price are given in absolute numbers; rebate is NOT a fraction of price) ? c) What is a correct name for "attributes" of tuples (such as price and rebate in Purchase) and "constructors" of tuples? Many thanks in advance Dmitri Pissarenko

Dmitri Pissarenko
a) How should I define the types of the attributes correctly?
data Purchase = P Double Double data Customer = C Int [Purchase] or, if you want named fields: data Purchase = P { price, rebate :: Double } data Customer = C { id :: Int, purchases :: [Purchase] }
b) Is it possible to impose a constraint on the "constructor" of tuple Purchase, so that the compiler throws an error, if one tries to create a purchase where rebate is greater than price (rebate and price are given in absolute numbers; rebate is NOT a fraction of price)?
One way would be to store it as a fraction, e.g. using an Int8 with implicit 256 (or 255) denominator, which elminates the problem. Or create a function that constructs only valid Purchases, and hide the P constructor (i.e. don't export it from the module).
c) What is a correct name for "attributes" of tuples (such as price and rebate in Purchase) and "constructors" of tuples?
I think the accepted lingo is "records with named fields". -kzm -- If I haven't seen further, it is by standing in the footprints of giants
participants (2)
-
Dmitri Pissarenko
-
Ketil Malde