如何在 D 中实现 Haskell *Maybe* 构造?
我想在 D 中实现来自 Haskell 的 Maybe
,只是为了它的地狱。 这是我到目前为止所得到的,但还不是很好。有什么想法如何改进吗?
class Maybe(a = int){ } //problem 1: works only with ints
class Just(alias a) : Maybe!(typeof(a)){ }
class Nothing : Maybe!(){ }
Maybe!int doSomething(in int k){
if(k < 10)
return new Just!3; //problem 2: can't say 'Just!k'
else
return new Nothing;
}
Haskell Maybe 定义:
data Maybe a = Nothing | Just a
I want to implement Maybe
from Haskell in D, just for the hell of it.
This is what I've got so far, but it's not that great. Any ideas how to improve it?
class Maybe(a = int){ } //problem 1: works only with ints
class Just(alias a) : Maybe!(typeof(a)){ }
class Nothing : Maybe!(){ }
Maybe!int doSomething(in int k){
if(k < 10)
return new Just!3; //problem 2: can't say 'Just!k'
else
return new Nothing;
}
Haskell Maybe definition:
data Maybe a = Nothing | Just a
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你个人使用这个,
我会使用标记的联合和结构(并且
enforce
这是在获取值时的情况)what if you use this
personally I'd use tagged union and structs though (and
enforce
it's a Just when getting the value)查看 std.typecons.Nullable。它与 Haskell 中的
Maybe
并不完全相同,但它是一种可以选择保存其实例化类型的值的类型。因此,实际上,它就像 Haskell 的Maybe
,尽管在语法上有点不同。如果您想查看源代码,请点击此处。Look at std.typecons.Nullable. It's not exactly the same as
Maybe
in Haskell, but it's a type which optionally holds a value of whatever type it's instantiated with. So, effectively, it's like Haskell'sMaybe
, though syntactically, it's a bit different. The source is here if you want to look at it.我还没有使用过 Maybe 库,但类似的东西似乎符合要求:
通过一些创造性的运算符重载,Maybe 结构可以表现得非常自然。此外,我已经模板化了 Maybe 结构,因此它可以与任何类型一起使用。
I haven't used the Maybe library, but something like this seems to fit the bill:
With some creative operator overloading, the Maybe struct could behave quite naturally. Additionally, I've templated the Maybe struct, so it can be used with any type.