Skip to content

Commit 8697ca5

Browse files
authored
Adjust center for isConvertibleToSlice and add another UT example (#466)
1 parent bbf0c99 commit 8697ca5

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

source/mir/math/stat.d

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1716,7 +1716,7 @@ Returns:
17161716
+/
17171717
template center(alias centralTendency = mean!(Summation.appropriate))
17181718
{
1719-
import mir.ndslice.slice: Slice, SliceKind, sliced, hasAsSlice;
1719+
import mir.ndslice.slice: isConvertibleToSlice, isSlice, Slice, SliceKind;
17201720
/++
17211721
Params:
17221722
slice = slice
@@ -1734,16 +1734,11 @@ template center(alias centralTendency = mean!(Summation.appropriate))
17341734
}
17351735

17361736
/// ditto
1737-
auto center(T)(T[] array)
1737+
auto center(T)(T x)
1738+
if (isConvertibleToSlice!T && !isSlice!T)
17381739
{
1739-
return center(array.sliced);
1740-
}
1741-
1742-
/// ditto
1743-
auto center(T)(T withAsSlice)
1744-
if (hasAsSlice!T)
1745-
{
1746-
return center(withAsSlice.asSlice);
1740+
import mir.ndslice.slice: toSlice;
1741+
return center(x.toSlice);
17471742
}
17481743
}
17491744

@@ -1763,6 +1758,32 @@ unittest
17631758
assert(x.center!hmean.all!approxEqual([-1.44898, -0.44898, 0.55102, 1.55102, 2.55102, 3.55102]));
17641759
assert(x.center!gmean.all!approxEqual([-1.99379516, -0.99379516, 0.00620483, 1.00620483, 2.00620483, 3.00620483]));
17651760
assert(x.center!median.all!approxEqual([-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]));
1761+
1762+
// center operates lazily, if original slice is changed, then
1763+
auto y = x.center;
1764+
assert(y.all!approxEqual([-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]));
1765+
x[0]++;
1766+
assert(y.all!approxEqual([-1.5, -1.5, -0.5, 0.5, 1.5, 2.5]));
1767+
}
1768+
1769+
/// Example of lazy behavior of center
1770+
version(mir_test)
1771+
@safe pure nothrow
1772+
unittest
1773+
{
1774+
import mir.algorithm.iteration: all;
1775+
import mir.math.common: approxEqual;
1776+
import mir.ndslice.allocation: slice;
1777+
import mir.ndslice.slice: sliced;
1778+
1779+
auto x = [1.0, 2, 3, 4, 5, 6].sliced;
1780+
auto y = x.center;
1781+
auto z = x.center.slice;
1782+
assert(y.all!approxEqual([-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]));
1783+
x[0]++;
1784+
// y changes, while z does not
1785+
assert(y.all!approxEqual([-1.5, -1.5, -0.5, 0.5, 1.5, 2.5]));
1786+
assert(z.all!approxEqual([-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]));
17661787
}
17671788

17681789
/// Center dynamic array

0 commit comments

Comments
 (0)