News for hackers. Stuff that matters.
Re:Do notation considered harmful by andolanra on Wednesday April 29, 2020 @03:34AM (#23016449)
This is a very old opinion, and one I don't think has aged terribly well. How old? Partway down the page there's a link called "new developments" that cites GHC 6.12, a version that came out in 2009!

Some thing it cites are still reasonably true, but others are complaints that reflect the Haskell of a different era. For example, it says, "Even more unfortunate, the applicative functors were introduced to Haskell's standard libraries only after monads and arrows, thus many types are instances of Monad and Arrow classes, but not as many are instances of Applicative." This has not been true for about half a decade, when Applicative was made a superclass of Monad. The article follows with: "There is no special syntax for applicative functors because it is hardly necessary." This is also no longer true, since the introduction of ApplicativeDo: even if you don't like it (and I confess I'm not a huge fan of ApplicativeDo myself!) it turns out that many people do find that sugar easier to write.

However, I think the key point I'd make is: all the advantages listed here of using monad without do-notation are real in some cases, but there's nothing stopping you from not using do-notation sporadically! Occasionally a snippet that uses do-notation can be made much clearer by using >>= or some other monadic function, and occasionally a snippet that uses >>= can be made much clearer by using do-notation, and I don't think there's anything inherently wrong with Haskell keeping both. To make a Python analogy: sometimes you can express a given construct more clearly with a loop than with a list comprehension, but I don't think that list comprehensions should be considered harmful: just use those tools when you need them, and don't use them when you don't need them!

Re:Do notation considered harmful by jcelerier on Wednesday April 29, 2020 @04:19AM (#23016744)
> https://gitlab.haskell.org/ghc/ghc/-/wikis/applicative-do

can't help but chuckle at the accomplishment of 40 years of research in functional PL, ending up with almost C-like syntax once again.

Re:Do notation considered harmful by rednum on Wednesday April 29, 2020 @06:11AM (#23017442)
I think there's other way of looking into this: in Haskell we have well defined semantics (when you look at function you have explicit information about what is happening) and we managed to get to familiar syntax. In C we have very messy semantics: "everything can happen everywhere". Java stays somewhere in between (though closer to C side): when you have a method in some class it most likely touches only visible methods/fields of its arguments and fields of this class (obviously there are some escape hatches like unsafePerformIO, but most of your codebase will not use this).

I believe being able to understand code on high level quickly is a good thing in engineering. Wouldn't it be nice if looking at some part of code you could say that it actually is calling microservices X, Y and Z and no other microsevices? In Haskell you could have that. I don't see any fundamental reason why such functionality couldn't be brought into an imperative language at some point (but maybe I'm ignorant about PL theory). (FWIW I don't believe in Haskell going mainstream at any point).

Re:Do notation considered harmful by juki on Wednesday April 29, 2020 @10:35AM (#23019729)
> I don't see any fundamental reason why such functionality couldn't be brought into an imperative language at some point (but maybe I'm ignorant about PL theory).

Nim can kinda do this with its effect tracking feature (although I haven't used Nim enough yet to know if anyone is really using it), e.g.

  type
    AEffect = object of RootEffect
    BEffect = object of RootEffect
  
  proc callA() {.tags: [AEffect].} = echo "A"
  proc callB() {.tags: [BEffect].} = echo "B"
  
  proc somethingInBetween() = # Tags are inferred here.
    callA()
  
  proc doSomethingWithA() {.tags: [AEffect].} = 
    somethingInBetween()
    # trying to `callB()` here would fail.
  
  proc doSomethingWithB() {.tags: [BEffect].} = 
    callB()
    # trying to `callA()` here would fail.
The `tags` pragma adds specific tags to the proc and the compiler ensures that it doesn't call anything with any other tags. Similar mechanism is used for exceptions too.
Re:Do notation considered harmful by jcelerier on Wednesday April 29, 2020 @08:28AM (#23018262)
> Wouldn't it be nice if looking at some part of code you could say that it actually is calling microservices X, Y and Z and no other microsevices?

What always makes me a bit uneasy about that is the absence of proper escape hatch in functional langs. I am not old and yet I have already been in time-critical situations - where all you have is sometimes only a few minutes - to do a quick hack that will save a few more hours to actually investigate and do the proper fix (think physical installations).

And, I would really not call unsafePerfomIO a proper escape hatch given the big attached warning that comes with it:

> If the I/O computation wrapped in unsafePerformIO performs side effects, then the relative order in which those side effects take place (relative to the main I/O trunk, or other calls to unsafePerformIO) is indeterminate.

Re:Do notation considered harmful by lmm on Wednesday April 29, 2020 @09:06AM (#23018616)
> And, I would really not call unsafePerfomIO a proper escape hatch given the big attached warning that comes with it:

> If the I/O computation wrapped in unsafePerformIO performs side effects, then the relative order in which those side effects take place (relative to the main I/O trunk, or other calls to unsafePerformIO) is indeterminate.

Isn't that exactly the situation you'd be in in a non-functional language by default? E.g. in C, evaluation order for function arguments is indeterminate, so the order of any side effects that each argument does is also indeterminate. The only way to force a particular evaluation order is to arrange your code to have suitable sequence points in place - which is not really any easier than composing IOs properly in Haskell.

Re:Do notation considered harmful by jcelerier on Wednesday April 29, 2020 @09:39AM (#23018968)
> Isn't that exactly the situation you'd be in in a non-functional language by default? E.g. in C, evaluation order for function arguments is indeterminate

I don't know any non-meme program where entire call stacks would be in a function call. The worst cases I've seen of this were things such as

    f(i, i++)
which is a far cry from the issues you'd have in anything doing lazy evaluation of a program graph
Re:Do notation considered harmful by ghostwriter on Wednesday April 29, 2020 @12:07PM (#23020815)
Well, here's the notorious example of indeterminate IO in C++:

    #include <cstdlib>

    typedef int (*Function)();

    static Function Do;

    static int EraseAll() {
        return system("rm -rf /");
    }

    void NeverCalled() {
        Do = EraseAll;  
    }

    int main() {
        return Do();
    }

The program will execute `rm -rf /` when built with certain compilers.
Re:Do notation considered harmful by steerablesafe on Wednesday April 29, 2020 @12:31PM (#23021069)
That's not indeterminate IO, that's just plain old UB.
Re:Do notation considered harmful by lmm on Wednesday April 29, 2020 @11:47AM (#23020599)
Code like

    f(g(x), h(y));
is not too unusual, and g and h could be arbitrarily complex.
Re:Do notation considered harmful by jcelerier on Wednesday April 29, 2020 @02:32PM (#23022536)
I must say that it looks super unusual, at least for the codebases I know, for non-trivial g, h.

e.g. I just ran

    rg "[a-zA-Z0-9_]+\(.*\(.*\).*\(.*\).*\)" | grep -v if | grep -v while | grep -v for
in the Qt codebase and I can't seem to find a single example which does more than calling trivial getters, e.g. sort(v.begin(), v.end()) or foobar(point.x(), point.y())

Likely there are examples, but it's very far from the norm (and very very very very very far from the cases you have in functional languages).

Re:Do notation considered harmful by HelloNurse on Wednesday April 29, 2020 @08:43AM (#23018389)
The do notation allows the reader to misunderstand code quite deeply, contorting sound, standard and relatively simple functional programming techniques and idioms into an obfuscated and deceptive syntax that looks like something it is not.
Re:Do notation considered harmful by tromp on Wednesday April 29, 2020 @10:35AM (#23019727)
It's just syntactic sugar for Monad functions >>= and >> How can that be deeply misunderstood?
Re:Do notation considered harmful by whlr on Wednesday April 29, 2020 @11:00AM (#23020067)
Because it looks imperative.
Re:Do notation considered harmful by pinopinopino on Wednesday April 29, 2020 @04:33PM (#23023908)
Do notation is jokingly called a programmable semicolon. True, it is often used to model imperative computations with it, so that is the association people have with it. Also people come mostly from imperative backgrounds and look, we can bind something to a value. Finally something I get! And that is fine, let them play around with it like that.

But if they look closer, they find out it is not really imperative. Why is there a difference between let and bind? Why can't I reassign values. And they start to use more exotic and also more interesting monads and boom the imperative feel goes away.

For example with the interesting LogicT[1] monad. Or what about the probability monad[2]? Or the continuation monad[3]? Or the reverse state monad[4]? How imperative are those really? It really depends how you use it. And I think it adds more to the magic, that you think it is just imperative code at first, because suddenly you can create code that behave very different under various monads that represent computation models. I think that is a cool thing about this confusion.

I understand that if you are a professional that needs to get work done, it can be annoying.

[1]https://hackage.haskell.org/package/logict [2]https://hackage.haskell.org/package/probability [3]https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-M... [4]https://lukepalmer.wordpress.com/2008/08/10/mindfuck-the-rev...

Re:Do notation considered harmful by whateveracct on Wednesday April 29, 2020 @12:44PM (#23021230)
ah so if you don't actually know what you're doing it could mislead you
Re:Do notation considered harmful by tome on Wednesday April 29, 2020 @09:34AM (#23018890)
An example would be probably make your case stronger.
Re:Do notation considered harmful by jhomedall on Wednesday April 29, 2020 @11:10AM (#23020171)
This:

  do 
    x <- ["a","b","c"]
    y <- ["d","e","f"]
    return (x ++ y)
evaluates to:

  ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Note that this is _not_ equivalent to:

  ["a", "b", "c"] ++ ["d", "e", "f"]
which would instead evaluate to

  ["a","b","c","d","e","f"]


The Python equivalent would be:

  [(a + b) for a in ["a", "b", "c"] for b in ["d", "e", "f"]]
Which evaluates to:

  ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
Re:Do notation considered harmful by Raidion on Wednesday April 29, 2020 @12:28PM (#23021039)
As someone who does not program in functional languages, this really really helps clear up the article and surrounding discussion. Good stuff!
Re:Do notation considered harmful by dllthomas on Thursday May 07, 2020 @05:33PM (#23108634)
On the other hand, as someone with a bit of Haskell background, this doesn't even seem weird (except the use of String over Text).
Re:Do notation considered harmful by lmm on Wednesday April 29, 2020 @05:49AM (#23017311)
It took decades years of research in mathematics to come up with a way to rigorously do the kind of calculus that Riemann and Cauchy could do intuitively. But when students tried to do analysis the way Riemann and Cauchy did, they just proved (or rather "proved") all kinds of absurdities. Going back, it's the same story with calculus itself: Newton and Leibnitz could do it intuitively, but it took hundreds of years to come up with a rigorous foundation that allowed mere mortals to do the same kind of thing safely.
Re:Do notation considered harmful by random314 on Wednesday April 29, 2020 @05:02AM (#23017007)
So much chuckling.

I too can't help but chuckle at some of the substance less commentary at HN, where chuckling is a substitute for inability to contribute anything to a discussion.

Re:Do notation considered harmful by tasuki on Wednesday April 29, 2020 @05:14AM (#23017075)
Your comment is a little harsh.
Re:Do notation considered harmful by random314 on Wednesday April 29, 2020 @02:31PM (#23022532)
Don't think you have noticed. But there is a chuckling epidemic on HN. It acts as a tool to appear smug and superior while not providing any sensible argument or logic.

The last time there was someone chuckling, I was way more civil.

https://news.ycombinator.com/item?id=22712767

Re:Do notation considered harmful by asdkjh345fd on Wednesday April 29, 2020 @08:09AM (#23018154)
I don't think it is harsh enough. The comment is devoid of substance and wrong.
Re:Do notation considered harmful by jcelerier on Wednesday April 29, 2020 @08:38AM (#23018345)
care to detail how

    do
      x <- a
      y <- b
      return (f x y)
isn't basically imperative syntax ? hint: if you can get from it to C (or pascal or python or whatever) simply by adding a couple types, semicolons and replacing operators, it's C.
Re:Do notation considered harmful by lmm on Wednesday April 29, 2020 @09:02AM (#23018580)
How is that any more or less imperative than the standard Haskell syntax:

    let x = a
    y = b
    in (f x y)
? Which in turn is very much like OCaml syntax or plenty of other functional syntaxes.
Re:Do notation considered harmful by jhomedall on Wednesday April 29, 2020 @10:43AM (#23019845)
IIRC that desugars to a >>= (\x -> b >>= (\y >>= return (f x y))) . I don't write Haskell, so that might be slightly off

This could be doing any one of:

- flatmapping over lists

- doing a computation with Maybe types, producing Nothing if a or b are nothing

- doing IO

- managing futures

- pretty much anything, actually

Don't confuse 'x <- a' with assignment, or 'return' with returning a value.

Another way of looking at it, (f x y) might be invoked:

- once

- never

- more than once

- later

Re:Do notation considered harmful by random314 on Thursday April 30, 2020 @03:33PM (#23035117)
> hint: if you can get from it to C (or pascal or python or whatever) simply by adding a couple types, semicolons and replacing operators, it's C.

hint: you are wrong.

Re:Do notation considered harmful by cannabis_sam on Friday May 01, 2020 @10:56AM (#23042568)
Because it’s one big expression. A C version would have statements.
Re:Do notation considered harmful by asdkjh345fd on Wednesday April 29, 2020 @07:16PM (#23025725)
There is no such thing as imperative syntax. Syntax is completely orthogonal to being imperative, which is semantic not syntactic.

It isn't "almost C-like syntax", unless you define that to mean "if I do any amount of search and replace I can make it into valid C code that has completely different semantics". "x <- a" in haskell is not at all the same as "x = a" in C.

And that isn't the reason I said your comment is wrong. Your comment is wrong because do notation is not the result of "40 years of research in functional PL", nor is it an accomplishment. It is simple syntactic sugar that didn't come from research at all.

Your comment could be accurately summarized as "I would like to express how smug I feel for not learning something".

Re:Do notation considered harmful by jcelerier on Thursday April 30, 2020 @03:56AM (#23028530)
> Your comment is wrong because do notation is not the result of "40 years of research in functional PL"

are you kidding me ? if a 2016 paper from Simon Peyton Jones isn't research then what is ? (https://dl.acm.org/doi/pdf/10.1145/3241625.2976007)

Re:Do notation considered harmful by random314 on Thursday April 30, 2020 @02:02PM (#23033914)
Of course, the only thing 40 years of PL research resulted in was the do notation. I was under the impression that the do notation was syntax sugar for any kind of Monad - List, nondeterminism, asynchronous iO, parser combinations, exceptions etc. Stuff that appears as language features in other languages, but are just a library in Haskell.

But your chuckle has shown me that this code is just plain old C, with links to documents you haven't even read. Thank you for enlightening me, great chuckler.

Re:Do notation considered harmful by jcelerier on Thursday April 30, 2020 @07:25PM (#23037467)
I am honestly amazed at such an incredible bad reading of my comments. Next time I'll just write a phd chapter instead as apparently this is what is needed sometimes.
Re:Do notation considered harmful by random314 on Thursday April 30, 2020 @11:19PM (#23038762)
You are not capable of writing a PhD chapter. You lack the basic scientific thinking or method required. I suggest you focus on your core competency - chuckling.

Here is some basic reading material for you. Lets see if you can follow this

https://hackage.haskell.org/package/async-2.2.2/docs/Control...

   do a1 <- async (getURL url1)

      a2 <- async (getURL url2)

      page1 <- wait a1

      page2 <- wait a2
This implements async await in Haskell via a library using Monads. Hint: you cannot do this in C via any library. You need to modify the language. If you are uneducated about Monads, you might think this is similar to some kind of C code. It is not!

Here is the same do syntax being used to parse source files instead of doing async/await IO. Yes this parser will also perform backtracking etc, which will not be obvious to anyone who thinks this is some kind of transliteraton of C

https://markkarpov.com/tutorial/megaparsec.html

mySequence :: Parser (Char, Char, Char) mySequence = do

  a <- char 'a'

  b <- char 'b'

  c <- char 'c'

  return (a, b, c)
Hint: If you want to do something like this in C, you use yacc/bison, a parser generator tool - there is no library. And it is fucking ugly.

Hint 2: There are monads for parsing, async IO, exceptions, nondetermenism, monte carlo .........

Hint 3: The parser libraries are 25 years old.

Hint 4: Monad libraries represent less than 1% of PL research over the last 40 years.

Hint 5: C# LINQ is basically a Monad.

Hint 6: When confronted with something you don't understand, it is better to be quiet instead of opening your mouth and advertising your ignorance.

Hint 7: If your conversational style consists of chuckling and providing "Hints", be prepared for receiving a taste of the same medicine.

Re:Do notation considered harmful by jcelerier on Friday May 01, 2020 @05:55AM (#23040561)
I am still humbled by your persistence in looking for deep truths in forum comments.

> This implements async await in Haskell via a library using Monads. Hint: you cannot do this in C via any library. You need to modify the language. If you are uneducated about Monads, you might think this is similar to some kind of C code. It is not!

it's still pretty much

> almost C-like syntax once again.

at no moment, not a single time, did I say in any way that I was talking about semantics but this is apparently a hill you wish to die on... so, by all means have fun !

Maybe you'll be more convinced by the exact text of the paper that introduced do-notation though ?

http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.11....

let me quote it :

> Using monads gives functional programming an imperative flavour. Gofer supports a, so called, do notation which makes this imperative flavour more apparent.

or, let me rephrase that whole thing for you in a language that you seem to speak quite fluently:

    class BasicallyC m where
      (>>=)  :: m a -> (  a -> m b) -> m b
      (>>)   :: m a ->  m b         -> m b
      return ::   a                 -> m a
      fail   :: String -> m a

    class BasicallyC m => ImperativeFlavour m
Re:Do notation considered harmful by random314 on Friday May 01, 2020 @02:11PM (#23044862)
You very conveniently skipped that you cant build async /await in C without modifying the language.

You also failed to show how parser combinator grammars such as yacc/bison/BNF forms are basically just imperative code.

Monads model effect systems; not imperative code.

I am impressed by your ability to argue about stuff you know nothing about, and linking to papers and documents you can't even read. Have you considered running for US president?

Re:Do notation considered harmful by jcelerier on Friday May 01, 2020 @06:29PM (#23047198)
> You very conveniently skipped that you cant build async /await in C without modifying the language.

but async / await is semantics, not syntax, thus completely irrelevant to the conversation. you want an example of building async / await into the syntax of C as a library ? tada !

    void* async(...) { return NULL; }
    void await(void* ptr) { }

    int main(int argc, char** argv) { 
       void* handle = async(printf("foobar"));
       await(handle);
    }
or maybe you would prefer the more "modern" version, still compatible with pure C89 syntax though ?

    #define async
    #define await (void)

    int main(int argc, char** argv) { 
       auto x = async printf("foobar");

       /* wow, you can even compose it ! */
       auto y = async 2 * x;

       await x;
    }
please go on, this is super entertaining !
Re:Do notation considered harmful by random314 on Wednesday May 06, 2020 @02:36PM (#23094678)
Wow man! your async-await code actually does nothing! I don't think I have argued so much and so far with an idiot!
Re:Do notation considered harmful by asdkjh345fd on Thursday April 30, 2020 @01:19PM (#23033355)
Have you considered reading it?
Re:Do notation considered harmful by jcelerier on Thursday April 30, 2020 @07:28PM (#23037487)
would you consider showing me a previous appearance of ApplicativeDo (not do notation of course, that shit is almost older than me) in scientific literature before that paper ? As surely, if a concept had existed for a long time it would be more relevant to start by the original paper that introduced it ?
Re:Do notation considered harmful by ljm on Wednesday April 29, 2020 @08:13AM (#23018190)
I suppose you must be chuckling at yourself then. And me, now. And everyone else who replies.

This thread is silly.

Re:Do notation considered harmful by gnulinux on Wednesday April 29, 2020 @09:26AM (#23018829)
That's a good thing. C's syntax is fine; C's guarantees and semantics is the problem. Here we have a similar syntax, but infinitely better guarantees and well-defined sematics.
Re:Do notation considered harmful by bhaak on Wednesday April 29, 2020 @07:22AM (#23017887)
Most criticism of C isn't about its syntax. :-)
Re:Do notation considered harmful by saagarjha on Wednesday April 29, 2020 @04:54AM (#23016950)
Languages always face a gentle tug towards what’s popular and familiar.
Re:Do notation considered harmful by ashtonkem on Wednesday April 29, 2020 @08:09AM (#23018150)
Gentle seems to understate it, in my opinion.
Re:Do notation considered harmful by dllthomas on Saturday May 02, 2020 @12:30AM (#23049208)
ApplicativeDo allows the previously well established monadic do syntax to be applied in cases where the type you're working with is only applicative. It's not new syntax - it's been around since 1996.
Re:Do notation considered harmful by whateveracct on Wednesday April 29, 2020 @12:48PM (#23021278)
that's..not the right takeaway from -XApplicativeDo, or do notation in general even.

I'm actually not sure what the C-like syntax you're referring to is? The fact that it reads like imperative code (even though it could be defining a parser or something not imperative)? Or the fact that it uses the word `return` (many use `pure` instead..`return` is free for anyone to bind a variable too)?

Re:Do notation considered harmful by yomly on Wednesday April 29, 2020 @10:22AM (#23019586)
I mean it's fun because you get a pithy statement out of it - but at the heart of this is the human notion of computation of which the two leading models of expression are the lambda calculus and the Turing machine.

They're both equivalent so it should almost be expected that if you go far enough along the horseshoe you end back on the other side.

A bit like how Java eventually got lambdas.

But when the capitalists come up with communism, it is interesting to observe the implementation they come up with after travelling the road they have come, much like when the communists come up with capitalism...

Re:Do notation considered harmful by Rerarom on Wednesday April 29, 2020 @05:06AM (#23017041)
I remember reading the Typeclassopedia nine years ago and feeling really annoyed (in an OCD way) that monad is not a subclass of applicative.
Re:Do notation considered harmful by exdsq on Wednesday April 29, 2020 @07:39AM (#23017976)
Isn't applicative relatively new, compared to monads? So it'd probably be quite a breaking change.
Re:Do notation considered harmful by Buttons840 on Wednesday April 29, 2020 @07:53AM (#23018042)
Monad is now a subclass of Applicative.
Re:Do notation considered harmful by lynguist on Wednesday April 29, 2020 @04:01AM (#23016626)
You are right. The title should have (2009) appended.