Future of D
ddcovery
antoniocabreraperez at gmail.com
Wed Dec 16 14:52:24 UTC 2020
On Wednesday, 16 December 2020 at 13:26:44 UTC, Paulo Pinto wrote:
> On Wednesday, 16 December 2020 at 10:04:03 UTC, ddcovery wrote:
>> ...
>>
>> Final conclusion... look at this:
>>
>> void main(){
>> 0.doThis!(n=>assert(n==0));
>> assert( 0.doThis!(n=>n) == 0 );
>> assert( "hello".doThis!(s=>s) == "hello" );
>> assert( "hello".doThis!(s=>s.length) == 5 );
>> assert( doThis!(u=>u)(true) );
>> }
>> auto doThis(alias f, T)(T value){
>> // Nothing in the "alias f" tells you that it must be an
>> unary function or
>> // witch type must return...
>> return f(value);
>> }
>>
>> Someone coming from java or c# will suffer an aneurysm, but it
>> is really... wonderful? :-)
>
> You mean like this, yeah it is a bit more boilerplate, but no I
> didn't suffer an aneurysm
>
> using System;
> using System.Linq.Expressions;
>
>
> public static class Helpers
> {
> public static R dothis<T, R>(this T val, Expression<Func<T,R>>
> f)
> {
> var func = f.Compile();
> return func(val);
> }
>
> public static void dothis<T>(this T val, Expression<Action<T>>
> f)
> {
> var func = f.Compile();
> func(val);
> }
> }
>
> public class Program
> {
> public static void Main()
> {
> 0.dothis(n => assert(() => n == 0));
> System.Diagnostics.Debug.Assert(0.dothis(n => n) == 0);
> System.Diagnostics.Debug.Assert("hello".dothis(n => n) ==
> "hello");
> System.Diagnostics.Debug.Assert(Helpers.dothis(true, n => n));
> }
>
> public static void assert(Expression<Func<bool>> exp) {
> var expc = exp.Compile();
> System.Diagnostics.Debug.Assert(expc());
> }
> }
Ahhhh... you read the entire post... thanks!!!
You have to recognize that you know D (and you like it)...
otherwise, first impression could have been "What?"... methods
are "extension" methods by default, you can put "auto" as a
result, you can declare an "alias f" and compiler will do the
magic inference... it is a lot of work under scenes (impressive
one)...
I'm curious about how a Java developer will try to solve the same
problem.
More information about the Digitalmars-d
mailing list