]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.scl.runtime/scl/Prelude.scl
Allow effects mapFst and mapSnd
[simantics/platform.git] / bundles / org.simantics.scl.runtime / scl / Prelude.scl
index 751294a11bb44ea03df62391d7120c83bf9a1a0c..e92603becb8e4300db875532c2b87ba090b742e8 100644 (file)
@@ -963,6 +963,9 @@ A class of monads with zero element satisfying
 """ 
 class (Monad m) => MonadZero m where
     mzero :: m a
+    mfilter :: (a -> Boolean) -> m a -> m a
+    
+    mfilter p m = m >>= (\x -> if p x then return x else mzero)
 
 "Injects a boolean test to a type beloning to `MonadZero`."
 guard :: MonadZero m => Boolean -> m ()
@@ -1105,7 +1108,21 @@ instance MonadE (Either a) where
 
 instance MonadE [] where
     bindE l f = concatMap f l
+
+/// MZeroE ///
+
+class (MonadE m, MonadZero m) => MonadZeroE m where
+    filter :: (a -> <e> Boolean) -> m a -> <e> m a
+    
+    filter p m = m `bindE` (\x -> if p x then return x else mzero)   
     
+instance MonadZeroE [] where
+    filter = filterList
+    
+instance MonadZeroE Maybe where
+    filter p (Just x) | not (p x) = Nothing
+    filter _ m = m 
+
 /// Category ///
 
 "Identity function."
@@ -1290,8 +1307,13 @@ fromMaybe :: a -> Maybe a -> a
 fromMaybe default maybeValue = match maybeValue with
     Just v -> v
     _ -> default
-    
-    
+
+"`maybe def f v` returns `def` if `v=Nothing` and `f x` if `v=Just x`."
+@inline
+maybe :: b -> (a -> <e> b) -> Maybe a -> <e> b
+maybe n _ Nothing  = n
+maybe _ f (Just x) = f x
+
 """
 Provides a default value if the first parameter is Nothing.
 The default value is evaluated only if needed. The function
@@ -1499,11 +1521,11 @@ snd :: (a,b) -> b
 snd (x,y) = y
 
 @inline
-mapFst :: (a -> b) -> (a,c) -> (b,c)
+mapFst :: (a -> <e> b) -> (a,c) -> <e> (b,c)
 mapFst f (x,y) = (f x, y)
 
 @inline
-mapSnd :: (a -> b) -> (c,a) -> (c,b)
+mapSnd :: (a -> <e> b) -> (c,a) -> <e> (c,b)
 mapSnd f (x,y) = (x, f y)
 
 instance (Ord a, Ord b) => Ord (a, b) where
@@ -1836,10 +1858,10 @@ foldr1 f l = loop (l!(len-1)) (len-2)
 `filter pred lst` returns those elements of `lst` that the predicate `pred` accepts. For example
 
     filter (> 3) [1, 2, 3, 4, 5, 6] = [4, 5, 6]
-""" 
+"""
 @inline
-filter :: (a -> <e> Boolean) -> [a] -> <e> [a]
-filter p l = build (\empty cons -> foldl (\cur x -> if p x then cons cur x else cur) empty l)
+filterList :: (a -> <e> Boolean) -> [a] -> <e> [a]
+filterList p l = build (\empty cons -> foldl (\cur x -> if p x then cons cur x else cur) empty l)
 
 """
 Takes those elements of the input list that match `(Just x)` and adds the contents to the resulting list. For example,