简体   繁体   English

读者目的Monad

[英]Purpose of Reader Monad

I am having difficulty in understanding the Reader Monad. 我很难理解Reader Monad。 My understanding from all the places I read, is that it allows to share a variable(Read Mode) to different function. 我从所有阅读的地方了解到,它允许将变量(读取模式)共享给其他功能。 Below is the implementation of two functions computation and samething (sorry for bad function names), one with Reader and one without it. 以下是两个函数的计算和相同内容的实现(不好的函数名称很抱歉),一个带有Reader,另一个不带Reader。 I don't get the benefit using Reader. 使用Reader无法获得任何好处。

module Moreunderstanding where
import Control.Monad.Reader


computation :: Reader Int Int

computation = do 
  a <- ask
  b <- asks square
  return (a + b) 


square :: Int -> Int
square x = x ^ 2


samething:: Int -> Int 

samething = do 
  a <- square
  b <- id
  return (a + b)

I am not sure what is that I am missing here. 我不确定在这里想念什么。

These do both do the same thing. 这些都做同样的事情。 In fact, the Reader monad is pretty much the same as the function monad (which you're using in samething ). 事实上,读者单子几乎是相同的功能单子(你使用其中samething )。 It becomes useful because of the MonadReader typeclass (which (->) a has an instance for) and ReaderT , which allow you to stack multiple monad transformers on top of one another. 由于MonadReader类型类(其中(->) a有一个实例)和ReaderT ,它变得很有用,它使您可以将多个monad转换器相互堆叠。

It's also a good statement of intent. 这也是一个很好的意图说明。 It means "I have a read-only value here that will be used in this computation". 这意味着“我这里有一个只读值,将在此计算中使用”。 I'd say that your intuition is pretty accurate though, there isn't much to the Reader monad, it's pretty simple. 我想说您的直觉是相当准确的,但Reader monad并没有太多内容,这很简单。

The Reader monad becomes more useful when you have several arguments that you have to pass around from function to function. 当您必须在函数之间传递多个参数时,Reader monad会变得更加有用。 For example if you're building some API endpoints and you want to pass a configuration object around. 例如,如果您要构建一些API端点,并且想要传递配置对象。 In that case it's much easier to use the Reader monad and keep the inner functions signature clean. 在这种情况下,使用Reader monad并使内部函数签名保持整洁会容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM