什么是“|"?因为在 Haskell 类定义中? [英] What's the "|" for in a Haskell class definition?

查看:35
本文介绍了什么是“|"?因为在 Haskell 类定义中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚| m -> w"部分在这样的类定义中的含义:

I can't figure out what the "| m -> w"-part means in a class definition like this:

class (Monoid w, Monad m) => MonadWriter w m | m -> w

这给类定义添加了哪些附加信息?

What additional information does this add to the class definition?

推荐答案

竖线是一个语法分隔符,本身没有任何意义,用于在多参数类型类上引入函数依赖,因此从技术上讲| 没有任何意义.据推测,| 被选为对 模式保护 函数.

The vertical bar is a syntactic separator with no meaning itself, used to introduce functional dependencies on a multi-parameter type class, so technically | means nothing whatsoever. Presumably | was chosen as a visual analogy to the same symbol's use for pattern guards on functions.

就函数依赖本身而言,只需阅读 x ->y 作为类型参数 x 唯一确定类型参数 y",意味着仅知道 x 就足以找到正确的实例.还有更复杂的问题,尤其是在启用其他 GHC 扩展的情况下,但大多数时候您无需担心它们.

As far as the functional dependencies themselves go, just read x -> y as "type parameter x uniquely determines type parameter y", meaning that knowing x alone is sufficient to find the correct instance. There are further complications, especially with other GHC extensions enabled, but most of the time you don't need to worry about them.

相反,在没有函数依赖的情况下,选择多参数类型类的实例需要知道所有类型参数.一个典型的例子有一个参数是容器类型,第二个参数是所包含元素的类型;诸如concatenate"或isEmpty"之类的函数不需要提及元素类型,只需要提及容器类型,因此会产生歧义.

In contrast, without functional dependencies, selecting an instance of a multi-parameter type class requires that all type parameters be known. A typical example has one parameter being a container type and a second being the type of the contained elements; functions such as "concatenate" or "isEmpty" need not mention the element type, only the container type, and thus would be ambiguous.

此外,如果您正在编写自己的类型类,请考虑使用 type family,这是一种可能最终取代函数依赖的新方法.粗略地说,类型系列允许您在实例中编写重载的类型定义,而不仅仅是重载的函数.

Also, if you're writing your own type classes, consider instead using type families, which are a new approach that may eventually replace functional dependencies. Roughly speaking, type families let you write overloaded type definitions inside an instance, not just overloaded functions.

这篇关于什么是“|"?因为在 Haskell 类定义中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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