r/AskComputerScience • u/brych_ant • 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!
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:
Write a problem on the tape.
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), wherexmeans "any variable" andMis 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), whereMandNare 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 ofxwere replaced witha)aby β-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
whileconstruct, right?Great explanation! I really feel like it's also important to stress that these
forandwhileconstructs 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
whileconstruct, 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
whileloops 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
forandwhileconstructs 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
11
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
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
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.
1
2
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
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.
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.
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.