我试图把我的头脑围绕在函数依赖上,但我自己是不会有任何进展的。在"Monad Transformers Step by Step“一文中,作者给出了这两种类型的定义:
class (Monad m) => MonadError e m | m -> e where
throwError :: e -> m a
catchError :: m a -> (e -> m a) -> m a
class (Monad m) => MonadReader r m | m -> r where
ask :: m r
local :: (r -> r) -> m a -> m a
根据我在网上找到的一些材料的理解,这意味着类型变量e
由m
决定。我只是不明白这是什么意思。它是如何确定的?有没有人可以先用最小的理论阐明一些问题,然后再把更多的理论内容联系起来呢?
谢谢
发布于 2013-11-18 13:03:09
这意味着类型系统总是能够从类型m
中确定类型(e
或r
)。
让我们做一个自己的例子:
class KnowsA a b | b -> a where
known :: b -> a
我们应该始终能够从b
中确定a
data Example1 = Example1 deriving (Show)
instance KnowsA Int Example1 where
known = const 1
类型系统知道,对于这个实例,只要它有一个Example1
,它的a
的类型就是Int
。它是怎么知道的?它不允许我们使用另一个类型的另一个实例。
如果我们添加
instance KnowsA [Char] Example1 where
known = const "one"
我们得到一个错误:
Functional dependencies conflict between instance declarations:
instance KnowsA Int Example1
instance KnowsA [Char] Example1
但是如果我们有一个不同类型的b
,我们可以为a
添加另一个不同类型的实例
data Example2 = Example2 deriving (Show)
instance KnowsA [Char] Example2 where
known = const "two"
main = do
print . known $ Example1
print . known $ Example2
这是可预测的输出
1
"two"
https://stackoverflow.com/questions/20040224
复制相似问题