[Functional Programming] Function modelling -- 3. Reader Monad

Reader Monad

 

Continue with previous post, here we have some helper functions:

const toUpper = s => s.toUpperCase();
const exclaim = s => `${s}!`;

And here is current code we have:

复制代码
const Fn = run => ({
  run,
  map: f => Fn(x => f(run(x))),
  chain: f =>
    Fn(x => console.log("run(x)", run(x), f(run(x))) || f(run(x)).run(x)),
  concat(otherFn) {
    return Fn(x => run(x).concat(otherFn.run(x)));
  }
});
复制代码

 


 

Monad

 

Monad is all about nesting, for example, we have 'Fn' instead a 'Fn':

Fn(x => Fn(y => ...))

Monad job is to flatten it.

 

To implement a Monad interface, we need to implement 'chain' function:

1
2
3
4
5
6
7
8
9
10
11
12
const Fn = run => ({
   run,
   concat(otherFn) {
      return Fn(x => run(x).concat(otherFn.run(x)))
   },
   map(f) {
      return Fn(f => f(run(x)))
   },
   chain(otherM) {
       
   }
})

'chain' function take other Monad as arguement. 

 

The implementation of 'chain' is pretty similar to 'map', the difference in meaning between 'map' & 'chain' is that we want to apply two 'Fn(method)' on the same value.

1
2
3
4
5
6
7
8
9
10
11
12
13
const Fn = run => ({
  run,
  map: f => Fn(
    x => f(run(x))
  ),
  chain: f => Fn(
    x => f(run(x))
          .run(x)
  ),
  concat(otherFn) {
    return Fn(x => run(x).concat(otherFn.run(x)));
  }
});

Taking an example:

Fn(toUpper)
  .chain(upper => Fn(y => exclaim(upper)))
  .run("hi"); // HI!

'run(x)' return value, in the example is the result of 'toUpper' which is 'HI'.

Then 'f(run(x))' return 'Fn' Monad:

Fn (
{ 
  run: [Function],
  map: [Function: map],
  chain: [Function: chain],
  concat: [Function: concat] 
})

Last when we call 'f(run(x)).run(x)', we will get 'HI!', which is running 'exclaim' function over 'HI'.

 

Also .run function unwrap Fn, everytimes we call .run(), we will get its value, instead of Fn().

For 'chain' method:

  chain(f) {
    // f() return another Fn
    // when you call .run(), it unwrapper Fn()
    return Fn((x) => f(run(x)).run(x));
  },

it call two times 'run()' but only add one 'Fn', which means it unwrap one nested 'Fn'.


 

 

Fn.of()

 

We have seen the example: 'Fn(upper)', we don't get used to that... we somehow lift a function 'upper' into a Functor, then data come last when we run ".run('hi')".

We can change that, by passing the data first into 'Fn.of(data)', then we can doing mapping, chainning.

But there is another interesting thing, in the previous example, data: 'hi' is the only input. If now we lift data into Fn.of('hi'), then we run ".run(another_data)", now we have two data input.

Let's see 'Fn.of()' function first:

1
2
3
4
5
6
7
8
9
10
11
const Fn = run => ({
  run,
  map: f => Fn(x => f(run(x))),
  chain: f =>
    Fn(x => console.log("run(x)", run(x), f(run(x))) || f(run(x)).run(x)),
  // run two functions and concat the result
  concat(otherM) {
    return Fn(x => run(x).concat(otherM.run(x)));
  }
});
Fn.of = x => Fn(() => x);

 

Example:

1
2
3
4
Fn.of("hi")
  .map(toUpper)
  .chain(upper => Fn(x => [upper, exclaim(x)]))
  .run("hello"); // [ 'HI', 'hello!' ]

As you can see, now we have two values. We have applied 'toUpper' transform on 'hi', and apply 'exclaim' function on "hello".

 

Example 2:

Fn.of("hi")
  .map(toUpper)
  .chain(upper => Fn(x => [upper, exclaim(x)])) // ["HI", 'hello!']
  .chain(ary => Fn(x => [exclaim(ary[0]), x])) // ["HI!", "hello"]
  .run("hello");

We can keep chaining based on previous chain's result. But this time, we keep 'x' as it is. So now, this is interesting thing, the data we pass with '.run('hello')', always keep the same value every time we try to read it.

You can use it can enviormenet configuration object, anytime you need to read env variable you can get it from 'chain'. This partten is called: "Read Monda".

 

Think about Angular, for example, it is similar to dependency injection. For React, you can use it as Provider / Context.

 


 

Fn.ask()

 

Let's define a convenient function call 'ask'. So instead of using "Fn()" constructor

.chain(upper => Fn(x => [upper, exclaim(x)])

We want to do:

1
2
3
4
5
6
7
8
9
10
11
12
const Fn = run => ({
  run,
  map: f => Fn(x => f(run(x))),
  chain: f =>
    Fn(x => console.log("run(x)", run(x), f(run(x))) || f(run(x)).run(x)),
  // run two functions and concat the result
  concat(otherFn) {
    return Fn(x => run(x).concat(otherFn.run(x)));
  }
});
Fn.of = x => Fn(() => x);
Fn.ask = Fn(x => x);

  

Then we can refactor the previous example:

1
2
3
4
5
Fn.of("hi")
  .map(toUpper)
  .chain(upper => Fn.ask.map(x => [upper, exclaim(x)])) // ["HI", 'hello!']
  .chain(ary => Fn.ask.map(x => [exclaim(ary[0]), x])) // ["HI!", "hello"]
  .run("hello");

  

 

posted @   Zhentiw  阅读(219)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-03-13 [Algorithm] Universal Value Tree Problem
2019-03-13 [HTML5] Using the focus event to improve navigation accessibility (nextElementSibling)
2019-03-13 [Javascript] Coding interview problem: Scheduler functional way
2018-03-13 [HTML 5] Atomic Relevant Busy
2018-03-13 [HTML 5] aria-live
2018-03-13 [Node.js] Proxy Requests for Local and Remote Service Parity
2018-03-13 [Node.js] Manage Configuration Values with Environment Variables
点击右上角即可分享
微信分享提示