我有以下文件:
module SimpleComposition where
class Domain a where
f :: a -> a
g :: a -> a
h = f . g
当试图将其加载到ghci时,我得到错误
srcplay.hs:7:5: error:
* No instance for (Domain c0) arising from a use of `f'
* In the first argument of `(.)', namely `f'
In the expression: f . g
In an equation for `h': h = f . g
我认为问题是f
和g
的类型都是forall a. Domain a => a ->a
,而不是简单的a -> a
,所以这些foralls都在妨碍我们。但我仍然想创作它们。怎样
这是单态性限制的错误。因为您将h = ...
编写为常量应用形式,所以编译器拒绝为其推断多态形式,而是寻找某种方法将其默认为具体类型,但没有可用的信息。
如果添加,则会编译
{-# LANGUAGE NoMonomorphismRestriction #-}
到文件顶部。但一个更好的想法是直接自己写签名:
h :: Domain a => a -> a
h = f . g
编译时启用或禁用了单态性限制。
请注意,在GHCi中,它在默认情况下是禁用的,但只有在加载模块后才会生效。在您仅加载的模块中,它仍然适用。