93 points · by lvguowei · 8y ago · 126 comments
But for some reason given the choice, people use them.
It makes things easier to reason about for most day to day problems.
I train people in programming for a leaving. "Map" is harder to understand than "for" to most of my students. "Reduce" harder than manual looping. Recursion harder than iteration. Immutable harder than mutable.
Now I always end up teaching the entire toolbox. Those are all very useful concepts that I use in production and I do want my students to have a large solution set to their future problems.
But there is a clear pattern in my teaching experiences.
>But for some reason given the choice, people use them.
There is no choice when it come to functional programming because the paradigm is based on Alonzo Church model of computation known as Lambda calculus which is declarative: Everything is an expression or, more specifically, a function. Because of that, statement like goto are forbidden. Goto is from the Alan Turing model of computation known as the Turing machine which is imperative; everything is a statement.
Guy Steele said that the lambda expression in Scheme is the ultimate GOTO because it's like an unconditional jump while remaining declarative and functional.
> I train people in programming for a leaving. "Map" is harder to understand than "for" to most of my students. "Reduce" harder than manual looping. Recursion harder than iteration. Immutable harder than mutable.
Careful! Tools that are easy for a trained expert to use and tools that are easy for a newbie to grasp are not only different sets of things — I'd go as far as to say that overlap between the two is very rare indeed.
Functional programming is great when you wrap your head around it, but it's a significant mental drag to understand. I haven't met people who honestly find it easier, if anything, it's more bragging rights that you can do it. (And useful bragging rights, when you can hack monads, lensing, folds, etc. you can solve some very challenging problems.)
I will make an observation in defense of functional programming: when you start to get "data pasta" (my term for the data equivalent of spaghetti code) where objects are linked all over the place and side effects abound, it becomes similarly incredibly difficult to reason about. What starts out simple quickly leads you into a trap.
That's my motivation for designing a functional language that uses typical imperative control structures, which are then translated into a functional form. I think you get a very simple mental model: imperative control, referential integrity and locality of effects. It also forbids pointers and recursive data structures; that was originally just so I could guarantee that reference counting was sufficient, but I'm now realizing that once you add a simple "path" type, you can do everything you want, but it also helps to avoid highly complex structures that are difficult to reason about.
"Immutable harder than mutable."
You can have both, though: https://pypi.org/project/pyrsistent-mutable/
I have exactly the opposite experience teaching programming. My students grasp recursion very quickly, immutable is easy, etc. In particular, students without prior programming experience pick up these FP concepts very quickly.
A while ago, I was working in company X, that sold a web platform for job boards, with multiple big and famous clients. One time, there was a bug in our platform, that had to do with a for-loop with an always-true condition. The loop -which was in our core platform code and so deployed in every single website we maintained- caused untold havok, as resources disappeard down a black hole and all our servers dropped to their knees and asked for mercy.
In the aftermath of the incident, when an explanation had to be given to those UpStairs running the show, it was put to them that the cause was an (effectively) unconditional loop. Now, as a lowly junior dev, I was not present in the deliberations but, given what followed, I can imagine the conversation:
Those UpStairs: "How can we ensure that the same thing never happens again?"
Senior Software Person: "Well, there is no way to ever be 100% safe. A for-
or while-loop can always go wrong."
Those UpStairs: "Is there any alternative to for- and while-loops?"
Senior Software Person: "Not really. I mean, there is recursion of course..."
Those UpStairs: "Recursion? What is that?"
Shortly after, we had a big emergency meeting to discuss What Should be Done
to Avoid the Same Problems in the Future, where we were instructed to not use
the looping constructs of the langauge in which our platform was written,
anymore. Instead, we should only ever use recursion to write loops.The language of our platform was C#, mind. A language that (to my knowledge, and certainly at the time, around 4.0) does not even support tail-call optimisation. Not to mention, it's just as easy to go into an infinite recursive loop as it is to go into an infinite imperative loop, if not easier.
Suffice to say that nobody followed the instructions given from On High, either because they found it too much work, or because they found it too stupid, or because they were just busy pulling their hair out.
I commend your skepticism, of course, but I don't think that's so hard to believe. I'm sure we all have stories of non-technical managers making stupid decisions based on complete misunderstanding of computers and programming languages and principles, after a quick explanation by a technical person.
I mean, imagine trying to explain recursion to someone who doesn't even really get for-loops.
Explicit loops have a use, as does explicit recursion, but in the vast majority of cases, I use higher-order functions, like map, filter, flatmap, and fold.
The real problem is choosing tools that have more power than you need. This increases the surface area for potential bugs and it requires future reader to parse more code that's just there for plumbing.
Can you explain this further? If you want to work your way through an array, for instance, you return once you have an empty array. If your result is stored in a data structure that can be appended, I don't see how it's possible to have an off-by-one error. You must be referring to another use case.
C# also has LINQ, available for many years i.e. since 3.5.
Also, when management is asking “How can we ensure that the same thing never happens again?” they rarely interested in language level. In my experience, they don’t care whether the problem was caused by for or any other f-word in the code. This question is usually about QA and deployment workflows.
For that reason alone I think tail call elimination is a must, especially in today's transpiling world.
This is an important insight.
I feel the JavaScript implementors are dragging their on getting tail call elimination widely supported.
I can't imagine having to do the same using an already existing looping construct with it's own edge cases and subtle semantics.
[0]: I didn't think about post-guards when I started, and adding them now would mean having to do some restructuring of the quite hairy emitting macro, which I won't do since I don't see the use case for post guards for anything else than making in-value a bit more elegant
With TCO being part of the spec and the potential replacement spec killed off, browsers really need to start getting with the program.
JavascriptCore (safari), Node v6, duktape, jerryscript, XS6, etc all have proper tail calls. It breaks the community to not implement them. It's not a standard if its not standard.
I don't think most of my loops are straightforward maps or filters of a single iterable. I need to reference various data sources and execute actions with side-effects. To do that using a functional framework, something like Haskell's mapM ("monadic map") is required. But that brings quite some mental overhead and I find it way too constraining for the typical case.
> more readable and safer and better optimized by the compiler.
I doubt these are in general qualities of non-builtin constructs vs builtin ones. But yes, too much builtin and non-orthogonal functionality leads to detrimental complexity.
In any case I don't think it matters much to most compilers whether you write a loop using syntactic sugar or as labels and jumps.
I’ve periodically done microbenchmarks of inner loops over the years and the various gcc outputs of the c++ loop functions are always performing slightly better than if I hand rolled. Perhaps with gcc7 or clang this is different.
Cool, so if that's all we should just use those. But wait, what about those dozens of megabytes of data, should we really zip/transpose/concat them? We should use non-strict evaluation then...
Any code examples?
What I was thinking of is hand-rolling
for (a; b; c;)
BODY
to a;
loop:
if (!b)
goto out;
BODY
c;
goto loop;
out:
...foreach(i in list){
if i == 0 { class.a() }
else { class.b() }
}
No need to be dogmatic.
For example, if you can express a finite state machine (FSM) as a number of mutually (tail) recursive functions. Then you can reuse this FSM as part of a larger FSM via a tail call. You can't do this with the iterative constructs in C et al---the whole FSM must be defined in one spot.
Doesn't it depend on how the iterations are compiled? Seeing how e.g. a normal continuation is compiled in C#.
foreach(var thing in Things)
{
if (thing.IsAlive)
yield return thing;
}
Those will compose (At least I think they will compose in the sense you mean) because they are alrerady sugar for a state machine and not a simple iteration. The for-loop construct didn't imply "loop here until done" in the sense that doesn't compose.Any decent compiler will handle it just fine. If you want to include crappy compilers, well, then we need to include the same for LISP and Scheme. Whatever the language specification may claim about tail recursion is not relevant when you sit down to produce code for the actual system at hand.
In Scheme, local functions are used for looping (via tail recursion). C doesn't even have those (other than as a GNU C extension).
If I remember correctly, there was briefly discussed interesting proposal to add explicit tail calls into Python almost decade ago. You would use keyword or syntax to perform tail-calls explicitly (not the tail call decorator hack). This would make tail calls actual looping construct.
--> return myself(...) # tail call
--> return var * myself(...) # not a tail call
But there is indeed something to be said about a construct that enforces the tail call guarantee. The point of SICP's scheme though is to keep the number of language constructs to a minimum for educational purposes. (define (map proc lst)
(if (null? lst)
'()
(cons (proc (car lst)) (map proc (cdr lst)))))
You might look at this and go "that's bad! it will blow the stack when the list is too long!". Well, some Schemes will dynamically grow the stack so that this straightforward code translates to an efficient process that doesn't hit arbitrary stack limits. Otherwise the programmer would have to contort this into an iterative, tail-recursive process, which would involve building the list backwards and reversing it at the end.That's what I did in my Forth dialect; I called it "goto".
Why not?
If we want to do something that requires a change to the language, e.g. the "async/await" stuff that seems to be popular these days, then we must convince the language designers that it's a good idea, wait for it to be implemented, wait for a new release of the language, and maybe (if we want our code to be portable) wait a few years for it to become widespread (e.g. new versions of RedHat, Debian, etc. to include it by default). Alternatively we could maintain a fork or patchset, which might be a lot of work and receive little support. We may also have to do this for multiple implementations, e.g. GCC + Clang + MSVC + .... We might also have to go through some form of standardisation effort (e.g. C++14, Haskell2010, etc.).
Our change may impact every user (e.g. if we add exceptions to a language, everyone must now worry about catching them, e.g. from callbacks). This impact may last for decades, even if that feature falls out of favour, since it must remain for backwards compatibility. Any subsequent language features must take our feature into account (e.g. if we added exceptions, and someone wants async/await, that person must consider how async/await deals with exceptions and vice versa).
On the other hand, if something can be implemented as a library then we don't have to wait for anyone: we can just write it. It will work with multiple implementations of the language. Those who don't want or care about our feature can just avoid the library. If the feature falls out of favour, we can just avoid importing that library in our new projects.
oh, sorry, I was reading peoples comments about map. both for iteration and recursion, the compiler (and it author) has to think pretty hard. with higher order functions it just says 'great'
Loops are closer to what CPU actually does. A compiler is therefore simpler to implement and will likely contain less surprises.
It’s easier to use a debugger on procedural-style or OO code (step in/over/out, local variables) compared to recursive functional style advertised by SICP.
In most runtimes, call stack is limited to a small size, couple of megabytes. Stack overflow exception is hard to handle in reasonable way. When instead using a loop with a stack container for state, it can be much larger, also easier to handle overflows i.e. implement soft and hard limits.
I dont find the argument convincing. By that assembly is closer to what CPU actually does, why not write code using goto (or binary)? We all can agree on its easy to write reasonably good code high-level languages. I think it because high-level languages are closer to the problem domain (or our thinking), hence it's easier to define the solution in these languages. same for recursion.
> It’s easier to use a debugger on procedural-style or OO code (step in/over/out, local variables) compared to recursive functional style advertised by SICP.
I feel exactly opposite. OO by definition have state bound to object outside the method (not actually local variable), so you have to watch all the objects method is affecting. Not pleasant experience when you have hundreds of objects. A recursive code on the other hand usually depends only on the local arguments so you can only focus on current step.
> In most runtimes, call stack is limited to a small size, a couple of megabytes. Stack overflow exception is hard to handle in a reasonable way. When instead using a loop with a stack container for the state, it can be much larger, also easier to handle overflows i.e. implement soft and hard limits.
Well, depends on the platform you are working on. For desktop at least it's definitely not "a couple of megabytes".
I feel that most of the time choice is between readability and performance. Sometimes maybe the solution is inherently iterative/recursive making choice easier. ymmv though.
Mostly agree.
> same for recursion
I don’t know about you, but in my problem domains loops are closer then recursion. Also loops are closer to my thinking. YMMV.
> Not pleasant experience when you have hundreds of objects
No one forces you to design your OO apps this way. When you only have a few objects, or when you only process them sequentially, there’s no need in complex OO model, a functional or procedural code will do fine.
However, there’re apps where there’re hundreds of interacting objects, such as a web browser.
> For desktop at least it's definitely not "a couple of megabytes".
On Windows it’s usually (=for apps linked with default settings) 1 megabyte.
Actually, the simplest example I can think of where this the case involves a sequence: binary search.
On the other hand, if you have to significantly rework the conceptual recursive solution to put it in tail-recursive form, an implementation using loops may end up being easier to understand.
* CPUs are dynamically scoped
* CPUs are weakly typed
* CPUs are dynamically typed
* CPUs only compare to zero
* CPUs have no way to represent OOP
and so on
All that said, tail calls are very close to how the CPU works. They are just GOTO with additional parameters. If you implement tail calls with dynamic scoping, the parameters would be registers and the tail call would be a change to the instruction pointer. That would be very close indeed.
Loops are not necessarily close to what a CPU actually does either, especially one supporting vector operations or out-of-order execution. Loops imply an ordering which may or may not be actually exist and many compilers are complicated by their presence.
Debuggers are a problem for any suitably high-level abstract code. Would a step-by-step word-at-a-time debugger help to debug a SQL query or even a complex arithmetical expression from Fortran? There is no getting away from the fact that high-level domain-specific code needs high-level domain-specific debuggers to be built alongside.
I know and I don’t think these are always good things.
> Loops are not necessarily close to what a CPU actually does either
Indeed, not necessarily, but very often. Unless automatic vectorization is involved, long loops are very often quite close to the machine code uploaded to CPU. Inside the CPU it’s free to do whatever, but on the public API, it’s still loop instructions.
> the fact that high-level domain-specific code needs high-level domain-specific debuggers to be built alongside.
That’s not a fact, that’s your opinion. I don’t code SQL nor Fortran, mostly C++ and C#, sometimes Python and others. The debuggers I have in corresponding IDEs are already built, they are sufficiently high-level for domain specific code, but the debuggers themselves aren’t domain specific, they are pretty general purpose.
Maps and folds do make structure explicit though. For example, it is very easy for a compiler to vectorise a "map" operation. Folds will always terminate.
> The debuggers I have in corresponding IDEs are already built, they are sufficiently high-level for domain specific code.
But does your debugger allow you to visualise the intermediate steps of an arithmetic expression? Does it understand Iterables/Enumerables and allow you to capture and inspect them? Can it handle concurrency and parallelism, or help you make sense of callbacks for non-blocking IO etc? My point is that the debugger is simply not as general purpose as most claim it to be. It sees the world word-at-a-time and only allows you to step statement-by-statement. It does not understand the composite data structures or control structures that you have built. This is less of a problem with low-level code, as typically there is limited abstraction. But it will be a problem for any sufficiently high-level abstract code (functional or otherwise).
That said, I love my for loops, too.
It only works if you are using recursion in place of a simple loop.
Many algorithms traditionally implemented with recursion (e.g. various tree searches) need that stack somewhere.
Technically it’s probably possible to “properly prepare” that, but practically both alternatives (recursion + built-in call stack, or loop + separate stack) are much easier to implement.
I have a STEM (non-CS) degree but very recently, started working as a programmer. Doing my first internship at a 'techy' corporate company. One of the things I'd be doing on the side is to go through https://mitpress.mit.edu/books/elements-computing-systems. The video introduction to it just gives me goosebumps to this day. I don't know why. It's fascinating.
Than there is other paradigm books such as "pragmatic programmer", "Thinking Like A Programmer", "Design Patterns: Elements of Reusable Object-Oriented Software", etc.
So far, I've done plenty of reading on Algorithm & Design Structure and leetcode here and there. In the past, I didn't qualify for internship at Google, Amazon or M$ as a software developer/engineer. I feel the reason why I didn't was because I didn't have a "computer science" keyword mentioned anywhere on my resume. Hence, my hope is after getting through "Element of Computing System" & Design Pattern, I'll be able to shove in "computer science" keyword one way or another on my resume.
I guess any time is good. It's generally a class you take as a freshman or sophomore. People who attend top engineering schools generally played around with these topics in high school or even in elementary school.
Also, it looks like MIT stopped teaching SICP.
https://news.ycombinator.com/item?id=11628080
> In the past, I didn't qualify for internship at Google, Amazon or M$ as a software developer/engineer. I feel the reason why I didn't was because I didn't have a "computer science" keyword mentioned anywhere on my resume.
Or you are competing against the best of the best CS students from around the world. People who aren't blown away by introductory stuff like elements of computing systems or who are just looking into SICP. I really don't think missing a keyword is why you didn't get the internship at google, amazon or microsoft.
> Hence, my hope is after getting through "Element of Computing System" & Design Pattern, I'll be able to shove in "computer science" keyword one way or another on my resume.
I've never had computer science on my resume though I majored in it. For my internships, I just listed the courses/projects I worked on. For my first job, I just listed the degrees I had ( BS and BA and the gpas for both ), along with the projects I worked on and the internships I had. After that, I just listed the university and degrees and my work experience. "Computer science" isn't something I ever listed in any resume. But then again, I was never really good at writing resumes.
I think you are really overthinking things but feel free to do what you want. If you are so intent on putting computer science on your resume, why not just major in computer science?
Now I'm aware that mutually recursive functions can be gracefully used to implement state machines and that the issue of jumping into the middle of a loop from a goto seems to be prized.
The former (mutually recursive function) seem to solve that problem, not necessarily in almost a general senses, however perhaps preventing some of the most nasty things Goto can do.
I'd like to know if mutually recursive function requires the underlying machinery to provide gotos. In my view, that would fully justify them. If not, then tail-recursion might be the only thing missing from WebAssembly.
[1] I can't find (or remember) who or where this originated! It seems to be folklore now, but it must have started somewhere.
[2] Many examples here: http://library.readscheme.org/page1.html
[3] Felleisen, Matthias. ‘On the Expressive Power of Programming Languages’. In Proc. ESOP. Copenhagen, Denmark, 1990. https://pdfs.semanticscholar.org/2798/5884a1947b656424b0956f...
I don't know much about WebAssembly so I don't know if gotos have a place or not but if they're useful and the only reason for not adding them is cargo-culting "gotos are teh 3v1l" it's a bit silly.
IMHO, the Web Assembly folks should focus on a simple, elegant core language that is easy to define and easy for a JIT to optimise. The machine architecture, whatever that may be now or in the future, should be secondary. Personally, I would never have called it "Web Assembly" either.
I'm not saying anything about what WebAssembly should or shouldn't look like, I haven't got the faintest idea about that, I was just criticizing the argument of the parent about the "nastiness" of goto that felt out of place in this context. If 99.99% of all wasm code is generated by compilers then it should mostly aim at providing a target that lets compiler output efficient code, not something that would be nice for humans to write or add arbitrary limitations to prevent coders from writing "nasty" code.
It wouldn't be that surprising if in the future we have dedicated processing units for Web Assembly. And I think that's what they're aiming at.
Just like Java had a few computers with processing units dedicated to accelerating Java bytecode. But on a much larger scale.
In any case I guess at some point one has to drop the high-level stuff and get real.
It's not a source language. It should be elegant, but not in the same way. An intermediate language should lend itself to mechanical synthesis and analysis (in whichever balance is most appropriate), and shouldn't worry about how writeable and readable it is to humans.
Java bytecode, for instance, is very 'simple' in a way, but no-one in their right mind writes code in Java bytecode assembly language.
There is such a thing as a bad intermediate language. These things need careful and skillful design, but shouldn't be mistaken for source languages.
When Dijkstra wrote "Go To Statement Considered Harmful", he was referring to source languages, not to machine languages or intermediate languages.
But from a pragmatic standpoint, it’s just too easy for someone to turn a tail-recursive function into non-tail recursive, causing a stack overflow eventually.
So when working in a large team, with run-of-the-mill programmers, I’d stick with loops.