Thread overview
Combining template conditions and contracts?
Feb 29, 2016
Ozan
Feb 29, 2016
Alex Parrill
Feb 29, 2016
Daniel Kozak
Feb 29, 2016
Daniel Kozak
February 29, 2016
Is it possible to combine  template conditions and contracts?
Like in the following


T square_root(T)(T x)  if (isBasicType!T) {
in
{
    assert(x >= 0);
}
out (result)
{
    assert((result * result) <= x && (result+1) * (result+1) > x);
}
body
{
    return cast(long)std.math.sqrt(cast(real)x);
}

Compiler says no. Maybe it's a missunderstanding from my side..

Thanks & regards, Ozan
February 29, 2016
On Monday, 29 February 2016 at 14:38:52 UTC, Ozan wrote:
> Is it possible to combine  template conditions and contracts?
> Like in the following
>
>
> T square_root(T)(T x)  if (isBasicType!T) {
> in
> {
>     assert(x >= 0);
> }
> out (result)
> {
>     assert((result * result) <= x && (result+1) * (result+1) > x);
> }
> body
> {
>     return cast(long)std.math.sqrt(cast(real)x);
> }
>
> Compiler says no. Maybe it's a missunderstanding from my side..
>
> Thanks & regards, Ozan

You have a spare { after the template constraint in your sample
February 29, 2016

Dne 29.2.2016 v 15:38 Ozan via Digitalmars-d-learn napsal(a):
>
> T square_root(T)(T x)  if (isBasicType!T) {
> in
> {
>     assert(x >= 0);
> }
> out (result)
> {
>     assert((result * result) <= x && (result+1) * (result+1) > x);
> }
> body
> {
>     return cast(long)std.math.sqrt(cast(real)x);
> } 

import std.traits;
import std.math;

template square_root(T) if (isBasicType!T) {
    auto square_root(T x)
    in
    {
        assert(x >= 0);
    }
    out (result)
    {
        assert((result * result) <= x && (result+1) * (result+1) > x);
    }
    body
    {
        return cast(long)std.math.sqrt(cast(real)x);
    }
}

void main()
{
    import std.stdio: writeln;
    writeln(square_root(2));
}


February 29, 2016
auto square_root(T)(T x) if (isBasicType!T)
in
{
    assert(x >= 0);
}
out (result)
{
    assert((result * result) <= x && (result+1) * (result+1) > x);
}
body
{
    return cast(long)std.math.sqrt(cast(real)x);
}

void main()
{
    import std.stdio: writeln;
    writeln(square_root(2));
}

Dne 29.2.2016 v 15:38 Ozan via Digitalmars-d-learn napsal(a):
> Is it possible to combine  template conditions and contracts?
> Like in the following
>
>
> T square_root(T)(T x)  if (isBasicType!T) {
> in
> {
>     assert(x >= 0);
> }
> out (result)
> {
>     assert((result * result) <= x && (result+1) * (result+1) > x);
> }
> body
> {
>     return cast(long)std.math.sqrt(cast(real)x);
> }
>
> Compiler says no. Maybe it's a missunderstanding from my side..
>
> Thanks & regards, Ozan