Haskell 中不同模块中的单独类和实例?

问题描述 投票:0回答:1

在一个模块中,我定义了一个类:

class Monad m => MonadTime m where
    currentTime :: m UTCTime

MonadTime
已导出。

在不同的模块中,我想创建一个实例:

-- MonadTime is imported

instance MonadTime IO where
    currentTime :: IO UTCTime
    currentTime = Data.Time.Clock.getCurrentTime

但是,问题是:

‘currentTime’不是类‘MonadTime’的(可见)方法

如果我将实例移动到定义类的第一个模块,则一切正常。但我的想法是在主模块中提供实现。

我该如何解决这个问题?

haskell
1个回答
0
投票

需要用方法导出,所以:

module MyModule(MonadTime(currentTime)) where

class Monad m => MonadTime m where
    currentTime :: m UTCTime

在另一个模块中:

module MyOtherModule where

import MyModule(MonadTime(currentTime))

instance MonadTime IO where
    currentTime :: IO UTCTime
    currentTime = Data.Time.Clock.getCurrentTime
© www.soinside.com 2019 - 2024. All rights reserved.