如何在Haskell中编写多态函数? [英] How to compose polymorphic functions in Haskell?

查看:64
本文介绍了如何在Haskell中编写多态函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文件:

module SimpleComposition where

class Domain a where
    f :: a -> a
    g :: a -> a

h = f . g

尝试在ghci中加载它时,出现错误

When trying to loading it in ghci, I get the error

src\play.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.域a =>a-> a ,而不仅仅是 a->,因此这些功能都无法解决.但是我仍然想组成它们.怎么样?

I believe the problem is that the type of both f and g is forall a. Domain a => a ->a and not simply a -> a, so these foralls are in the way. But I still want to compose them. How?

推荐答案

这是同构限制'的错.因为您将 h = ... 编写为常量应用形式,所以编译器拒绝为它推断出多态形式,而是寻找某种方式将其默认为具体类型-但没有信息可做.

This is the monomorphism restriction's fault. Because you wrote h = ... as a constant applicative form, the compiler refuses to infer a polymorphic form for it and instead looks for some way to default it to a concrete type – but there is no information available to do that.

如果您添加,它进行编译

It does compile if you add

{-# LANGUAGE NoMonomorphismRestriction #-}

到文件顶部.但是一个更好的主意是自己直接写出签名:

to the top of the file. But a better idea is to just write the signature explicitly yourself:

h :: Domain a => a -> a
h = f . g

使用启用或禁用的单态性限制进行编译.

That compiles with the monomorphism restriction either enabled or disabled.

请注意, GHCi默认情况下处于禁用状态,但只有在模块加载后才能生效.在您仅加载的模块中,它仍然适用.

Note that within GHCi it is disabled by default, but that only comes into action after the module has been loaded. In a module you're only loading, it still applies.

这篇关于如何在Haskell中编写多态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆