“One or Both”是否有规范的haskell类型? [英] Is there a canonical haskell type for "One or Both"?

查看:108
本文介绍了“One or Both”是否有规范的haskell类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己需要一个包含 A ,也许是 B 的数据结构,他们。如果我要为这个东西破解一个通用数据类型,它可能看起来像:

 数据OneOrBoth ab = A a | B b | AB a b 

maybeA :: OneOrBoth a b - >也许
maybeB :: OneOrBoth a b - >也许b
或者L :: OneOrBoth a b - >或者b - 优选
或者R :: OneOrBoth a b - >或者b - 偏好b
hasBoth,hasExactlyOne,hasA,hasB :: OneOrBoth a b - > Bool

这个数据结构是否有名字?是否有一种规范的方式来处理Haskell中的一个或两个结构?

解决方案

Data.These


这可以用来表示两个值的组合,其中
组合是在任何输入时定义的。在代数上,类型
这些AB 表示(A + B + AB),它不会轻易地将因素简单地归入
的总和和乘积 - A(B,Maybe A)不清楚,
很难使用。


I find myself needing a data structure that contains maybe an A, maybe a B, and definitely one of them. If I were to hack up a general data type for this thing, it would probably look like:

data OneOrBoth a b = A a | B b | AB a b

maybeA :: OneOrBoth a b -> Maybe a
maybeB :: OneOrBoth a b -> Maybe b
eitherL :: OneOrBoth a b -> Either a b -- Prefers a
eitherR :: OneOrBoth a b -> Either a b -- Prefers b
hasBoth, hasExactlyOne, hasA, hasB :: OneOrBoth a b -> Bool

Does this data structure have a name? Is there a canonical way to handle one-or-both structures in Haskell?

解决方案

Data.These

This can be useful to represent combinations of two values, where the combination is defined if either input is. Algebraically, the type These A B represents (A + B + AB), which doesn't factor easily into sums and products — a type like Either A (B, Maybe A) is unclear and awkward to use.

这篇关于“One or Both”是否有规范的haskell类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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