Skip to content

Commit

Permalink
Merge pull request #4825 from 9il/master
Browse files Browse the repository at this point in the history
add ndslice.slice.as
  • Loading branch information
andralex committed Oct 1, 2016
2 parents 2f8e693 + a3d18eb commit d387277
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions std/experimental/ndslice/slice.d
Expand Up @@ -8,6 +8,7 @@ Authors: Ilya Yaroshenko
Source: $(PHOBOSSRC std/_experimental/_ndslice/_slice.d)
Macros:
SUBREF = $(REF_ALTTEXT $(TT $2), $2, std,experimental, ndslice, $1)$(NBSP)
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
T4=$(TR $(TDNW $(LREF $1)) $(TD $2) $(TD $3) $(TD $4))
STD = $(TD $(SMALL $0))
Expand Down Expand Up @@ -919,6 +920,55 @@ unittest
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).
+/
Expand Down

0 comments on commit d387277

Please sign in to comment.