5

haskell で代数 DT について学んでいます。私がやりたいのは、既存のものを「拡張」する新しい ADT を作成することです。私が望むものを表現する方法が見つかりません。誰かが別のパターンを提案したり、解決策を提案したりできますか? それらを異なるタイプにしたいのですが、コピーして貼り付けるのはばかげた解決策のようです。以下のコードは、私が求めているものを最もよく表しています。

data Power =
  Abkhazia |
  -- A whole bunch of World powers and semi-powers
  Transnistria
    deriving (Eq, Show)

data Country = 
  --Everything in Power | 
  Netural |
  Water
    deriving (Eq, Show)

編集:少し説明が必要だと思います...これができるようになりたいです(ghciで)

let a = Abkhazia :: Country

そしてそうではない

let a = Power Abkhazia :: Country
4

2 に答える 2

8

それらをツリーとして表す必要があります。

  data Power
      = Abkhazia
      | Transnistria
    deriving (Eq, Show)

  data Country 
      = Powers Power -- holds values of type `Power`
      | Netural      -- extended with other values.
      | Water
    deriving (Eq, Show)

編集:質問への拡張により、これは少し簡単になります。国と権力の両方のタイプは、「国」としていくつかの共通の動作を共有します。これは、Haskell のオープンで拡張可能な型クラス機能を使用して、データ型に共通の動作を与えることを示唆しています。例えば

  data Power = Abkhazia | Transistria 

  data Countries = Neutral | Water

次に、Power と Countries の両方が共有するものの型クラス:

  class Countrylike a where
      landarea :: a -> Int -- and other things country-like entities share

  instance Countrylike Power where
      landarea Abkhazia    = 10
      landarea Transistria = 20

  instance Countrylike Countries where
      landarea Neutral     = 50
      landarea Water       = 0

landareaその後、勢力または国できれいに使用できます。また、インスタンスを追加することで、将来的に新しいタイプに拡張できます。

于 2012-06-17T18:07:46.403 に答える
2
{-# LANGUAGE GADTs, StandaloneDeriving #-}
data POWER
data COUNTRY

data CountryLike a where
    Abkhazia :: CountryLike a 
    Transnistria :: CountryLike a
    Netural :: CountryLike COUNTRY
    Water :: CountryLike COUNTRY

deriving instance Show (CountryLike a)
deriving instance Eq (CountryLike a)

type Power      = CountryLike POWER
type Country    = CountryLike COUNTRY

foo :: Power
foo = Abkhazia

bar :: Country
bar = Abkhazia

baz :: Country
baz = Netural

編集: 代替案は次のようになりますtype Power = forall a. CountryLike a(利点:Powerのサブタイプを作成しCountryます。欠点: これにより、たとえばPower -> Int上位の型が作成され、煩わしい傾向があります (型推論など))

于 2012-06-17T22:55:40.680 に答える