concepts

Dennis Ritchie via Digitalmars-d digitalmars-d at puremagic.com
Thu May 21 06:25:55 PDT 2015


On Thursday, 21 May 2015 at 11:16:47 UTC, ZombineDev wrote:
> On Thursday, 21 May 2015 at 11:05:10 UTC, Dennis Ritchie wrote:
>> Is it possible to write something like this in the compile 
>> time?
>>
>> auto foo(T)(T t)
>>    if (is(T == immutable(int)) && t == 5)
>>    // Error: variable t cannot be read at compile time
>> {
>>    // ...
>> }
>>
>> void main()
>> {
>>    immutable(int) n = 5;
>>    foo(n);
>> }
>
> Although the compiler already has enough information, this is 
> not possible because the template constraints are not allowed 
> to use the runtime parameters (they are compile-time only 
> constraints). It would be more doable like this:
>
> auto foo(T)(T t)
>     if (is(T == immutable(int)))
> {
>     assert(t == 5);
> }
>
> void main()
> {
>     immutable int n = 6;
>     foo(n); // Possible in the future:
>     // dmd test.d --deep-asserts-verification
>     // Error: function foo has an assert which can't satisfied:
>     // assert(5 == n) <- n is 6
> }

Yes, but I can do that I need check use strings ( source is taken 
away http://ddili.org/ders/d.en/mixin.html ):

import std.conv : to;
import std.string : split;
import std.stdio : writeln;

int[] filter(string predicate)(in int[] numbers)
     if (predicate.split[0] == "number" &&
         predicate.split[1] == ">" &&
         predicate.split[2].to!int <= int.max)
{
     int[] result;

     foreach (number; numbers) {
         if (mixin (predicate)) {
             result ~= number;
         }
     }

     return result;
}

void main()
{
     auto a = [1, 2, 3, 4, 5];

     writeln(a.filter!"number > 3"); // [4, 5]
}
-----
http://rextester.com/LNTB90172

Code Ali is not safe, because I can refer to the inner filter 
function directly in a function call :)

import std.conv : to;
import std.string : split;
import std.stdio : writeln;

int[] filter(string predicate)(in int[] numbers)
{
     int[] result;

     foreach (number; numbers) {
         if (mixin (predicate)) {
             result ~= number;
         }
     }

     return result;
}

void main()
{
     auto a = [1, 2, 3, 4, 5];

     writeln(a.filter!"result != [1, 2]"); // [1, 2]
}
-----
http://rextester.com/LNTB90172


More information about the Digitalmars-d mailing list