473,396 Members | 1,938 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Calculator

Hello,

I wanna make a calculator where i can give the input in one word. for
example : (15*3) / (2+3)
I think i most read this in as a string and then share it in different parts
to do the calculation. But i don't now how tho start with it. Can somebody
help me.

Thanks in advanced.
Nov 14 '05 #1
58 4042

Flipke wrote:
Hello,

I wanna make a calculator where i can give the input in one word. for
example : (15*3) / (2+3)
I think i most read this in as a string and then share it in different parts to do the calculation. But i don't now how tho start with it. Can somebody help me.

Thanks in advanced.


You might ask your teaching assistant/professor for some hints on how
to get started on your homework.

You could also google for "recursive descent parser", that being a
standard approach for this sort of problem. K&R also has an
calculator, though
their example program uses RPN.

-David

Nov 14 '05 #2

"Flipke" <am**********@hotmail.com> wrote in message
news:ld********************@scarlet.biz...
Hello,

I wanna make a calculator where i can give the input in one word. for
example : (15*3) / (2+3)
I think i most read this in as a string and then share it in different
parts
to do the calculation.
Yes, 'divide and conquer' is a good practice in programming.
But i don't now how tho start with it.
First, as you said, read the input. The next step
is to parse it into meaningful segments (e.g. (15 * 3),
15, etc.). You'll need to keep track of the parentheses
in order to implement the correct precedence of the
arithmetic operations. A recursive approach is the most
common approach to this kind of problem.

Can somebody
help me.


Yes, but we need something to help you with. Nobody will
write it for you. Show the code of your best attempt, and
ask specific questions.

-Mike
Nov 14 '05 #3
Flipke wrote:

Hello,

I wanna make a calculator where i can give the input in one word. for
example : (15*3) / (2+3)
I think i most read this in as a string and then share it in different parts
to do the calculation. But i don't now how tho start with it. Can somebody
help me.

Thanks in advanced.


Have a look at Kruse, "Data Structures and Program Design". He shows how
to develop a simple formula evaluator. IIRC he uses a parse tree rather
than recursive descent. His original version used Pascal, but that's close
enough to C to translate. Or you might look at a more recent edition--
I think he has ceased fighting the inevitable and now uses C or C++ as his
illustration language.
--
Julian V. Noble
Professor Emeritus of Physics
jv*@lessspamformother.virginia.edu
^^^^^^^^^^^^^^^^^^
http://galileo.phys.virginia.edu/~jvn/

"For there was never yet philosopher that could endure the
toothache patiently."

-- Wm. Shakespeare, Much Ado about Nothing. Act v. Sc. 1.
Nov 14 '05 #4


Flipke wrote:
Hello,

I wanna make a calculator where i can give the input in one word. for
example : (15*3) / (2+3)
I think i most read this in as a string and then share it in different parts
to do the calculation. But i don't now how tho start with it. Can somebody
help me.

Thanks in advanced.


As I recall in data structures you can use stacks to convert it to RPN, then
push that on to 2 stacks to calculate it.
BTW the question is off topic.
Nov 14 '05 #5
"Julian V. Noble" writes:
Flipke wrote:

Hello,

I wanna make a calculator where i can give the input in one word. for
example : (15*3) / (2+3)
I think i most read this in as a string and then share it in different
parts
to do the calculation. But i don't now how tho start with it. Can
somebody
help me.

Thanks in advanced.


Have a look at Kruse, "Data Structures and Program Design". He shows how
to develop a simple formula evaluator. IIRC he uses a parse tree rather
than recursive descent. His original version used Pascal, but that's close
enough to C to translate. Or you might look at a more recent edition--
I think he has ceased fighting the inevitable and now uses C or C++ as his
illustration language.


Just out of curiosity I looked up the C/C++ version of the Kruse book on
Amazon to read the reviews. I have never seen such a collection of hateful
reviews of a book! I don't think it is possible to "salt" Amazon without a
great deal of effort so the book is likely despised by these people (31),
mostly students. As I understand it, he uses STL to explain data structures
which seems like a bad approach to me. A data structures class should be
*writing* STL , not *using* it. In any event I simply must see a copy of
this book. AFAIK there is no ACCU review.

Back to the OPs question. My guess is that most of the answers are too
high falutin' for what he is expected to do. If this is a first semester
class, surely the instructor doesn't expect him to get into recursive
descent parsers and all that stuff. I would expect a student in a later
course to phrase the question differently. And there is also the slim
possibility that it isn't a student problem at all.
Nov 14 '05 #6

Flipke wrote:
Hello,

I wanna make a calculator where i can give the input in one word. for
example : (15*3) / (2+3)
It's an expression, not a word. (note an expression is a collection of
operands and operators, or in some cases only operand(s))
I think i most read this in as a string and then share it in different parts to do the calculation. But i don't now how tho start with it. Can somebody help me. Break the problem down. I recommend writing a simple RPN calculator
first, because it's the easiest.
Thanks in advanced.


Nov 14 '05 #7
In article <3e************@individual.net>,
osmium <r1********@comcast.net> wrote:
Just out of curiosity I looked up the C/C++ version of the Kruse book on
Amazon to read the reviews. I have never seen such a collection of hateful
reviews of a book! I don't think it is possible to "salt" Amazon without a
great deal of effort so the book is likely despised by these people (31),
mostly students.


There was a scandal not long ago in which it turned out that
a bunch of Amazon "reviewers" were the authors themselves -- and
sometimes more than one "review" of their own books. "Salting" Amazon
is, then, perhaps a bit easier than you might expected.
[NB, I know nothing about the merits of the book in question.]
--
"No one has the right to destroy another person's belief by
demanding empirical evidence." -- Ann Landers
Nov 14 '05 #8

"Flipke" <am**********@hotmail.com> wrote

I wanna make a calculator where i can give the input in one word. for
example : (15*3) / (2+3)
I think i most read this in as a string and then share it in different
parts
to do the calculation. But i don't now how tho start with it. Can somebody
help me.

To write a parser, firstly many of the rules of good programming don't apply
to parsers.
Normally the caller should ensure that the input is valid. For a parser, the
caller cannot do this without without writing another parser himself. So you
have to be very careful about handling errors.
Normally you should not have mutually recursive functions. For a parser,
this structure is natural.
Normally you should not have global variables. A parser is one place where
code is often neater if you do use globals.

How do you do it? The basic principle is that when you hit a bracket, you
call the top-level function on the contents. This is why parsers are
mutually recursive.

Arithmetical expressions have the bodmas (brackets, of, divide, multiply,
add, subtract) rule.

What you want to do is declare a global pointer to input so far. Then you
write a function called gettoken() which returns the token (number,
operator, parentheses) in the input stream, but does not remove it. Then
write a function called match() which discards the token from the stream,
but only if it is of the type passed. Otherwise it flags an error.

Then write three functions, expression(), term() and factor(). A factor is
either a raw number or an open parenthesis containing an expression
(recursion). A term is either a raw factor, or a series of factos connected
by divides and multiplies. An expression is either a raw term, or a series
of terms connected by additions and subtractions.

Once you have all this working, you basically have your calculator. It is
quite hard, so post your attempt if you get stuck.
Nov 14 '05 #9
In article <d5**********@nwrdmz03.dmz.ncs.ea.ibs-infra.bt.com>,
Malcolm <re*******@btinternet.com> wrote:
To write a parser, firstly many of the rules of good programming don't apply
to parsers. Normally the caller should ensure that the input is valid.
[Good] programs are full of "validate" functions which don't know if
their input is valid until they look at it.

A database "find and lock" (to avoid race conditions) routine won't
know whether the input field is a match until it does the search.

It's normal defensive programming to assume that the input might not
be valid and to protect against such cases. Think of all the verbage
about how strcpy() is a fault in the design of C and it becomes clear
that it's often a bad idea to -assume- that all necessary checks
have been done before a routine is called.
Normally you should not have mutually recursive functions.
Sez who? ;-)

The difficulty with mutually recursive functions is in the possibility
of indefinite stack space usage. The alternative to recursive functions
is to write the equivilent iterative function -- but the equivilent
iterative function will often need indefinite memory allocation
and so suffer the same fate [except that you can detect failed
memory allocation but you can't detect whether there's enough room
to call any particular function.]
Normally you should not have global variables.


Ah? This is comp.lang.c . The operation of fopen() and kin use
global variables almost by definition, and there's no other I/O
operators available, so compliant hosted programs will almost always
use global variables.
--
"No one has the right to destroy another person's belief by
demanding empirical evidence." -- Ann Landers
Nov 14 '05 #10
In article <d5**********@canopus.cc.umanitoba.ca>,
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote:
In article <d5**********@nwrdmz03.dmz.ncs.ea.ibs-infra.bt.com>,
Malcolm <re*******@btinternet.com> wrote:

Normally you should not have global variables.


Ah? This is comp.lang.c . The operation of fopen() and kin use
global variables almost by definition, and there's no other I/O
operators available, so compliant hosted programs will almost always
use global variables.


How's that? I can store a FILE * in any number of ways, none of which
require global variables.

If you're saying that stdin, stdout, and stderr are globals, what does
it matter?

Cheers,
- jonathan
Nov 14 '05 #11
Jonathan Adams <jw*****@gmail.com> writes:
In article <d5**********@canopus.cc.umanitoba.ca>,
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote:
In article <d5**********@nwrdmz03.dmz.ncs.ea.ibs-infra.bt.com>,
Malcolm <re*******@btinternet.com> wrote:
>
>Normally you should not have global variables.
Ah? This is comp.lang.c . The operation of fopen() and kin use
global variables almost by definition, and there's no other I/O
operators available, so compliant hosted programs will almost always
use global variables.


How's that? I can store a FILE * in any number of ways, none of which
require global variables.


Sure but the FILE object it points to is almost certainly global.
If you're saying that stdin, stdout, and stderr are globals, what does
it matter?


I'm not sure what you're asking.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #12

"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:C8******************@newsread2.news.pas.earth link.net...

"Flipke" <am**********@hotmail.com> wrote in message
news:ld********************@scarlet.biz...
Hello,

I wanna make a calculator where i can give the input in one word. for
example : (15*3) / (2+3)
I think i most read this in as a string and then share it in different
parts
to do the calculation.
Yes, 'divide and conquer' is a good practice in programming.


No, Divide and conquer is not the solution,
the solution is tranform / convert.

(15*3) / (2+3) --> this is not the thing you need. you may divide it upto a
small level but after some stage, things would not be as easy.
Convert the problem into Reverse Polish Notation.

(15*3) / (2 + 3)
===
You differntite operations and operands,

e.g.
2+3 is written as + 2 3
3*2 + 1
should be written as
+ * 3 2 1
Add the product of 3 and 2 to one.

+ _*_3_2_ 1
+ 6 1
7
But i don't now how tho start with it.


To start with, do not use 15 , 16 ( 2 digit numbers, use 1 digit number, and
+ * - as simple operators. )

Then convert into POLISH notations.

"you need to go to *algorithms* not *lang.c*"

First, as you said, read the input. The next step
is to parse it into meaningful segments (e.g. (15 * 3),
15, etc.). You'll need to keep track of the parentheses
in order to implement the correct precedence of the
arithmetic operations. A recursive approach is the most
common approach to this kind of problem.

Can somebody
help me.


Yes, but we need something to help you with. Nobody will
write it for you. Show the code of your best attempt, and
ask specific questions.

-Mike

Purnank.
Nov 14 '05 #13
osmium wrote:

"Julian V. Noble" writes:
Have a look at Kruse, "Data Structures and Program Design". He shows how
to develop a simple formula evaluator. IIRC he uses a parse tree rather
than recursive descent. His original version used Pascal, but that's close
enough to C to translate. Or you might look at a more recent edition--
I think he has ceased fighting the inevitable and now uses C or C++ as his
illustration language.


Just out of curiosity I looked up the C/C++ version of the Kruse book on
Amazon to read the reviews. I have never seen such a collection of hateful
reviews of a book! I don't think it is possible to "salt" Amazon without a
great deal of effort so the book is likely despised by these people (31),
mostly students. As I understand it, he uses STL to explain data structures
which seems like a bad approach to me. A data structures class should be
*writing* STL , not *using* it. In any event I simply must see a copy of
this book. AFAIK there is no ACCU review.


Well, I rather liked the book and found it helpful when I first encountered
the Pascal version back in the late 1980's. I see some of the reviewers really
trashed it. Possibly the 2nd edition of the C version (revised by colaborators)
isn't as good as the original. That would come as no surprise---I can name half
a dozen texts that were first rate in their original edition and that got pro-
gressively worse with each succeeding one.

--
Julian V. Noble
Professor Emeritus of Physics
jv*@lessspamformother.virginia.edu
^^^^^^^^^^^^^^^^^^
http://galileo.phys.virginia.edu/~jvn/

"For there was never yet philosopher that could endure the
toothache patiently."

-- Wm. Shakespeare, Much Ado about Nothing. Act v. Sc. 1.
Nov 14 '05 #14
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.org> wrote:
Jonathan Adams <jw*****@gmail.com> writes:
In article <d5**********@canopus.cc.umanitoba.ca>,
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote:
In article <d5**********@nwrdmz03.dmz.ncs.ea.ibs-infra.bt.com>,
Malcolm <re*******@btinternet.com> wrote:
>
>Normally you should not have global variables.

Ah? This is comp.lang.c . The operation of fopen() and kin use
global variables almost by definition, and there's no other I/O
operators available, so compliant hosted programs will almost always
use global variables.


How's that? I can store a FILE * in any number of ways, none of which
require global variables.


Sure but the FILE object it points to is almost certainly global.


Which, if true,[1] would be an implementation detail of libc that
doesn't impact its users. The interface is all in terms of FILE
pointers.

The basic advice "Normally you should not have global variables" is
reasonably sound, if a little too black-and-white. At the very least,
global variables should be used with care.

Cheers,
- jonathan

[1] I've seen versions of libc which dynamically allocates their FILE
*s, beyond a certain point. For example, the Solaris implementation.
I'm fairly certain any reasonably modern UNIX will do so. stdin,
stdout, and stderr all have to be statically allocated, of course.
Nov 14 '05 #15
In article <jw***************************@news1nwk.sfbay.sun. com>,
Jonathan Adams <jw*****@gmail.com> wrote:
> In article <d5**********@canopus.cc.umanitoba.ca>,
> ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote: >> The operation of fopen() and kin use
>> global variables almost by definition, and there's no other I/O
>> operators available, so compliant hosted programs will almost always
>> use global variables.
stdin,
stdout, and stderr all have to be statically allocated, of course.


C89 indicates that they are "expressions" of type FILE*, so
in -theory- they could perhaps be functions that return the appropriate
address, such as an address of a static variable with file scope
instead of a global variable. I don't remember reading anything
that would -require- that globals be used for those three. On the
other hand, I don't think I have ever run into an implementation where
they weren't globals. (Hence my qualification "almost by definition".)
--
Are we *there* yet??
Nov 14 '05 #16

"Jonathan Adams" <jw*****@gmail.com> wrote

Which, if true,[1] would be an implementation detail of libc that
doesn't impact its users. The interface is all in terms of FILE
pointers.

The basic advice "Normally you should not have global variables" is
reasonably sound, if a little too black-and-white. At the very least,
global variables should be used with care.

One of the weaknesses of C is that there is no distinction between a
"function", which calculates something, and a "procedure" which does
something, i.e. interacts with hardware.
Procedures naturally contain global variables, because the computer is
attached to various shared devices. Functions don't (though malloc() is a
special case), because a function is naturally defined by its parameters.
Good design normally involves separating your functions from your
procedures.
Nov 14 '05 #17
"Malcolm" <re*******@btinternet.com> writes:
[...]
One of the weaknesses of C is that there is no distinction between a
"function", which calculates something, and a "procedure" which does
something, i.e. interacts with hardware.
Procedures naturally contain global variables, because the computer is n
attached to various shared devices. Functions don't (though malloc() is a
special case), because a function is naturally defined by its parameters.
Good design normally involves separating your functions from your
procedures.


What some languages (e.g., Pascal) call a "procedure" is simply a
function returning void in C. There's no implication that a procedure
interacts with hardware and/or refers to global variables, nor is
there any particular implication (apart from style, perhaps) that a
function doesn't. A procedure can interact only through its
parameters just as easily as a function can interact only through its
parameters and result. The only difference is that a procedure
doesn't return a value.

A trivial example:

void increment(int *n)
{
*n ++;
}

Perhaps you're using the term "procedure" to refer to some other
concept.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #18
On Wed, 11 May 2005 18:04:05 +0530, in comp.lang.c , "Purnank"
<pu**************@in.bosch.com> wrote:
Convert the problem into Reverse Polish Notation.
What on earth for? Simply write a parser (or better yet, download one
already-written and tested) , and move on.
"you need to go to *algorithms* not *lang.c*"


this is correct.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #19
"Malcolm" <re*******@btinternet.com> wrote:
"Jonathan Adams" <jw*****@gmail.com> wrote

Which, if true,[1] would be an implementation detail of libc that
doesn't impact its users. The interface is all in terms of FILE
pointers.

The basic advice "Normally you should not have global variables" is
reasonably sound, if a little too black-and-white. At the very least,
global variables should be used with care.


One of the weaknesses of C is that there is no distinction between a
"function", which calculates something, and a "procedure" which does
something, i.e. interacts with hardware.


You forget a "functure", which interacts with the hardware and then
calculates something from the result; a "fucedure", which calculates
something and then sends the result to hardware; and a "procion", which
neither interacts with hardware, nor calculates something.

Gosh. Am I dismayed at the lack of such a proliferation of routine types
in C! We must've been living in the dark ages of computing for years,
when we could have had all these separate "functions" and "procedures",
all with their own declaration types, to enliven our code! Makes me want
to bail out of C and start using ADA, that, it really does.

Richard
Nov 14 '05 #20

"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote

You forget a "functure", which interacts with the hardware and then
calculates something from the result; a "fucedure", which calculates
something and then sends the result to hardware; and a "procion", which
neither interacts with hardware, nor calculates something.

Normally you would say that a procedure can call a function, but if a
function calls a procedure then it becomes a procedure.
The whole point of the separation is to get rid of "functures" and
"procions", so that if, for instance, I want to calculate raster data from
wavelets stored in a JPEG file, the bulk of the calculation (the function)
is separate from the IO (the procedures which read the data in from the disk
drive).

I'm not sure what a "procion" would be. Can you give an example?

However of course the issue isn't open and shut - there are lots of reasons
for not introducing this distinction as a function type qualifier.
Nov 14 '05 #21
"Malcolm" <re*******@btinternet.com> writes:
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote
You forget a "functure", which interacts with the hardware and then
calculates something from the result; a "fucedure", which calculates
something and then sends the result to hardware; and a "procion", which
neither interacts with hardware, nor calculates something.

Normally you would say that a procedure can call a function, but if a
function calls a procedure then it becomes a procedure.
The whole point of the separation is to get rid of "functures" and
"procions", so that if, for instance, I want to calculate raster data from
wavelets stored in a JPEG file, the bulk of the calculation (the function)
is separate from the IO (the procedures which read the data in from the disk
drive).


Then you're making a distinction that has no relationship I can see to
the usual distinction between a "procedure" and a "function".

In Pascal, a "procedure" is a subroutine that doesn't return a result
(though it can indirectly return a result via a parameter); a
"function" is a subroutine that does return a result. Functions can
call procedures, and procedures can call functions. The C equivalent
to a Pascal procedure is a void function; the C equivalent to a Pascal
function is a non-void function. Several other languages (many of
them Pascal-based) use the same terminology.

The distinction has nothing whatsoever to do with interacting or not
interacting with hardware, and I don't know of any language that makes
such a distinction at the language level.

If you want to talk about distinguishing between subroutines that
interact with hardware vs. ones that don't, please pick different
terms.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #22
"Keith Thompson" <ks***@mib.org> wrote

Then you're making a distinction that has no relationship I can see to
the usual distinction between a "procedure" and a "function".

In Pascal, a "procedure" is a subroutine that doesn't return a result
(though it can indirectly return a result via a parameter); a
"function" is a subroutine that does return a result.

So a function calculates something - ie is a number of set of numbers that
is defined by the arguments.
A procedure doesn't calculate something, because it doesn't return anything.
So obviously it must do something if it is to have any purpose whatsoever.

However Pascal hasn't made the distinction very well, because both functions
and procedures are allowed to interact with global variables or to modify
their arguments. So you can have a procedure which is effectively a function
but just doesn't happen to return its value using function notation, or a
function whose main purpose is the side effects, and tis thus effectively a
procedure.

I think my definitions are capturing the same idea, but in a better way.
Nov 14 '05 #23
Malcolm wrote:
"Keith Thompson" <ks***@mib.org> wrote
Then you're making a distinction that has no relationship I can see to
the usual distinction between a "procedure" and a "function".

In Pascal, a "procedure" is a subroutine that doesn't return a result
(though it can indirectly return a result via a parameter); a
"function" is a subroutine that does return a result.
So a function calculates something - ie is a number of set of numbers that
is defined by the arguments.


What if the value returned is determined by by HW rather than
parameters? For example, getchar which has *no* parameters.
A procedure doesn't calculate something, because it doesn't return anything.
So obviously it must do something if it is to have any purpose whatsoever.
What about a routine the prime purpose of which is to do something, but
also returns a value? Such as putc?

What about a "procedure" the prime purpose of which is to modify it's
input parameters, such as qsort? It definitely "returns" something, i.e.
a sorted array.

I often write functions which return a value where the primary purpose
is to *do* something and the return value indicates what it did, or
whether it succeeded etc. The C *function* main being a prime example in
a lot of programs.
However Pascal hasn't made the distinction very well, because both functions
and procedures are allowed to interact with global variables or to modify
their arguments. So you can have a procedure which is effectively a function
but just doesn't happen to return its value using function notation, or a
function whose main purpose is the side effects, and tis thus effectively a
procedure.

I think my definitions are capturing the same idea, but in a better way.


If you are defining a different concept it is best to use a different
name, rather than one which already as a meaning people are familiar
with. You also need to realise that the world is not a simple place.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #24
Malcolm wrote:
"Keith Thompson" <ks***@mib.org> wrote

Then you're making a distinction that has no relationship I can see
to the usual distinction between a "procedure" and a "function".

In Pascal, a "procedure" is a subroutine that doesn't return a
result (though it can indirectly return a result via a parameter);
a "function" is a subroutine that does return a result.


So a function calculates something - ie is a number of set of
numbers that is defined by the arguments.
A procedure doesn't calculate something, because it doesn't return
anything. So obviously it must do something if it is to have any
purpose whatsoever.

However Pascal hasn't made the distinction very well, because both
functions and procedures are allowed to interact with global
variables or to modify their arguments. So you can have a procedure
which is effectively a function but just doesn't happen to return
its value using function notation, or a function whose main purpose
is the side effects, and tis thus effectively a procedure.


Hardware, globals, modifying arguments have nothing to do with it.
The essential difference is that a function returns a value, and
can be embedded in an expression. A procedure performs actions,
and cannot be embedded in an expression.

x = 1 + 2 * f(g);

is a use of the function f, while

x = 1 + 2 * p(g);

is invalid syntax with the procedure p. For C, a procedure is a
void function. In Pascal the returned value of a function must be
used (but can be deposited in a junk variable).

--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Nov 14 '05 #25
Flash Gordon wrote:
.... snip ...
What if the value returned is determined by by HW rather than
parameters? For example, getchar which has *no* parameters.


But it does have parameters, namely the global value of stdin. The
parameters just happen to be hidden from the casual user. You can
affect that global value (and thus the action of getchar) by
redirecting the programs input stream.

--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Nov 14 '05 #26
In article <42***************@yahoo.com>,
CBFalconer <cb********@worldnet.att.net> wrote:
Hardware, globals, modifying arguments have nothing to do with it.
The essential difference is that a function returns a value, and
can be embedded in an expression. A procedure performs actions,
and cannot be embedded in an expression.

#include <stdio.h>

void myproc(int param) {
printf( "myproc: %d\n", param );
}

int main(void) {
int rez;
rez = (myproc(7), 42);
printf( "main: %d\n", rez );
return 0;
}
The comma operator is part of an expression.
--
'The short version of what Walter said is "You have asked a question
which has no useful answer, please reconsider the nature of the
problem you wish to solve".' -- Tony Mantler
Nov 14 '05 #27

"Flash Gordon" <sp**@flash-gordon.me.uk> wrote
..
So a function calculates something - ie is a number of set of numbers
that is defined by the arguments.
What if the value returned is determined by by HW rather than parameters?
For example, getchar which has *no* parameters.

Exactly. sqrt() is obviously a function. Is "get_mouse_position()" also a
function? I'm saying it is not, it is a procedure.
What about a routine the prime purpose of which is to do something, but
also returns a value? Such as putc?

What about a "procedure" the prime purpose of which is to modify it's
input parameters, such as qsort? It definitely "returns" something, i.e. a
sorted array.
Exactly. The designers of Pascal were trying to express the difference
between a function and a procedure, but did't do so in a way that is useful
to the programmer.
Ideally a function would not be allowed to alter its arguments. So qsort
would be

void *qsort(const void *array ... etc)

taking an array as input and returning a sorted array. However efficiency
considerations preclude this. I often write functions which return a value where the primary purpose is
to *do* something and the return value indicates what it did, or whether
it succeeded etc. The C *function* main being a prime example in a lot of
programs.

So it doesn't actually make sense to say that a procedure cannot return a
value. Writing an image to disk is basically output, for example, but you
have to input the amount of free space left on the drive.

If you are defining a different concept it is best to use a different
name, rather than one which already as a meaning people are familiar with.
You also need to realise that the world is not a simple place.

We can't really surrender the term "function" to ANSI. Essentially I am
using the same concept as Pascal, but defining it in a better way.
Most good ideas are inherently simple, but the implications are not
necessarily simple. I don't think anyone apart from you is accusing me of
being simplistic here, though I might be wrong.
Nov 14 '05 #28

"CBFalconer" <cb********@yahoo.com> wrote
Hardware, globals, modifying arguments have nothing to do with it.
The essential difference is that a function returns a value, and
can be embedded in an expression. A procedure performs actions,
and cannot be embedded in an expression.

That's a good point. The Pascal distinction is useful to the compiler
writer. My definition is useful to the programmer.
Nov 14 '05 #29
>Malcolm wrote:
So a function calculates something - ie is a number of set of
numbers that is defined by the arguments.
A procedure doesn't calculate something, because it doesn't return
anything. So obviously it must do something if it is to have any
purpose whatsoever.
[snippage]

In article <42***************@yahoo.com>
CBFalconer <cb********@worldnet.att.net> wrote:Hardware, globals, modifying arguments have nothing to do with it.
The essential difference is that a function returns a value, and
can be embedded in an expression. A procedure performs actions,
and cannot be embedded in an expression.


I think this is not quite what Malcolm is trying to express.

In compiler circles, the idea I think he has in mind is usually
referred to as a "pure" function. A pure function is one whose
outputs depend only on its (obvious) inputs; it has no side effects.
Examples of such functions include the usual mathematical functions.
Of course their implementations in Standard C are not actually
pure, because of their behavior when invoked with out-of-range
arguments; but if we were to ignore this, we could, for instance,
take something like:

for (i = 0; i < n; i++)
a[i] = b[i] * asin(x);

and compile it as:

temp = asin(x);
for (i = 0; i < n; i++)
a[i] = b[i] * temp;

and thus call asin(x) exactly once, regardless of the value of n
(which could even be <= 0).

C compilers cannot (usually) make this optimization. The reason
is that asin(x) is not actually a pure function. Consider what
happens if the code fragment above is entered with x set to 3.14159
and n set to 0. If the compiler does call asin(x), the asin()
function will generally set errno to EDOM, which is not permitted
in Standard C. (Not in this particular case, with n==0, that is.
On the other hand, x>1.0 but n==7, a Standard C system *should*
set errno to EDOM. But note that C99 says that whether errno
becomes EDOM is implementation-defined.)

(Fortunately, a sufficiently clever C compiler can still optimize the
above -- it merely needs to test for n>0 before setting the temporary.)

A pure function can always be called any number of times (including
zero or some infinite number) without changing any program state.
Something that is not a pure function -- which, in the general
case, covers everything you can write in C or Pascal or indeed many
other languages -- cannot. There are a few languages, such as ML,
in which *everything* is a pure function, i.e., there is no such
thing as "state". Of course, "producing output" is usually an
irreversible change of state, so programs written in such languages
can never produce output either. This makes them useless -- which
means there is invariably some sort of exception to the "no state"
rule. In the purest of these languages, the sole exception is that
a complete program produces output in the form of a function return
value. Most of them have a slightly-less-pure mode, such as an
interactive command line, as well.

C tends to go quite far in the other direction: almost everything
one does in C, one does with side effects.

Incidentally, note that a random number generator function (whether
pseudo-random or really, truly random) is never a "pure" function.
Thus, any language that includes a random number function is not
"mathematically pure".
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #30
Malcolm wrote:
"Flash Gordon" <sp**@flash-gordon.me.uk> wrote
So a function calculates something - ie is a number of set of numbers
that is defined by the arguments.
What if the value returned is determined by by HW rather than parameters?
For example, getchar which has *no* parameters.


Exactly. sqrt() is obviously a function. Is "get_mouse_position()" also a
function? I'm saying it is not, it is a procedure.


Well, you are flying in the face of normal usage.
What about a routine the prime purpose of which is to do something, but
also returns a value? Such as putc?

What about a "procedure" the prime purpose of which is to modify it's
input parameters, such as qsort? It definitely "returns" something, i.e. a
sorted array.


Exactly. The designers of Pascal


Wirth is only one person.
were trying to express the difference
between a function and a procedure, but did't do so in a way that is useful
to the programmer.
I don't see that there is any major problem, although I did only spend a
few years writing SW in Pascal.
Ideally a function would not be allowed to alter its arguments. So qsort
would be

void *qsort(const void *array ... etc)

taking an array as input and returning a sorted array. However efficiency
considerations preclude this.
So your definitions are not useful in the real world. That makes them
rather less useful than the definitions in Pascal.
I often write functions which return a value where the primary purpose is
to *do* something and the return value indicates what it did, or whether
it succeeded etc. The C *function* main being a prime example in a lot of
programs.


So it doesn't actually make sense to say that a procedure cannot return a
value. Writing an image to disk is basically output, for example, but you
have to input the amount of free space left on the drive.


So functions cannot modify their parameters and return a value.
Procedures, on the other hand, can't modify their parameters and can
return a value. It does not sound like a very useful definition of
function and procedure to me.
If you are defining a different concept it is best to use a different
name, rather than one which already as a meaning people are familiar with.
You also need to realise that the world is not a simple place.


We can't really surrender the term "function" to ANSI.


Every where else I've come across the terms function and procedure in
computing as distinct items, a function is something that returns a
value and a procedure is something that doesn't. Languages which only
have things which return a value call them functions.
Essentially I am
using the same concept as Pascal, but defining it in a better way.
Most good ideas are inherently simple, but the implications are not
necessarily simple. I don't think anyone apart from you is accusing me of
being simplistic here, though I might be wrong.


As far as I can see your definition's can be implemented in C (as much
as they can in any language) with the following:

#define procedure
#define function

Then you can do things like:

procedure void my_procedure(int);
procedure int my_procedure_returning_int(int);
function int my_function(int);

So I can't see the use of your definition. As far as I can see the
definitions in Pascal and other languages are more useful.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #31
CBFalconer wrote:
Flash Gordon wrote:

... snip ...
What if the value returned is determined by by HW rather than
parameters? For example, getchar which has *no* parameters.

But it does have parameters, namely the global value of stdin. The
parameters just happen to be hidden from the casual user. You can
affect that global value (and thus the action of getchar) by
redirecting the programs input stream.


How would one programmatically affect the value of stdin? It is usually
#define'd as the address of a FILE structure long before run time.

You're all spinning your wheels on this procedure vs function stuff.
There is no procedure in C. Our subroutines are all functions.

In a free country, you can call a void function a procedure if you want
to. You can also call it a streetcar if you want to.

--
Joe Wright mailto:jo********@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #32
CBFalconer <cb********@yahoo.com> writes:
Flash Gordon wrote:

... snip ...

What if the value returned is determined by by HW rather than
parameters? For example, getchar which has *no* parameters.


But it does have parameters, namely the global value of stdin. The
parameters just happen to be hidden from the casual user. You can
affect that global value (and thus the action of getchar) by
redirecting the programs input stream.


This must be some new meaning of the word "parameters" that I was
previously unaware of.

Yes, anything that affects the behavior of a routine can loosely be
considered to be a parameter, but the word specifically refers to the
stuff between the parentheses in the declaration. Since we're
discussing the misuse of well-known terms ("procedure" and "function"
to refer to odd concepts, it's a fairly important point.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #33
"Malcolm" <re*******@btinternet.com> writes:
"Flash Gordon" <sp**@flash-gordon.me.uk> wrote

[...]
What about a "procedure" the prime purpose of which is to modify it's
input parameters, such as qsort? It definitely "returns" something, i.e. a
sorted array.

Exactly. The designers of Pascal were trying to express the difference
between a function and a procedure, but did't do so in a way that is useful
to the programmer.


No, they did it in a way that's extremely useful to the programmer; I
certainly found it so back when I was a Pascal programmer. A function
directly returns a result, and a function call can occur as part of an
expression. A procedure does not return a result, and a procedure
call can appear only as a statement. (C, of course, doesn't make
quite the same distinction between void and non-void functions.)

In my (perhaps somewhat limited) experience, these meanings of the
terms "procedure" and "function" are nearly universal.

[...]
If you are defining a different concept it is best to use a different
name, rather than one which already as a meaning people are familiar with.
You also need to realise that the world is not a simple place.

We can't really surrender the term "function" to ANSI. Essentially I am
using the same concept as Pascal, but defining it in a better way.


No, you're not. You're using the same terms that Pascal uses, but
you're assigning different meanings to them.

I'm not just talking about ANSI. I'm talking about the nearly
universal usage of the terms "procedure" and "function" over the past
several decades.

There is a related concept that may be close to what you're talking
about: a "pure" function. A pure function, loosely, is one that
computes a result using only its explicit parameters; it doesn't refer
to any global variables, none of its local variables are "static" in
the C sense, it has no side effects. The mathematical functions are
examples of this; time() is not, since it refers to an implicit
global. If an optimizer sees two calls to a pure function with the
same arguments, it can safely replace them with a single call.

Neither Pascal nor C makes any language-level distinction between
"pure" functions and other functions. (Ada does, if I recall
correctly.)

Note that the distinction involves side effects and global variables.
There's no mention of hardware. *All* code interacts with hardware,
at least with memory and the CPU.

Again, if you're going to make distinctions like this, *please* pick
terms other than "procedure" and "function". We know what they mean,
and it's not what you think they mean.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #34
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <42***************@yahoo.com>,
CBFalconer <cb********@worldnet.att.net> wrote:
Hardware, globals, modifying arguments have nothing to do with it.
The essential difference is that a function returns a value, and
can be embedded in an expression. A procedure performs actions,
and cannot be embedded in an expression.

#include <stdio.h>

void myproc(int param) {
printf( "myproc: %d\n", param );
}

int main(void) {
int rez;
rez = (myproc(7), 42);
printf( "main: %d\n", rez );
return 0;
}
The comma operator is part of an expression.


Right. That's because myproc() is a function. C doesn't have
"procedures" in the Pascal sense; void functions are the nearest
equivalent, but there are differences.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #35
"Malcolm" <re*******@btinternet.com> writes:
"CBFalconer" <cb********@yahoo.com> wrote
Hardware, globals, modifying arguments have nothing to do with it.
The essential difference is that a function returns a value, and
can be embedded in an expression. A procedure performs actions,
and cannot be embedded in an expression.

That's a good point. The Pascal distinction is useful to the compiler
writer. My definition is useful to the programmer.


The Pascal distinction is equally useful to the programmer.

If you can specify just what distinction you're making *without*
misapplying the terms "procedure" and "function", I might be able to
decide whether your definition would be useful to programmers.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #36

"Keith Thompson" <ks***@mib.org> wrote
Again, if you're going to make distinctions like this, *please* pick
terms other than "procedure" and "function". We know what they mean,
and it's not what you think they mean.

I see what you are saying.

I think that if some silly committe that can't even come up with a language
definition that anyone wants to adopt uses the term "function", their
definition can't affect the way we use the word.

A function is something that returns a result based on a set of arguments.
The mathematical definiton goes into the "domain" in which it is defined.

So a function cannot take any action, it cannot do anything. If a piece of
code does something, it isn't a function, it is something else. The obvious
word to choose for this is "procedure".

However I do accept that the Pascal definition is in a sense a purely
syntactical one, and there is room for confusion by redefining the terms.
The problem is that the line between modifying an argument or global and
interacting with hardware is a loose one. If you write to memory-mapped
screen, is this "interacting with hardware?". What if the progrma is the
same but the monitor isn't physically attached?.

If a Pacal procedure neither modifies its arguments nor modifies globals nor
interacts with hardware, what exactly is it doing (sleep maybe)?

Can't you see that my definition essentially expresses the same idea?
Nov 14 '05 #37
"Malcolm" <re*******@btinternet.com> writes:
"Keith Thompson" <ks***@mib.org> wrote
Again, if you're going to make distinctions like this, *please* pick
terms other than "procedure" and "function". We know what they mean,
and it's not what you think they mean.
I see what you are saying.


I don't think you do.
I think that if some silly committe that can't even come up with a language
definition that anyone wants to adopt uses the term "function", their
definition can't affect the way we use the word.
So you're blaming the ISO C committee for their use of the word
"function". That's not what we're talking about here. We're talking
about the consistent common use of the terms "function" and
"procedure" in the programming community for the last several decades.
It is not an arbitrary invention of the committee; it's de facto
standard terminology that probably predates the C language.

That means this discussion is arguably off-topic here, except that
something *might* come out of it that could be useful in C
programming. For example, an implementation-defined #pragma might be
used to assert that a function is "pure". The compiler can use this
information to perform certain optimizations, and to diagnose
operations within the function that make it "impure". Such a #pragma
might even be included in a future version of the standard.

That might be a useful discussion to have here, but only if we're able
to discuss it coherently.
A function is something that returns a result based on a set of arguments.
The mathematical definiton goes into the "domain" in which it is defined.
That's a mathematical function. In programming terms, it's sometimes
referred to as a "pure" function. Not all functions (in the
programming sense) are "pure".
So a function cannot take any action, it cannot do anything. If a piece of
code does something, it isn't a function, it is something else. The obvious
word to choose for this is "procedure".

However I do accept that the Pascal definition is in a sense a purely
syntactical one, and there is room for confusion by redefining the terms.
There's no room for anything other than confusion.
The problem is that the line between modifying an argument or global and
interacting with hardware is a loose one. If you write to memory-mapped
screen, is this "interacting with hardware?". What if the progrma is the
same but the monitor isn't physically attached?.

If a Pacal procedure neither modifies its arguments nor modifies globals nor
interacts with hardware, what exactly is it doing (sleep maybe)?

Can't you see that my definition essentially expresses the same idea?


No. A function that modifies its arguments, modifies global
variables, and interacts with hardware is a function. It's not a
mathematically pure function, but we're discussing software here, not
(just) pure mathematics.

Once again, the usage of the terms "function" and "procedure" is well
established.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #38
Keith Thompson wrote:
CBFalconer <cb********@yahoo.com> writes:
Flash Gordon wrote:

... snip ...

What if the value returned is determined by by HW rather than
parameters? For example, getchar which has *no* parameters.


But it does have parameters, namely the global value of stdin.
The parameters just happen to be hidden from the casual user.
You can affect that global value (and thus the action of getchar)
by redirecting the programs input stream.


This must be some new meaning of the word "parameters" that I was
previously unaware of.

Yes, anything that affects the behavior of a routine can loosely
be considered to be a parameter, but the word specifically refers
to the stuff between the parentheses in the declaration. Since
we're discussing the misuse of well-known terms ("procedure" and
"function" to refer to odd concepts, it's a fairly important point.


You never had to use old-fashioned Cobol, did you? The closest
thing to a function or procedure is 'perform', and there is no
parameter passing mechanism whatsoever. So you create some global
variables for the use of the performed paragraph, stuff values in
them, and use self discipline to not use them for other purposes.
This way it is possible to create fairly cleanly structured code.

--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Nov 14 '05 #39
CBFalconer <cb********@yahoo.com> writes:
Keith Thompson wrote:
CBFalconer <cb********@yahoo.com> writes:
Flash Gordon wrote:

... snip ...

What if the value returned is determined by by HW rather than
parameters? For example, getchar which has *no* parameters.

But it does have parameters, namely the global value of stdin.
The parameters just happen to be hidden from the casual user.
You can affect that global value (and thus the action of getchar)
by redirecting the programs input stream.


This must be some new meaning of the word "parameters" that I was
previously unaware of.

Yes, anything that affects the behavior of a routine can loosely
be considered to be a parameter, but the word specifically refers
to the stuff between the parentheses in the declaration. Since
we're discussing the misuse of well-known terms ("procedure" and
"function" to refer to odd concepts, it's a fairly important point.


You never had to use old-fashioned Cobol, did you? The closest
thing to a function or procedure is 'perform', and there is no
parameter passing mechanism whatsoever. So you create some global
variables for the use of the performed paragraph, stuff values in
them, and use self discipline to not use them for other purposes.
This way it is possible to create fairly cleanly structured code.


Sure, you can emulate parameter passing in a language that doesn't
provide it. My only point was about the use of the term "parameter"
in a newsgroup that discuss a language whose standard has a very
specific definition of the term. Flash Gordon clearly was referring
to "parameters" in the C sense of the term.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #40
On Sat, 14 May 2005 17:15:51 +0000 (UTC), Malcolm
<re*******@btinternet.com> wrote:
"CBFalconer" <cb********@yahoo.com> wrote
Hardware, globals, modifying arguments have nothing to do with it.
The essential difference is that a function returns a value, and
can be embedded in an expression. A procedure performs actions,
and cannot be embedded in an expression.

That's a good point. The Pascal distinction is useful to the compiler
writer. My definition is useful to the programmer.


Your definition is useful to no one (unless you like talking to
yourself) because everyone else already knows what the word means in the
context of programming, and has done for the last 35 years or more (IIRC
the terms 'procedure' and 'function' were around before Pascal was
created in 1968, possibly in ALGOL-60).

(I recall someone published a political essay where they defined 'right'
and 'left' the opposite way round. It was perfectly legitimate, because
they defined their terms, but also totally useless...)

Pick some different words if you want to create different concepts...

Chris C
Nov 14 '05 #41

"Chris Croughton" <ch***@keristor.net> wrote

Pick some different words if you want to create different concepts...

If you can show that the concepts are different, the of course I would do
so. But that's what is in dispute.
Nov 14 '05 #42
"Malcolm" <re*******@btinternet.com> writes:
"Chris Croughton" <ch***@keristor.net> wrote

Pick some different words if you want to create different concepts...

If you can show that the concepts are different, the of course I would do
so. But that's what is in dispute.


I don't know why there's any dispute.

function foo(x: integer) return integer;
begin
talk_to_some_hardware_device(x);
foo := query_some_hardware_device;
end;

Pascal calls this a function. You don't. QED.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #43
On Sun, 15 May 2005 01:03:17 +0000 (UTC), Malcolm
<re*******@btinternet.com> wrote:
"Chris Croughton" <ch***@keristor.net> wrote

Pick some different words if you want to create different concepts...
If you can show that the concepts are different, the of course I would do
so. But that's what is in dispute.


You say:
One of the weaknesses of C is that there is no distinction between a
"function", which calculates something, and a "procedure" which does
something, i.e. interacts with hardware.
Everyone else says "if it returns a value then it's a function, if not
then it's a procedure", nothing whatever to do with "interacting with
hardware" (which every program does anyway; perhaps you mean "interacts
with peripherals").

You also say:
Procedures naturally contain global variables, because the computer is
attached to various shared devices. Functions don't (though malloc() is a
special case), because a function is naturally defined by its parameters.


Again, this is not true of the way the words have been used in the last
30+ years, Pascal (and Algol, and Modula, etc.) procedures need not do
anything with global variables at all (they can return output through
their parameters), and functions can happily make use of global
variables.

Your use of the words is not the same as the traditional interpretation.
Your quoted statements only make sense by your definitions of the words,
they make no sense at all using the traditional definitions.

Chris C
Nov 14 '05 #44

"Keith Thompson" <ks***@mib.org> wrote

I don't know why there's any dispute.

function foo(x: integer) return integer;
begin
talk_to_some_hardware_device(x);
foo := query_some_hardware_device;
end;

Pascal calls this a function. You don't. QED.

American ass:
farts
British ass
farts, eats carrots, appears in nativity scenes.

American billion
1, 000, 000, 000
British billion
1, 000, 000, 000, 000

American state:
subsidiary division of the country.
British state.
superior union of two countries, one province, and a principality.

Now case one is obviously one word which hapens to mean two different
things. As far as I know there is no etymological or other connection, apart
from one incidental point of similarity.

Case two is really confusing and a total nuisance. The concept is "the next
division up from a million", but we have defined it differently.So the
uniformed person can end up with a wildly exaggerated idea of the American
national debt.

My functions and Pascal's functions, however, are like case three. They
express the same concept "unit of territory which is sovereign" but the
definition is different. To say that the British shouldn't use the term "the
state" because it has been bagged by the USA would be ridiculous. In fact
philosphers could argue about what the rights of a "state" ought to be -
should Texas be allowed to compete in the football (example 4?) world cup,
for example?

Similarly we can agree what a "function" is in mathematics, agree that
programming functions have enough similarities to use the same word, and
then argue about exactly how to define a "function" in a way that is useful.
Which is what we are doing.
Nov 14 '05 #45
In article <d6**********@nwrdmz01.dmz.ncs.ea.ibs-infra.bt.com>,
Malcolm <re*******@btinternet.com> wrote:
Similarly we can agree what a "function" is in mathematics, agree that
programming functions have enough similarities to use the same word, and
then argue about exactly how to define a "function" in a way that is useful.
Which is what we are doing.


A "function" in mathematics is not defined by a formulae but
by a set of tuples, with the range of any one tuple member
potentially being infinitely large. There need not be any discernable
"pattern" to the tuples.

Something like f = { x -> x*x | x in integers, x from 5 to infinity }
is not the function itself but rather just a shorthand for the
function: the function is {(5, 25), (6,36), (7,49)} and so on
for all of the infinity of positive integers.

About the only programming language that I have ever encountered
which even comes close to getting this right is Maple, which allows
you to make arbitrary assignments such as f(3,-1/2,8*I) := 42
to -define- the function f at (3,-1/2,8i) .

It is clear that "function" in mathematics and "function" in C are
never going to be reconcilable, so the exercise is pointless.
The closest you would be able to get on the mathematics side
would not be "functions" but rather at most "functions which are
representable as the union of formulae applied over limited ranges".

even with that, I would be interested to see the mathematical
union-of-formulaes function corresponding to something as relatively
simple in C as "the next prime number after the whole number given as
the argument".
--
History is a pile of debris -- Laurie Anderson
Nov 14 '05 #46
Keith Thompson wrote:
CBFalconer <cb********@yahoo.com> writes:
Keith Thompson wrote:
CBFalconer <cb********@yahoo.com> writes:

Flash Gordon wrote:

... snip ...

>What if the value returned is determined by by HW rather than
>parameters? For example, getchar which has *no* parameters.

But it does have parameters, namely the global value of stdin.
The parameters just happen to be hidden from the casual user.
You can affect that global value (and thus the action of getchar)
by redirecting the programs input stream.

This must be some new meaning of the word "parameters" that I was
previously unaware of.

Yes, anything that affects the behavior of a routine can loosely
be considered to be a parameter, but the word specifically refers
to the stuff between the parentheses in the declaration. Since
we're discussing the misuse of well-known terms ("procedure" and
"function" to refer to odd concepts, it's a fairly important point.
You never had to use old-fashioned Cobol, did you?


Fortunately for me, I haven't.
The closest
thing to a function or procedure is 'perform', and there is no
parameter passing mechanism whatsoever. So you create some global
variables for the use of the performed paragraph, stuff values in
them, and use self discipline to not use them for other purposes.
This way it is possible to create fairly cleanly structured code.

I've come across SW written in assembler that way. However, it is still
accessing global variable rather than passing parameters in the
conventional sense.
Sure, you can emulate parameter passing in a language that doesn't
provide it. My only point was about the use of the term "parameter"
in a newsgroup that discuss a language whose standard has a very
specific definition of the term. Flash Gordon clearly was referring
to "parameters" in the C sense of the term.


Or the Pascal sense, or the way the term is used in other languages I've
used. I thought this was obvious. I could equally have invented some
non-portable function for reading from a piece of HW.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #47

"Chris Croughton" <ch***@keristor.net> wrote

Everyone else says "if it returns a value then it's a function, if not
then it's a procedure", nothing whatever to do with "interacting with
hardware" (which every program does anyway; perhaps you mean "interacts
with peripherals").

No, that's the subtle but confusing point.
Memory you don't own is hardware.

Let's take this bit of code.

void grey(unsigned char *rgb, int width, int height)
{
unsigned char lum;
int i;
int ii;

for(i=0;i<height;i++)
for(ii=0;ii<width;ii++)
{
lum = luminance(rgb[0], rgb[1], rgb[2]);
rgb[0] = lum;
rgb[1] = lum;
rgb[2] = lum;
rgb += 3;
}
}

is it calculating something or doing something? Normally you would say it is
calculating something - what an image would be if converted form colour to
black and white.
But let's say we have memory-mapped screen, and pass it the screen buffer.
Now it is doing something - it's painting the screen grey.

However let's say we write the function like this.

unsigned char *grey(unsigned char *rgb, int width, int height)
{
unsigned char *answer;
answer = malloc(width * height * 3);
... etc ..
return answer;
}

Now it's a function. It is definitely calculating something rather than
doing something.

But what's really important here? The important difference is whether we
pass the first function a screen buffer, in which case it hardware
dependent, or memory that is local to the calling function, in which case it
is completely portable.

Now let's say we make a slight change to the first example.

/*
Make an image greysclae
Returns: average luminance.
*/
int grey(unsigned char *rgb, int width, int height)

Now grey() is a function, on your definiton. Is this change of any
importance or real interest to the calling programmer? Is that definition
actually capturing a useful difference?

Nov 14 '05 #48
"Malcolm" <re*******@btinternet.com> writes:
"Keith Thompson" <ks***@mib.org> wrote

I don't know why there's any dispute.

function foo(x: integer) return integer;
begin
talk_to_some_hardware_device(x);
foo := query_some_hardware_device;
end;

Pascal calls this a function. You don't. QED.
[snip] My functions and Pascal's functions, however, are like case three. They
express the same concept "unit of territory which is sovereign" but the
definition is different. To say that the British shouldn't use the term "the
state" because it has been bagged by the USA would be ridiculous. In fact
philosphers could argue about what the rights of a "state" ought to be -
should Texas be allowed to compete in the football (example 4?) world cup,
for example?

Similarly we can agree what a "function" is in mathematics, agree that
programming functions have enough similarities to use the same word, and
then argue about exactly how to define a "function" in a way that is useful.
Which is what we are doing.


My followup was in response to your previous statement:

] If you can show that the concepts are different, the of course I would do
] so. But that's what is in dispute.

I understood the concepts in question to be "functions" as you use the
term, and "functions" as the term is used in, say, Pascal or any of a
number of other languages. If something is a function under one
definition of the term, and is not a function under another definition
of the term, then the two definitions refer to different concepts.

There is an ambiguity in the meaning of the term "state" between
American English and British English. There is no such ambiguity in
the meaning of the term "function" in the context of programming
languages, or at least there isn't nearly as great an ambiguity as
you're trying to create. The word is used differently in pure
mathematics; if you want to discuss that, there are several newsgroups
in the sci.math hierarchy.

Take a look at the responses in this thread. Unless I've missed
something, everyone other than you has said that the meanings of
"function" and "procedure" are already perfectly clear in the context
of programming languages, and they simply do not mean what you claim
they mean. What you're calling a "function" seems similar to what's
known as a "pure function". You may well have something important to
say about pure functions, but if you're more interested in redefining
words than in actually communicating with the rest of us, I for one am
not going to waste any more time trying to figure out what it might
be.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #49
On Sun, 15 May 2005 20:00:20 +0000 (UTC), Malcolm
<re*******@btinternet.com> wrote:
"Chris Croughton" <ch***@keristor.net> wrote

Everyone else says "if it returns a value then it's a function, if not
then it's a procedure", nothing whatever to do with "interacting with
hardware" (which every program does anyway; perhaps you mean "interacts
with peripherals").
No, that's the subtle but confusing point.
Memory you don't own is hardware.


I own all of it, I paid for it when I bought the computer. It's still
hardware. At work I don't own the compiler I use (my employer does),
but it's still software. The same for the CPU etc. Yet another
meaningless distinction and yet more redefining of words in general use.

(And if you are referring to 'own' in some memory management sense --
off-topic for c.l.c -- then it's still a meaningless distinction, as
your examples show.)
Let's take this bit of code.

void grey(unsigned char *rgb, int width, int height)
{
unsigned char lum;
int i;
int ii;

for(i=0;i<height;i++)
for(ii=0;ii<width;ii++)
{
lum = luminance(rgb[0], rgb[1], rgb[2]);
rgb[0] = lum;
rgb[1] = lum;
rgb[2] = lum;
rgb += 3;
}
}

is it calculating something or doing something? Normally you would say it is
calculating something - what an image would be if converted form colour to
black and white.
But let's say we have memory-mapped screen, and pass it the screen buffer.
Now it is doing something - it's painting the screen grey.
Yup. So by your reasoning whether it is a 'function' or a 'procedure'
depends on the parameters when it is called. How is that even vaguely
useful?

To me, it's a 'procedure' (well, it would be in Pascal, in C it's a
"function returning void" regardless of what the parameters are).
However let's say we write the function like this.

unsigned char *grey(unsigned char *rgb, int width, int height)
{
unsigned char *answer;
answer = malloc(width * height * 3);
... etc ..
return answer;
}

Now it's a function. It is definitely calculating something rather than
doing something.
But if you pass it a pointer to a memory-mapped screen then by your
reasoning it's a 'procedure' again because it's accessing 'hardware'.
But what's really important here? The important difference is whether we
pass the first function a screen buffer, in which case it hardware
dependent, or memory that is local to the calling function, in which case it
is completely portable.
So you are now defining it by how it is called. What will you call it
if sometimes it is called with a pointer to screen memory and others to
a local screen buffer?
Now let's say we make a slight change to the first example.

/*
Make an image greysclae
Returns: average luminance.
*/
int grey(unsigned char *rgb, int width, int height)

Now grey() is a function, on your definiton. Is this change of any
importance or real interest to the calling programmer? Is that definition
actually capturing a useful difference?


Yes, it is. It is caputuring a difference in how it is used, the syntax
used to call it. That is essential information when programming, if
call it in the wrong way then I can expect to either lose the result or
get a syntax error by expecting a result when there isn't one.

Whether it accesses 'hardware' (whatever that is, I might be running
over the JVM) or not is not relevant to whether it is a 'function' or a
'procedure', and as you have demonstrated the same code may access
'hardware' or not depending how it is called.

Chris C
Nov 14 '05 #50

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: mwh | last post by:
Hi. If you remember, I posted Expressons Help. Now I am making a calculator with javascript. I can't get this to work: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"...
6
by: Rafael | last post by:
Hi Everyone, I need some help with my calculator program. I need my program to do 2 arguments and a 3rd, but the 3rd with different operators. Any help would be great. Here is my code.... ...
3
by: Paul | last post by:
I want to make a simple calculator program but dont know where to get started. This is not GUI but a simple terminal program. It would get input like this Enter number: 5 + 10
3
by: Art | last post by:
Hi, In part of my application the user may need to do a simple arithmetic calculation in order to get the value to put in a text box. I was thinking that it would be good if I could display the...
3
by: PieMan2004 | last post by:
Hi, ive been looking for a solid java community to help me when im tearing out my hair :) Basically ive constructed a GUI that has to represent the same look and functions of the typical windows...
24
by: firstcustomer | last post by:
Hi, Firstly, I know NOTHING about Javascript I'm afraid, so I'm hoping that someone will be able to point me to a ready-made solution to my problem! A friend of mine (honest!) is wanting to...
19
by: TexasNewbie | last post by:
This was originally just a calculator without a decimal point. After I added the decimal, it now tells me invalid second number. //GUI Calculator Program import javax.swing.*; import...
5
Deathwing
by: Deathwing | last post by:
Hi everyone one I'm playing around with trying to make an expense calculator. I would like it so that the user can keep enter expenses until they have no more expenses. Then I would like for the...
3
by: itsmichelle | last post by:
This is a very primative code of a java swing calculator. I have assigned all the number buttons and the operator buttons and I can add, subtract, multiply, and divide two numbers together. However,...
3
by: mandy335 | last post by:
public class Calculator { private long input = 0; // current input private long result = 0; // last input/result private String lastOperator = ""; // keeps track of...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.