Browse files

Merge pull request #342 from stepancheg/maybe-map

sequences: implement `map` and `filter` functions for Maybe
  • Loading branch information...
2 parents e9927b7 + bb617f8 commit 419f54286e031f625a95c232b343c54df5fb63c5 @jckarter committed Aug 17, 2012
Showing with 33 additions and 0 deletions.
  1. +16 −0 lib-clay/sequences/sequences.clay
  2. +17 −0 test/sequences/maybe/test.clay
View
16 lib-clay/sequences/sequences.clay
@@ -20,6 +20,22 @@ alias sliceUpto(..args) = force(slicedUpto(..args));
alias group(..args) = force(grouped(..args));
+
+//
+// specializations for Maybe
+//
+
+[M when Maybe?(M)]
+overload map(f, m:M) =
+ maybe(m, v -> Maybe(f(v)), () -> nothing(Type(f(just(m)))));
+
+[T]
+overload filter(f, m:Maybe[T]) =
+ if (just?(m) and f(just(m)))
+ m
+ else
+ nothing(T);
+
//
//
View
17 test/sequences/maybe/test.clay
@@ -0,0 +1,17 @@
+import sequences.*;
+
+import test.*;
+
+
+main() = testMain(
+ TestSuite("sequences for Maybe", array(
+ TestCase("map", test => {
+ expectEqual(test, "map just", Maybe(4), map(x -> x + 1, Maybe(3)));
+ expectEqual(test, "map nothing", nothing(Int), map(x -> x + 1, nothing(Int)));
+ }),
+ TestCase("filter", test => {
+ expectEqual(test, "filter just pos", Maybe(4), filter(x -> x % 2 == 0, Maybe(4)));
+ expectEqual(test, "filter just neg", nothing(Int), filter(x -> x % 2 == 0, Maybe(3)));
+ expectEqual(test, "filter nothing", nothing(Int), filter(x -> x % 2 == 0, nothing(Int)));
+ }),
+ )));

0 comments on commit 419f542

Please sign in to comment.