zoukankan      html  css  js  c++  java
  • [Functional Programming] Monad

    Before we introduce what is Monad, first let's recap what is a pointed functor:

    A pointed functor is a Functor with .of() method

    Why pointed Functor is imporant? here

    OK, now, let's continue to see some code:

    const mmo = Maybe.of(Maybe.of('nunchucks'));
    // Maybe(Maybe('nunchucks'))

    We don't really want nested Functor, it is hard for us to work with, we need to remember how deep is the nested Functor.

    To solve the problem we can have a new method, call '.join()'.

    mmo.join();
    // Maybe('nunchucks')

    What '.join()' does is just simply reduce one level Functor.

    So how does implememation of 'join()' looks like?

    Maybe.prototype.join = function join() {
      return this.isNothing() ? Maybe.of(null) : this.$value;
    };

    As you can see, we just return 'this.$value', instead of put the value into Maybe again.

    With those in mind, let's define what is Monad!

    Monads are pointed functors that can flatten

    Let's see a example, how to use join:

    // join :: Monad m => m (m a) -> m a
    const join = mma => mma.join();
    
    // firstAddressStreet :: User -> Maybe Street
    const firstAddressStreet = compose(
      join,
      map(safeProp('street')),
      join,
      map(safeHead), safeProp('addresses'),
    );
    
    firstAddressStreet({
      addresses: [{ street: { name: 'Mulburry', number: 8402 }, postcode: 'WC2N' }],
    });
    // Maybe({name: 'Mulburry', number: 8402})

    For now, each map opreation which return a nested map, return call 'join' after.

    Let's abstract this into a function called chain.

    // chain :: Monad m => (a -> m b) -> m a -> m b
    const chain = curry((f, m) => m.map(f).join());
    
    // or
    
    // chain :: Monad m => (a -> m b) -> m a -> m b
    const chain = f => compose(join, map(f));

    Now we can rewrite the previous example which .chain():

    // map/join
    const firstAddressStreet = compose(
      join,
      map(safeProp('street')),
      join,
      map(safeHead),
      safeProp('addresses'),
    );
    
    // chain
    const firstAddressStreet = compose(
      chain(safeProp('street')),
      chain(safeHead),
      safeProp('addresses'),
    );

    To get a feelings about chain, we give few more examples:

    // getJSON :: Url -> Params -> Task JSON
    getJSON('/authenticate', { username: 'stale', password: 'crackers' })
      .chain(user => getJSON('/friends', { user_id: user.id }));
    // Task([{name: 'Seimith', id: 14}, {name: 'Ric', id: 39}]);
    
    // querySelector :: Selector -> IO DOM
    querySelector('input.username')
      .chain(({ value: uname }) => querySelector('input.email')
      .chain(({ value: email }) => IO.of(`Welcome ${uname} prepare for spam at ${email}`)));
    // IO('Welcome Olivia prepare for spam at olivia@tremorcontrol.net');
    
    Maybe.of(3)
      .chain(three => Maybe.of(2).map(add(three)));
    // Maybe(5);
    
    Maybe.of(null)
      .chain(safeProp('address'))
      .chain(safeProp('street'));
    // Maybe(null);

    Theory

    The first law we'll look at is associativity, but perhaps not in the way you're used to it.

    // associativity
    compose(join, map(join)) === compose(join, join);
    

    These laws get at the nested nature of monads so associativity focuses on joining the inner or outer types first to achieve the same result. A picture might be more instructive:

    monad associativity law

    The second law is similar:

    // identity for all (M a)
    compose(join, of) === compose(join, map(of)) === id;
    

    It states that, for any monad Mof and join amounts to id. We can also map(of) and attack it from the inside out. We call this "triangle identity" because it makes such a shape when visualized:

    monad identity law

    Now, I've seen these laws, identity and associativity, somewhere before... Hold on, I'm thinking...Yes of course! They are the laws for a category. But that would mean we need a composition function to complete the definition. Behold:

    const mcompose = (f, g) => compose(chain(f), g);
    
    // left identity
    mcompose(M, f) === f;
    
    // right identity
    mcompose(f, M) === f;
    
    // associativity
    mcompose(mcompose(f, g), h) === mcompose(f, mcompose(g, h));

    They are the category laws after all. Monads form a category called the "Kleisli category" where all objects are monads and morphisms are chained functions. I don't mean to taunt you with bits and bobs of category theory without much explanation of how the jigsaw fits together. The intention is to scratch the surface enough to show the relevance and spark some interest while focusing on the practical properties we can use each day.

    More detail

  • 相关阅读:
    URL中传参带有%2F等特殊字符
    js根据对象数组中某一属性值,合并相同项,并对某一属性累加处理
    windows传输文件到linux
    npm 切换源
    linux下安装java
    PowerShell:因为在此系统上禁止运行脚本,解决方法
    wget: 未找到命令
    发货通知单禁止手工新增
    固定提前期
    容差码
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10427945.html
Copyright © 2011-2022 走看看