【发布时间】:2019-09-18 06:28:18
【问题描述】:
假设我想为UTCTime 创建一个包装器:
data CustomDateStamp = CustomDateStamp
{
stampValue :: UTCTime
} deriving (Show, Eq, Ord, Typeable)
现在说我想为“现在”构建一个默认值,例如
instance Default CustomDateStamp where
def = CustomDateStamp getCurrentTime def
这(显然)失败了:
• Couldn't match expected type ‘UTCTime’
with actual type ‘IO UTCTime’
• In the first argument of ‘CustomDateStamp’, namely ‘getCurrentTime’
In the expression: CustomDateStamp getCurrentTime def
In an equation for ‘def’: def = CustomDateStamp getCurrentTime def
|
98 | def = CustomDateStamp getCurrentTime def
| ^^^^^^^^^^^^^^
我的问题是,如何在实例定义中使用副作用操作?这甚至可能吗?处理这种情况的首选方法是什么?
【问题讨论】:
-
这不是一个好主意。在惰性语言中,很难预测表达式何时被评估,但另一方面,我们并不在意,因为纯度确保最终结果是相同的。您的实例破坏了此属性:
let t=def in (t,t)不再等同于(def, def),因为后者可以评估为具有不同组件的对。更务实的是,def可能仅在打印到屏幕时而不是在创建时进行评估,从而导致非常令人费解的时间戳。
标签: haskell types default monads side-effects