就我个人而言,我会去RecordWildCards
并称它为一天。但是,这是另一个有趣的方式,在某些情况下可能会很有用:谨慎风,使用动态类型来获得改变类型的折叠!
{-# LANGUAGE DeriveDataTypeable #-}
import Data.Dynamic (dynApp, fromDynamic, toDyn)
import Data.List (foldl')
import Data.Typeable (Typeable)
-- Add the 'Typeable' instance to enable runtime type information.
data Zone = Zone
{ zId, zOwnerId, zPodsP0, zPodsP1, zPodsP2, zPodsP3 :: Int
} deriving (Show, Typeable)
mkZone :: [String] -> Maybe Zone
mkZone = fromDynamic . foldl' dynApp (toDyn Zone) . map (toDyn . readInt)
where
-- This type-specialised 'read' avoids an ambiguous type.
readInt :: String -> Int
readInt = read
这将启动类型从Zone
构造,:
Int -> Int -> Int -> Int -> Int -> Int -> Zone
然后相继其应用于每个Int
从输入读取,改变它的类型:
Int -> Int -> Int -> Int -> Int -> Zone
Int -> Int -> Int -> Int -> Zone
Int -> Int -> Int -> Zone
Int -> Int -> Zone
Int -> Zone
Zone
而且它的工作原理:
> mkZone ["1", "2", "3", "4", "5", "6"]
Just (Zone {zId = 1, zOwnerId = 2, zPodsP0 = 3, zPodsP1 = 4, zPodsP2 = 5, zPodsP3 = 6})
如果提供的参数太少,你会得到Nothing
因为运行时转换失败:
> mkZone ["1", "2", "3", "4", "5"]
Nothing
不过,如果你提供太多许多参数,你会得到一个异常:
> mkZone ["1", "2", "3", "4", "5", "6", "7"]
*** Exception: Type error in dynamic application.
Can't apply function <<Zone>> to argument <<Int>>
这是很容易通过使用dynApply
而不是dynApp
来修复,其返回Maybe
而不是抛出。而且只要你在Maybe
正在工作,你还不如用Text.Read.readMaybe
处理分析错误:
{-# LANGUAGE DeriveDataTypeable #-}
import Control.Monad ((<=<))
import Data.Dynamic (Dynamic, dynApply, fromDynamic, toDyn)
import Data.List (foldl')
import Data.Typeable (Typeable)
import Text.Read (readMaybe)
data Zone = Zone { … } deriving (Show, Typeable)
mkZone :: [String] -> Maybe Zone
mkZone = fromDynamic <=< foldl' go (Just (toDyn Zone)) . map readInt
where
go :: Maybe Dynamic -> Maybe Int -> Maybe Dynamic
go mAcc mx = do
acc <- mAcc
x <- mx
dynApply acc $ toDyn x
readInt :: String -> Maybe Int
readInt = readMaybe
真正虽然,可能不这样做。