Maybe is not foldable
authorwidmogrod <widmogrod@gmail.com>
Fri, 29 Dec 2017 23:18:52 +0000 (00:18 +0100)
committerwidmogrod <widmogrod@gmail.com>
Fri, 29 Dec 2017 23:18:52 +0000 (00:18 +0100)
src/Monad/Maybe/Just.php
src/Monad/Maybe/Maybe.php
src/Monad/Maybe/Nothing.php
test/Functional/ConcatTest.php

index 5e60a67..1629c74 100644 (file)
@@ -81,4 +81,15 @@ class Just implements Maybe
     {
         return $this->value;
     }
+
+    /**
+     * foldl _ z Nothing = z
+     * foldl f z (Just x) = f z x
+     *
+     * @inheritdoc
+     */
+    public function reduce(callable $function, $accumulator)
+    {
+        return $function($accumulator, $this->value);
+    }
 }
index a249e2c..0f8425d 100644 (file)
@@ -9,6 +9,7 @@ use Widmogrod\FantasyLand;
 
 interface Maybe extends
     FantasyLand\Monad,
+    FantasyLand\Foldable,
     Common\ValueOfInterface,
     FantasyLand\Monoid
 {
index af00a27..91df3dd 100644 (file)
@@ -73,4 +73,15 @@ class Nothing implements Maybe
     {
         return null;
     }
+
+    /**
+     * foldl _ z Nothing = z
+     * foldl f z (Just x) = f z x
+     *
+     * @inheritdoc
+     */
+    public function reduce(callable $function, $accumulator)
+    {
+        return $accumulator;
+    }
 }
index 08c9d1a..3e652cb 100644 (file)
@@ -5,6 +5,8 @@ declare(strict_types=1);
 namespace test\Functional;
 
 use Widmogrod\Functional as f;
+use Widmogrod\Monad\Maybe\Just;
+use Widmogrod\Monad\Maybe\Nothing;
 
 class ConcatTest extends \PHPUnit\Framework\TestCase
 {
@@ -59,6 +61,14 @@ class ConcatTest extends \PHPUnit\Framework\TestCase
                     3
                 ]),
             ],
+            'Just of lists' => [
+                '$array' => Just::of(f\fromIterable(['a', 1, 3])),
+                '$expected' => f\fromIterable(['a', 1, 3]),
+            ],
+            'Nothing of lists' => [
+                '$array' => Nothing::mempty(),
+                '$expected' => f\fromNil()
+            ],
         ];
     }
 }