How to implement Haskell * Maybe * build in D?

I want to implement Maybe from Haskell to D, just for that. This is what I have so far, but it is not so 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 Could be a definition:

 data Maybe a = Nothing | Just a 
+4
source share
3 answers

Take a look at std.typecons.Nullable . This is not exactly the same as Maybe in Haskell, but it is a type that does not necessarily contain the value of any type with which it created an instance. Thus, efficiently, like Haskell Maybe , although syntactically, it is slightly different. The source is here if you want to look at it.

+4
source

what if you use this

 class Maybe(T){ } class Just(T) : Maybe!(T){ T t; this(T t){ this.t = t; } } class Nothing : Maybe!(){ } Maybe!int doSomething(in int k){ if(k < 10) return new Just!int(3); else return new Nothing; } 

I personally would use tagged unions and structures, though (and enforce is just getting the value)

+5
source

I have not used the Maybe library, but something like this seems to count:

 import std.stdio; struct Maybe(T) { private { bool isNothing = true; T value; } void opAssign(T val) { isNothing = false; value = val; } void opAssign(Maybe!T val) { isNothing = val.isNothing; value = val.value; } T get() @property { if (!isNothing) return value; else throw new Exception("This is nothing!"); } bool hasValue() @property { return !isNothing; } } Maybe!int doSomething(in int k) { Maybe!int ret; if (k < 10) ret = 3; return ret; } void main() { auto retVal = doSomething(5); assert(retVal.hasValue); writeln(retVal.get); retVal = doSomething(15); assert(!retVal.hasValue); writeln(retVal.hasValue); } 

With some overloading of the creative operator, the Maybe structure can behave quite naturally. In addition, I have templated the Maybe structure, so it can be used with any type.

+4
source

Source: https://habr.com/ru/post/1386066/


All Articles