Last week, in general forum someone introduced the possibility to implement the .? operator in D: https://forum.dlang.org/thread/blnjoaleswqnaojou...@forum.dlang.org

I decided to implement a simple solution with a funciontal syntax:

string fatherName = dot(person).dot(a=>a.father).dot(a=>a.name).get("unknown"); Person grandFather = dot(person).dot(a=>a.father).dot(a=>a.father).get;

That are equivalent to (dart code)

String fatherName = person?.father?.name??"unknown"
Person grandFather = person?.father?.father

The code is

auto dot(T)(T t){ return Dot!T(t); }

struct Dot(T) {
  private Nullable!T value; // = Nullable!T.init;

  this (T v)
  {
    static if(isAssignable!(T, typeof(null) ))
    {
      if(v !is null){
        value = nullable(v);
      }
    } else {
      value = nullable(v);
    }
  }

  template dot(R)
  {
    Dot!R dot( R function(T) fun)
    {
static assert(!isAssignable!(typeof(null), R), "Sorry, f returning type can't be typeof(null)");
      return value.isNull() ?
        Dot!R() :
        Dot!R(fun(value.get()));
      } 
    }
  }
  T get(T defaultValue)
  {
    return this.value.get(defaultValue);
  }
        
  static  if(isAssignable!(T, typeof(null) ))
  {
    T get()
    {
      return this.value.isNull ? null : this.value.get;
    }
  }             
}

I tried to adapt to template syntax (as a syntax sugar):

auto name = dot(person).dt!"a.father".dt!"a.father".get;

but I have not succeeded

Example: I tried with a global function

Dot!R dt(alias fun, T, R)(Dot!T t){
 auto f = cast(R function(T)) unaryFun!fun;
 return t.dot!R(f);
}

I really need to investigate more about unaryFun! :-)

I will appreciate any idea/guidance

Thank you!!!






Reply via email to