What is the difference between a monad and a closure?

社会主义新天地 提交于 2020-01-01 02:43:29

问题


i am kinda confused reading the definition between the two. Can they actually intersect in terms of definition? or am i completely lost? Thanks.


回答1:


Closures, as the word tends to be used, are just functions (or blocks of code, if you like) that you can treat like a piece of data and pass to other functions, etc. (the "closed" bit is that wherever you eventually call it, it behaves just as it would if you called it where it was originally defined). A monad is (roughly) more like a context in which functions can be chained together sequentially, and controls how data is passed from one function to the next.




回答2:


They're quite different, although monads will often use closures to capture logic.

Personally I would try to get solid on the definition of closures (essentially a piece of logic which also captures its environment, i.e. local variables etc) before worrying about monads. They can come later :)

There are various questions about closures on Stack Overflow - the best one to help you will depend on what platform you're working on. For instance, there's:

  • What are closures in .NET?
  • Function pointers, closures and lambda

Personally I'm only just beginning to "grok" monads (thanks to the book I'm helping out on). One day I'll get round to writing an article about them, when I feel I understand them well enough :)




回答3:


A "closure" is an object comprising 1) a function, and 2) the values of its free variables where it's constructed.

A "monad" is a class of functions that can be composed in a certain way, i.e. by using associated bind and return higher-order function operators, to produce other functions.




回答4:


I think monads are a little more complicated than closures because closures are just blocks of code that remember something from the point of their definitions and monads are a construct for "twisting" the usual function composition operation.



来源:https://stackoverflow.com/questions/790719/what-is-the-difference-between-a-monad-and-a-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!