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

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

问题描述

我无法弄清楚像这样的类定义中的| m - > w-part意味着什么:

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

这会添加到类定义中的附加信息是什么?

解决方案

竖线是一个本身没有意义的句法分隔符,用于在多参数类型类上引入函数依赖关系,所以技术上是 | 毫无意义。据推测, | 被视为类似于相同符号用于模式守卫功能。



就功能依赖本身而言,只要阅读 x - > y 作为类型参数 x 唯一确定类型参数 y ,这意味着知道 x 就足以找到正确的实例。还有其他问题,尤其是其他GHC扩展功能启用后,但大多数时候您不必担心它们。相反,没有函数依赖关系,选择一个多参数类型类的实例需要知道所有的类型参数。一个典型的例子有一个参数是容器类型,第二个参数是包含的元素的类型;像concatenate或isEmpty这样的函数不需要提及元素类型,只需要提及容器类型,这样就不会引起混淆。



另外,如果你正在编写你自己的类型类,请考虑使用类型家庭,这是一种可能最终取代功能依赖关系的新方法。粗略地说,类型族允许您在实例中写入重载的类型定义,而不仅仅是重载函数。


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.

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.

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.

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天全站免登陆