[英]What is the type keyword in Haskell
偶然發現 Haskell 中的 type 關鍵字:
type Item = String
但不確定它的作用,如何使用它或它與data
有何不同。 在線谷歌搜索沒有任何幫助。
我嘗試在這樣的代碼中實現它:
import System.IO
main = do
putStrLn "Hello, what's your name?"
type Item = String
let test :: Item
test = "chris"
putStrLn test
但我有一個錯誤
解析輸入“類型”的錯誤
請用外行的話來說什么是type
,如何使用它,它與數據有什么不同?
它是一個類型別名。 這意味着您可以在代碼中使用Item
,而您可以使用String
。
例如,當您想要為更復雜的類型命名時,通常會使用類型別名。 例如:
import Data.Map(Map)
type Dictionary = Map String String
在這里你可以使用Dictionary
而不是每次都寫Map String String
。
此外,如果您想指定您正在使用Item
,則經常使用它,然后在類型簽名和文檔中使用別名,這通常比編寫String
更好。
如果您還不知道要為特定 object 使用哪種類型,也可以使用它。 通過使用類型別名,您可以使用Item
,並且稍后如果您更改了為Item
定義類型或使其成為另一種類型的別名。 這使得更改類型更加方便。
我嘗試在這樣的代碼中實現它:import System.IO main = do putStrLn "Hello, what's your name?" type Item = String let test:: Item test = "chris" putStrLn test
類型別名是在頂層定義的,所以不在do
塊中,這會使類型定義在本地范圍內。 雖然,就像@moonGoose 所說,有一些建議可以使類型定義更具本地范圍,但目前情況並非如此。
您可以定義類型別名,如:
import System.IO
type Item = String
main = do
putStrLn "Hello, what's your name?"
let test :: Item
test = "chris"
putStrLn test
type A = B
意思完全一樣
typedef B A
在 C 或 C++ 中,它的行為與簡單的基本相同
a = b
除了A
和B
是類型級別的實體,而不是值級別的實體。 例如
Prelude> type A = Int
Prelude> :i A
type A = Int -- Defined at <interactive>:1:1
Prelude> a = 37
Prelude> a
37
因為現在A = Int
,我可以在任何地方都使用類型標識符A
我也可以直接使用Int
:
Prelude> 37 :: Int
37
Prelude> 37 :: A
37
乃至
Prelude> (37 :: Int) :: A
37
請注意,這里沒有進行類型轉換,就像您在其他語言中可能所做的那樣。 Int
和A
只是同一類型的不同名稱,因此使用兩者進行注釋只是重言式。
將此與data
(或newtype
)進行對比,后者定義了一個新的、單獨的類型,恰好包含指定類型的數據。
Prelude> data A' = A' { getA :: Int }
Prelude> (37 :: Int) :: A'
<interactive>:12:2: error:
• Couldn't match expected type ‘A'’ with actual type ‘Int’
• In the expression: (37 :: Int) :: A'
In an equation for ‘it’: it = (37 :: Int) :: A'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.