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

  • 相关阅读:
    很简单的企业管理器我写程序的方式,几个自定义控件。
    当OO遇到了持久化?!
    [自定义服务器控件] 第一步:文本框。
    [面向过程——老酒换新瓶] (一)开篇:是面向过程还是面向对象?
    个人理财小助手 —— 设计思路、功能说明
    《Head First 设计模式》 终于出中文版了。
    其实添加数据也可以这样简单——表单的第一步抽象(针对数据访问层)《怪怪设计论: 抽象无处不在 》有感
    基类、接口的应用——表单控件:一次添加、修改一条记录,一次修改多条记录。(上)
    其实添加数据也可以这样简单——表单的第三步抽象(针对UI及后置代码)
    转帖:客户端表单通用验证checkForm(oForm) js版
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10427945.html
Copyright © 2011-2022 走看看