Answer the question
In order to leave comments, you need to log in
Why are monads needed?
After reading the article , I realized that a monad is a wrapper over a sequence of methods that allows you to handle errors that occur if one of the methods did not receive data and crashed.
Actually a question - correctly I understood idea?
The second question that was raised in the comments is why not throw an exception instead of returning a half result.
If possible, explain in simple terms.
Answer the question
In order to leave comments, you need to log in
I once was at a lecture on funkts. programming and the lecturer said that if you are asking why you should use monads, then you don't need to use monads, so listen to a smart person (lecturer) and relax :)
Wow, it just won't work. Roughly speaking, this is an alternative to nulls, but not only. They basically summarize a lot of things.
I recommend reading: habrahabr.ru/post/151703 + run through the comments. There they give good links, and they express good thoughts.
What you described is a special case.
Here are some special cases (Haskell vs pseudocode).
Note that in Haskell the code is linear
. What is done by monads is often inlined in other languages. The convenience of a non-built-in solution is that there are quite a few functions that work with any monads (mapM, filterM, ...), which can be problematic to apply to things built into the language.
1.nullable
do
x <- foo
y <- bar x
return $ baz y
x = foo();
if (x) {
y = bar();
if (y) {
return baz(y); } }
do
x <- lines str
y <- words x
return $ length y
for (x in lines(str))
for (y in words(x))
yield y.length();
do
h1 <- ContT $ withFile "1.txt" ReadMode
h2 <- ContT $ withFile "2.txt" WriteMode
liftIO $ ...use handles...
using (h1 = File.Open("1.txt", File.Mode.Read)) {
using (h2 = File.Open("2.txt", File.Mode.Write)) {
...use files... }}
do
-- сразу список файлов открываем
hs <- mapM (\name -> ContT (withFile name ReadMode))
["1.txt", "2.txt", "3.txt", "4.txt"]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question