From a3d18ebbec9a6b5f2d1d145fd3eece12e6dc8ffb Mon Sep 17 00:00:00 2001 From: Ilya Yaroshenko Date: Fri, 30 Sep 2016 20:12:28 +0200 Subject: [PATCH] add slice.as --- std/experimental/ndslice/slice.d | 50 ++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/std/experimental/ndslice/slice.d b/std/experimental/ndslice/slice.d index 4fa71e323..5b0bc881f 100644 --- a/std/experimental/ndslice/slice.d +++ b/std/experimental/ndslice/slice.d @@ -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)) @@ -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). +/