Haskell Maybe Type Class
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
instance Monad Maybe where
return x = Just x
Just x >>= f = f x
↑
+ → (a -> m b)
+ → f x ⇒ (a -> m b) a ⇒ m b
Nothing >>= _ = Nothing
How to use Maybe in function
Maybe is useful for pattern matching
f = \x -> x + 1
maybe'::b -> (a -> b) -> Maybe a -> b
maybe' n f Nothing = n
maybe' n f (Just a) = f a
-- or use case of
maybe'::b -> (a -> b) -> Maybe a -> b
maybe' n f x = case x of
Nothing -> n
Just a -> f a
maybe' 0 f Nothing = 0
maybe' 0 f (Just 3) = 4
Maybe a or Maybe
data Maybe a = Nothing | Just a
-- yep, there is somthing relative to polynomial!
data Tree a = Empty | Node a (Tree a) (Tree a)
insert::Tree a -> Tree a -> Tree a
insert Empty (Node a l r) = (Node a l r)
insert _ _ = Empty
class Node< T>{
T data;
Node left;
Node right;
}
template< class T>
class Node{
T data;
Node left;
Node right;
};
enum Color{
red,
green,
blue
};
Color color = red;
switch(color){
case red: cout<<"red"; break;
case green: cout<<"green"; break;
case blue: cout<<"blue"; break;
}