How to Understand functor and monad

Source: Internet
Author: User
1. Compound function Operators
Prelude> :t (.)(.) :: (b -> c) -> (a -> b) -> a -> cPrelude> (.) ((+) 5) ((*) 2) 413

  

Therefore, the function of the (.) operator is to pass 4 as a parameter to (*) 2) function, and then pass the result to (+) 5) function.

This is the compound function in mathematics:

F (x) = 2x

G (x) = x + 5

G (f (x) = g (2x) = (2x) + 5 = 2x + 5

G (f (4) = 2*4 + 5 = 13

 

2. functor
194 {- | The ‘Functor‘ class is used for types that can be mapped over.195 Instances of ‘Functor‘ should satisfy the following laws:196 197 > fmap id  ==  id198 > fmap (f . g)  ==  fmap f . fmap g199 200 The instances of ‘Functor‘ for lists, ‘Data.Maybe.Maybe‘ and ‘System.IO.IO‘201 satisfy these laws.202 -}203 204 class  Functor f  where205     fmap        :: (a -> b) -> f a -> f b206 207     -- | Replace all locations in the input with the same value.208     -- The default definition is @‘fmap‘ . ‘const‘@, but this may be209     -- overridden with a more efficient version.210     (<$)        :: a -> f b -> f a211     (<$)        =  fmap . const

ID is a function.

Prelude> :t idid :: a -> aPrelude> id "Daniel""Daniel"Prelude> id 11Prelude> id TrueTruePrelude> id Just "Happy"Just "Happy"Prelude> id NothingNothing

Functor is a kind of typeclass used to define a set of permitted operations. Here it is fmap, and it puts forward the conditions to be met for fmap:

  • Fmap id = ID
  • Fmap (F. G) = fmap F. fmap g

Can be regarded as "exchange law" and "Allocation Law"

Prelude Data.Char> fmap isDigit ((++) [‘0‘..‘9‘] [‘a‘..‘f‘])[True,True,True,True,True,True,True,True,True,True,False,False,False,False,False,False]

  

Prelude Data.Char> :t isDigitisDigit :: Char -> Bool

  

Fmap not only can operate the list (in this case, it works the same as the map function of the list), but also can operate on maybe

Prelude Data.Char> fmap isDigit (Just ‘a‘)Just FalsePrelude Data.Char> fmap isDigit (Nothing)NothingPrelude Data.Char> fmap isDigit (Just ‘1‘)Just True

  

3. manod

Like functor, monad is also a set of operations that can be performed to define types.

Prelude Data.Char> :i Monadclass Monad m where  (>>=) :: m a -> (a -> m b) -> m b  (>>) :: m a -> m b -> m b  return :: a -> m a  fail :: String -> m a  -- Defined in `GHC.Base‘instance Monad Maybe -- Defined in `Data.Maybe‘instance Monad (Either e) -- Defined in `Data.Either‘instance Monad [] -- Defined in `GHC.Base‘instance Monad IO -- Defined in `GHC.Base‘instance Monad ((->) r) -- Defined in `GHC.Base‘

  

As you can see, these operations include (>>=) (>>>) return fail

(>>) Execute two operations, but discard the result of the previous operation.

Prelude Data.Char> :t (>>)(>>) :: Monad m => m a -> m b -> m bPrelude Data.Char> (>>) "Daniel" "King""KingKingKingKingKingKing"

  

212 213 {- | The ‘Monad‘ class defines the basic operations over a /monad/,214 a concept from a branch of mathematics known as /category theory/.215 From the perspective of a Haskell programmer, however, it is best to216 think of a monad as an /abstract datatype/ of actions.217 Haskell‘s @[email protected] expressions provide a convenient syntax for writing218 monadic expressions.219 220 Minimal complete definition: ‘>>=‘ and ‘return‘.221 222 Instances of ‘Monad‘ should satisfy the following laws:223 224 > return a >>= k  ==  k a225 > m >>= return  ==  m226 > m >>= (\x -> k x >>= h)  ==  (m >>= k) >>= h227 228 Instances of both ‘Monad‘ and ‘Functor‘ should additionally satisfy the law:229 230 > fmap f xs  ==  xs >>= return . f231 232 The instances of ‘Monad‘ for lists, ‘Data.Maybe.Maybe‘ and ‘System.IO.IO‘233 defined in the "Prelude" satisfy these laws.234 -}235 236 class  Monad m  where237     -- | Sequentially compose two actions, passing any value produced238     -- by the first as an argument to the second.239     (>>=)       :: forall a b. m a -> (a -> m b) -> m b240     -- | Sequentially compose two actions, discarding any value produced241     -- by the first, like sequencing operators (such as the semicolon)242     -- in imperative languages.243     (>>)        :: forall a b. m a -> m b -> m b244         -- Explicit for-alls so that we know what order to245         -- give type arguments when desugaring246 247     -- | Inject a value into the monadic type.248     return      :: a -> m a249     -- | Fail with a message.  This operation is not part of the250     -- mathematical definition of a monad, but is invoked on pattern-match251     -- failure in a @[email protected] expression.252     fail        :: String -> m a253 254     {-# INLINE (>>) #-}255     m >> k      = m >>= \_ -> k256     fail s      = error s

  

(>>=) Is to pass the result of the previous operation as a parameter to the next operation, but note that the normal conversion from A to B needs to be performed using return (a-> B) (A-> MB), that is, (a-> Ma) (a-B) = (a-> MB)

Prelude Data.Char> :t returnreturn :: Monad m => a -> m aPrelude Data.Char> :t (>>=)(>>=) :: Monad m => m a -> (a -> m b) -> m bPrelude Data.Char> (>>=) (return ((++) "Daniel" "King")) ((:) ‘X‘)"XDanielKing"

  

Prelude Data.Char> (>>=) (return ((++) "Daniel" "King")) ((++) "Hello ")"Hello DanielKing"

  

Therefore, (>>=) and return are used in combination, and the effect is very similar to the pipeline operation in UNIX.

Monad is designed to allow pure's Haskell to generate some side effect, or save some state information besides its own values.

For example, the (+ +) "Daniel" "King") result is passed to the subsequent action, which can be used to update the status information.

 

The obvious applications are Io and exception handling.

 

 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.