安装 data-default-class 和 data-default-extra
$ cabal install data-default-class
Installed data-default-class-0.1.2.0
$ cabal install data-default-extra
Installed data-default-extra-0.1.0
Prelude> :set -hide-package data-default
Prelude> :m +Data.Default
Prelude Data.Default>
data-default-class 和 data-default-extra 这两个库为一大串基本类型提供了缺省值。
Prelude Data.Default> def :: Int
0
Prelude Data.Default> def :: Double
0.0
Prelude Data.Default> def :: (Int, Int)
(0,0)
Prelude Data.Default> def :: Maybe Int
Nothing
Prelude Data.Default> def :: String
""
Prelude Data.Default Data.Text> def :: Text
""
示例
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
import GHC.Generics
import Data.Default
data A = A Int Double deriving (Show, Generic)
instance Default A
data B = B Int Double deriving (Show, Generic, Default)
main = do
print (def :: A) -- A 0 0.0
print (def :: B) -- B 0 0.0