Haskell中如何在不同模块分离类与实例?
问题解决方法
原因分析
报错的核心原因是:定义MonadTime类的模块中,类的方法currentTime未被正确导出,导致其他模块无法识别该方法;或者实例实现中显式添加的类型签名,需要编译器明确关联到类的方法,但方法不可见时就会触发错误。而将实例放在类定义模块时,方法默认可见,因此能正常运行。
方案一:修改类模块的导出列表
在定义MonadTime的模块里,导出类时明确包含其方法,确保其他模块能访问到currentTime:
module TimeClass (MonadTime(currentTime)) where import Data.Time.Clock (UTCTime) class Monad m => MonadTime m where currentTime :: m UTCTime
之后在主模块中正常导入并实现实例,保留类型签名也不会报错:
import TimeClass (MonadTime) import Data.Time.Clock (getCurrentTime, UTCTime) instance MonadTime IO where currentTime :: IO UTCTime currentTime = getCurrentTime
方案二:移除实例中的显式类型签名
如果不想修改类模块的导出配置,可以直接去掉实例里currentTime的类型签名,Haskell会通过类定义自动推断类型:
import TimeClass (MonadTime) import Data.Time.Clock (getCurrentTime) instance MonadTime IO where currentTime = getCurrentTime
内容的提问来源于stack exchange,提问作者igr
相关产品推荐
相关产品推荐

