Real World Haskell - 第3章 Part3 Algebraic data types
Real World Haskell で Haskell を継続的に勉強中。
Defining Types, Streamlining Functions
Chapter 3. Defining Types, Streamlining Functions
Algebraic data types
- algebraic data type は value constructor を複数持てる
data Bool = False | True
type CardHolder = String type CardNumber = String type Address = [String] data BillingInfo = CreditCard CardNumber CardHolder Address | CashOnDelivery | Invoice CustomerID deriving (Show)
- Algebraic data types は構造が同じだけど意味が違うデータを区別できる
- tuple では無理
If you're using compound values widely in your code (as almost all non-trivial programs do), adding data declarations will benefit you in both type safety and readability.
- C/C++ の struct との違い
The main difference between the two is that the fields in the Haskell type are anonymous and positional.
In C, the elements of an enum are integers.
- C/C++ の union との違い
A big difference between the two is that a union doesn't tell us which alternative is actually present;
参考