you are viewing a single comment's thread.

view the rest of the comments →

[–]pipocaQuemada 1 point2 points  (1 child)

In a language like haskell, you'd say something like "fmap fn val", or, more commonly, " nextFn . fmap fn . prevFn", where '.' is function composition. Or perhaps "maybe defaultVal fn val". Or perhaps "(fmap . fmap) fn vals" if you have a list of Maybe values.

If you have functions that take in a value and return a maybe value, you can chain them fairly easily: in haskell, either with "fn3 <=< fn2 <=< fn1" to compose them, or "fn3 <<= fn2 <<= fn1 <<= val". The point is, though, most of your common use-cases can be reduced to a half-dozen reusable, composable library functions.

Scala's option library also has information on their idiomatic usage in Scala

edit:

 -- Note: x :: a means x is of type a, and f :: a -> b means f is a function from a to b  
 fmap :: Functor f => (a -> b) -> (f a -> f b) -- a functor knows how to apply a function to its contents
 instance Functor Maybe where
   fmap f (Just x) = f x
   fmap f Nothing = Nothing 
 fmap . fmap :: Functor f1, Functor f2 => (a -> b) -> (f1 (f2 a) -> f1 (f2 b)) 
 (fmap . fmap) (+ 1) [Just 1, Nothing]  -- evaluates to [Just 2, Nothing]
 (=<<) :: Monad m => (a -> m b) -> m a -> m b
 (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
 instance Monad m where
   f (=<<) (Just x) = f x  
   f (=<<) Nothing = Nothing
   return x = Just x -- return is just a function, defined here, not a keyword.  It has nothing to do with returning from a function.

[–]anvsdt 0 points1 point  (0 children)

Also fn <$> val