简体   繁体   English

Haskell类定义中的“|”是什么?

[英]What's the “|” for in a Haskell class definition?

I can't figure out what the "| m -> w"-part means in a class definition like this: 我无法弄清楚“| m - > w”-part在类定义中意味着什么:

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. 被选择作为相同符号用于功能上的图案防护的视觉类比。

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. 就功能依赖性本身而言,只需读取x -> y作为“类型参数x唯一确定类型参数y ”,这意味着仅知道x就足以找到正确的实例。 There are further complications, especially with other GHC extensions enabled, but most of the time you don't need to worry about them. 还有其他复杂情况,特别是启用了其他GHC扩展,但大多数时候您不需要担心它们。

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. 诸如“concatenate”或“isEmpty”之类的函数不需要提及元素类型,只需要提及容器类型,因此是不明确的。

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. 粗略地说,类型族允许您在实例中编写重载类型定义 ,而不仅仅是重载函数。

它指定了功能依赖

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM