B
B
beduin012015-07-09 10:29:39
Programming
beduin01, 2015-07-09 10:29:39

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

3 answer(s)
V
Vov Vov, 2015-07-09
@balamut108

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 :)

S
Sergey, 2015-07-09
Protko @Fesor

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.

A
Alexander Ruchkin, 2015-07-09
@VoidEx

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

instead of
x = foo();
if (x) {
    y = bar();
    if (y) {
        return baz(y); } }

2. lists
do
    x <- lines str
    y <- words x
    return $ length y

instead of
for (x in lines(str))
    for (y in words(x))
        yield y.length();

3. continue
do
    h1 <- ContT $ withFile "1.txt" ReadMode
    h2 <- ContT $ withFile "2.txt" WriteMode
    liftIO $ ...use handles...

instead of
using (h1 = File.Open("1.txt", File.Mode.Read)) {
    using (h2 = File.Open("2.txt", File.Mode.Write)) {
        ...use files... }}

And you can, for example, like this:
do
    -- сразу список файлов открываем
    hs <- mapM (\name -> ContT (withFile name ReadMode))
        ["1.txt", "2.txt", "3.txt", "4.txt"]

And how to make so with using'ami?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question