Implement hope_option:validate/2
[hope.git] / src / hope_option.erl
index 529158d..996e342 100644 (file)
@@ -1,20 +1,25 @@
 -module(hope_option).
 
--behavior(hope_monad).
+-behavior(hope_gen_monad).
 
 -export_type(
     [ t/1
     ]).
 
 -export(
-    [ put/2
-    , get/2
-    , return/1
+    % Generic monad interface
+    [ return/1
     , map/2
-    , iter/2
     , pipe/2
+
+    % Specific to hope_option:t()
+    , return/2
+    , put/2
+    , get/2
+    , iter/2
     , of_result/1
     , of_undefined/1
+    , validate/2
     ]).
 
 
 -spec put(A, fun((A) -> boolean())) ->
     t(A).
 put(X, F) ->
-    case F(X)
-    of  true  -> {some, X}
-    ;   false -> none
-    end.
+    return(X, F).
 
 -spec get(t(A), Default :: A) ->
     A.
@@ -42,6 +44,14 @@ get(none     , Y) -> Y.
 return(X) ->
     {some, X}.
 
+-spec return(A, fun((A) -> boolean())) ->
+    t(A).
+return(X, Condition) ->
+    case Condition(X)
+    of  true  -> {some, X}
+    ;   false -> none
+    end.
+
 -spec map(t(A), fun((A) -> (B))) ->
     t(B).
 map({some, X}, F) -> {some, F(X)};
@@ -71,3 +81,13 @@ of_result({error, _}) -> none.
     t(A).
 of_undefined(undefined) -> none;
 of_undefined(X)         -> {some, X}.
+
+-spec validate(t(A), fun((A) -> boolean())) ->
+    t(A).
+validate(none, _) ->
+    none;
+validate({some, X}=T, F) ->
+    case F(X)
+    of  false -> none
+    ;   true  -> T
+    end.
This page took 0.028982 seconds and 4 git commands to generate.