quantity-polymorphism.dhover×342all
#!/usr/bin/env dub
/+ dub.sdl:
    name "uom_quantity_polymorphism"
    dependency "sparkles:math" path="../../../.."
    dflags "-preview=in" "-preview=dip1000"
    targetPath "build"
+/
/**
 * Units of measure — dimensional polymorphism and the inference ceiling, over
 * `sparkles:math`'s `Vector`.
 *
 * A physically-based raytracer wants generic, dimension-correct geometry:
 * `dot` of two length-vectors is an *area*, `lengthSquared` is an area, a
 * `magnitude` is a length, and `normalize` yields a *dimensionless* direction.
 * D's IFTI (implicit function template instantiation) delivers this *forward*:
 * the result dimension is computed from the arguments' dimensions by the same
 * "checker evaluates" arithmetic every non-F# system in the survey uses. What D
 * (and every evaluator) cannot do is *invert* it — infer an argument dimension
 * from a desired result type. There are no principal types here; see
 * theory/type-system-mechanisms.md § "evaluators vs solvers" and
 * theory/kennedy-types.md.
 *
 * Composition finding: `sparkles:math.Vector` composes for `dot` (ordering A —
 * `Quantity!(dim, Vec3)`), but its `dot` is dimension-blind (`cast(CommonType)`),
 * and it ships no 3-D `cross`, `magnitude`, or `normalize` at all — a raytracer
 * needs them, and they must be dimension-aware. This prototype wraps the numeric
 * `Vector.dot` to restore the dimension, and implements `cross`/`magnitude`/
 * `normalize` locally: concrete input for the `sparkles:math` co-design (see
 * quantity-vector-composition.d).
 *
 * Companion to docs/research/units-of-measure/theory/type-system-mechanisms.md.
 *
 * Run with: `dub run --single quantity-polymorphism.d`
 */
module 
(module) uom_quantity_polymorphism

Units of measure — dimensional polymorphism and the inference ceiling, over sparkles:math's Vector.

A physically-based raytracer wants generic, dimension-correct geometry: dot of two length-vectors is an area, lengthSquared is an area, a magnitude is a length, and normalize yields a dimensionless direction. D's IFTI (implicit function template instantiation) delivers this forward: the result dimension is computed from the arguments' dimensions by the same "checker evaluates" arithmetic every non-F# system in the survey uses. What D (and every evaluator) cannot do is invert it — infer an argument dimension from a desired result type. There are no principal types here; see theory/type-system-mechanisms.md § "evaluators vs solvers" and theory/kennedy-types.md.

Composition finding: sparkles:math.Vector composes for dot (ordering A — Quantity!(dim, Vec3)), but its dot is dimension-blind (cast(CommonType)), and it ships no 3-D cross, magnitude, or normalize at all — a raytracer needs them, and they must be dimension-aware. This prototype wraps the numeric Vector.dot to restore the dimension, and implements cross/magnitude/ normalize locally: concrete input for the sparkles:math co-design (see quantity-vector-composition.d).

Companion to docs/research/units-of-measure/theory/type-system-mechanisms.md.

Run with: dub run --single quantity-polymorphism.d

uom_quantity_polymorphism
;
import
(package) sparkles
sparkles
.
(package) sparkles.math
math
.
(module) sparkles.math.vector

Vector primitives for linear algebra in game and graphics code.

Provides a fixed-size numeric vector type with optional named fields, component-wise arithmetic, scalar operations, dot product, and aliases for common vector sizes.

vector
:
(alias struct) uom_quantity_polymorphism.Vector = sparkles.math.vector.Vector(T, ulong N, string[] fieldNames = makeDefaultFieldNames!N) if (isNumeric!T && (N > 0))

Fixed-size numeric vector with optional named components.

Vector
;
import
(package) std
std
.
(module) std.traits

Templates which extract information about types and symbols at compile time.

Category Templates
Symbol Name traits fullyQualifiedName mangledName moduleName packageName
Function traits isFunction arity functionAttributes hasFunctionAttributes functionLinkage FunctionTypeOf isSafe isUnsafe isFinal ParameterDefaults ParameterIdentifierTuple ParameterStorageClassTuple Parameters ReturnType SetFunctionAttributes variadicFunctionStyle
Aggregate Type traits BaseClassesTuple BaseTypeTuple classInstanceAlignment EnumMembers FieldNameTuple Fields hasAliasing hasElaborateAssign hasElaborateCopyConstructor hasElaborateDestructor hasElaborateMove hasIndirections hasMember hasStaticMember hasNested hasUnsharedAliasing InterfacesTuple isInnerClass isNested MemberFunctionsTuple RepresentationTypeTuple TemplateArgsOf TemplateOf TransitiveBaseTypeTuple
Type Conversion CommonType AllImplicitConversionTargets ImplicitConversionTargets CopyTypeQualifiers CopyConstness isAssignable isCovariantWith isImplicitlyConvertible isQualifierConvertible
Type Constructors InoutOf ConstOf SharedOf SharedInoutOf SharedConstOf SharedConstInoutOf ImmutableOf QualifierOf
Categories of types allSameType ifTestable isType isAggregateType isArray isAssociativeArray isAutodecodableString isBasicType isBoolean isBuiltinType isCopyable isDynamicArray isEqualityComparable isFloatingPoint isIntegral isNarrowString isConvertibleToString isNumeric isOrderingComparable isPointer isScalarType isSigned isSIMDVector isSomeChar isSomeString isStaticArray isUnsigned
Type behaviours isAbstractClass isAbstractFunction isCallable isDelegate isExpressions isFinalClass isFinalFunction isFunctionPointer isInstanceOf isIterable isMutable isSomeFunction isTypeTuple
General Types ForeachType KeyType Largest mostNegative OriginalType PointerTarget Signed Unconst Unshared Unqual Unsigned ValueType Promoted
Misc lvalueOf rvalueOf Select select
User-Defined Attributes hasUDA getUDAs getSymbolsByUDA

Source

std/traits.d

@copyrightCopyright The D Language Foundation 2005 - 2009.@licenseBoost License 1.0.@authorsWalter Bright, Tomasz Stachowiak (isExpressions), Andrei Alexandrescu, Shin Fujishiro, Robert Clipsham, David Nadlinger, Kenji Hara, Shoichi Kato
traits
:
(alias template) uom_quantity_polymorphism.Unqual = core.internal.traits.Unqual(T : const(U), U)

taken from std.traits.Unqual

Unqual
;
/// The raytracer's numeric payload for a 3-vector quantity. alias
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
=
(struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

Fixed-size numeric vector with optional named components.

Vector
!(double, 3);
/// A dimension: an exponent vector in the free abelian group `ℤ³` over /// (mass, length, time), stored as its unique normal form. struct
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
{ int
(field) int uom_quantity_polymorphism.Dim.mass
mass
;
int
(field) int uom_quantity_polymorphism.Dim.length
length
;
int
(field) int uom_quantity_polymorphism.Dim.time
time
;
} /// The group operation: `sign = +1` multiplies dimensions, `-1` divides.
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
uom_quantity_polymorphism.Dim uom_quantity_polymorphism.combine(in uom_quantity_polymorphism.Dim a, in uom_quantity_polymorphism.Dim b, in int sign) pure nothrow @nogc @safe

The group operation: ``sign = +1 multiplies dimensions, -1 divides.

combine
(in
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
(parameter) const(uom_quantity_polymorphism.Dim) a
a
, in
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
(parameter) const(uom_quantity_polymorphism.Dim) b
b
, in int
(parameter) const(int) sign
sign
) @safe pure nothrow @nogc
in (
(parameter) const(int) sign
sign
== 1 ||
(parameter) const(int) sign
sign
== -1)
{ return
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
(
mass:
(parameter) const(uom_quantity_polymorphism.Dim) a
a
.
(field) int uom_quantity_polymorphism.Dim.mass
mass
+
(parameter) const(int) sign
sign
*
(parameter) const(uom_quantity_polymorphism.Dim) b
b
.
(field) int uom_quantity_polymorphism.Dim.mass
mass
,
length:
(parameter) const(uom_quantity_polymorphism.Dim) a
a
.
(field) int uom_quantity_polymorphism.Dim.length
length
+
(parameter) const(int) sign
sign
*
(parameter) const(uom_quantity_polymorphism.Dim) b
b
.
(field) int uom_quantity_polymorphism.Dim.length
length
,
time:
(parameter) const(uom_quantity_polymorphism.Dim) a
a
.
(field) int uom_quantity_polymorphism.Dim.time
time
+
(parameter) const(int) sign
sign
*
(parameter) const(uom_quantity_polymorphism.Dim) b
b
.
(field) int uom_quantity_polymorphism.Dim.time
time
,
); } /// CTFE unit label for an exponent vector (only ever evaluated at compile time).
(alias) object.string = string
string
string uom_quantity_polymorphism.unitString(in uom_quantity_polymorphism.Dim d) pure @safe

CTFE unit label for an exponent vector (only ever evaluated at compile time).

unitString
(in
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
(parameter) const(uom_quantity_polymorphism.Dim) d
d
) @safe pure
{ import
(package) std
std
.
(module) std.conv

A one-stop shop for converting values from one type to another.

Category Functions
Generic asOriginalType castFrom parse to toChars bitCast
Strings text wtext dtext writeText writeWText writeDText hexString
Numeric octal roundTo signed unsigned
Exceptions ConvException ConvOverflowException

Source

std/conv.d

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara
conv
:
(alias template) to = std.conv.to(T)

The to template converts a value from one type _to another. The source type is deduced and the target type must be specified, for example the expression to!int(42.0) converts the number 42 from double _to int. The conversion is "safe", i.e., it checks for overflow; to!int(4.2e10) would throw the ConvOverflowException exception. Overflow checks are only inserted when necessary, e.g., to!double(42) does not do any checking because any int fits in a double.

Conversions from string _to numeric types differ from the C equivalents atoi() and atol() by checking for overflow and not allowing whitespace.

For conversion of strings _to signed types, the grammar recognized is: $(PRE $(I Integer): $(I Sign UnsignedInteger) $(I UnsignedInteger) $(I Sign): $(B +) $(B -))

For conversion _to unsigned types, the grammar recognized is: $(PRE $(I UnsignedInteger): $(I DecimalDigit) $(I DecimalDigit) $(I UnsignedInteger))

to
;
(alias) object.string = string
string
(local variable) string result
result
;
void
void uom_quantity_polymorphism.unitString.put(in string symbol, in int exp) pure nothrow @safe
put
(in
(alias) object.string = string
string
(parameter) const(string) symbol
symbol
, in int
(parameter) const(int) exp
exp
)
{ if (
(parameter) const(int) exp
exp
== 0)
return; if (
(local variable) string result
result
.
(field) ulong string.length
length
> 0)
(local variable) string result
result
~= ' ';
(local variable) string result
result
~=
(parameter) const(string) symbol
symbol
;
if (
(parameter) const(int) exp
exp
!= 1)
(local variable) string result
result
~= "^" ~
(parameter) const(int) exp
exp
.
string std.conv.to!string.to!(const(int))(const(int) __param_0) pure nothrow @safe

The to template converts a value from one type to another. The source type is deduced and the target type must be specified, for example the expression to`!int(42.0)` converts the number 42 from `double` to `int`. The conversion is "safe", i.e., it checks for overflow; to!int(4.2e10) would throw the ConvOverflowException exception. Overflow checks are only inserted when necessary, e.g., ``to!double(42) does not do any checking because any int fits in a double.

Conversions from string to numeric types differ from the C equivalents atoi() and atol() by checking for overflow and not allowing whitespace.

For conversion of strings to signed types, the grammar recognized is: Integer: Sign UnsignedInteger UnsignedInteger Sign: + -

For conversion to unsigned types, the grammar recognized is: UnsignedInteger: DecimalDigit DecimalDigit UnsignedInteger

Examples

Converting a value to its own type (useful mostly for generic code) simply returns its argument.

int a = 42;
int b = to!int(a);
double c = to!double(3.14); // c is double with value 3.14

Converting among numeric types is a safe way to cast them around.

Conversions from floating-point types to integral types allow loss of precision (the fractional part of a floating-point number). The conversion is truncating towards zero, the same way a cast would truncate. (To round a floating point value when casting to an integral, use roundTo.)

import std.exception : assertThrown;

int a = 420;
assert(to!long(a) == a);
assertThrown!ConvOverflowException(to!byte(a));

assert(to!int(4.2e6) == 4200000);
assertThrown!ConvOverflowException(to!uint(-3.14));
assert(to!uint(3.14) == 3);
assert(to!uint(3.99) == 3);
assert(to!int(-3.99) == -3);

When converting strings to numeric types, note that D hexadecimal and binary literals are not handled. Neither the prefixes that indicate the base, nor the horizontal bar used to separate groups of digits are recognized. This also applies to the suffixes that indicate the type.

To work around this, you can specify a radix for conversions involving numbers.

auto str = to!string(42, 16);
assert(str == "2A");
auto i = to!int(str, 16);
assert(i == 42);

Conversions from integral types to floating-point types always succeed, but might lose accuracy. The largest integers with a predecessor representable in floating-point format are 2^24-1 for float, 2^53-1 for double, and 2^64-1 for real (when real is 80-bit, e.g. on Intel machines).

// 2^24 - 1, largest proper integer representable as float
int a = 16_777_215;
assert(to!int(to!float(a)) == a);
assert(to!int(to!float(-a)) == -a);

Conversion from string types to char types enforces the input to consist of a single code point, and said code point must fit in the target type. Otherwise, ConvException is thrown.

import std.exception : assertThrown;

assert(to!char("a") == 'a');
assertThrown(to!char("ñ")); // 'ñ' does not fit into a char
assert(to!wchar("ñ") == 'ñ');
assertThrown(to!wchar("😃")); // '😃' does not fit into a wchar
assert(to!dchar("😃") == '😃');

// Using wstring or dstring as source type does not affect the result
assert(to!char("a"w) == 'a');
assert(to!char("a"d) == 'a');

// Two code points cannot be converted to a single one
assertThrown(to!char("ab"));

Converting an array to another array type works by converting each element in turn. Associative arrays can be converted to associative arrays as long as keys and values can in turn be converted.

import std.string : split;

int[] a = [1, 2, 3];
auto b = to!(float[])(a);
assert(b == [1.0f, 2, 3]);
string str = "1 2 3 4 5 6";
auto numbers = to!(double[])(split(str));
assert(numbers == [1.0, 2, 3, 4, 5, 6]);
int[string] c;
c["a"] = 1;
c["b"] = 2;
auto d = to!(double[wstring])(c);
assert(d["a"w] == 1 && d["b"w] == 2);

Conversions operate transitively, meaning that they work on arrays and associative arrays of any complexity.

This conversion works because to`!short` applies to an `int`, to!wstring applies to a string, to`!string` applies to a `double`, and to!(double[]) applies to an int[]. The conversion might throw an exception because ``to!short might fail the range check.

int[string][double[int[]]] a;
auto b = to!(short[wstring][string[double[]]])(a);

Object-to-object conversions by dynamic casting throw exception when the source is non-null and the target is null.

import std.exception : assertThrown;
// Testing object conversions
class A {}
class B : A {}
class C : A {}
A a1 = new A, a2 = new B, a3 = new C;
assert(to!B(a2) is a2);
assert(to!C(a3) is a3);
assertThrown!ConvException(to!B(a3));

Stringize conversion from all types is supported.

  • String to string conversion works for any two string types having (char, wchar, dchar) character widths and any combination of qualifiers (mutable, const, or immutable).

  • Converts array (other than strings) to string. Each element is converted by calling ``to!T.

  • Associative array to string conversion. Each element is converted by calling ``to!T.

  • Object to string conversion calls toString against the object or returns "null" if the object is null.

  • Struct to string conversion calls toString against the struct if it is defined.

  • For structs that do not define toString, the conversion to string produces the list of fields.

  • Enumerated types are converted to strings as their symbolic names.

  • Boolean values are converted to "true" or "false".

  • char, wchar, dchar to a string type.

  • Unsigned or signed integers to strings.

    special case

    : Convert integral value to string in radix radix. radix must be a value from 2 to 36. value is treated as a signed value only if radix is 10. The characters A through Z are used to represent values 10 through 36 and their case is determined by the letterCase parameter.

  • All floating point types to all string types.

  • Pointer to string conversions convert the pointer to a size_t value. If pointer is char*, treat it as C-style strings. In that case, this function is @system.

See formatValue on how toString should be defined.

// Conversion representing dynamic/static array with string
long[] a = [ 1, 3, 5 ];
assert(to!string(a) == "[1, 3, 5]");

// Conversion representing associative array with string
int[string] associativeArray = ["0":1, "1":2];
assert(to!string(associativeArray) == `["0":1, "1":2]` ||
       to!string(associativeArray) == `["1":2, "0":1]`);

// char* to string conversion
assert(to!string(cast(char*) null) == "");
assert(to!string("foo\0".ptr) == "foo");

// Conversion reinterpreting void array to string
auto w = "abcx"w;
const(void)[] b = w;
assert(b.length == 8);

auto c = to!(wchar[])(b);
assert(c == "abcx");

Strings can be converted to enum types. The enum member with the same name as the input string is returned. The comparison is case-sensitive.

A ConvException is thrown if the enum does not have the specified member.

import std.exception : assertThrown;

enum E { a, b, c }
assert(to!E("a") == E.a);
assert(to!E("b") == E.b);
assertThrown!ConvException(to!E("A"));
to
!
(alias) object.string = string
string
;
}
void uom_quantity_polymorphism.unitString.put(in string symbol, in int exp) pure nothrow @safe
put
("kg",
(parameter) const(uom_quantity_polymorphism.Dim) d
d
.
(field) int uom_quantity_polymorphism.Dim.mass
mass
);
void uom_quantity_polymorphism.unitString.put(in string symbol, in int exp) pure nothrow @safe
put
("m",
(parameter) const(uom_quantity_polymorphism.Dim) d
d
.
(field) int uom_quantity_polymorphism.Dim.length
length
);
void uom_quantity_polymorphism.unitString.put(in string symbol, in int exp) pure nothrow @safe
put
("s",
(parameter) const(uom_quantity_polymorphism.Dim) d
d
.
(field) int uom_quantity_polymorphism.Dim.time
time
);
return
(local variable) string result
result
.
(field) ulong string.length
length
> 0 ?
(local variable) string result
result
: "(dimensionless)";
} /// A graded quantity: a `Payload` (`double`, or `Vec3` for a dimensioned vector) /// tagged with its dimension (composition ordering A). struct
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double)

A graded quantity: a Payload (double, or Vec3 for a dimensioned vector) tagged with its dimension (composition ordering A).

Quantity
(Dim dim, Payload = double)
{
(alias) Payload = double
Payload
(field) double uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double).value
value
;
enum
(alias) object.string = string
string
(constant) string uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double).symbol = "m s^-1"
symbol
=
string uom_quantity_polymorphism.unitString(in uom_quantity_polymorphism.Dim d) pure @safe

CTFE unit label for an exponent vector (only ever evaluated at compile time).

unitString
(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.dim = Dim(0, 0, 0)
dim
);
/// `+`/`-` within one grade. Quantity
Quantity opBinary(string op)(in Quantity rhs) const

+/- within one grade.

opBinary
(string op)(in
(unresolved type) Quantity
Quantity
(parameter) Quantity rhs
rhs
) const
if (op == "+" || op == "-") => Quantity(mixin("value " ~ op ~ " rhs.value")); /// `*`/`/` between quantities: dimensions combine, payloads multiply (at least /// one side scalar; two vectors are `dot`/`cross`-ed, never `*`-ed). auto
auto opBinary(string op, Dim rhsDim, RP)(in Quantity!(rhsDim, RP) rhs) const

*// between quantities: dimensions combine, payloads multiply (at least one side scalar; two vectors are dot/cross-ed, never *-ed).

opBinary
(string op, Dim rhsDim, RP)(in
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double).rhsDim = Dim(0, 0, 1)
Quantity
!(
(unresolved type) rhsDim
rhsDim
, RP)
(parameter) Quantity!(rhsDim, RP) rhs
rhs
) const
if (op == "*" || op == "/") { auto
_error_ p
p
= mixin("value " ~ op ~ " rhs.value");
return
(template instance) Quantity!(combine(dim, rhsDim, op == "*" ? 1 : -1), Unqual!(typeof(p)))
Quantity
!(
uom_quantity_polymorphism.Dim uom_quantity_polymorphism.combine(in uom_quantity_polymorphism.Dim a, in uom_quantity_polymorphism.Dim b, in int sign) pure nothrow @nogc @safe

The group operation: ``sign = +1 multiplies dimensions, -1 divides.

combine
(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.dim = Dim(0, 1, 0)
dim
,
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double).rhsDim = Dim(0, 0, 1)
rhsDim
,
(constant) string uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double).op = "/"
op
== "*" ? 1 : -1),
(alias) core.internal.traits.Unqual!(const(double), double) = double

taken from std.traits.Unqual

Unqual
!(typeof(
(local variable) const(double) p
p
)))(
(local variable) const(double) p
p
);
} /// Scale by a plain dimensionless scalar, keeping the dimension. auto
auto opBinary(string op)(in double s) const

Scale by a plain dimensionless scalar, keeping the dimension.

opBinary
(string op)(in double
(parameter) double s
s
) const
if (op == "*" || op == "/") { auto
_error_ p
p
= mixin("value " ~ op ~ " s");
return
(template instance) Quantity!(dim, Unqual!(typeof(p)))
Quantity
!(
(unresolved type) dim
dim
, Unqual!(typeof(p)))(p);
} /// Render through an `appender` (see quantity-affine-torsor.d for why).
(alias) object.string = string
string
string uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double).toString() const pure @safe

Render through an appender (see quantity-affine-torsor.d for why).

toString
() const @safe
{ import
(package) std
std
.
(module) std.array

Functions and types that manipulate built-in arrays and associative arrays.

This module provides all kinds of functions to create, manipulate or convert arrays:

Function Name Description

| array | Returns a copy of the input in a newly allocated dynamic array. | | appender | Returns a new Appender or RefAppender initialized with a given array. | | assocArray | Returns a newly allocated associative array from a range/ranges of keys and values. | | byPair | Construct a range iterating over an associative array by key/value tuples. | | insertInPlace | Inserts into an existing array at a given position. | | join | Concatenates a range of ranges into one array. | | minimallyInitializedArray | Returns a new array of type T. | | replace | Returns a new array with all occurrences of a certain subrange replaced. | | replaceFirst | Returns a new array with the first occurrence of a certain subrange replaced. | | replaceInPlace | Replaces all occurrences of a certain subrange and puts the result into a given array. | | replaceInto | Replaces all occurrences of a certain subrange and puts the result into an output range. | | replaceLast | Returns a new array with the last occurrence of a certain subrange replaced. | | replaceSlice | Returns a new array with a given slice replaced. | | replicate | Creates a new array out of several copies of an input array or range. | | sameHead | Checks if the initial segments of two arrays refer to the same place in memory. | | sameTail | Checks if the final segments of two arrays refer to the same place in memory. | | split | Eagerly split a range or string into an array. | | staticArray | Creates a new static array from given data. | | uninitializedArray | Returns a new array of type T without initializing its elements. |

Source

std/array.d

@copyrightCopyright Andrei Alexandrescu 2008- and Jonathan M Davis 2011-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu and Jonathan M Davis
array
:
(alias template) appender = std.array.appender(A)() if (isDynamicArray!A)

Convenience function that returns an $(LREF Appender) instance, optionally initialized with array.

appender
;
import
(package) std
std
.
(module) std.format

This package provides string formatting functionality using printf style format strings.

Submodule Function Name Description
package
format
Converts its arguments according to a format string into a string.

| package | sformat | Converts its arguments according to a format string into a buffer. |

| package | FormatException | Signals a problem while formatting. |

| write | formattedWrite | Converts its arguments according to a format string and writes the result to an output range. |

| write | formatValue | Formats a value of any type according to a format specifier and writes the result to an output range. |

| read | formattedRead | Reads an input range according to a format string and stores the read values into its arguments. |

| read | unformatValue | Reads a value from the given input range and converts it according to a format specifier. |

| spec | FormatSpec | A general handler for format strings. |

| spec | singleSpec | Helper function that returns a FormatSpec for a single format specifier. |

Limitation

This package does not support localization, but adheres to the rounding mode of the floating point unit, if available.

Format Strings

The functions contained in this package use format strings. A format string describes the layout of another string for reading or writing purposes. A format string is composed of normal text interspersed with format specifiers. A format specifier starts with a percentage sign '%', optionally followed by one or more parameters and ends with a format indicator. A format indicator may be a simple format character or a compound indicator.

Format strings are composed according to the following grammar:

FormatString: FormatStringItem FormatString FormatStringItem: Character FormatSpecifier FormatSpecifier: '%' Parameters FormatIndicator

FormatIndicator: FormatCharacter CompoundIndicator FormatCharacter: see remark below CompoundIndicator: '(' FormatString '%)' '(' FormatString '%|' Delimiter '%)' Delimiter empty Character Delimiter

Parameters: Position Flags Width Precision Separator Position: empty Integer '$'** *Integer* **':'** *Integer* **'$' Integer ':' '$'** *Flags*: *empty* *Flag* *Flags* *Flag*: **'-'**|**'+'**|**' '**|**'0'**|**'#'**|**'='** *Width*: *OptionalPositionalInteger* *Precision*: *empty* **'.'** *OptionalPositionalInteger* *Separator*: *empty* **','** *OptionalInteger* **','** *OptionalInteger* **'?'** *OptionalInteger*: *empty* *Integer* **'*'** *OptionalPositionalInteger*: *OptionalInteger* **'*'** *Integer* **'$'

Character '%%' AnyCharacterExceptPercent Integer: NonZeroDigit Digits Digits: empty Digit Digits NonZeroDigit: '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' Digit: '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'

Note

FormatCharacter is unspecified. It can be any character that has no other purpose in this grammar, but it is recommended to assign (lower- and uppercase) letters.

Note

The Parameters of a CompoundIndicator are currently limited to a '-' flag.

Format Indicator

The format indicator can either be a single character or an expression surrounded by '%(' and '%)'. It specifies the basic manner in which a value will be formatted and is the minimum requirement to format a value.

The following characters can be used as format characters:

FormatCharacter Semantics
's'
To be formatted in a human readable format.
Can be used with all types.
'c'
To be formatted as a character.
'd'
To be formatted as a signed decimal integer.
'u'
To be formatted as a decimal image of the underlying bit representation.
'b'
To be formatted as a binary image of the underlying bit representation.
'o'
To be formatted as an octal image of the underlying bit representation.
'x' / 'X'
To be formatted as a hexadecimal image of the underlying bit representation.
'e' / 'E'
To be formatted as a real number in decimal scientific notation.
'f' / 'F'
To be formatted as a real number in decimal natural notation.
'g' / 'G'
To be formatted as a real number in decimal short notation.
Depending on the number, a scientific notation or
a natural notation is used.
'a' / 'A'
To be formatted as a real number in hexadecimal scientific notation.
'r'
To be formatted as raw bytes.
The output may not be printable and depends on endianness.

The compound indicator can be used to describe compound types like arrays or structs in more detail. A compound type is enclosed within '%(' and '%)'. The enclosed sub-format string is applied to individual elements. The trailing portion of the sub-format string following the specifier for the element is interpreted as the delimiter, and is therefore omitted following the last element. The '%|' specifier may be used to explicitly indicate the start of the delimiter, so that the preceding portion of the string will be included following the last element.

The format string inside of the compound indicator should contain exactly one format specifier (two in case of associative arrays), which specifies the formatting mode of the elements of the compound type. This format specifier can be a compound indicator itself.

Note

Inside a compound indicator, strings and characters are escaped automatically. To avoid this behavior, use "%-(" instead of "%(".

Flags

There are several flags that affect the outcome of the formatting.

Flag Semantics
'-'
When the formatted result is shorter than the value
given by the width parameter, the output is left
justified. Without the '-' flag, the output remains
right justified.

There are two exceptions where the '-' flag has a different meaning: (1) with 'r' it denotes to use little endian and (2) in case of a compound indicator it means that no special handling of the members is applied. | | '=' | When the formatted result is shorter than the value given by the width parameter, the output is centered. If the central position is not possible it is moved slightly to the right. In this case, if '-' flag is present in addition to the '=' flag, it is moved slightly to the left. | | '+' / *' '* | Applies to numerical values. By default, positive numbers are not formatted to include the + sign. With one of these two flags present, positive numbers are preceded by a plus sign or a space. When both flags are present, a plus sign is used.

In case of 'r', a big endian format is used. | | '0' | Is applied to numerical values that are printed right justified. If the zero flag is present, the space left to the number is filled with zeros instead of spaces. | | '#' | Denotes that an alternative output must be used. This depends on the type to be formatted and the format character used. See the sections below for more information. |

Width, Precision and Separator

The width parameter specifies the minimum width of the result.

The meaning of precision depends on the format indicator. For integers it denotes the minimum number of digits printed, for real numbers it denotes the number of fractional digits and for strings and compound types it denotes the maximum number of elements that are included in the output.

A separator is used for formatting numbers. If it is specified, the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by providing a number or a ''* after the ','.

In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of digits. If the argument is a negative number, the precision and separator parameters are considered unspecified. For width, the absolute value is used and the '-' flag is set.

The separator can also be followed by a '?'. In that case, an additional argument is used to specify the symbol that should be used to separate the chunks.

Position

By default, the arguments are processed in the provided order. With the position parameter it is possible to address arguments directly. It is also possible to denote a series of arguments with two numbers separated by ':', that are all processed in the same way. The second number can be omitted. In that case the series ends with the last argument.

It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.

Types

This section describes the result of combining types with format characters. It is organized in 2 subsections: a list of general information regarding the formatting of types in the presence of format characters and a table that contains details for every available combination of type and format character.

When formatting types, the following rules apply:

  • If the format character is upper case, the resulting string will be formatted using upper case letters.

  • The default precision for floating point numbers is 6 digits.

  • Rounding of floating point numbers adheres to the rounding mode of the floating point unit, if available.

  • The floating point values NaN and Infinity are formatted as nan and inf, possibly preceded by '+' or '-' sign.

  • Formatting reals is only supported for 64 bit reals and 80 bit reals. All other reals are cast to double before they are formatted. This will cause the result to be inf for very large numbers.

  • Characters and strings formatted with the 's' format character inside of compound types are surrounded by single and double quotes and unprintable characters are escaped. To avoid this, a '-' flag can be specified for the compound specifier (e.g. "%-(%s%)" instead of "%(%s%)" ).

  • Structs, unions, classes and interfaces are formatted by calling a toString method if available. See module std.format.write for more details.

  • Only part of these combinations can be used for reading. See module std.format.read for more detailed information.

This table contains descriptions for every possible combination of type and format character:

<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as...
<td rowspan="1">null</td> 's'
null

|<td rowspan="3">bool</td> 's' | false or true |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integrals 0 or 1 with the same format character.

Please note, that 'o' and 'x' with '#' flag might produce unexpected results due to special handling of the value 0. |

| 'r' | \0 or \1 |

|<td rowspan="4">Integral</td> 's', 'd' | A signed decimal number. The '#' flag is ignored. |

| 'b', 'o', 'u', 'x', 'X' | An unsigned binary, decimal, octal or hexadecimal number.

In case of 'o' and 'x', the '#' flag denotes that the number must be preceded by 0 and 0x, with the exception of the value 0, where this does not apply. For 'b' and 'u' the '#' flag has no effect. |

| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' | As a floating point value with the same specifier.

Default precision is large enough to add all digits of the integral value.

In case of 'a' and 'A', the integral digit can be any hexadecimal digit. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="5">Floating Point</td> 'e', 'E' | Scientific notation: Exactly one integral digit followed by a dot and fractional digits, followed by the exponent. The exponent is formatted as 'e' followed by a '+' or '-' sign, followed by at least two digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'f', 'F' | Natural notation: Integral digits followed by a dot and fractional digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted.

Please note: the difference between 'f' and 'F' is only visible for NaN and Infinity. |

| 's', 'g', 'G' | Short notation: If the absolute value is larger than 10 ^^ precision or smaller than 0.0001, the scientific notation is used. If not, the natural notation is applied.

In both cases precision denotes the count of all digits, including the integral digits. Trailing zeros (including a trailing dot) are removed.

If '#' flag is present, trailing zeros are not removed. |

| 'a', 'A' | Hexadecimal scientific notation: 0x followed by 1 (or 0 in case of value zero or denormalized number) followed by a dot, fractional digits in hexadecimal notation and an exponent. The exponent is build by p, followed by a sign and the exponent in decimal notation.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">Character</td> 's', 'c' | As the character.

Inside of a compound indicator 's' is treated differently: The character is surrounded by single quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integral that represents the character. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">String</td> 's' | The sequence of characters that form the string.

Inside of a compound indicator the string is surrounded by double quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'r' | The sequence of characters, each formatted with 'r'. |

| compound | As an array of characters. |

|<td rowspan="3">Array</td> 's' | When the elements are characters, the array is formatted as a string. In all other cases the array is surrounded by square brackets and the elements are separated by a comma and a space. If the elements are strings, they are surrounded by double quotes and non printable characters are escaped. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="2">Associative Array</td> 's' | As a sequence of the elements in unpredictable order. The output is surrounded by square brackets. The elements are separated by a comma and a space. The elements are formatted as key:value. |

| compound | As a sequence of the elements in unpredictable order. Each element is formatted according to the specifications given inside of the compound specifier. The first specifier is used for formatting the key and the second specifier is used for formatting the value. The order can be changed with positional arguments. For example "%(%2$s (%1$s), %)" will write the value, followed by the key in parenthesis. |

|<td rowspan="2">Enum</td> 's' | The name of the value. If the name is not available, the base value is used, preceeded by a cast. |

| All, but 's' | Enums can be formatted with all format characters that can be used with the base value. In that case they are formatted like the base value. |

|<td rowspan="3">Input Range</td> 's' | When the elements of the range are characters, they are written like a string. In all other cases, the elements are enclosed by square brackets and separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Struct</td> 's' | When the struct has neither an applicable toString nor is an input range, it is formatted as follows: StructType(field1, field2, ...). |

|<td rowspan="1">Class</td> 's' | When the class has neither an applicable toString nor is an input range, it is formatted as the fully qualified name of the class. |

|<td rowspan="1">Union</td> 's' | When the union has neither an applicable toString nor is an input range, it is formatted as its base name. |

|<td rowspan="2">Pointer</td> 's' | A null pointer is formatted as 'null'. All other pointers are formatted as hexadecimal numbers with the format character 'X'. |

| 'x', 'X' | Formatted as a hexadecimal number. |

|<td rowspan="3">SIMD vector</td> 's' | The array is surrounded by square brackets and the elements are separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Delegate</td> 's', 'r', compound | As the .stringof of this delegate treated as a string.

Please note: The implementation is currently buggy and its use is discouraged. |

Source

std/format/package.d

Examples

Simple use:

// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");

// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");

Compound specifiers allow formatting arrays and other compound types:

/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
 */
    assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
    assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");

/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
 */
    assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");

/*
These compound format specifiers may be nested in the case of a
nested array argument:
 */
    auto mat = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]];

    assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
    assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
    assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");

/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
 */
    assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
    assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
    assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);

Using parameters:

// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");

// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == ">   1234.57<");

// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");

// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");

Providing parameters as arguments:

// Width as argument
assert(format(">%*s<", 10, "abc") == ">       abc<");

// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");

// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");

// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");

// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == "   000/002147/483647");
@copyrightCopyright The D Language Foundation 2000-2021.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, and Kenji Hara
format
:
(alias template) formattedWrite = std.format.write.formattedWrite(Writer, Char, Args...)(auto ref Writer w, scope const Char[] fmt, Args args)

Converts its arguments according to a format string and writes the result to an output range.

The second version of formattedWrite takes the format string as a template argument. In this case, it is checked for consistency at compile-time.

Params: w = an $(REF_ALTTEXT output range, isOutputRange, std, range, primitives), where the formatted result is written to fmt = a $(MREF_ALTTEXT format string, std,format) args = a variadic list of arguments to be formatted Writer = the type of the writer w Char = character type of fmt Args = a variadic list of types of the arguments

Returns: The index of the last argument that was formatted. If no positional arguments are used, this is the number of arguments that where formatted.

Throws: A $(REF_ALTTEXT FormatException, FormatException, std, format) if formatting did not succeed.

Note: In theory this function should be @nogc. But with the current implementation there are some cases where allocations occur. See $(REF_ALTTEXT $(D sformat), sformat, std, format) for more details.

formattedWrite
;
auto
(local variable) std.array.Appender!string sink
sink
=
std.array.Appender!string std.array.appender!string() pure nothrow @safe

Convenience function that returns an Appender instance, optionally initialized with array.

appender
!
(alias) object.string = string
string
();
static if (is(
(alias) Payload = double
Payload
== double))
uint std.format.write.formattedWrite!(std.array.Appender!string, char, const(double), string)(ref std.array.Appender!string w, scope const(char[]) fmt, const(double) __param_2, string __param_3) pure @safe

Converts its arguments according to a format string and writes the result to an output range.

The second version of formattedWrite takes the format string as a template argument. In this case, it is checked for consistency at compile-time.

Note

In theory this function should be @nogc. But with the current implementation there are some cases where allocations occur. See sformat for more details.

Examples

import std.array : appender;

auto writer1 = appender!string();
formattedWrite(writer1, "%s is the ultimate %s.", 42, "answer");
assert(writer1[] == "42 is the ultimate answer.");

auto writer2 = appender!string();
formattedWrite(writer2, "Increase: %7.2f %%", 17.4285);
assert(writer2[] == "Increase:   17.43 %");
@paramw an output range, where the formatted result is written to@paramfmt a format string@paramargs a variadic list of arguments to be formatted@paramWriter the type of the writer w@paramChar character type of fmt@paramArgs a variadic list of types of the arguments@returnsThe index of the last argument that was formatted. If no positional arguments are used, this is the number of arguments that where formatted.@throwsA FormatException if formatting did not succeed.
formattedWrite
(
(local variable) std.array.Appender!string sink
sink
, "%.6g %s",
(field) double uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double).value
value
,
(constant) string uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double).symbol = "m s^-1"
symbol
);
else {
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])).value
value
.
void sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).toString!(std.array.Appender!string)(ref scope std.array.Appender!string writer) const pure @safe

Writes the vector as (name0: value0, name1: value1, ...).

toString
(
(local variable) std.array.Appender!string sink
sink
);
uint std.format.write.formattedWrite!(std.array.Appender!string, char, string)(ref std.array.Appender!string w, scope const(char[]) fmt, string __param_2) pure @safe

Converts its arguments according to a format string and writes the result to an output range.

The second version of formattedWrite takes the format string as a template argument. In this case, it is checked for consistency at compile-time.

Note

In theory this function should be @nogc. But with the current implementation there are some cases where allocations occur. See sformat for more details.

Examples

import std.array : appender;

auto writer1 = appender!string();
formattedWrite(writer1, "%s is the ultimate %s.", 42, "answer");
assert(writer1[] == "42 is the ultimate answer.");

auto writer2 = appender!string();
formattedWrite(writer2, "Increase: %7.2f %%", 17.4285);
assert(writer2[] == "Increase:   17.43 %");
@paramw an output range, where the formatted result is written to@paramfmt a format string@paramargs a variadic list of arguments to be formatted@paramWriter the type of the writer w@paramChar character type of fmt@paramArgs a variadic list of types of the arguments@returnsThe index of the last argument that was formatted. If no positional arguments are used, this is the number of arguments that where formatted.@throwsA FormatException if formatting did not succeed.
formattedWrite
(
(local variable) std.array.Appender!string sink
sink
, " %s",
(constant) string uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])).symbol = "m"
symbol
);
} return
(local variable) std.array.Appender!string sink
sink
[];
} } enum
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.lengthDim = Dim(0, 1, 0)
lengthDim
=
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
(length: 1);
enum
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.timeDim = Dim(0, 0, 1)
timeDim
=
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
(time: 1);
alias
(alias) uom_quantity_polymorphism.Length = uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double)
Length
=
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.lengthDim = Dim(0, 1, 0)
Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.lengthDim = Dim(0, 1, 0)
lengthDim
, double);
alias
(alias) uom_quantity_polymorphism.Displacement = uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))
Displacement
=
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.lengthDim = Dim(0, 1, 0)
Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.lengthDim = Dim(0, 1, 0)
lengthDim
,
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
);
alias
(alias) uom_quantity_polymorphism.Direction = uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"]))
Direction
=
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]))

A graded quantity: a Payload (double, or Vec3 for a dimensioned vector) tagged with its dimension (composition ordering A).

Quantity
!(
(struct) uom_quantity_polymorphism.Dim

A dimension: an exponent vector in the free abelian group ℤ³ over (mass, length, time), stored as its unique normal form.

Dim
(),
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
);
// --- Dimension-polymorphic geometry (generic over the dimension via IFTI) ----- /// `sqr` on a scalar quantity: `Quantity!(d)` → `Quantity!(2·d)`. Forward /// inference computes the result grade from the argument's — the `sqr` litmus. auto
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.sqr!(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double) q) pure nothrow @nogc @safe

sqr on a scalar quantity: Quantity!(d)Quantity!(2·d). Forward inference computes the result grade from the argument's — the sqr litmus.

sqr
(Q)(in
(alias) Q = uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double)
Q
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double)) q
q
) =>
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double)) q
q
*
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double).opBinary!("*", Dim(0, 1, 0), double)(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double) rhs) const pure nothrow @nogc @safe

*// between quantities: dimensions combine, payloads multiply (at least one side scalar; two vectors are dot/cross-ed, never *-ed).

q
;
/// Dimension-aware dot product: `dot(Quantity!(a,Vec3), Quantity!(b,Vec3))` is a /// scalar `Quantity!(a·b)`. `dot(length, length) = area`. This *restores* the /// dimension that `Vector.dot` (dimension-blind `cast(CommonType)`) discards. auto
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.dot!(Dim(0, 1, 0), Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x, in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) y) pure nothrow @nogc @safe

Dimension-aware dot product: dot`(Quantity!(a,Vec3), Quantity!(b,Vec3))` is a scalar `Quantity!(a·b)`. dot(length, length) = area. This restores the dimension that Vector.dot`` (dimension-blind cast(CommonType)) discards.

dot
(Dim a, Dim b)(in
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.a = Dim(0, 1, 0)
Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.a = Dim(0, 1, 0)
a
,
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
)
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
, in
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.b = Dim(0, 1, 0)
Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.b = Dim(0, 1, 0)
b
,
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
)
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) y
y
)
=>
(template instance) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double)
Quantity
!(
uom_quantity_polymorphism.Dim uom_quantity_polymorphism.combine(in uom_quantity_polymorphism.Dim a, in uom_quantity_polymorphism.Dim b, in int sign) pure nothrow @nogc @safe

The group operation: ``sign = +1 multiplies dimensions, -1 divides.

combine
(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.a = Dim(0, 1, 0)
a
,
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.b = Dim(0, 1, 0)
b
, 1), double)(
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
.
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])).value
value
.
double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).dot!double(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) rhs) const pure nothrow @nogc @safe

Dot product between two vectors.

dot
(
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) y
y
.
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])).value
value
));
/// Squared length: `dot` with self. `lengthSquared(length-vec) = area`. auto
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.lengthSquared!(Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x) pure nothrow @nogc @safe

Squared length: dot with self. ``lengthSquared(length-vec) = area.

lengthSquared
(Dim a)(in
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]))

A graded quantity: a Payload (double, or Vec3 for a dimensioned vector) tagged with its dimension (composition ordering A).

Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.a = Dim(0, 1, 0)
a
,
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
)
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
) =>
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.dot!(Dim(0, 1, 0), Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x, in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) y) pure nothrow @nogc @safe

Dimension-aware dot product: dot`(Quantity!(a,Vec3), Quantity!(b,Vec3))` is a scalar `Quantity!(a·b)`. dot(length, length) = area. This restores the dimension that Vector.dot`` (dimension-blind cast(CommonType)) discards.

dot
(
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
,
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
);
/// Magnitude: `|v| = sqrt(Σ vᵢ²)` has the *same* dimension as the components /// (`sqrt` of an area grade back to length). Dimension-aware. auto
uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double) uom_quantity_polymorphism.magnitude!(Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x) pure nothrow @nogc @safe

Magnitude

|v| = sqrt(Σ vᵢ²) has the same dimension as the components (sqrt of an area grade back to length). Dimension-aware.

magnitude
(Dim a)(in
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]))

A graded quantity: a Payload (double, or Vec3 for a dimensioned vector) tagged with its dimension (composition ordering A).

Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.a = Dim(0, 1, 0)
a
,
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
)
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
)
{ import
(package) std
std
.
(module) std.math

Contains the elementary mathematical functions (powers, roots, and trigonometric functions), and low-level floating-point operations. Mathematical special functions are available in std.mathspecial.

Category Members
Constants E PI PI_2 PI4 M1_PI M2_PI M2_SQRTPI LN10 LN2 LOG2 LOG2E LOG2T LOG10E SQRT2 SQRT1_2
Algebraic abs fabs sqrt cbrt hypot poly nextPow2 truncPow2
Trigonometry sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh atanh
Rounding ceil floor round lround trunc rint lrint nearbyint rndtol quantize
Exponentiation & Logarithms pow powmod exp exp2 expm1 ldexp frexp log log2 log10 logb ilogb log1p scalbn
Remainder fmod modf remainder remquo
Floating-point operations approxEqual feqrel fdim fmax fmin fma isClose nextDown nextUp nextafter NaN getNaNPayload cmp
Introspection isFinite isIdentical isInfinity isNaN isNormal isSubnormal signbit sgn copysign isPowerOf2
Hardware Control IeeeFlags ieeeFlags resetIeeeFlags FloatingPointControl

The functionality closely follows the IEEE754-2008 standard for floating-point arithmetic, including the use of camelCase names rather than C99-style lower case names. All of these functions behave correctly when presented with an infinity or NaN.

The following IEEE 'real' formats are currently supported:

  • 64 bit Big-endian 'double' (eg PowerPC)

  • 128 bit Big-endian 'quadruple' (eg SPARC)

  • 64 bit Little-endian 'double' (eg x86-SSE2)

  • 80 bit Little-endian, with implied bit 'real80' (eg x87, Itanium)

  • 128 bit Little-endian 'quadruple' (not implemented on any known processor!)

  • Non-IEEE 128 bit Big-endian 'doubledouble' (eg PowerPC) has partial support

Unlike C, there is no global 'errno' variable. Consequently, almost all of these functions are pure nothrow.

Source

std/math/package.d

@copyrightCopyright The D Language Foundation 2000 - 2011. D implementations of tan, atan, atan2, exp, expm1, exp2, log, log10, log1p, log2, floor, ceil and lrint functions are based on the CEPHES math library, which is Copyright (C) 2001 Stephen L. Moshier <steve@moshier.net> and are incorporated herein by permission of the author. The author reserves the right to distribute this material elsewhere under different copying permissions. These modifications are distributed here under the following terms:@licenseBoost License 1.0.@authorsWalter Bright, Don Clugston, Conversion of CEPHES math library to D by Iain Buclaw and David Nadlinger
math
:
(alias) sqrt = float std.math.algebraic.sqrt(float x) pure nothrow @nogc @safe

Compute square root of x.

      $(TABLE_SV
      $(TR $(TH x)         $(TH sqrt(x))   $(TH invalid?))
      $(TR $(TD -0.0)      $(TD -0.0)      $(TD no))
      $(TR $(TD $(LT)0.0)  $(TD $(NAN))    $(TD yes))
      $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD no))
      )
sqrt
;
return
(template instance) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double)
Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.a = Dim(0, 1, 0)
a
, double)(
double std.math.algebraic.sqrt(double x) pure nothrow @nogc @safe

Compute square root of x.

x sqrt(x) invalid?
-0.0 -0.0 no
<0.0 yes
+ + no
sqrt
(
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
.
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])).value
value
.
double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).dot!double(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) rhs) const pure nothrow @nogc @safe

Dot product between two vectors.

dot
(
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
.
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])).value
value
)));
} /// 3-D cross product — **absent from `sparkles:math.Vector`**, implemented here. /// Dimension-aware: `cross(length, length)` is an area-normal.
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.cross3(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) a, in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) b) pure nothrow @nogc @safe

3-D cross product — absent from sparkles:math.Vector, implemented here. Dimension-aware: cross(length, length) is an area-normal.

cross3
(in
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) a
a
, in
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) b
b
) @safe pure nothrow @nogc
=>
(struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])
Vec3
(
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) a
a
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).y
y
*
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) b
b
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).z
z
-
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) a
a
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).z
z
*
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) b
b
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).y
y
,
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) a
a
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).z
z
*
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) b
b
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).x
x
-
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) a
a
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).x
x
*
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) b
b
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).z
z
,
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) a
a
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).x
x
*
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) b
b
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).y
y
-
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) a
a
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).y
y
*
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) b
b
.
(field) double sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).x
x
,
); /// ditto (dimensioned wrapper). auto
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) uom_quantity_polymorphism.cross!(Dim(0, 1, 0), Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x, in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) y) pure nothrow @nogc @safe

ditto (dimensioned wrapper).

cross
(Dim a, Dim b)(in
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.a = Dim(0, 1, 0)
Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.a = Dim(0, 1, 0)
a
,
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
)
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
, in
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.b = Dim(0, 1, 0)
Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.b = Dim(0, 1, 0)
b
,
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
)
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) y
y
)
=>
(template instance) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]))
Quantity
!(
uom_quantity_polymorphism.Dim uom_quantity_polymorphism.combine(in uom_quantity_polymorphism.Dim a, in uom_quantity_polymorphism.Dim b, in int sign) pure nothrow @nogc @safe

The group operation: ``sign = +1 multiplies dimensions, -1 divides.

combine
(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.a = Dim(0, 1, 0)
a
,
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.b = Dim(0, 1, 0)
b
, 1),
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
)(
sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.cross3(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) a, in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) b) pure nothrow @nogc @safe

3-D cross product — absent from sparkles:math.Vector, implemented here. Dimension-aware: cross(length, length) is an area-normal.

cross3
(
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
.
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])).value
value
,
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) y
y
.
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])).value
value
));
/// Normalize a dimensioned vector to a dimensionless unit `Direction`.
(alias) uom_quantity_polymorphism.Direction = uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"]))
Direction
uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"])) uom_quantity_polymorphism.normalize!(Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x) pure nothrow @nogc @safe

Normalize a dimensioned vector to a dimensionless unit Direction.

normalize
(Dim a)(in
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]))

A graded quantity: a Payload (double, or Vec3 for a dimensioned vector) tagged with its dimension (composition ordering A).

Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.a = Dim(0, 1, 0)
a
,
(alias) uom_quantity_polymorphism.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
)
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
)
=>
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"]))
Direction
(
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
.
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])).value
value
/
sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).opBinary!("/", double)(double rhs) const pure nothrow @nogc @safe

Component-wise scalar multiplication/division.

magnitude
(
(parameter) const(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))) x
x
).
(field) double uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double).value
value
);
@("Quantity.polymorphism.dimension-aware-geometry") @safe pure nothrow @nogc unittest { auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) edge1
edge1
=
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))
Displacement
(
(struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])
Vec3
(2, 0, 0)); // metres
auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) edge2
edge2
=
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))
Displacement
(
(struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])
Vec3
(0, 3, 0)); // metres
// dot / lengthSquared of length-vectors are AREAS. auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) a
a
=
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.dot!(Dim(0, 1, 0), Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x, in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) y) pure nothrow @nogc @safe

Dimension-aware dot product: dot`(Quantity!(a,Vec3), Quantity!(b,Vec3))` is a scalar `Quantity!(a·b)`. dot(length, length) = area. This restores the dimension that Vector.dot`` (dimension-blind cast(CommonType)) discards.

dot
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) edge1
edge1
,
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) edge2
edge2
);
static assert(is(typeof(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) a
a
) == Quantity!(Dim(length: 2), double)));
assert(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) a
a
.
(field) double uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double).value
value
== 0);
auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) l2
l2
=
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.lengthSquared!(Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x) pure nothrow @nogc @safe

Squared length: dot with self. ``lengthSquared(length-vec) = area.

lengthSquared
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) edge1
edge1
);
static assert(is(typeof(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) l2
l2
) == Quantity!(Dim(length: 2), double)));
assert(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) l2
l2
.
(field) double uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double).value
value
== 4);
// magnitude is a length again; normalize is dimensionless. auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double) m
m
=
uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double) uom_quantity_polymorphism.magnitude!(Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x) pure nothrow @nogc @safe

Magnitude

|v| = sqrt(Σ vᵢ²) has the same dimension as the components (sqrt of an area grade back to length). Dimension-aware.

magnitude
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) edge1
edge1
);
static assert(is(typeof(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double) m
m
) == Length));
assert(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double) m
m
.
(field) double uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double).value
value
== 2);
static assert(is(typeof(
uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"])) uom_quantity_polymorphism.normalize!(Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x) pure nothrow @nogc @safe

Normalize a dimensioned vector to a dimensionless unit Direction.

normalize
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) edge1
edge1
)) == Direction));
// cross of two length-vectors is an area-normal. auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) n
n
=
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) uom_quantity_polymorphism.cross!(Dim(0, 1, 0), Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x, in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) y) pure nothrow @nogc @safe

ditto (dimensioned wrapper).

cross
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) edge1
edge1
,
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) edge2
edge2
);
static assert(is(typeof(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) n
n
) == Quantity!(Dim(length: 2), Vec3)));
assert(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) n
n
.
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])).value
value
==
bool sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).opEquals(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) rhs) const pure nothrow @nogc @safe

Component-wise equality (compares the backing components directly, so it is well-defined despite the union — the compiler-generated == over a union is not).

Vec3
(0, 0, 6));
// sqr forward-infers the doubled grade. static assert(is(typeof(
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.sqr!(uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double) q) pure nothrow @nogc @safe

sqr on a scalar quantity: Quantity!(d)Quantity!(2·d). Forward inference computes the result grade from the argument's — the sqr litmus.

sqr
(
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double)
Length
(3.0))) == Quantity!(Dim(length: 2), double)));
// Polymorphism does not loosen the within-grade rule: adding a length to an // area still does not compile. static assert(!__traits(compiles,
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double)
Length
(1.0) +
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.lengthSquared!(Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x) pure nothrow @nogc @safe

Squared length: dot with self. ``lengthSquared(length-vec) = area.

lengthSquared
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) edge1
edge1
)));
} void
void D main() @safe
main
() @safe
{ import
(package) std
std
.
(module) std.stdio
Category Symbols
File handles _popen File isFileHandle openNetwork stderr stdin stdout
Reading chunks lines readf readfln readln
Writing toFile write writef writefln writeln
Misc KeepTerminator LockType StdioException

Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio is publically imported when importing std.stdio.

There are three layers of I/O:

  1. The lowest layer is the operating system layer. The two main schemes are Windows and Posix.

  2. C's stdio.h which unifies the two operating system schemes.

  3. std.stdio, this module, unifies the various stdio.h implementations into a high level package for D programs.

Source

std/stdio.d

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Alex Rønne Petersen
stdio
:
(alias template) writeln = std.stdio.writeln(T...)(T args)

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Params: args = the items to write to stdout

Throws: In case of an I/O error, throws an $(LREF StdioException). Example: Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main() { string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }

} ---

writeln
;
// A triangle's two edges (metres): dot, cross (normal), and areas. auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) e1
e1
=
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))
Displacement
(
(struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])
Vec3
(4, 0, 0));
auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) e2
e2
=
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"]))
Displacement
(
(struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])
Vec3
(0, 3, 0));
auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) area2
area2
=
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.lengthSquared!(Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x) pure nothrow @nogc @safe

Squared length: dot with self. ``lengthSquared(length-vec) = area.

lengthSquared
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) e1
e1
); // m^2
auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) normal
normal
=
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) uom_quantity_polymorphism.cross!(Dim(0, 1, 0), Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x, in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) y) pure nothrow @nogc @safe

ditto (dimensioned wrapper).

cross
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) e1
e1
,
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) e2
e2
); // m^2, an area-vector
auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"])) unit
unit
=
uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"])) uom_quantity_polymorphism.normalize!(Dim(0, 2, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) x) pure nothrow @nogc @safe

Normalize a dimensioned vector to a dimensionless unit Direction.

normalize
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) normal
normal
); // dimensionless direction
auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double) speed
speed
=
(struct) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double)
Length
(6.0) /
uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), double).opBinary!("/", Dim(0, 0, 1), double)(in uom_quantity_polymorphism.Quantity!(Dim(0, 0, 1), double) rhs) const pure nothrow @nogc @safe

*// between quantities: dimensions combine, payloads multiply (at least one side scalar; two vectors are dot/cross-ed, never *-ed).

timeQty
(2.0); // m / s : a velocity scalar
// FORWARD inference works, and composes through a chain: each grade below is // computed by IFTI from the arguments, never annotated. auto
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"])) chained
chained
=
uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"])) uom_quantity_polymorphism.normalize!(Dim(0, 2, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) x) pure nothrow @nogc @safe

Normalize a dimensioned vector to a dimensionless unit Direction.

normalize
(
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) uom_quantity_polymorphism.cross!(Dim(0, 1, 0), Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x, in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) y) pure nothrow @nogc @safe

ditto (dimensioned wrapper).

cross
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) e1
e1
,
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) e2
e2
)); // (m·m)-vec -> dimensionless dir
static assert(is(typeof(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"])) chained
chained
) == Direction));
// The CEILING: D dispatches on argument types, never on the *result* type, so // there is no inverse of `sqr`. `magnitude` maps grade `a` -> `a`; `sqr` maps // `a` -> `2a`; but no generic function can be *asked* for "the grade whose // square is an area" — the target grade must be given at the call site, not // inferred from a desired return type. That return-type inference is exactly // Kennedy's AG-unification; an evaluator like D (and every non-F# system in // the survey) confirms spelled-out grades, it does not solve for them.
void std.stdio.writeln!(string, uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])))(string __param_0, uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) __param_1) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("edge1 = ",
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) e1
e1
);
void std.stdio.writeln!(string, uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double))(string __param_0, uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) __param_1) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("|edge1|² = ",
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) area2
area2
);
void std.stdio.writeln!(string, uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])), string)(string __param_0, uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) __param_1, string __param_2) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("cross(e1,e2) = ",
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), Vector!(double, 3LU, ["x", "y", "z"])) normal
normal
, " (area-normal; Vector has no cross — local impl)");
void std.stdio.writeln!(string, uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"])))(string __param_0, uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"])) __param_1) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("normalize(normal)= ",
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 0, 0), Vector!(double, 3LU, ["x", "y", "z"])) unit
unit
);
void std.stdio.writeln!(string, uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double))(string __param_0, uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double) __param_1) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("6 m / 2 s = ",
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, -1), double) speed
speed
);
void std.stdio.writeln!(string, uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double), string)(string __param_0, uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) __param_1, string __param_2) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("dot(e1,e2) = ",
uom_quantity_polymorphism.Quantity!(Dim(0, 2, 0), double) uom_quantity_polymorphism.dot!(Dim(0, 1, 0), Dim(0, 1, 0))(in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) x, in uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) y) pure nothrow @nogc @safe

Dimension-aware dot product: dot`(Quantity!(a,Vec3), Quantity!(b,Vec3))` is a scalar `Quantity!(a·b)`. dot(length, length) = area. This restores the dimension that Vector.dot`` (dimension-blind cast(CommonType)) discards.

dot
(
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) e1
e1
,
(local variable) uom_quantity_polymorphism.Quantity!(Dim(0, 1, 0), Vector!(double, 3LU, ["x", "y", "z"])) e2
e2
), " (dimension-aware; Vector.dot alone loses the m²)");
} /// Small helper: a scalar time quantity (keeps `main` readable).
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.timeDim = Dim(0, 0, 1)
Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.timeDim = Dim(0, 0, 1)
timeDim
, double)
uom_quantity_polymorphism.Quantity!(Dim(0, 0, 1), double) uom_quantity_polymorphism.timeQty(in double s) pure nothrow @nogc @safe

Small helper: a scalar time quantity (keeps main readable).

timeQty
(in double
(parameter) const(double) s
s
) @safe pure nothrow @nogc
=>
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.timeDim = Dim(0, 0, 1)
Quantity
!(
(constant) uom_quantity_polymorphism.Dim uom_quantity_polymorphism.timeDim = Dim(0, 0, 1)
timeDim
, double)(
(parameter) const(double) s
s
);