4

我正在整理一个 Traveler 实现,并从定义我的数据结构开始。我在尝试定义Ship. 我从一些简单的data定义开始。

data Ship = Ship Cargo Hull Weapons Engines

data Cargo = WholeMagilla
           | MostOfIt
           | HalfOfIt
           | SomeOfIt

data Hull = Heavy
          | AboveAverage
          | Average
          | Meh

data Weapons = WarMonger
             | BadMofo
             | CautiousCarl
             | Pacifist

data Engines = WarpSuperFast
             | WarpFairlyFast
             | WarpFast
             | Turtle

现在这是我的问题。我想根据其他类型的值来限制一个类型可以是什么值。示例:可能Ship

Ship WholeMagilla Heavy Pacifist Turtle
Ship WholeMagilla Meh   WarMonger Turtle
Ship WholeMagilla Meh Pacifist WarpSuperFast

因此,如果 aPlayer有足够Credits的值,它们最多可以有两种类型的最大值,代价是最小化其余的值。那么,在这两者之间有所有的可能性。我开始可视化一个图形,其路径由该路径中已有的节点决定。这有助于我思考问题,但不能帮助我编写一个能够得到我想要的结果的函数。有人能指出我正确的方向吗?

4

1 回答 1

2

您可以将“信用”与您的对象相关联并使用智能构造函数。然后,将所有内容包装在一个模块中,只导出智能构造函数,而不导出构造Ship函数,这样用户就不会误用它。

这是代码(为简单起见,我已经剥离了您的构造函数):

data Ship = Ship Cargo Hull deriving Show  

class Credit a where                                                       
    credit :: a -> Int   

instance Credit Cargo where
    credit WholeMagilla = 1        
    credit MostOfIt = 2

instance Credit Hull where 
    credit Heavy = 1       
    credit AboveAverage = 2       

data Cargo = WholeMagilla                                                  
           | MostOfIt deriving Show

data Hull = Heavy                                                          
          | AboveAverage deriving Show

max_credit :: Int
max_credit = 3

ship :: Cargo -> Hull -> Ship
ship c h                                                                   
    | credit c + credit h < max_credit = Ship c h 
    | otherwise = error "Too many credits"  

main :: IO ()                                                              
main = do                                                                  
    print $ ship WholeMagilla Heavy     
    print $ ship WholeMagilla AboveAverage                                 
于 2012-08-23T20:01:32.653 回答