Teaching new tricks to an old dog (C++ -->Ada)

  • Thread starter Turamnvia Suouriviaskimatta
  • Start date
G

Georg Bauhaus

Ioannis said:
How can this be done in Ada?

The same way, using the random number generator and the
STL-like containers. (See Ada 95 for the genertors, and
AI-302 or Ada 2005 for the STL-like container library.)

Functions are passed to a passive iterator like in

...
procedure some_proc (e: int);
...
iterate(some_vec, some_proc'access);


Georg
 
G

Guest

Georg said:
Ada 2005 adds downward closures. They have been available in GNAT/GCC
for a number of years now.
For pure Ada 95 there is a workaround using dispatching.

Is a function object similar to a downward closure?

Well, I tried to google what Ada "downward closures" are but since I
don't know the language, I'm not sure I properly understood how they
work (shame on me!).

An example of using a C++ standard function object to find the index
of the first element in a vector being greater than 666 looks like

std::vector<int> vec;
...
std::vector<int>::iterator it = std::find_if(vec.begin(), vec.end(),
std::bind2nd(std::greater<int>(), 666));
if(it == vec.end())
std::cout << "Not found!\n";
else
std::cout << "Found at index " << (it - vec.begin()) << ", value =" << *it << '\n';

Of course, it would be nicer, easier and more flexible if you could write
something like (syntax totally hypothetical!):
std::vector<int>::iterator it = std::find_if(vec.begin(), vec.end(),
lambda{x; x>666} );

Adding something like this to C++ is currently under discussion / pre-study
and it is not yet clear how the result will look like...

Falk
 
I

Ioannis Vranos

Georg said:
The same way, using the random number generator and the
STL-like containers. (See Ada 95 for the genertors, and
AI-302 or Ada 2005 for the STL-like container library.)

Functions are passed to a passive iterator like in

...
procedure some_proc (e: int);
...
iterate(some_vec, some_proc'access);


Has Ada this level of abstraction and compile-time safety? (the same
code made more high-level):


#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>
#include <functional>
#include <map>
#include <iterator>


int main()
{
using namespace std;

vector<int> vec(1000);

map<int, int> iimap;

// Seeds the random number generator
srand(time(0));

// Use rand() to fill vector with values
// As you see the operation is entirely safe.
generate(vec.begin(), vec.end(), rand);


// Finds the first occurrence of an int smaller than 1000
vector<int>::iterator p= find_if(vec.begin(), vec.end(),
bind2nd(less<int>(), 1000) );

int index= distance(vec.begin(), p);

// Stores the index and the value in a map
iimap[index]= *p;


cout<<"index: "<<index<<"\tValue: "<<iimap[index]<<"\n";
}


C:\c>temp
index: 32 Value: 169

C:\c>
 
G

Georg Bauhaus

Ioannis said:
For example consider this simple bullet-proof code for string input and
processing:


#include <iostream>
#include <string>

int main()
{
using namespace std;

string s;

while(cin)
{
getline(cin,s);

/*Do things with s */;
}
}

When I run your program and have it read the null
device, it stops after reading 536870883 bytes if s.length()
is right. This number is 29 bytes less than 2^29; however,
s.max_size() is printed as 1073741820, which is 4 bytes less
than 2^30.
There is 1G of memory in the system. Is this an implementation
detail/system specific? I'm not now expecting a compiler for
any language to read past 512M, but I'd like to know what
is going on.

I noticed

size_type max_size () const
{ return (npos - 1)/sizeof (charT); } // XXX

in the header file for string, the XXX is in the original.
 
?

=?ISO-8859-1?Q?Falk_Tannh=E4user?=

Georg said:
When I run your program and have it read the null
device, it stops after reading 536870883 bytes if s.length()
is right. This number is 29 bytes less than 2^29; however,
s.max_size() is printed as 1073741820, which is 4 bytes less
than 2^30.

The program should read

#include <iostream>
#include <istream>
#include <string>

int main()
{
std::string s;
while(std::getline(std::cin, s))
{
// Do things with s
}
return 0;
}

so that the loop body is not executed after failing of getline().
However, even the original version, while reading from /dev/null,
should execute the loop only once and leave the string 's' empty
since End Of File should be detected on the first attempt to
read a character. Could it be there is something seriously wrong
with your compiler / standard library installation?

Falk
 
A

Alberto

In that case, it looks like the compiler failed to detect that shortcoming.

Well, it's time for me to join the 'American Dentist Association vs
C++' flame war:

1. Is Ada case-insensitive as Pascal? In that case, Ada==ADA

2. The C++ exception mechanism should be very similar to aDa's,
because it was inspired partially from it [1].

3. Many of you want us to believe that ADa performs ra nge checking
without loss of performance: it can be true at compile time with fixed
ranges, but it can't definitely be done without chechinkg array bounds
every time data is accessed if we don't know these bounds before
compiling (e.g.: typical cases where dynamic allocation of memory is
used)

4. Also, some people wrote that C++ is bad because it is difficult
(but not imposible, see Comeau C++) to follow 100% the Standard. The
same can be said to adA, because at least if we own a compiler of the
'83 Standard, we can't have the derivation a virtual function
mechanisms, only interfaces (pure virtual classes)[2]. To me, it
sounds reasonable to work with the last version of a compiler when
possible.

5. In fact, there are standard mechanisms (STL) to handle these array
bound checking issues with ease.

6. I don't know what's the point with "aDA being used in avionics or
rocket science". Planes and rockets are falling from the sky from time
to time; a few satellites are lost, too; NASA once failed to mix SI
units and British unit system (where's the stronger type and range
checking here?)...

Regards,

[1] "The C++ Programming Language" 3rd Special Edition, Bjarne
Stroustrup, 24.2

[2] "The C++ Programming Language" 3rd Special Edition, Bjarne
Stroustrup, 1.4

P.S.: For the next battle, I suggest comp.lang.ada vs
comp.lang.visualbasic.
 
G

Georg Bauhaus

Ioannis said:
Has Ada this level of abstraction and compile-time safety? (the same
code made more high-level):

The starting point of the aforementioned AI-302/Ada 2005 container
library is Charles, which is STL in Ada, including a rich set
of algorithms. But I don't think that a comparison of language
facilities is best served by concentrating on algorithms written
in the language to overcome some of the languages shortcomings.
That's cheating.

Notice how you use e.g. distance to work around things that
are more present in Ada than in C++ "proper". Notice also that
template metaprogramming is a lot more present in C++ than in Ada.

Now if the basis of C++ can and should be overcome as you demonstrate,
why stick to the baiss of C++ when obviously all the value is in STL?
Glad we have D at least :)

And yes, all sorts of compile time checking is done with Ada 2005
containers. Only many of the checks have to do with the Ada language
"proper". Given there is little template metaprogramming in Ada,
different things are checked at other levels.

// Use rand() to fill vector with values
// As you see the operation is entirely safe.
generate(vec.begin(), vec.end(), rand);


As an Ada example

package int_Vectors is new Ada.Containers.Vectors(C.int);
-- supplies type Vector of int, i.e. "std::vector<int>"

vec: Vector;
...
procedure rand (i: Cursor);
-- stores a random value in the element at cursor i

iterate(vec, rand'access);


I think you recognize the idiom. But we are in a sense no longer
talking about programming *languages*, this is about libraries,
so I'd rather stop here.
 
A

Adrien Plisson

Alberto said:
Well, it's time for me to join the 'American Dentist Association vs
C++' flame war:

it is "American DentAL Association", so if you want to flame, at least
flame with exactitude...
P.S.: For the next battle, I suggest comp.lang.ada vs
comp.lang.visualbasic.

this one would be very fun...
 
A

Adrien Plisson

Alberto said:
6. I don't know what's the point with "aDA being used in avionics or
rocket science". Planes and rockets are falling from the sky from time
to time;

Ada is also used in particular rockets called missiles, and its job
inside is just to make them fall... but fall gracefully.
 
I

Ioannis Vranos

Georg said:
The starting point of the aforementioned AI-302/Ada 2005 container
library is Charles, which is STL in Ada, including a rich set
of algorithms. But I don't think that a comparison of language
facilities is best served by concentrating on algorithms written
in the language to overcome some of the languages shortcomings.
That's cheating.


Actually these are the high-level facilities of C++ (yes its library)
which can be implemented with the language itself by the way.

This is the preferred way of programming in C++, and I am going to move
to that way (I am still learning C++).

Notice how you use e.g. distance to work around things that
are more present in Ada than in C++ "proper". Notice also that
template metaprogramming is a lot more present in C++ than in Ada.


Template metaprogramming is a very useful field. I am not sure if you
are mentioning it as an advantage or disadvantage, it is about turning
run-time operations to compile-time.


Now if the basis of C++ can and should be overcome as you demonstrate,
why stick to the baiss of C++ when obviously all the value is in STL?


This is the recommended way of programming in C++. The low level parts
are to be used only when we can't do otherwise.


These standard library facilities get also much inlined, thus producing
even more efficient code than the use of the low level parts!
 
A

Alex R. Mosteo

Alberto said:
Well, it's time for me to join the 'American Dentist Association vs
C++' flame war:

Boh, the flaming here has been pretty low. In fact I'm getting very
interesting info from both fronts and both languages.
1. Is Ada case-insensitive as Pascal? In that case, Ada==ADA

Here, you're the one being insensitive :p
6. I don't know what's the point with "aDA being used in avionics or
rocket science". Planes and rockets are falling from the sky from time
to time; a few satellites are lost, too; NASA once failed to mix SI
units and British unit system (where's the stronger type and range
checking here?)...

I suppose the point is that people programming things which may cause
human deaths (I see the jokes coming...) see Ada as a better tool than
others, for reasons we can argue indefinitely...
 
G

Georg Bauhaus

Ioannis said:
Template metaprogramming is a very useful field. I am not sure if you
are mentioning it as an advantage or disadvantage, it is about turning
run-time operations to compile-time.

I'm mentioning it as an advantage, in spite of the time that the
translation tool chain needs to execute the template metaprograms,
and in spite of the not so helpful error messages you get, currently.

It is interesting though that programmers are fond of the new
programming language called templates. A clever trick to achieve
cognitive consonance that lets people maintain both the view that
C++ is great (because of templates) and that C++ should be avoided
(because of the low level parts).

Georg
 
L

Larry Kilgallen

Yes you can write completely safe, bullet-proof code in C++ and without
sacrificing efficiency (and some times even improving it!) by using the
high level C++ constructs. Examples are: find family (which includes
find_if etc), search family, generate, fill, for_each, count, mismatch,
equal, transform, copy, swap, replace, remove, unique, rotate, sort,
bound, merge, partition, includes, set (like set_union), heap (like
make_heap - makes sequences behave as heaps), comparisons (like min,
max, lexicographical_compare), permutation, etc families.


We can say it is an entirely completely safe, high level language of its
own, and in this way you may never use loops for most things!

Are there compilers for it ?

By which I mean, compilers that will balk at compiling when users fail
to make those careful choices of high-level constructs.
 
L

Larry Kilgallen

Well, it's time for me to join the 'American Dentist Association vs
C++' flame war:

1. Is Ada case-insensitive as Pascal? In that case, Ada==ADA

Nobody objects to someone using the name ADA in a program written in Ada.
The comments are about someone using improper capitalization in text
written in English, a language which is case-sensitive.
3. Many of you want us to believe that ADa performs ra nge checking
without loss of performance: it can be true at compile time with fixed
ranges, but it can't definitely be done without chechinkg array bounds
every time data is accessed if we don't know these bounds before
compiling (e.g.: typical cases where dynamic allocation of memory is
used)

As has been stated, it is _much_ more efficient that do-it-yourself
range checking written in C++, because the compiler has more data.
For those who insist on _no_ range checking (compute intensive inner
loops), turn off the range checking if it gets in the way for that
one area of code. But be certain it gets in the way first - it
is common to make bad guesses about whether range checking will
affect overall performance. Ada programmers are better able than
C* programmers to know that, because in Ada it is easier to turn
range checking on and off.
mechanisms, only interfaces (pure virtual classes)[2]. To me, it
sounds reasonable to work with the last version of a compiler when
possible.

That does not seem so reasonable to people working on a mission-critical
30 year project. In many cases such circumstances warrant working with
the compiler originally used for the project.
 
L

Larry Kilgallen

Ada is also used in particular rockets called missiles, and its job
inside is just to make them fall... but fall gracefully.

Gracefully is a matter of perspective, depending on whether it is
falling in your own neighborhood.
 
D

Dmitry A. Kazakov

1. Is Ada case-insensitive as Pascal? In that case, Ada==ADA

Well, Ada is not English. So Ada's rules about names are not applicable to
Ada's name. BTW, with C++ it is even worse: "C++" isn't a valid C++ name!
Though it nicely reflects the semantic of its usage: use what we have now,
it will be better later! :)-))
2. The C++ exception mechanism should be very similar to aDa's,
because it was inspired partially from it [1].

Yes, but there is a sufficient difference. Ada's exceptions are values of
same predefined type. It has advantages and disadvantages. Being on Ada's
side I start with advantages and leave disadvantages to you:

1.

exception
when A => ...
when B => ...

is strictly equivalent to

exception
when B => ...
when A => ...

2. C++ has no truly dynamic classes. But if it some time will, then how
would it deal with:

class BaseException
{
public :
virtual void TellStories () = 0;
};

try
{
...
{ // Nested
int I = 123;
class NewException : public BaseException
{
public
void TellStories () { printf ("%d", I); }
};
throw NewException ();
}
...
}
catch (BaseException& Error)
{
Error.TellStories ();
}

3. The size of all exception objects has an upper bound.
3. Many of you want us to believe that ADa performs ra nge checking
without loss of performance: it can be true at compile time with fixed
ranges, but it can't definitely be done without chechinkg array bounds
every time data is accessed if we don't know these bounds before
compiling (e.g.: typical cases where dynamic allocation of memory is
used)

But even then bounds checking is not needed for every access. Example:

procedure Dynamic (A : Some_Array) is
subtype Index is Array_Index range A'Range;
J : Index := A'First;

for I in A'Range loop
A (I) := .. -- No checks
...
J := I;
end loop;
A (J) := ... -- Still no checks

C++ completely lacks the notion of constrained subtypes which makes the
above possible.
4. Also, some people wrote that C++ is bad because it is difficult
(but not imposible, see Comeau C++) to follow 100% the Standard. The
same can be said to adA, because at least if we own a compiler of the
'83 Standard, we can't have the derivation a virtual function
mechanisms, only interfaces (pure virtual classes)[2]. To me, it
sounds reasonable to work with the last version of a compiler when
possible.

As long as you have only one compiler vendor...
5. In fact, there are standard mechanisms (STL) to handle these array
bound checking issues with ease.

They cannot be so effective as in Ada.

1. See above about constraining.
2. C++ is unable to allocate objects of indefinite size on the stack.
 
I

Ioannis Vranos

Georg said:
I'm mentioning it as an advantage, in spite of the time that the
translation tool chain needs to execute the template metaprograms,
and in spite of the not so helpful error messages you get, currently.

It is interesting though that programmers are fond of the new
programming language called templates.

It is a paradigm. Given that most languages support only one paradigm
(and many times *not* well - e.g. Java and OO paradigm, no complete
multiple inheritance support), one may tend to describe templates as a
"language" of its own, but it is one the four paradigms supported *well*
(=completely) by C++.

A clever trick to achieve
cognitive consonance that lets people maintain both the view that
C++ is great (because of templates) and that C++ should be avoided
(because of the low level parts).

It is better to say that C++ is *both* a high level and a low level
language, and unless one can't do otherwise, he should stick with the
high level part of it.
 
G

Georg Bauhaus

Falk said:
Well, I tried to google what Ada "downward closures" are but since I
don't know the language, I'm not sure I properly understood how they
work (shame on me!).

I believe downward closures are not at all Ada-specific.

In Ada, you pass a function f as a parameter to another
function g(..., f) *even* when f is declared at a place more
deeply nested than the declaration of g.
So f has access to objects up the nesting level, i.e. to
its environment, g has not.

For example, the Ada container library provides procedures
"iterate", consuming a container and a procedure pointer.
In abbreviated peudo-notation:

container library:

procedure iterate(a container X, a procedure P);
-- invoke P for every element in X

your program:

procedure work (a container X) {
... local declarations

procedure f (a cursor K) {
-- local procedure with access to X's element a K,
-- and to the local declarations
...
}

iterate(a container, f);
}

When iterate executes, both the local declarations and f still
exist, they are accessible. But iterate is declared somewhere
else, f is more nested.

The accessibility rules imply that iterate can only invoke f, or
pass it on to other procedures, but f cannot for example be
assigned to a global variable because when work has executed,
f becomes inaccessible.

Here is a small and simple Ada 2005 example that I think comes
fairly close to the (here named) lambda expression you have given.

procedure find_gt_666 is

vec: Vector; -- of integers
here: Cursor := No_Element; -- end()

procedure first_gt_666(x: Cursor) is
begin
if not Has_Element(here) and then Element(x) > 666 then
here := x;
end if;
end first_gt_666;

begin
... populate vec

iterate(vec, first_gt_666'access);

... use Element(here)
end find_gt_666;

Of course, it would be nicer, easier and more flexible if you could write
something like (syntax totally hypothetical!):
std::vector<int>::iterator it = std::find_if(vec.begin(), vec.end(),
lambda{x; x>666} );

Eiffel agents might come even closer to this as they can be defined
in place.

Georg
 
J

Jerry Coffin

Martin Dowie wrote:

[ ... ]
Sorry, but if you make a link to a news item /about/ a particular
tool, at least /I/ am going to believe that you are making a point
about the tool and not the OS it works on! Why not provide a link
directly to a page about X running on top of either Windows or
UNIX?! :)

"Think before you ask these questions Mitch."

The subject at hand was the use of C++ in the air traffic control
system.

As such, X running on top of Windows and/or UNIX becomes relevant ONLY
when tied to the development of air traffic control software. This page
shows exactly that. A page only about X on Windows or UNIX would not.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,205
Messages
2,571,067
Members
47,673
Latest member
MahaliaPal

Latest Threads

Top