monet / monet.js

monet.js - Monadic types library for JavaScript
https://monet.github.io/monet.js/
MIT License
1.6k stars 114 forks source link

Understanding the reader monad #160

Open ghost opened 6 years ago

ghost commented 6 years ago

After reading the docs, I was still trying to understand the purpose of Reader monad.

import { Reader } from 'monet'

interface Config {
  greeting: string
  surround: string
}

function greetName(name: string): Reader<Config, string> {
  return Reader(config => `${config.greeting} ${name}`)
}

function surround(input: string): Reader<Config, string> {
  return Reader(config => `${config.surround}${input}${config.surround}`)
}

function render(name: string) {
  return greetName(name).flatMap(surround)
}

console.log(render('Tom').run({ greeting: 'Hello', surround: '~' }))

I understand the render function doesn't have to make reference to the config, but it still feels like additional boilerplate over currying. Is there a better use of the reader monad?

ulfryk commented 5 years ago

@khoomeister one of basic examples is communication with db - you can create a bunch of platform agnostic operations on db and then pass proper driver when calling run.

ayoung4 commented 5 years ago

check out this so question https://stackoverflow.com/questions/54148553/approach-to-thread-resources-like-connections-in-functional-programming/56998664?noredirect=1#comment100545963_56998664