Functional\replicate tests + implementation
authorwidmogrod <widmogrod@gmail.com>
Thu, 21 Dec 2017 18:01:28 +0000 (19:01 +0100)
committerwidmogrod <widmogrod@gmail.com>
Thu, 21 Dec 2017 18:01:28 +0000 (19:01 +0100)
src/Functional/infinit.php
test/Functional/ReplicateTest.php [new file with mode: 0644]

index 55ae7fe..bbdcf58 100644 (file)
@@ -72,13 +72,7 @@ const replicate = 'Widmogrod\Functional\replicate';
 function replicate(int $n, $a = null): Listt
 {
     return curryN(2, function (int $n, $a): Listt {
-        if ($n < 1) {
-            return fromNil();
-        }
-
-        return ListtCons::of(function () use ($n, $a) {
-            return [$a, replicate($n - 1, $a)];
-        });
+        return take($n, repeat($a));
     })(...func_get_args());
 }
 
diff --git a/test/Functional/ReplicateTest.php b/test/Functional/ReplicateTest.php
new file mode 100644 (file)
index 0000000..479f5ea
--- /dev/null
@@ -0,0 +1,39 @@
+<?php
+
+namespace test\Functional;
+
+use Eris\Generator;
+use Eris\TestTrait;
+use function Widmogrod\Functional\eql;
+use function Widmogrod\Functional\filter;
+use function Widmogrod\Functional\length;
+use function Widmogrod\Functional\replicate;
+
+class ReplicateTest extends \PHPUnit_Framework_TestCase
+{
+    use TestTrait;
+
+    public function test_it_should_generate_infinite_list()
+    {
+        $this->forAll(
+            Generator\choose(1, 100),
+            Generator\int()
+        )->then(function ($n, $value) {
+            $list = replicate($n, $value);
+
+            return length($list) === $n;
+        });
+    }
+
+    public function test_it_should_generate_repetive_value()
+    {
+        $this->forAll(
+            Generator\choose(1, 100),
+            Generator\int()
+        )->then(function ($n, $value) {
+            $list = replicate($n, $value);
+
+            return length(filter(eql($value), $list)) === $n;
+        });
+    }
+}