有一個名爲數據類型的上下文棄用的功能,可以讓你做到這一點:
{-# LANGUAGE DatatypeContexts #-}
data Num a => Time a = Second a deriving (Show)
t = Second (5 :: Int)
main = print t
這對執行GHC 7.8.3(對不起,沒有7.10檢查),但警告你這個折舊:
t.hs:1:14: Warning:
-XDatatypeContexts is deprecated: It was widely considered a
misfeature, and has been removed from the Haskell language.
Second 5
非過時的方式來做到這一點是使用Generalized Algebraic Datatypes(GADTs)(並且你需要獨立deriving
以及):
{-# LANGUAGE GADTs, StandaloneDeriving #-}
data Time a where
Second :: Num a => a -> Time a
deriving instance Show a => Show (Time a)
t = Second (5 :: Int)
main = print t
如果試圖創建一些變量非Num
,你會得到一個編譯錯誤:
t = Second "a"
t.hs:12:5:
No instance for (Num [Char]) arising from a use of ‘Second’
In the expression: Second "a"
In an equation for ‘t’: t = Second "a"
你確定有一個任意的'Num'?如果我在'Import Data.Complex'之後做了'秒(1:+ 2)'會怎麼樣?允許複雜的時間有意義嗎?相反,最好是有多個構造函數,所以'data Time = Seconds Int |毫秒Int |微秒Int |分鐘Int |小時國際? – bheklilr
根據F先生和本,似乎標準沒有任何限制(更不用說Num了)。 – GeneralBecos