News for hackers. Stuff that matters.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by nbevans on Monday February 22, 2016 @04:52AM (#11149713)
I was thinking about this the other day too. Recursion in CS101 is taught in such a bizarre way. At least it was back when I was in CS101. It was almost as though CS tries to discourage its usage simply because "most minds cannot understand it as easily as iterative loops".
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by mixedCase on Monday February 22, 2016 @05:22AM (#11149806)
>It was almost as though CS tries to discourage its usage simply because "most minds cannot understand it as easily as iterative loops".

Wouldn't that be enough reason? They're supposed to teach you how to write good code, and that includes readable code.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by derefr on Monday February 22, 2016 @06:05AM (#11149990)
No, "they" are not. Maybe you're thinking of Software Engineering? Computer Science is supposed to teach you about the branch of mathematics called Computer Science. Recursion is a very important part of that—important enough that the need to address it early was one of the things that made Scheme an obvious choice for a teaching language for decades.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by argonaut on Monday February 22, 2016 @06:51AM (#11150176)
No. This is an overly restrictive definition.

Computer Science is it's own, highly diverse field, composed of software engineering, algorithms, theory of computation, human-computer-interaction, AI, systems engineering, databases, security, graphics, scientific computing, and many other sub-divisions.

CS hasn't been solely a branch of mathematics for decades.

See what Stanford considers part of CS: http://www-cs.stanford.edu/research

See what Berkeley considers part of EECS: http://www.eecs.berkeley.edu/Research/Areas/

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by pjmlp on Monday February 22, 2016 @07:26AM (#11150334)
In Portuguese universities informatics Software Engineering and Computer Science are part of the same degree, there isn't a clear distinction as such.

It is up to you to choose which lectures you want to use your optional credits for.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by the_af on Monday February 22, 2016 @08:22AM (#11150588)
True, there often is no clear distinction.

On the other hand, I studied CS in South America, and I can count on one hand the lectures which aimed to teach you "how to write good code". Maybe one or two of them, and only in the macro "good software engineering practices" sense. Most of the others assumed you sort of picked up how to code on your own, or that you asked other students or TAs on the side. There absolutely were NO "how to code" lectures, and the overall idea you got was that CS was a theory-heavy degree. Recursion, proofs, type theory, graph theory, etc, were absolutely the focus of the degree.

There was a different degree called "Software Engineering" (and not CS) from the same university, but I think they heavily overlap in content, so in practice the point remains.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by pjmlp on Thursday February 25, 2016 @02:40AM (#11172949)
In Portugal, at least back on my university days, the only bad ones which might relate to a pure US CS theory only degree was "Mathematics degree with specialization in computation".

On my case beyond Architecture design, there was hardly any "how to write good code" lecture.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by marklgr on Monday February 22, 2016 @07:00AM (#11150221)
It's more readable because other programmers have been taught the imperative style too, because their teachers find it more readable, because <tail call here>.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by nbevans on Monday February 22, 2016 @06:56AM (#11150199)
Not enough reason in my opinion. The thing is all the people in my CS101 that couldn't fluently grasp recursion generally didn't do very well and I don't think many of them ended up working in software jobs.

Recursion, good code and readable code are not related; I don't understand this point.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by rer0tsaz on Monday February 22, 2016 @07:06AM (#11150247)
Iterative loops are much easier to analyze and reason about, by humans and by computers. For example, they always terminate. To paraphrase Dijkstra, "I regard general recursion as an order of magnitude more complicated than just repetition, and I don't like to crack an egg with a sledgehammer."

https://tinyletter.com/programmingphilosophy/letters/i-don-t...

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by nbevans on Monday February 22, 2016 @07:36AM (#11150382)
Dijkstra was from a different era from when mutable state wasn't frowned upon.

Note to self: This may not go down well here but I'm willing to take the flack.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by rer0tsaz on Monday February 22, 2016 @09:15AM (#11150870)
He actually discusses it a bit in the previous paragraph, which does not seem to be online anywhere:

> When programming languages emerged, the "dynamic" nature of the assignment statement did not seem to fit too well into the "static" nature of traditional mathematics. For lack of an adequate theory mathematicians did not feel to easy about it, and, because it is the repetitive construct that creates the need for assignment to variables, mathematicians did not feel to easy about repetition either. When programming languages without assignments and without repetition --such as pure LISP-- were developed many felt greatly relieved. They were back on familiar grounds and saw a glimmer of hope of making programming an activity with a firm and respectable mathematical basis. (Up to this very day there is among the more theoretically inclined computing scientists still a widespread feeling that recursive programs "come more naturally" than repetitive ones.)

Continued https://tinyletter.com/programmingphilosophy/letters/i-don-t...

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by douche on Monday February 22, 2016 @10:01AM (#11151184)
I've always felt that imperative programming is more in line with the way the overwhelming majority of people are exposed to algorithmic instructions; cookbooks, furniture instructions, Lego construction, driving directions, pick-your-own-adventure books, etc. Especially given how piss-poor most mathematics instruction is, unless you happen to be a mathematician and have put in the effort to recast your brain along those lines, it's easier to come to grips with the imperative style vs more mathematically inspired paradigms.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by nbevans on Monday February 22, 2016 @10:10AM (#11151263)
I wasn't slighting Dijkstra but merely commenting on the era of the time.

You can for example see how primitive things were back then by describing "mutable state" as "dynamic" and "immutable" as "static". Dynamic and static these days have entirely different connotations typically more associated with type systems.

Things have moved on and now in 2016 mutable state is increasingly being pushed out of codebases in favour of immutable practices. Recursion is (and always has been) one way of doing that.

:)

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by pjmlp on Monday February 22, 2016 @07:21AM (#11150308)
> For example, they always terminate.

How do you terminate?

   for(;;) {
   }
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by meggar on Monday February 22, 2016 @08:38AM (#11150667)
break;
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by pjmlp on Monday February 22, 2016 @08:45AM (#11150712)
Not all programming languages have break; C syntax was just an example.

Also break is no different from using return (to keep C syntax as example) when recursing.

If you guard break with if then you also need to prove if the "if" condition does indeed provide a dataflow path to break.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by AnimalMuppet on Monday February 22, 2016 @01:41PM (#11153179)
> If you guard break with if then you also need to prove if the "if" condition does indeed provide a dataflow path to break.

In all cases, for all possible inputs.

On the other hand, if that's what your for loop looks like, you probably have the same problem of proving that your recursion terminates (in all cases, for all possible inputs).

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by pjmlp on Monday February 22, 2016 @02:04PM (#11153373)
Of course, I was just arguing against the OP that all loops terminate.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by mafribe on Monday February 22, 2016 @07:35AM (#11150372)

    Iterative loops are much easier to analyze and reason about,
This is not the case. Loops and recursion can be translated into each other, hence are of equal complexity in terms of reasoning. And you see that when you write down the Hoare-logic axioms for either.

What Dijkstra had in mind was probably simple, syntactically constrained forms of loops, like for-loops where the loop variable is read-only in the loop body. They are simpler than general recursion, sure. But there are corresponding simpler forms of recursion, e.g. primitive recursion or tail recursion that are much simpler than general recursion.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by AnimalMuppet on Monday February 22, 2016 @01:35PM (#11153118)
> Loops and recursion can be translated into each other...

True.

> ... hence are of equal complexity in terms of reasoning.

False. That's like saying that Stokes' Theorem says that the integral of a differential form over the boundary of a manifold is equal to the integral of it's derivative over the whole manifold, and therefore the two integrals are equally easy to do. In fact, the two integrals are often not equally easy to do, which is the primary practical reason that we care about Stokes' Theorem - it gives us a way to convert hard integrals into easier ones.

You cannot use formal equivalence to prove practical ease of doing the problem.

But the situation isn't even that simple. A blanket statement that "loops are much easier to analyze and reason about" is also false. It depends on the situation, and often on who's doing the reasoning. Different people think in different ways.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by Jtsummers on Monday February 22, 2016 @02:13PM (#11153429)
> You cannot use formal equivalence to prove practical ease of doing the problem.

Agree completely, but want to bring it back to another computing topic: Technically, anything that can be computed with one Turing-complete language can be computed with another. And every language clearly is not equivalent in terms of ease of understanding and reasoning about as every other language.

Trivially, compare computations in brainfuck to computations in C. Compare the recursive definition of tree traversal available in lisps to languages without recursion (some BASIC variants and others) where you have to jump through hoops and self-manage a stack.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by mafribe on Monday February 22, 2016 @03:32PM (#11154046)

    compare computations in brainfuck to computations in C. 
I'd suggest that this is an orthogonal issue. It's better to compare two otherwise identical languages, one where Turing-completeness is achieved by loops, another where the same is done by recursion. (Or a language that offers both). Then formal reasoning is of the same complexity.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by mafribe on Monday February 22, 2016 @03:30PM (#11154025)

    You cannot use formal equivalence to prove 
I'm afraid I have to disagree here. There is a mechanical translation from loops to recursion and back. Likewise, there is an associated mechanical translation from Hoare-triples and associated proofs for reasoning about loops to Hoare-triples and associated proofs for reasoning about recursion and back.

So in a hard way, the complexity of formal reasoning about the correctness of loops and recursion must be the same.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by AnimalMuppet on Monday February 22, 2016 @04:08PM (#11154305)
That doesn't mean that the reasoning in a human brain is equally difficult, or equally error-prone. If nothing else, doing the transformations (and back) adds to the cognitive burden.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by mafribe on Monday February 22, 2016 @05:38PM (#11154907)
That depends primarily on the programmer's experience, if you are used to loops but not recursion, then obviously the former is simpler than the latter, and vice versa. If you are equally familiar with both, they then thinking about it is equally difficult.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by rer0tsaz on Monday February 22, 2016 @08:01AM (#11150492)
Yes, that is the point I tried to make. Use simple, constrained forms such as (C) "for(int i = 0; i < n; i++) { ... }" with n an int and no modification of i in the body, or (Python) "for e in l:" where l is a list that is not modified in the body. Then your code is very easy to analyze, not just in theory but also in practice for compilers, tools and people reading your code. Many language designers have realized this and provide special syntax for this very common case. I'm not aware of any language that has special syntax for primitive recursion, but it's an interesting idea.

My apologies for making an absolute statement with unclear terms, thus inviting uncharitable interpretations.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by mafribe on Monday February 22, 2016 @08:21AM (#11150582)
I agree, that simple loops that you describe are easier to analyse than full recursion.

But simple loops are not as expressive as full loops (where you can modify the loop variable). As a simple example, try to phrase the Euclid's algorithm for computing the GCD using "for(int i = 0; i < n; i++) { ... }" where "i" is not modified in the loop body.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by rer0tsaz on Monday February 22, 2016 @08:55AM (#11150771)
Just use n = max(a, b). Of course that doesn't help you much unless you're adhering to strict safety standards (e.g. power of ten rules), it just shifts the burden of proof from termination to correctness. And there's no such trick with the Ackermann function.

I'm really just advocating a rule of least power. Don't go into full general recursion just because you can.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by mafribe on Monday February 22, 2016 @07:56AM (#11150465)
Why is this being down-voted? Could somebody please explain why they think what I wrote is wrong? I'd be happy to learn something new about loops and recursion.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by conceit on Monday February 22, 2016 @02:33PM (#11153585)
Wasn't me, but it's probably because iterative loops are believed to be easier to reason about. OTOH the recursive definition for the Fibonacci or factorial numbers seem easier, for one because they map to the literal explanation.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by mafribe on Monday February 22, 2016 @03:26PM (#11154002)

    iterative loops are believed to be easier to reason about.
This cannot be the case, because you can translate loops into recursion and vice versa, so every reasoning problem that one finds with loops is also a problem in reasoning about recursion and vice versa. If you look at the Hoare-logic rules this shows up clearly. In both case you need a suitably invariant, and you need a termination argument.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by conceit on Tuesday February 23, 2016 @11:01PM (#11164476)
Does the translation come for free? If not, it's probably complicated to reason about.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by nilved on Monday February 22, 2016 @07:28AM (#11150339)
Loops aren't any safer than recursion. A loop is a special case of recursion and is just as susceptible to the halting problem.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by chriswarbo on Monday February 22, 2016 @02:25PM (#11153526)
> Iterative loops are much easier to analyze and reason about, by humans and by computers. For example, they always terminate.

It's a bit of an apples-to-oranges comparison to compare (proper, bounded) for-loops to general recursion. A more appropriate question would be whether humans and computers find, say, primitive recursion or structural recursion easier to analyse and reason about than for-loops.

The difference between general- and primitive-recursion becomes very apparent when working in Coq, for example!

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by _pmf_ on Monday February 22, 2016 @07:55AM (#11150462)
> For example, they always terminate.

No. In fact, it's a huge problem in imperative code at all layers.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by pjmlp on Monday February 22, 2016 @07:24AM (#11150322)
I never got what the problem with recursion in CS101 might be.

In Portuguese universities, by time you get to this programming issues you already had enough maths to be able to relate recursion to how mathematical proofs work.

At least it was so for me and most of my friends back in the 90's.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by fleitz on Monday February 22, 2016 @04:56AM (#11149727)
I prefer it to loops, I find it more concise, it makes you really think about what your code is doing when you make it recursive.

Often I find subtle bugs in my loops where as with recursion the compiler seems to pick them up for me.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by bliti on Monday February 22, 2016 @05:23AM (#11149809)
In what scenario do you prefer recursion over a loop? Your comment made me think of code readability and maintainability. But I'm not judging. Really curious how you manage to prefer recursion over loops.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by chriswarbo on Monday February 22, 2016 @07:29AM (#11150346)
I prefer recursion to loops since loops bundle everything together in one environment; variables left over from previous iterations are still in scope, which is confusing and may cause problems, e.g. using a variable before it's been updated for this iteration, or after it's been updated for the next iteration, etc.

Recursion is just function calls. The only things which are in scope are those required by this iteration, accepted as arguments. The only thing I need to produce is a return value. This is a small, well-defined interface, as opposed to the self-interfering spaghetti code of a loop.

By accepting values as arguments and calling functions with different values, the problem of when and what to assign variables goes away; the language does it automatically by binding arguments.

Also, recursion (like function calls in general) allows thinking in terms of values, which are timeless and explicit in the code, rather than state, which is implicit and varies during execution.

Semi-related: http://chriswarbo.net/blog/2012-10-02-looping_in_javascript....

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by whatever12981 on Monday February 22, 2016 @05:55AM (#11149951)
Anecdote: After 12 hours of programming, I still had to implement some easy string search. I could not think straight at that stage and several imperative solutions failed. Then I thought "dammit, let's use a functional approach with recursion". It was faster to write, tail recursive, and correct the first time.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by eterm on Monday February 22, 2016 @06:20AM (#11150045)
Which environment are you working in that doesn't have a string search as part of the standard library?
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by whatever72163 on Monday February 22, 2016 @06:30AM (#11150088)
INTERCAL. Seriously, what does it have to do with the point I made?
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by mda on Monday February 22, 2016 @05:28AM (#11149840)
If working with trees, recursion is usually easier to understand.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by jalanb on Monday February 22, 2016 @09:57AM (#11151145)
If working with recursively expressed data, recursively expressed algorithms are usually easier to understand.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by StefanHamminga on Monday February 22, 2016 @05:44AM (#11149900)
My 2c: Building a hierarchical structure requiring opening and closing tags/code/etc (like HTML) is where I like to use recursion. The code structure matches the data structure, so you only have to reason about it once.
Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by tel on Monday February 22, 2016 @08:46AM (#11150713)
I think it's rather universal that, for instance, a depth-first tree traversal is best done recursively.

In my experience, I almost always prefer recursion since it allows me to work more closely with the structure of the original data that I'm interested in instead of a set of a proxy indices which I have to track separately.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by gjm11 on Monday February 22, 2016 @07:12AM (#11150270)
Other commenters have already mentioned that recursion is often a more natural fit for "recursively-defined" structures like trees. Here's an example using nothing more exotic than integers.

Suppose you want to compute the greatest common divisor of two non-negative integers. There's a famous algorithm that goes all the way back to Euclid's Elements, which you can write iteratively like this:

    def gcd(a,b):
        if a<b: a,b = b,a
        while b != 0:
            a,b = b,a%b
        return a
That's pretty nice, and it's the way I would usually implement it. But in terms of readability I think the following is better:

    def gcd(a,b):
        if a<b: return gcd(b,a)
        if b==0: return a
        return gcd(b, a%b)
because it makes it explicit that the point is that at every point in the computation you're replacing gcd(a,b) with gcd(a',b') in such a way that the calculation keeps getting easier.

It turns out that if the gcd of a,b is d then there are always integers x,y such that ax+by=d, and it's sometimes useful to compute x,y along with d. (For instance: if d=1 then you have ax=1 mod b, so this gives you an efficient way of computing reciprocals in modular arithmetic.)

Here's how that goes, iteratively and then recursively. (I notice that I've used two extra state variables for the iterative version. That's what seems like the most natural approach. I'm not sure whether there's a convenient way to use only two.)

    def xgcd(a,b):
        p,q,r,s = 1,0,0,1 # a = p.a0+q.b0, b = r.a0+s.b0
        if a<b: a,b, p,q, r,s = b,a, r,s, p,q
        while b != 0:
            k = a//b
            a,b, p,q, r,s = b,a-k*b, r,s, p-k*r,q-k*s
        return a,p,q

    def xgcd(a,b):
        if a<b:
            d,x,y = xgcd(b,a)
            return d,y,x
        if b==0: return a,1,0
        k = a//b
        d,x,y = xgcd(b,a-k*b) # d = x.b + y.(a-kb)
        return d,y,x-k*y
The difference isn't dramatic in any of these cases, but I think the recursive versions are clearer because the code is closer to the underlying mathematical theorems -- e.g., gcd(a,b) = gcd(b, a mod b) -- that make it work.

[EDITED to add:] Perhaps it's useful to think of it this way. If you wanted to explain how, say, that iterative xgcd function works, you'd do it with a loop invariant; in fact, I actually wrote one, in that first comment "explaining" what p,q,r,s signify. (In real code I would be more verbose about it.) The recursive function gets the same idea across in the language itself: each iteration of the loop becomes a call to xgcd, and the loop invariant becomes the fact that the corresponding call to xgcd actually computes what it's supposed to compute.

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by mbucc on Monday February 22, 2016 @09:37AM (#11151007)
Nice. Here's an Erlang version of your code, which I think reads even more like math:

  gcd(A, B) when B == 0 -> A;
  gcd(A, B) when A < B  -> gcd(B, A);
  gcd(A, B)             -> gcd(B, A rem B).
I also really appreciated the posting of more of Dijkstra's thoughts (from rer0tsaz) above, in particular this line struck a chord:

  When programming languages emerged, the "dynamic" nature of
  the assignment statement did not seem to fit too well into the
  "static" nature of traditional mathematics.
  
(Along those lines, Erlang's recasting of the equals sign as a pattern matching operator felt so natural when I learned how it worked.)

[Edit: zap redundant sentence.]

Re:It Is What It Is (And Nothing Else) – Why Recursion Still... by bliti on Monday February 22, 2016 @04:56PM (#11154595)
That syntax definitely helps. It is readable even though the variable names are non-descriptive.