Skip to content

(Proposal) Concepts/Traits (enhanced generic constraints) #129

@AdamSpeight2008

Description

@AdamSpeight2008

Traits

Traits are a specification a Type / Method must have to be valid. This specification is validation at both compile-time and runtime. The runtime cost maybe worth it for additional safety,

Basic Grammar

        trait ::= "Trait" identifier specification
specification ::= '{' spec+ '}'
         spec ::= 

incomplete

A trait can be define in a separate construct, like a class / struct.

Examples

trait Zero { static readonly Zero ()->T }
trait Unit { static readonly Unit ()->T }
trait [+] ( static [+] (T,T)->T } // operator + (addition)
trait [-] { static [-] (T,T)->T } // operator - (subtraction)

A trait can "inherit" other existing traits. eg.

trait SimpleCalc <: { Zero, Unit, [+], [-] }

This allows "constrained generics" over numeric types.

Summation< T > ( IEnumerable<T> nums )
  T has SimpleCalc
{
  T total = T.Zero();
  foreach( T num in nums)
    total = total + num; // += can't be used as the specification didn't specify it.
  return total;
}

A trait can also be anonymously define at the point of use

foo <T> ()
  T has Trait { ... }
{
 // method code 
}

Value Traits

Value Trait are checked against the value of a variable, if it possible to valid at compile-time it is, if not it is validated at runtime.

 trait NonNull <T : class> { != null }


int CharCount ( string s )
  s is NonNull 
{
  return s.Length;
}

Note: T! could be an alias for the NonNull Trait


I do require help to spec-out this idea, I think it has potential has *(as see it) that traits would also enable other current proposals / part of them.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions