Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Haskell *Maybe* construct in D?

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
like image 460
Arlen Avatar asked Dec 13 '22 07:12

Arlen


1 Answers

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;
}

personally I'd use tagged union and structs though (and enforce it's a Just when getting the value)

like image 57
ratchet freak Avatar answered Dec 30 '22 16:12

ratchet freak