Fix traversable issue #30
authorwidmogrod <widmogrod@gmail.com>
Sun, 23 Oct 2016 22:42:08 +0000 (00:42 +0200)
committerwidmogrod <widmogrod@gmail.com>
Sun, 23 Oct 2016 22:42:36 +0000 (00:42 +0200)
example/ExampleOfTraversableTest.php [new file with mode: 0644]
src/Primitive/Listt.php

diff --git a/example/ExampleOfTraversableTest.php b/example/ExampleOfTraversableTest.php
new file mode 100644 (file)
index 0000000..d85a2fb
--- /dev/null
@@ -0,0 +1,31 @@
+<?php
+
+namespace example;
+
+use Widmogrod\Primitive\Listt;
+use Widmogrod\Functional as f;
+use Widmogrod\Monad\Maybe as m;
+
+function value_is($x)
+{
+    return $x % 2 == 1 ? m\nothing() : m\just($x);
+}
+
+class ExampleOfTraversableTest extends \PHPUnit_Framework_TestCase
+{
+    public function test_it_traverse_just()
+    {
+        $list = Listt::of([2, 4]);
+        $result = f\traverse('example\value_is', $list);
+
+        $this->assertEquals(m\just([2, 4]), $result);
+    }
+
+    public function test_it_traverse_nothing()
+    {
+        $list = Listt::of([1, 2, 3, 4]);
+        $result = f\traverse('example\value_is', $list);
+
+        $this->assertEquals(m\nothing(), $result);
+    }
+}
index 6f12fdf..1e65217 100644 (file)
@@ -99,8 +99,12 @@ class Listt implements
     public function traverse(callable $transformation)
     {
         return f\foldr(function ($ys, $x) use ($transformation) {
-            return call_user_func($transformation, $x)->map(f\append)->ap($ys);
-        }, self::of([]), $this);
+            $functor =  $transformation($x);
+
+            return $functor
+                ->map(f\append)
+                ->ap($ys ? $ys : $functor::of([])); // https://github.com/widmogrod/php-functional/issues/30
+        }, false, $this);
     }
 
     /**