r/AskComputerScience • • Feb 19 '21

Why does a language have if statements, for and while loops, and so on? Can we solve every problem with only these structures?

Hi,

I would like to know if we can solve every problem with a programming language's default (c-like languages) commands? Why does a language have an if statement, loops, for exemple? Can we solve problems without it?

I believe that these structures are abstractions, and there existence is correlated to low level details. But I may be wrong.

Thanks a lot!

35 Upvotes

55 comments sorted by

27

u/trinopoty Feb 19 '21

Loops basically boil down to jumps and if statements during compilation.

If statements themselves are however irreplaceable as far as programming goes. Without the ability to conditionally jump into different places in the code, you'd be pretty limited in what you can implement. Jumps (conditional or unconditional) are one of the basic requirements to make something turing complete.

3

u/brych_ant Feb 19 '21

Thanks ! So everything comes down to turing completeness? Regarding the implementation of structures in programming languages?

10

u/trinopoty Feb 19 '21

Well not everything has to be turing complete. There are entire classes of languages that don't care about being turing complete. SQL comes to mind. But these are pretty niche languages that require support from other languages.

Current technology only allows us to execute turing complete code in hardware (someone with better knowledge might correct me here). Most processors available on the market today go well above and beyond the minimum requirement for being turing complete. For instance, fancy mathematics are not a minimum requirement for being turing complete but most if not all processors have it.

2

u/brych_ant Feb 19 '21

Thanks for clarifying this to me!

1

u/Roboguy2 Feb 20 '21

Most processors available on the market today go well above and beyond the minimum requirement for being turing complete.

Maybe I am misreading you here, but there are no processors that go beyond being Turing-complete in terms of computational power. In fact, a Turing machine has no limitation on memory size so there are no physical machines which match the power of a Turing machine in that way. However, standard CPUs equal the power of Turing machines if we exclude the possibility of running out of memory, which is frequently a reasonable thing to do.

1

u/trinopoty Feb 20 '21

https://softwareengineering.stackexchange.com/a/230548/309753

The minimum requirements for a Turing machine are just that.

Most processors implement all sorts of fancy mechanisms. Both Von Neumann and Harvard architectures are much more advanced than a turing machine.

Modern x86 or ARM processors are so much more advanced than turing machines.

1

u/Roboguy2 Feb 20 '21

I may not have worded that too well. What I mean is there is no computation that can be performed by a modern processor which cannot be performed by a Turing machine. The Turing machine may be clunkier, but it can still get the result. There has not been a processor made, despite fancy modern features, that contradicts the physical Church-Turing thesis.

2

u/trinopoty Feb 20 '21

That is true. But my point was that processors you can actually go out and buy for everyday use are more advanced than a turing machine.

Most people do care about how much time it takes for a processor to do something and they probably won't be too happy if you replace their processors with a basic turing machine that's slow and clunky.

9

u/east_lisp_junk Feb 19 '21

Alternatively, you could replace if with while and a fresh did_this_already variable.

5

u/trinopoty Feb 19 '21

But you can't have `while` without a conditional jump. Basically, you can't have `while` without `if`.

8

u/east_lisp_junk Feb 19 '21

You absolutely can define a Turing-complete language with only while and no built-in if (and untyped lambda calculus has neither -- both are derived constructs).

4

u/trinopoty Feb 19 '21

You can if you want. My point is that a `while` inherently uses an `if` which basically defeats the point of not having an `if` construct in a language.

-7

u/visvis Feb 19 '21

It does not. While is not translated into another language construct, it is translated directly into assembly for the target CPU, just like if.

0

u/[deleted] Feb 19 '21

[deleted]

-4

u/visvis Feb 19 '21

The's not what the response I replied to says. It say while inherently uses an if, which is false. If is a language construct. While does not use if, but rather while and if use the same assembly language construct.

-1

u/visvis Feb 19 '21

While is not implemented using if. Both are implemented using a conditional branch in the machine's assembly language, for example JZ on x86 for a simple boolean test on x86. You can offer either one of the two in the language.

7

u/trinopoty Feb 19 '21

We're basically arguing over syntax here. You can make your language use `conditional_jump` keyword or you can have it use `if` keyword. It means exactly the same thing. `if` is basically an alias for `conditional jump` in any modern language I know of.

-4

u/Felicia_Svilling Feb 19 '21

No it isn't. You can make a loop with a conditional jump for example. You can't make a loop with just an if statement.

-1

u/trinopoty Feb 20 '21

You actually can. As long as the language also has an unconditional jump. You can in C for instance. But I'll leave that as an exercise for you.

2

u/Felicia_Svilling Feb 20 '21

Yes, sure but you have to have that unconditional jump. That is the difference. If you don't have unconditional jumps, you can't implement a conditional jump with just if statements.

0

u/trinopoty Feb 20 '21

What I meant to say was: You need the ability to jump to arbitrary locations in code.

An unconditional jump is just a conditional jump with a true condition. Actually, you can write assembly code (in x86 or ARM, because I have some knowledge of those two) without ever using an unconditional `jmp` instruction and only using `jz` (or the ARM equivalent). You can even write a compiler for this for C if you want.

And I think you're overly focused on a particular language(s). And I'm usually talking in terms of the underlying concepts.

2

u/Felicia_Svilling Feb 20 '21

I understood you perfectly fine.

You can implement an if with conditional jump. You can't implement a conditional jump with if statements. You need to use both if statements and some kind of jump statement (conditional or not) to implement an if.

→ More replies (0)

6

u/Roboguy2 Feb 19 '21 edited Feb 19 '21

If statements themselves are however irreplaceable as far as programming goes.

Jumps (conditional or unconditional) are one of the basic requirements to make something turing complete.

These two statements have some subtleties. There are some surprising examples of Turing complete languages, like FRACTRAN, which have no language-level branching/jumping constructs in them (at least, in the usual sense).

Other examples would include Iota and Jot and SKI combinator calculus. While one perspective of these last languages would be to look at application of their combinators as a kind of function call (a sort of jump), another perspective (which is also a possible "practical" implementation) is to look at the language instead as a small collection of rewrite rules which define the language. The interpreter would go through a program and try to apply these rewrite rules until there are no more that can be applied (if that ever happens).

You could argue that there is branching and jumps in such a language, it is just implicit. However, it is still not actually directly accessible to the programmer as a language construct in the way that if, while, goto, etc are in a language like C.

41

u/DonaldPShimoda Feb 19 '21

Ah, okay, this is a neat question!

I would like to know if we can solve every problem with a programming language's default (c-like languages) commands?

The answer is "no", because the set of all problems in the universe includes questions which cannot be answered by computers. (There is another phrasing of your question to which the answer is "yes", and I'll come back to that later.)

One definition of computer science might be "the study of computability". What does it mean for something to be "computable"? This is actually not an easy question to answer, but some smart people came up with some possible definitions that we still use today.

Turing Computability

One of these answers came from Alan Turing in 1936 with the invention of the Turing machine". A Turing machine is a conceptual device (called an abstract machine) consisting of an infinitely long "tape" and a device to read from and write to that tape, and which can navigate the "cells" of that tape one at a time in a sequential order. There are two steps of configuration for a Turing machine:

  1. Write a problem on the tape.

  2. Configure the device to be able to respond to each cell in the problem.

So first you decide on an "alphabet", which is a finite set of symbols that are relevant to your problem. Then, you write down instructions like "if you read symbol Foo, write Wubbit over it and move one cell to the right". I won't write out a detailed example here, but this is a good one.

One of the most important results of Turing's work on this is that he was able to prove that there were some problems that could not be solved by a Turing machine (which he actually named the a-machine, for "automatic machine"). Specifically, Turing was able to formally prove that his Turing machine could not solve the Entscheidungsproblem — a mathematical challenge problem posed by Hilbert and Ackerman in 1928. From Wikipedia:

The problem asks for an algorithm that considers, as input, a statement and answers "Yes" or "No" according to whether the statement is universally valid, i.e., valid in every structure satisfying the axioms.

The German name literally means "decision problem", and we now call these yes/no questions in general "decision problems".

In general, we accept Turing's definition of computability, which essentially comes out to "whatever a Turing machine can solve".

But there was another...

Church Computability

I mentioned Turing published his work on the Turing machine in 1936.

Also in 1936, Alonzo Church published his work on the lambda calculus. Church was interested in investigating the foundations of mathematics, and he was particularly interested in the Entscheidungsproblem, so his lambda calculus was an attempt to answer the same question Turing did — only Church and Turing didn't know each other, much less that other people were working on the same problem and planning to publish at the same time.

The lambda calculus is a system where you construct terms, and then follow a set of rules to reduce them to a value. There are three classes of terms in the lambda calculus:

  • Variables, of the form x, y, etc.

  • Functions (called "abstractions") of the form (λx.M), where x means "any variable" and M is another complete term in the lambda calculus (called a "lambda term"). (The λ is just syntax, like the parentheses.)

  • Function applications of the form (M N), where M and N are both lambda terms.

Then, there are exactly two rules for how to reduce a lambda term:

α-conversion ("alpha conversion"), which is (λx.M[x]) → (λy.M[y]). This says that for any function definition term, you can change the name of its bound variable by changing that same variable throughout the inner term M and still have the same meaning. This frees us from having to worry too much about what names we pick.

β-reduction ("beta reduction"), which is ((λx.M) E) → (M[x := E]). This says that a function application is evaluated by replacing all occurrences of x in M with copies of E.

A simple example might be:

  • ((λx.((λy.y) x)) a)

  • ((λy.y) a) by β-reduction (we replaced the function application with the function's inner term, where all occurrences of x were replaced with a)

  • a by β-reduction

If you're thinking "wow that looks awful to use", you're right! It is no fun to solve problems in the pure lambda calculus.

But there's an important result: the lambda calculus is capable of answering the exact set of questions that the Turing machine can answer. The two models are computationally equivalent. The fact that they were each derived independently of the other and published almost simultaneously is incredible, but it also suggests that the notions of computability employed by Turing and Church are in fact fundamental. We call their combined result the Church-Turing thesis, which gives us the definition of "computable" we still use today.

Turing Completeness

In this framework of computability there is an idea called "Turing completeness". A system is considered "Turing-complete" if a Turing machine can be encoded within it. Most modern programming languages are Turing-complete, which effectively means that they are capable of answering the same questions as a Turing machine. (Technically it means they are capable of answering at least the set of questions answerable by a Turing machine, but in general this distinction isn't useful.)

So we come back to your question:

can [we] solve every problem with a programming language's default (c-like languages) commands?

And the answer is "no", because most programming languages can only solve computable problems — those which can be solved by a Turing machine (or the lambda calculus).

Okay, but what I really meant was...

I said we could rephrase your question and potentially change the answer to "yes". The new question:

can [we] solve every computable problem with a programming language's default (c-like languages) commands?

Since we now have a formal definition of what it means to be "computable", we've limited the possible sets of inputs to only those questions that we know can be answered. So now we have to investigate what it is you mean by "default commands".

In most programming languages, terms fall under one of two categories: expressions and statements.

An expression is a term which reduces to a smaller expression, until it becomes a value. (A value is a fundamental term that cannot be reduced.)

A statement is a term that produces side-effects and does not reduce to a value.

In C, 5 + x is an expression while a function definition is a statement. And, indeed, loops in C are statements: they provide a specialized context in which computation can occur, but they do not reduce to expressions themselves. (You can't do x = for (int i; ...).) This is not true in all languages; the so-called "functional" languages generally use loops as expressions, and many of these languages simply lack statements at all!

So let's refine the question further:

If we remove all statements from C and limit ourselves to its expressions, can we simulate a Turing machine?

I think the answer is "no", because we must write a finite amount of bytes to have a C program that is valid, and without a loop this means we cannot process an infinitely long input. We need the ability to express "this program can run forever even though the program itself is of finite length".

So we rephrase the question again:

If we remove all statements from C except the while loop, can we simulate a Turing machine?

I believe the answer to this is "yes" (assuming we encode the tape in such a way that we don't need the use of statement-type read/write functionality).

To put it another way: in any Turing-complete programming language, there exists a subset of its forms which can fully simulate a Turing machine, so you could hypothetically throw away the rest and still have a language capable of answering exactly the same questions.

Abstractions

You said:

I believe that these structures are abstractions

And you're right! So then there's a question of "why do we have abstractions?"

Abstractions provide the ability to concisely express complex ideas. A for-loop is just a specialized while-loop, but we find it to be useful, for instance.

In 1991, Matthias Felleisen published a paper titled "On the expressive power of programming languages". In it, he defined a formal way of comparing two programming languages' "expressive power". This allows us to answer questions about whether a given abstraction actually increases our ability to express complex ideas, or if it's just a rephrasing of an existing capability. Using this notion of expressiveness, you can produce a smallest-subset of a language's forms that has the computational utility of the Turing machine without losing any expressive power by cutting out the extra.

A couple years ago, Shriram Krishnamurthi (a former student of Felleisen's who now specializes in the intersection of programming languages and CS education) gave a talk about that paper, which may provide more insight.

5

u/brych_ant Feb 19 '21 edited Feb 19 '21

Thanks a lot for your answer! It really helped me!

3

u/DonaldPShimoda Feb 19 '21

Happy to help! Lemme know if you have any follow-up questions. :)

2

u/Sandarr95 Feb 20 '21

Using recursion you can also built infinite "loops", meaning we wouldn't need the while construct, right?

Great explanation! I really feel like it's also important to stress that these for and while constructs are designed for "human" use and we're probably not done designing these valuable to have constructs.

2

u/DonaldPShimoda Feb 20 '21

Using recursion you can also built infinite "loops", meaning we wouldn't need the while construct, right?

This is dependent on both the structure of the recursion as well as the implementation of the compiler! On paper, recursion is fine, but in practice we have to worry about things like running out of memory due to constantly adding new frames to the stack. Some C compilers perform tail-call optimization, but of course this will only help with tail-call recursion!

So I focused on while loops because that's easier and less messy. But you raise a good point, and perhaps I should've made some space for it.

Great explanation!

Thank you! I try to contribute good content. :)

I really feel like it's also important to stress that these for and while constructs are designed for "human" use and we're probably not done designing these valuable to have constructs.

This is true! Computers are perfectly fine with pure assembly. Everything we build on top of that is just for human use. There's lots of work to be done in investigating what makes some abstractions more useful than others or easier to use.

2

u/dissonantloos Feb 20 '21

Impressive answer and fascinating read.

1

u/DonaldPShimoda Feb 20 '21

Thanks! This is cool stuff and I love sharing about it.

11

u/[deleted] Feb 19 '21

There are languages that don't have loops though I'm unaware of any that lack if statements. In languages without loops recursion is used instead, Haskell is like this for instance. Once compiled however "loops" and "recursion" don't exist in the machine code.

Can we solve every problem with just a few simple commands? Sort of. In computability theory something very simple like FlooP can "solve any problem" in the sense that it can be used to represent every computable function. However in the sense of solving problems in the real world FlooP is quite useless.

2

u/brych_ant Feb 19 '21

Thanks for your reply!

6

u/[deleted] Feb 19 '21

[removed] — view removed comment

3

u/[deleted] Feb 19 '21

???

1

u/Roboguy2 Feb 19 '21 edited Feb 19 '21

There are languages that don't have loops though I'm unaware of any that lack if statements.

This might, to an extent, depend on what you classify as an "if statement," but neither Iota nor Jot have if statements in the traditional sense. Likewise for FRACTRAN, which I mentioned in another comment.

5

u/mplang Feb 19 '21

Check-out One-instruction set computers. Nearly all programming constructs are strictly unnecessary, but reading, writing, and maintaining code would be miserable without them. And there's no way our software (really, our world) would be this advanced without them!

1

u/brych_ant Feb 19 '21

Thanks! I will definetely check it out!

1

u/TransientVoltage409 Feb 19 '21

I was going to mention single-instruction sets too. It's fascinating to realize that literally every computable function (Turing completeness) can be expressed in terms of a single instruction and enough memory.

There's an entire gamut of esoteric languages where the entire point is to create languages that are technically T-C yet incredibly awkward and painful to actually use. It makes me appreciate how "real" languages go out of their way to make life easier.

2

u/khedoros Feb 19 '21

Can we solve problems without it?

You don't need much to make a language that can (theoretically, and in an impractical way) solve any problem that a more conventional language can. There are designs for computers with a single instruction, for example. There are other esoteric languages that define a small handful of instructions (fewer than 10). Basically, instructions to select a data cell to modify, how to modify them, do input and output, some kind of looping construct, and some kind of conditional evaluation.

Going back to the core question: Why have those things if we technically don't need them? Basically because we can represent our thoughts more effectively with carefully-chosen abstractions. It's easier for the author to encode the calculations that they need to occur, and also easier for a someone else later on to understand. The programmer doesn't only want to efficiently specify what they want done, they also want to give some clues about their intentions because it makes the code easier to reason about.

So, for example, you can have a construct like if condition, then goto location (which itself is usually about 1-2 CPU instructions). It can represent a loop, a single conditional, branching conditional, function call, a jump to an arbitrary position in code, and so on. Those are all situations that it's useful to the programmer to differentiate between, because it shapes their assumptions about what the code is trying to do.

Even beyond that, it gives the compiler or interpreter hints about what is being done, which they can sometimes use to apply optimizations (for example, unrolling a for loop, precalculating values that are known to be constant, inlining functions to reduce function call overhead, and others).

It's basically the choice between handing a road worker a hammer and a chisel to tear up the road, or handing them a jackhammer. They're both technically capable of the same job, but one of them is a much more powerful tool.

1

u/brych_ant Feb 19 '21

Thanks!!

2

u/david-chaves Feb 19 '21

The ancient programming language APL had none of them: no "if"s and no loops. APL does everything compounding matrix operations.

People say that APL is a write-only language: once you write a line in it, you won't be able to read or understand it years later. Therefore, I think that "if"s and loops are just mental tools to make us easier to "think" algorithms.

See https://en.wikipedia.org/wiki/APL_syntax_and_symbols

1

u/brych_ant Feb 19 '21

That is very interesting, I will take a look, thanks!!

2

u/adamnemecek Feb 19 '21

You might be interested in one instruction set computers

1

u/brych_ant Feb 19 '21

Thanks, I will check it out!

1

u/Felicia_Svilling Feb 19 '21 edited Feb 19 '21

I would like to know if we can solve every problem with a programming language's default

Yes, but it is actually easier to show it the other way around.

Why does a language have an if statement, loops, for exemple? Can we solve problems without it?

Yes, you can solve any mathemical problem with just recursive functions, as Alonzo Church proved by his paper on Lambda Calculus.

By extension you can also solve them with loops and if statements. Just create a big loop and use if statements inside to dispatch on the code for the various functions you want to call, with each loop representing one function call.

So why do we loops and if statements in imperative languages? Well originally we had goto, but Edgar Djikistra considered them harmful so we limited people to just using loops and conditions.

2

u/brych_ant Feb 19 '21

Interesting, thanks for your reply!

1

u/Miitch__ Feb 19 '21

I'd say only if statement (or some other boolean condition) is necessary in languages. Many languages do fine even without while or for loops. For example Haskell doesn't have while or for loops and only uses recursive calls to achieve some kind of loop.

0

u/MirrorLake Feb 19 '21 edited Feb 19 '21

I'm not nearly articulate enough to hold this discussion, however, these are some snippets from Wikipedia that are relevant to the question.

Gödel's incompleteness theorems

The first incompleteness theorem states that no consistent system of axioms whose theorems can be listed by an effective procedure (i.e., an algorithm) is capable of proving all truths about the arithmetic of natural numbers. For any such consistent formal system, there will always be statements about natural numbers that are true, but that are unprovable within the system. The second incompleteness theorem, an extension of the first, shows that the system cannot demonstrate its own consistency.

[Turing completeness] (https://en.wikipedia.org/wiki/Turing_completeness)

Computability theory characterizes problems as having, or not having, computational solutions. The first result of computability theory is that there exist problems for which it is impossible to predict what a (Turing-complete) system will do over an arbitrarily long time.

The classic example is the halting problem: create an algorithm that takes as input a program in some Turing-complete language and some data to be fed to that program, and determines whether the program, operating on the input, will eventually stop or will continue forever. It is trivial to create an algorithm that can do this for some inputs, but impossible to do this in general. For any characteristic of the program's eventual output, it is impossible to determine whether this characteristic will hold.

Turing machine

The Turing machine is capable of processing an unrestricted grammar, which further implies that it is capable of robustly evaluating first-order logic in an infinite number of ways. This is famously demonstrated through lambda calculus.

1

u/brych_ant Feb 19 '21

Thanks for your reply!

2

u/MirrorLake Feb 19 '21

It's a great question. For more details, also check out chapter 8 of "Automata Theory" by Hopcroft or chapter 6 of "Introduction to the Theory of Computation" by Sipser for a bit more depth, although experience from a discrete mathematics course is probably helpful first.