跳轉到內容

Haskell/種類

來自 Wikibooks,開放世界中的開放書籍

面向 C++ 使用者的種類

[編輯 | 編輯原始碼]
  • * 是任何具體型別,包括函式。它們都具有 * 種類
 type MyType = Int
 type MyFuncType = Int -> Int
 myFunc :: Int -> Int
 typedef int MyType;
 typedef int (*MyFuncType)(int);
 int MyFunc(int a);
  • * -> * 是一個接受一個型別引數的模板。它就像一個從型別到型別的函式:你輸入一個型別,結果是一個型別。MyData 的兩種用法可能會造成混淆(儘管你可以隨意為它們取不同的名稱) - 第一個是型別建構函式,第二個是資料建構函式。它們分別等效於 C++ 中的類模板和建構函式。上下文可以解決歧義 - 在 Haskell 期望型別的地方(例如,在型別簽名中),MyData 是一個型別建構函式,在期望值的地方,它是一個數據建構函式。


 data MyData t -- type constructor with kind * -> *
               = MyData t -- data constructor with type a -> MyData a
 *Main> :k MyData
 MyData :: * -> *
 *Main> :t MyData
 MyData :: a -> MyData a
 template <typename t> class MyData
 {
    t member;
 };
  • * -> * -> * 是一個接受兩個型別引數的模板


 data MyData t1 t2 = MyData t1 t2
 template <typename t1, typename t2> class MyData
 {
    t1 member1;
    t2 member2;
    MyData(t1 m1, t2 m2) : member1(m1), member2(m2) { }
 };
  • (* -> *) -> * 是一個接受一個種類為 (* -> *) 的模板引數的模板


 data MyData tmpl = MyData (tmpl Int)
 template <template <typename t> class tmpl> class MyData
 {
    tmpl<int> member1;
    MyData(tmpl<int> m) : member1(m) { }
 };
華夏公益教科書