python的代数类型(特别是提供sum类型,又称标记联合)
sumtypes的Python项目详细描述
sumtypes
sumtypes为python提供代数数据类型。主要的好处是 sum类型的实现(akaTagged Unions),python没有 的任何本地表示。产品类型只是具有多个 属性。
文档位于https://sumtypes.readthedocs.org/
此模块使用attrs库提供类似属性的特性 验证和默认值。
示例
装饰您的课程,使其成为一个总和类型:
importattrfromsumtypesimportsumtype,constructor,match@sumtypeclassMyType(object):# constructors specify names for their argumentsMyConstructor=constructor('x')AnotherConstructor=constructor('x','y')# You can also make use of any feature of the attrs# package by using attr.ib in constructorsThirdConstructor=constructor(one=attr.ib(default=42),two=attr.ib(validator=attr.validators.instance_of(int)))
(attrs package,和attr.ib documentation)
然后通过调用构造函数来构造它们:
v=MyType.MyConstructor(1)v2=MyType.AnotherConstructor('foo',2)
您可以从标记的对象中获取值:
assertv.x==1assertv2.x=='foo'assertv2.y==2
检查使用的构造函数:
asserttype(v)isMyType.MyConstructor
而且,像scala case类一样,构造函数类型是main的一个子类 类型:
assertisinstance(v,MyType)
标记的对象支持相等:
assertv==MyType.MyConstructor(1)assertv!=MyType.MyConstructor(2)
也支持简单的模式匹配。把一个函数写在 总和类型的情况:
@match(MyType)classget_number(object):defMyConstructor(x):returnxdefAnotherConstructor(x,y):returnydefThirdConstructor(one,two):returnone+twoassertget_number(v)==1assertget_number(v2)==2
match确保处理所有案例。如果你真的想写 “部分功能”(即不涵盖所有情况的功能),使用 match_partial。
另见
在过去的几年里,图书馆的生态系统 用python编程已经爆炸了。以下是我推荐的一些库:
- effect-用于隔离副作用的库
- pyrsistent-python中的持久(优化的不可变)数据结构
- toolz-纯fp函数的通用库
- fn.py-一组受scala启发的工具,包括奇怪的lambda语法、选项类型和monad
谢谢
感谢Rackspace允许我参与这个项目,并且 优秀的open source employee contribution policy
许可证
sumtypes是根据mit许可证获得许可的:
版权所有(c)2015 Christopher Armstrong
兹免费准许任何人取得 本软件和相关文档文件(“软件”),用于处理 不受限制的软件,包括但不限于 使用、复制、修改、合并、发布、分发、再授权和/或出售 软件,并允许向其提供软件的人员这样做, 必须满足以下条件:
上述版权公告及本许可公告须包括在 软件的拷贝或大部分。
本软件按“原样”提供,无任何形式的保证,明示或 默示的,包括但不限于适销性、适用性的保证 为了特殊目的和不侵权。在任何情况下,作者或 版权持有人应对任何索赔、损害或其他责任负责,无论 在合同诉讼、侵权诉讼或其他诉讼中,由 与软件的连接或软件的使用或其他交易。