mirror of
https://github.com/dlang/phobos.git
synced 2025-05-12 07:08:48 +03:00
add slice.as
This commit is contained in:
parent
b2978040ca
commit
a3d18ebbec
1 changed files with 50 additions and 0 deletions
|
@ -8,6 +8,7 @@ Authors: Ilya Yaroshenko
|
||||||
Source: $(PHOBOSSRC std/_experimental/_ndslice/_slice.d)
|
Source: $(PHOBOSSRC std/_experimental/_ndslice/_slice.d)
|
||||||
|
|
||||||
Macros:
|
Macros:
|
||||||
|
SUBREF = $(REF_ALTTEXT $(TT $2), $2, std,experimental, ndslice, $1)$(NBSP)
|
||||||
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
|
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
|
||||||
T4=$(TR $(TDNW $(LREF $1)) $(TD $2) $(TD $3) $(TD $4))
|
T4=$(TR $(TDNW $(LREF $1)) $(TD $2) $(TD $3) $(TD $4))
|
||||||
STD = $(TD $(SMALL $0))
|
STD = $(TD $(SMALL $0))
|
||||||
|
@ -919,6 +920,55 @@ unittest
|
||||||
assert(shape[1] == 0);
|
assert(shape[1] == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/++
|
||||||
|
Convenience function that creates a lazy view,
|
||||||
|
where each element of the original slice is converted to the type `T`.
|
||||||
|
It uses $(SUBREF selection, mapSlice) and $(REF_ALTTEXT $(TT to), to, std,conv)$(NBSP)
|
||||||
|
composition under the hood.
|
||||||
|
Params:
|
||||||
|
slice = a slice to create a view on.
|
||||||
|
Returns:
|
||||||
|
A lazy slice with elements converted to the type `T`.
|
||||||
|
+/
|
||||||
|
template as(T)
|
||||||
|
{
|
||||||
|
///
|
||||||
|
auto as(size_t N, Range)(Slice!(N, Range) slice)
|
||||||
|
{
|
||||||
|
static if (is(slice.DeepElemType == T))
|
||||||
|
{
|
||||||
|
return slice;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
import std.conv : to;
|
||||||
|
import std.experimental.ndslice.selection : mapSlice;
|
||||||
|
return mapSlice!(to!T)(slice);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
unittest
|
||||||
|
{
|
||||||
|
import std.experimental.ndslice.slice : as;
|
||||||
|
import std.experimental.ndslice.selection : diagonal;
|
||||||
|
|
||||||
|
auto matrix = slice!double([2, 2], 0);
|
||||||
|
auto stringMatrixView = matrix.as!string;
|
||||||
|
assert(stringMatrixView ==
|
||||||
|
[["0", "0"],
|
||||||
|
["0", "0"]]);
|
||||||
|
|
||||||
|
matrix.diagonal[] = 1;
|
||||||
|
assert(stringMatrixView ==
|
||||||
|
[["1", "0"],
|
||||||
|
["0", "1"]]);
|
||||||
|
|
||||||
|
/// allocate new slice composed of strings
|
||||||
|
Slice!(2, string*) stringMatrix = stringMatrixView.slice;
|
||||||
|
}
|
||||||
|
|
||||||
/++
|
/++
|
||||||
Base Exception class for $(MREF std, experimental, ndslice).
|
Base Exception class for $(MREF std, experimental, ndslice).
|
||||||
+/
|
+/
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue