# project euler 26

226 views

### CSYH (QAQ)

Sep 4, 2023, 5:19:53 AMSep 4
to
I am new to Ada, I know is there a good way to start this program?
thanks
https://projecteuler.net/problem=26

### Niklas Holsti

Sep 4, 2023, 7:06:18 AMSep 4
to
First invent/discover the method (algorithm) for solving the problem,
without thinking about the programming language.

I don't think any language has built-in features that would lead to a
direct solution, although some functional language with lazy evaluation
could come close, because such languages can manipulate unbounded
(potentially infinite) sequences of values. Such sequences can be
handled in Ada, too, but with more effort -- they are not "built in" to Ada.

### Dmitry A. Kazakov

Sep 4, 2023, 8:39:20 AMSep 4
to
Infinite division does not require big numbers, which Ada 22 has, but I
wound not use them anyway because the performance would be abysmal.

BTW, Ada is perfect for numeric algorithms no need to resort to
functional mess... (:-))

The problem itself requires as you said mathematical analysis, because a
naive method of comparing partial division result with itself is
obviously wrong. E.g. let you have

0.12341234...

you could not conclude that the period is (1234) because it could
actually be (123412345).

--
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de

### Dmitry A. Kazakov

Sep 4, 2023, 10:23:57 AMSep 4
to
Ok, I leave it to you checking if my implementation is correct.

procedure Test is

N : constant := 1000;

function Period (Divisor : Positive) return String is
type Remainder is record
Index : Positive;
Value : Positive;
end record;
Result : String (1..N);
Value : Integer := 1;
Remainders : array (1..N) of Remainder;
begin
for Index in Result'Range loop
Value := Value * 10;
Result (Index) :=
Character'Val (Character'Pos ('0') + Value / Divisor);
Value := Value mod Divisor;
if Value = 0 then
return ""; -- Non-periodic
end if;
if Index > 1 then
for Item in 1..Index - 1 loop
declare
This : Remainder renames Remainders (Item);
begin
if Value = This.Value then
return Result (This.Index + 1..Index);
end if;
end;
end loop;
end if;
Remainders (Index) := (Index, Value);
end loop;
raise Constraint_Error with "Period calculation error";
end Period;

Max_Period : Unbounded_String;
Max_Divisor : Positive;
begin
for Divisor in 2..999 loop
declare
This : constant String := Period (Divisor);
begin
if This /= "" then
Put_Line
( "1 /"
& Integer'Image (Divisor)
& " has "
& This
& " in period"
);
end if;
if Length (Max_Period) < This'Length then
Max_Period := To_Unbounded_String (This);
Max_Divisor := Divisor;
end if;
end;
end loop;
Put_Line
( "The first longest period is "
& To_String (Max_Period)
& " in 1 /"
& Integer'Image (Max_Divisor)
);
end Test;
It gives the longest period for 1/983.

### Ben Bacarisse

Sep 4, 2023, 12:01:09 PMSep 4
to
"Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:

> On 2023-09-04 13:06, Niklas Holsti wrote:
>> On 2023-09-04 12:19, CSYH (QAQ) wrote:
>>> I am new to Ada, I know is there a good way to start this program?
>>> thanks
>>> https://projecteuler.net/problem=26
>> First invent/discover the method (algorithm) for solving the problem,
>> without thinking about the programming language.
>> I don't think any language has built-in features that would lead to a
>> direct solution, although some functional language with lazy evaluation
>> could come close, because such languages can manipulate unbounded
>> (potentially infinite) sequences of values. Such sequences can be handled
>> in Ada, too, but with more effort -- they are not "built in" to Ada.
>
> Infinite division does not require big numbers, which Ada 22 has, but I
> wound not use them anyway because the performance would be abysmal.
>
> BTW, Ada is perfect for numeric algorithms no need to resort to functional
> mess... (:-))

Perfect? That's a bold claim!

Mind you, I don't think this problem is really a numerical one in that
sense. It needs some simple integer arithmetic but then every language
is perfect for that sort of arithmetic.

Using a functional mess (Haskell) a simple, native solution (i.e. using
no modules) is only 9 lines long.

I don't want to start a language war. Ada is just more 'wordy' by
deliberate design so a simple Ada solution is inevitably going to be
longer in terms of lines. Rather my purpose in posting is to steer the
OP away from thinking of this as a numerical problem in the classical
sense. It really isn't.

--
Ben.

### Dmitry A. Kazakov

Sep 4, 2023, 3:20:58 PMSep 4
to
On 2023-09-04 18:01, Ben Bacarisse wrote:
> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>
>> On 2023-09-04 13:06, Niklas Holsti wrote:
>>> On 2023-09-04 12:19, CSYH (QAQ) wrote:
>>>> I am new to Ada, I know is there a good way to start this program?
>>>> thanks
>>>> https://projecteuler.net/problem=26
>>> First invent/discover the method (algorithm) for solving the problem,
>>> without thinking about the programming language.
>>> I don't think any language has built-in features that would lead to a
>>> direct solution, although some functional language with lazy evaluation
>>> could come close, because such languages can manipulate unbounded
>>> (potentially infinite) sequences of values. Such sequences can be handled
>>> in Ada, too, but with more effort -- they are not "built in" to Ada.
>>
>> Infinite division does not require big numbers, which Ada 22 has, but I
>> wound not use them anyway because the performance would be abysmal.
>>
>> BTW, Ada is perfect for numeric algorithms no need to resort to functional
>> mess... (:-))
>
> Perfect? That's a bold claim!

Ada is a very improved descendant of Algol 60, which was designed to
codify algorithms.

> Mind you, I don't think this problem is really a numerical one in that
> sense. It needs some simple integer arithmetic but then every language
> is perfect for that sort of arithmetic.

building abstractions as in the case of OOP)

> Using a functional mess (Haskell) a simple, native solution (i.e. using
> no modules) is only 9 lines long.

Apart from the fundamental inconsistency of functional paradigm:
computing is about transition of states and nothing else; the imperative
languages express solutions, i.e. an algorithm. Functional, and in
general, declarative languages express puzzles.

They remind me a math examination tasks on studying a function. Here is
a definition. Go figure out the properties and behavior...

Or, if you want, functional is like a chess composition: white to move
and checkmate in 4 moves. Challenging, but Ada is about playing chess.

### Ben Bacarisse

Sep 4, 2023, 4:18:20 PMSep 4
to
"Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:

> On 2023-09-04 18:01, Ben Bacarisse wrote:
>> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>>
>>> On 2023-09-04 13:06, Niklas Holsti wrote:
>>>> On 2023-09-04 12:19, CSYH (QAQ) wrote:
>>>>> I am new to Ada, I know is there a good way to start this program?
>>>>> thanks
>>>>> https://projecteuler.net/problem=26
>>>> First invent/discover the method (algorithm) for solving the problem,
>>>> without thinking about the programming language.
>>>> I don't think any language has built-in features that would lead to a
>>>> direct solution, although some functional language with lazy evaluation
>>>> could come close, because such languages can manipulate unbounded
>>>> (potentially infinite) sequences of values. Such sequences can be handled
>>>> in Ada, too, but with more effort -- they are not "built in" to Ada.
>>>
>>> Infinite division does not require big numbers, which Ada 22 has, but I
>>> wound not use them anyway because the performance would be abysmal.
>>>
>>> BTW, Ada is perfect for numeric algorithms no need to resort to functional
>>> mess... (:-))
>> Perfect? That's a bold claim!
>
> Ada is a very improved descendant of Algol 60, which was designed to codify
> algorithms.

Yes, though I was respond to you narrower remark about being perfect for
numeric algorithms. Are you expending that to perfect for every kind of
algorithm?

>> Mind you, I don't think this problem is really a numerical one in that
>> sense. It needs some simple integer arithmetic but then every language
>> is perfect for that sort of arithmetic.
>
> That is still all about algorithms

Yes but, again, that's not what I was responding to.

> (rather than about for example building
> abstractions as in the case of OOP)

That's interesting. You don't consider using functions and procedures
(possibly higher-order ones) to be a way to build abstractions?

>> Using a functional mess (Haskell) a simple, native solution (i.e. using
>> no modules) is only 9 lines long.
>
> Apart from the fundamental inconsistency of functional paradigm: computing
> is about transition of states and nothing else; the imperative languages
> express solutions, i.e. an algorithm. Functional, and in general,
> declarative languages express puzzles.

Rather than try to unpick that paragraph I'll just say that they can,
none the less, give simple solutions to this sort of programming
problem.

--
Ben.

### Dmitry A. Kazakov

Sep 4, 2023, 5:00:26 PMSep 4
to
On 2023-09-04 22:18, Ben Bacarisse wrote:
> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>
>> On 2023-09-04 18:01, Ben Bacarisse wrote:
>>> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>>>
>>>> BTW, Ada is perfect for numeric algorithms no need to resort to functional
>>>> mess... (:-))
>>> Perfect? That's a bold claim!
>>
>> Ada is a very improved descendant of Algol 60, which was designed to codify
>> algorithms.
>
> Yes, though I was respond to you narrower remark about being perfect for
> numeric algorithms.

> Are you expending that to perfect for every kind of
> algorithm?

Algorithms are defined in terms of established types, e.g. model numbers
or other well known structures. Ada works pretty good for non-numeric
algorithms too. So well, that many Ada programmers never go beyond this
stage and proclaim anathema to anything above it.

>> (rather than about for example building
>> abstractions as in the case of OOP)
>
> That's interesting. You don't consider using functions and procedures
> (possibly higher-order ones) to be a way to build abstractions?

No, they do not introduce new types and do not form some structure of
their values. And "using" is not an abstraction anyway.

### Ben Bacarisse

Sep 4, 2023, 7:16:52 PMSep 4
to
"Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:

> On 2023-09-04 22:18, Ben Bacarisse wrote:
>> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>>
>>> On 2023-09-04 18:01, Ben Bacarisse wrote:
>>>> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>>>>
>>>>> BTW, Ada is perfect for numeric algorithms no need to resort to functional
>>>>> mess... (:-))
>>>> Perfect? That's a bold claim!
>>>
>>> Ada is a very improved descendant of Algol 60, which was designed to codify
>>> algorithms.
>> Yes, though I was respond to you narrower remark about being perfect for
>> numeric algorithms.
>

:-)

>>> (rather than about for example building
>>> abstractions as in the case of OOP)
>>
>> That's interesting. You don't consider using functions and procedures
>> (possibly higher-order ones) to be a way to build abstractions?
>
> No, they do not introduce new types and do not form some structure of their
> values. And "using" is not an abstraction anyway.

The term "abstraction" is usually taken to be more general than that so
as to include function (or procedural) abstraction.

Ada is good at that, but the syntax is sufficiently cumbersome that I
think it discourages people from exploiting that part of the language.
Mind you, I am no Ada expert so maybe it's simpler to do than I think.

procedure Euler_26 is

function Period(Divisor: Positive) return Positive is
Index: Natural := 0;
Carry: Natural := 1;

package Carry_Maps is new Ordered_Maps(Natural, Natural);
use Carry_Maps;
Carries: Map;
Loc: Cursor;
begin
loop
Loc := Carries.Find(Carry);
exit when Loc /= No_Element;
Carries.Insert(Carry, Index);
Index := Index + 1;
Carry := Carry mod Divisor * 10;
end loop;
return Index - Element(Loc);
end Period;

Max_Period: Natural := 1;
Divisor_With_Max_Period: Natural := 1;
begin
for D in 2..999 loop
declare Ds_Period: constant Positive := Period(D);
begin
if Ds_Period > Max_Period
then
Divisor_With_Max_Period := D;
Max_Period := Ds_Period;
end if;
end;
end loop;
Put_Line(Integer'Image(Divisor_With_Max_Period));
end Euler_26;

The part that finds the D that maximises Period(D) is just boilerplate
code. I know this can be abstracted out in Ada, but I think the syntax
is messy. I was hoping to find (or be able to write) a generic function
that takes an 'iterable' (if that's the right word) and a function, and
which returns the element that maximises the function. I got stuck
trying. Maybe someone can help?

I know it won't make this program shorter, but it would be interesting
to know how it might be done.

--
Ben.

### Dmitry A. Kazakov

Sep 5, 2023, 3:23:51 AMSep 5
to
On 2023-09-05 01:16, Ben Bacarisse wrote:

> The term "abstraction" is usually taken to be more general than that so
> as to include function (or procedural) abstraction.

These are means of software decomposition rather than abstraction (of
something).

> Ada is good at that, but the syntax is sufficiently cumbersome that I
> think it discourages people from exploiting that part of the language.
> Mind you, I am no Ada expert so maybe it's simpler to do than I think.

If the program does not resemble electric transmission noise, some
people call the language syntax cumbersome... (:-))

>
>
> procedure Euler_26 is
>
> function Period(Divisor: Positive) return Positive is

You cannot use a number here because the period may have leading zeros.

> I know it won't make this program shorter, but it would be interesting
> to know how it might be done.

The goal of engineering is not making programs shorter, it is to make
them understandable, safer, reusable, maintainable, extensible, integrable.

### Ben Bacarisse

Sep 5, 2023, 11:18:21 AMSep 5
to
"Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:

> On 2023-09-05 01:16, Ben Bacarisse wrote:
>
>> The term "abstraction" is usually taken to be more general than that so
>> as to include function (or procedural) abstraction.
>
> These are means of software decomposition rather than abstraction (of
> something).

That's not how the word is usually used. Obviously I can't (and don't
want to) change your mind, but algorithms can be abstracted as well as
data.

I was hoping someone could how me how in for the example program I gave
since that's an area of Ada I am not familiar with (but I's sure it's
possible).

>> Ada is good at that, but the syntax is sufficiently cumbersome that I
>> think it discourages people from exploiting that part of the language.
>> Mind you, I am no Ada expert so maybe it's simpler to do than I think.
>
> If the program does not resemble electric transmission noise, some people
> call the language syntax cumbersome... (:-))

That's true. But there are also constructs that are genuinely
cumbersome in some languages. Anyway, to find out more, I was hoping
someone would show me what it looks like in Ada -- I outlined what I
wanted to do after the code I posted.

>> procedure Euler_26 is
>> function Period(Divisor: Positive) return Positive is
>
> You cannot use a number here because the period may have leading
> zeros.

The function returns the decimal period of 1/Divisor. I don't believe
there is a bug, but if you think you've found one, I'd like to know

Of course there can be leading zeros, but my algorithm ignores the
digits and determines the period using the "carry" instead.

>> I know it won't make this program shorter, but it would be interesting
>> to know how it might be done.
>
> The goal of engineering is not making programs shorter, it is to make them
> understandable, safer, reusable, maintainable, extensible, integrable.

Yes. That's exactly why I was asking for someone who knows Ada better
to show me how to write the reusable component I described. There was
boiler plate code in my program that could be abstracted out into a
generic function (or package?) so that any function can be maximised
over some range or, better yet, any iterable type (if that's how Ada
does things).

Can someone here show me how?

--
Ben.

### Dmitry A. Kazakov

Sep 5, 2023, 1:09:01 PMSep 5
to
On 2023-09-05 17:18, Ben Bacarisse wrote:

> There was
> boiler plate code in my program that could be abstracted out into a
> generic function (or package?) so that any function can be maximised
> over some range or, better yet, any iterable type (if that's how Ada
> does things).

> Can someone here show me how?

You define some classes. Either generic or tagged. E.g. a generic class
of functions that uses two generic classes of the argument and the value:

generic
-- Ordered argument
type Argument_Type is private;
with function Next (Value : Argument_Type)
return Argument_Type is <>;
with function "<" (Left, Right : Argument_Type)
return Boolean is <>;
with function "=" (Left, Right : Argument_Type)
return Boolean is <>;
-- Comparable value
type Value_Type is private;
with function "<" (Left, Right : Value_Type ) return Boolean is <>;
-- Function type
with function Func (Argument : Argument_Type) return Value_Type;
function Generic_Maximum_At (Left, Right : Argument_Type)
return Value_Type;

and the implementation

function Generic_Maximum_At (Left, Right : Argument_Type)
return Value_Type is
Argument : Argument_Type := Left;
Max : Value_Type;
Value : Value_Type;
begin
if Right < Left then
raise Constraint_Error with "Empty interval";
end if;
Max := Func (Argument);
while not (Argument = Right) loop
Argument := Next (Argument);
Value := Func (Argument);
if Max < Value then
Max := Value;
end if;
end loop;
return Max;
end Generic_Maximum_At;

or you can choose to pass the function as an argument:

generic
-- Ordered argument
type Argument_Type is private;
with function Next (Value : Argument_Type)
return Argument_Type is <>;
with function "<" (Left, Right : Argument_Type)
return Boolean is <>;
-- Comparable value
type Value_Type is private;
with function "<" (Left, Right : Value_Type) return Boolean is <>;
function Generic_Maximum_At
( Left, Right : Argument_Type;
Func : access function (Argument : Argument_Type)
return Value_Type
) return Value_Type;

Or you can make it a package which is usually a better choice as one can
pack into it several entities sharing the same generic interface:

generic
-- Ordered argument
type Argument_Type is private;
with function Next (Value : Argument_Type)
return Argument_Type is <>;
with function "<" (Left, Right : Argument_Type )
return Boolean is <>;
with function "=" (Left, Right : Argument_Type)
return Boolean is <>;
-- Comparable value
type Value_Type is private;
with function "<" (Left, Right : Value_Type) return Boolean is <>;
package Generic_Discrete_Comparable_Valued is
function Maximum_At
( Left, Right : Argument_Type;
Func : access function (Argument : Argument_Type)
return Value_Type
) return Value_Type;
-- Other useless functions
end Generic_Discrete_Comparable_Valued;

The generic classes of arguments/values can be in turn factored out into
reusable generic packages:

generic
-- Ordered argument
type Argument_Type is private;
with function Next (Value : Argument_Type) return Argument_Type is <>;
with function "<" (Left, Right : Argument_Type) return Boolean is <>;
with function "=" (Left, Right : Argument_Type) return Boolean is <>;
package Generic_Arguments is
end Generic_Arguments;

generic
-- Comparable value
type Value_Type is private;
with function "<" (Left, Right : Value_Type ) return Boolean is <>;
package Generic_Values is
end Generic_Values;

generic
with package Arguments is new Generic_Arguments (<>);
with package Values is new Generic_Values (<>);
package Generic_Discrete_Comparable_Valued is
use Arguments, Values;
function Maximum_At
( Left, Right : Argument_Type;
Func : access function (Argument : Argument_Type)
return Value_Type
) return Value_Type;
-- Other useless functions
end Generic_Discrete_Comparable_Valued;

### moi

Sep 5, 2023, 1:35:16 PMSep 5
to
On 05/09/2023 08:23, Dmitry A. Kazakov wrote:
> On 2023-09-05 01:16, Ben Bacarisse wrote:
>
>> The term "abstraction" is usually taken to be more general than that so
>> as to include function (or procedural) abstraction.
>
> These are means of software decomposition rather than abstraction (of
> something).

They are both of these things, actually.

>
>> Ada is good at that, but the syntax is sufficiently cumbersome that I
>> think it discourages people from exploiting that part of the language.
>> Mind you, I am no Ada expert so maybe it's simpler to do than I think.
>
> If the program does not resemble electric transmission noise, some
> people call the language syntax cumbersome... (:-))

8-)

>>
>>
>> procedure Euler_26 is
>>
>>     function Period(Divisor: Positive) return Positive is
>
> You cannot use a number here because the period may have leading zeros.
>
>> I know it won't make this program shorter, but it would be interesting
>> to know how it might be done.
>
> The goal of engineering is not making programs shorter, it is to make
> them understandable, safer, reusable, maintainable, extensible, integrable.

Hear, hear!

Functionalists do seem to have an obsession with brevity at all costs.
It's very strange.

--
Bill F.

### Ben Bacarisse

Sep 5, 2023, 9:10:26 PMSep 5
to
"Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:

Thank you. I can't yet see how to use any of these alternatives, but
that's my problem. Are there any good online sources on Ada generic
programming so I can find out how to implement and use this short of
package?

--
Ben.

### Dmitry A. Kazakov

Sep 6, 2023, 3:06:35 AMSep 6
to
It is pretty much straightforward. E.g. the last one:

package Arguments is new Generic_Arguments (Integer, Integer'Succ);
package Values is new Generic_Values (Integer);
package Functions is
new Generic_Discrete_Comparable_Valued (Arguments, Values);

Now you can print the maximum of your Period function:

Put_Line
( "Max at"
& Integer'Image (Functions.Maximum_At (2, 999, Period'Access))
);

> Are there any good online sources on Ada generic
> programming so I can find out how to implement and use this short of
> package?

Actually I provided an implementation above. Here it is again:

package body Generic_Discrete_Comparable_Valued is
function Maximum_At
( Left, Right : Argument_Type;
Func : access function (Argument : Argument_Type)
return Value_Type
) return Value_Type is
Argument : Argument_Type := Left;
Max : Value_Type;
Value : Value_Type;
begin
if Right < Left then
raise Constraint_Error with "Empty interval";
end if;
Max := Func (Argument);
while not (Argument = Right) loop
Argument := Next (Argument);
Value := Func (Argument);
if Max < Value then
Max := Value;
end if;
end loop;
return Max;
end Maximum_At;
end Generic_Discrete_Comparable_Valued;

(The packages Generic_Arguments and Generic_Values have no bodies)

### Ben Bacarisse

Sep 6, 2023, 11:16:52 AMSep 6
to
Sure, but I am new to Ada. Well actually I first wrote Ada in the early
80s, but the project didn't go with Ada (too new I suspect) so reading
one book was the extent of my learning.

> package Arguments is new Generic_Arguments (Integer, Integer'Succ);
> package Values is new Generic_Values (Integer);

I'd probably choose more generic names for the packages since these are
more general than the names suggest. I might go with Generic_Enumerated
(since it has 'Next') and Generic_Ordered.

Just to test I knew what was going on, I changed 'while not (Argument =
Right)' to 'while Argument < Right' so as to remove the need for having
an "=" function. I doubt there are any types with "<" but not "=" but I
wanted to confirm I understood the code.

> package Functions is
> new Generic_Discrete_Comparable_Valued (Arguments, Values);
>
>
> Now you can print the maximum of your Period function:
>
> Put_Line
> ( "Max at"
> & Integer'Image (Functions.Maximum_At (2, 999, Period'Access))
> );

Thanks.

(A minor issue: to meet the specification we either need 1000 here or
the loop needs to be changed to include the upper bound (like the for
loop did in the original). Whilst it's easy to pass "one past the top
index" for Integer and so on, if the code can be made more generic it
would have to use all the values in the range because Ada has not done
the C++ hack of having XXX.end() be an iterator "one past" the actual
end of a range.)

I am curious to know how reusable this is. Can the packages be
instantiated in such a way that the argument ranges over the elements
of, say, and Ordered_Map? In some languages (C++!) one could pass a
pair of iterators here (cursors, I think in Ada-speak). I tried to do
that but I don't think Ada's cursors are ordered by < though they do
have a Next function. And if that method does work (it's quite likely
it was only my ignorance of the language that stopped it working) would
it work for built-in arrays which don't seem to have cursors.

Maybe a more generic a solution would involve passing something that can
be iterated over, rather than two values of an "enumerated" type? I
mean enumerated in the mathematical sense -- it may be the wrong word in

I am asking you but I am also the group. I appreciate your help,
but don't want you to feel any obligation to keep helping!

>> Are there any good online sources on Ada generic
>> programming so I can find out how to implement and use this short of
>> package?
>
> Actually I provided an implementation above. Here it is again:

Sorry, missed that first time round.

--
Ben.

### Dmitry A. Kazakov

Sep 6, 2023, 11:54:50 AMSep 6
to
On 2023-09-06 17:16, Ben Bacarisse wrote:

> I am curious to know how reusable this is. Can the packages be
> instantiated in such a way that the argument ranges over the elements
> of, say, and Ordered_Map?

Sure:

package Integer_Maps is
use Integer_Maps;
package Cursor_Arguments is new Generic_Arguments (Cursor);
package Map_Values is new Generic_Values (Integer);
package Map_Functions is
new Generic_Discrete_Comparable_Valued
(Cursor_Arguments, Map_Values);

Then given X is a map: X : Map;

Map_Functions.Maximum_At (X.First, X.Last, Element'Access)

> Maybe a more generic a solution would involve passing something that can
> be iterated over, rather than two values of an "enumerated" type? I
> mean enumerated in the mathematical sense -- it may be the wrong word in

Yes, but Ada does not have built-in range types. Therefore such design
will not work out of the box with discrete types because 2..999 is not a
create an interval type for the purpose or else use an ordered set of
integers.

> I am asking you but I am also the group. I appreciate your help,
> but don't want you to feel any obligation to keep helping!

No problem.

### Ben Bacarisse

Sep 6, 2023, 7:32:27 PMSep 6
to
"Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:

> On 2023-09-06 17:16, Ben Bacarisse wrote:
>
>> I am curious to know how reusable this is. Can the packages be
>> instantiated in such a way that the argument ranges over the elements
>> of, say, and Ordered_Map?
>
> Sure:
>
>
> package Integer_Maps is
> use Integer_Maps;
> package Cursor_Arguments is new Generic_Arguments (Cursor);

Ah! So the arguments correspond to the "with" functions in the order
listed, and, since Cursor already has Next, there no need to specify
anything. One could (I've just tried) use => notation. You could have
written

package Arguments is new Generic_Arguments (Next => Positive'Succ,
Argument_Type => Positive);

in your first example -- swapping the order just to make the point
obvious. This tripped me up when I was playing around with a Cursors
solution.

There are a couple of details that prevent your Maximum_At function from
working properly in this case though. First, we can't have an empty
map, because X.Last can't be compared with X.First when either is
No_Element, so the test for Right < Left fails before the desired error
can be raised.

Second, if I try to use a Vector rather than an Ordered_Map, I am told
that:

test2.adb:97:05: error: instantiation error at line 12
test2.adb:97:05: error: no visible subprogram matches the specification for "<"

It would seem that vector cursors can't be compared using < (at least by
default). Maybe the installation needs more arguments.

Anyway, I am still not sure how to write a generic test for an empty
range.

> package Map_Values is new Generic_Values (Integer);
> package Map_Functions is
> new Generic_Discrete_Comparable_Valued
> (Cursor_Arguments, Map_Values);
>
> Then given X is a map: X : Map;
>
> Map_Functions.Maximum_At (X.First, X.Last, Element'Access)

It's possible I was not clear about what I was aiming for. I was hoping
to be able to find the maximum of some arbitrary function, taking the
function's arguments from any sequential collection. Either a simple
range of values, an array or vector of values, a list of values or even
an ordered map of values -- any ordered list of values.

The bottom line is the last argument should be something very general
like the Period function.

A fix (though it's not really ideal) would be to use function
composition here (inventing . as the composition operator):

Map_Functions.Maximum_At (X.First, X.Last, Period'Access . Element'Access)

but I don't think Ada has a function composition operator, does it?

Another solution would be to write Maximum_At so that it knows it has a
cursor argument, but then I don't think it would work for native arrays,
would it? And we'd loose plain ranges altogether.

>> Maybe a more generic a solution would involve passing something that can
>> be iterated over, rather than two values of an "enumerated" type? I
>> mean enumerated in the mathematical sense -- it may be the wrong word in
>
> Yes, but Ada does not have built-in range types. Therefore such design will
> not work out of the box with discrete types because 2..999 is not a proper
> object in Ada. However, talking about abstractions, you can create an
> interval type for the purpose or else use an ordered set of integers.

But then (I think) the only function one could pass would be something
like Element as in you example above. Using an ordered set of integers
would not allow

Map_Functions.Maximum_At (Set.First, Set.Last, Period'Access)

would it?

>> I am asking you but I am also the group. I appreciate your help,
>> but don't want you to feel any obligation to keep helping!
>
> No problem.

You seem to be on your own as far as helping out is concerned!

--
Ben.

### Francesc Rocher

Sep 7, 2023, 3:31:12 AMSep 7
to
El dia dilluns, 4 de setembre de 2023 a les 11:19:53 UTC+2, CSYH (QAQ) va escriure:
> I am new to Ada, I know is there a good way to start this program?
> thanks
> https://projecteuler.net/problem=26

Hi CSHY,

Please take a look at my Euler tools repository, https://github.com/rocher/euler_tools (not the best math lib you'll find, I know).
I used this library tools to solve problem 26 here: https://github.com/rocher/alice-project_euler-rocher
Let me know what you think.

### Dmitry A. Kazakov

Sep 7, 2023, 5:02:08 AMSep 7
to
On 2023-09-07 01:32, Ben Bacarisse wrote:
> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>
>> On 2023-09-06 17:16, Ben Bacarisse wrote:
>>
>>> I am curious to know how reusable this is. Can the packages be
>>> instantiated in such a way that the argument ranges over the elements
>>> of, say, and Ordered_Map?
>>
>> Sure:
>>
>>
>> package Integer_Maps is
>> use Integer_Maps;
>> package Cursor_Arguments is new Generic_Arguments (Cursor);
>
> Ah! So the arguments correspond to the "with" functions in the order
> listed, and, since Cursor already has Next, there no need to specify
> anything.

Yes, because the formal argument is

with function Next (Value : Argument_Type)
return Argument_Type is <>;

If it were

with function Next (Value : Argument_Type)
return Argument_Type;

You would have to specify the actual. The part "is <>" tells to match a
visible function Next.

> There are a couple of details that prevent your Maximum_At function from
> working properly in this case though. First, we can't have an empty
> map, because X.Last can't be compared with X.First when either is
> No_Element, so the test for Right < Left fails before the desired error
> can be raised.

Yes, cursors is bad idea, in the end they all are pointers. No_Element
is an equivalent of null which shows.

However Maximum_At will propagate Constraint_Error if either of the
bounds is No_Element. So the implementation would work.

> Second, if I try to use a Vector rather than an Ordered_Map, I am told
> that:
>
> test2.adb:97:05: error: instantiation error at line 12
> test2.adb:97:05: error: no visible subprogram matches the specification for "<"
>
> It would seem that vector cursors can't be compared using < (at least by
> default). Maybe the installation needs more arguments.

Vector has a proper index type. All you have to do is. Given

package Integer_Vectors is

Wrap Element into a function:

V : Integer_Vectors.Vector;
function Element (Index : Integer) return Integer is
begin
return V.Element (Index);
end Element;
...

and use the wrapper.

> Anyway, I am still not sure how to write a generic test for an empty
> range.

The problem is that the implementation of Cursor that breaks
abstraction. The abstraction of an argument does not permit ideal
non-values. Cursors and pointers have non-values. So if you want to test
add a test for value validity to the abstraction:

generic
-- Ordered argument
type Argument_Type is private;
with function Valid (Value : Argument_Type) return Boolean is <>;
...
package Generic_Arguments is

Then you would pass Has_Element for it. For integers you would use
wrapped X'Valid (there is no Integer'Valid, unfortunately. Only X'Valid
where X is an object).

> It's possible I was not clear about what I was aiming for. I was hoping
> to be able to find the maximum of some arbitrary function, taking the
> function's arguments from any sequential collection.

That is a different abstraction. You need a generic collection instead
of generic ordered values. E.g.

generic
with package Arguments is new Ada.Containers.Ordered_Sets (<>);
with package Values is new Generic_Values (<>);
package Generic_Comparable_Valued is
use Arguments, Values;
function Maximum_At
( Domain : Set;
Func : access function (Argument : Element_Type)
return Value_Type
) return Value_Type;
-- Other useless functions
end Generic_Comparable_Valued;

package body Generic_Comparable_Valued is
function Maximum_At
( Domain : Set;
Func : access function (Argument : Element_Type)
return Value_Type
) return Value_Type is
Max : Value_Type;
Value : Value_Type;
Position : Cursor;
begin
if Domain.Is_Empty then
raise Constraint_Error with "Empty set";
end if;
Position := Domain.First;
Max := Func (Element (Position));
while Position /= Domain.Last loop
Position := Next (Position);
Value := Func (Element (Position));
if Max < Value then
Max := Value;
end if;
end loop;
return Max;
end Maximum_At;
end Generic_Comparable_Valued;

> Either a simple
> range of values, an array or vector of values, a list of values or even
> an ordered map of values -- any ordered list of values.

In practice such abstraction have too much physical and mental overhead.
E.g. large sets of values implemented differently from
Ada.Containers.Ordered_Sets depending on the operations required. For
example, let you need a set complement? Usually programmers simply stick
with software patterns instead. Too much reliance of libraries make
programs incoherent.

> The bottom line is the last argument should be something very general
> like the Period function.
>
> A fix (though it's not really ideal) would be to use function
> composition here (inventing . as the composition operator):
>
> Map_Functions.Maximum_At (X.First, X.Last, Period'Access . Element'Access)
>
> but I don't think Ada has a function composition operator, does it?

No as it would require closures. So you can have a generic composition
operator, no problem, but not a first-class one. However you can simply
add Maximum_At with four arguments to the package.

> Another solution would be to write Maximum_At so that it knows it has a
> cursor argument, but then I don't think it would work for native arrays,
> would it? And we'd loose plain ranges altogether.

You can write a generic package creating array cursors:

generic
type Index_Type is (<>);
type Element_Type is private;
type Array_Type is array (Index_Type range <>) of Element_Type;
package Array_Cursors is
type Cursor is private;
function First (Container : Array_Type) return Cursor;
function Element (Position : Cursor) return Element_Type;
function "<" (Left, Right : Cursor) return Boolean;
...
private
package Dirty_Tricks is
use Dirty_Tricks;
type Cursor is record
Domain : Object_Pointer;
Index : Index_Type;
end record;
end Array_Cursors;

package body Array_Cursors is
function "<" (Left, Right : Cursor) return Boolean is
begin
if Left.Domain = null or else Left.Domain /= Right.Domain then
raise Constraint_Error with "Incomparable cursors";
end if;
return Left.Index < Right.Index;
end "<";

function Element (Position : Cursor) return Element_Type is
begin
if Position.Domain = null or else
Position.Index not in Position.Domain'Range
then
raise Constraint_Error with "Invalid cursor";
else
return Position.Domain (Position.Index);
end if;
end Element;

function First (Container : Array_Type) return Cursor is
begin
if Container'Length = 0 then
raise Constraint_Error with "Empty array";
else
end if;
end First;

end Array_Cursors;

> But then (I think) the only function one could pass would be something
> like Element as in you example above. Using an ordered set of integers
> would not allow
>
> Map_Functions.Maximum_At (Set.First, Set.Last, Period'Access)
>
> would it?

Ordered_Set cursors are ordered like Ordered_Map ones, so it should work.

>>> I am asking you but I am also the group. I appreciate your help,
>>> but don't want you to feel any obligation to keep helping!
>>
>> No problem.
>
> You seem to be on your own as far as helping out is concerned!

Because it started as a numeric puzzle. You should have asked directly

### Ben Bacarisse

Sep 7, 2023, 9:32:05 PMSep 7
to
"Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:

> On 2023-09-07 01:32, Ben Bacarisse wrote:
>> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>>
>>> On 2023-09-06 17:16, Ben Bacarisse wrote:
>>>
>>>> I am curious to know how reusable this is. Can the packages be
>>>> instantiated in such a way that the argument ranges over the elements
>>>> of, say, and Ordered_Map?
>>>
>>> Sure:
>>>
>>>
>>> package Integer_Maps is
>>> use Integer_Maps;
>>> package Cursor_Arguments is new Generic_Arguments (Cursor);
>> Ah! So the arguments correspond to the "with" functions in the order
>> listed, and, since Cursor already has Next, there no need to specify
>> anything.
>
> Yes, because the formal argument is
>
> with function Next (Value : Argument_Type)
> return Argument_Type is <>;
>
> If it were
>
> with function Next (Value : Argument_Type)
> return Argument_Type;
>
> You would have to specify the actual. The part "is <>" tells to match a
> visible function Next.

Thanks. I remember that now. Given Ada's preference for words, it's a
mysterious choice.

>> There are a couple of details that prevent your Maximum_At function from
>> working properly in this case though. First, we can't have an empty
>> map, because X.Last can't be compared with X.First when either is
>> No_Element, so the test for Right < Left fails before the desired error
>> can be raised.
>
> Yes, cursors is bad idea, in the end they all are pointers. No_Element is
> an equivalent of null which shows.
>
> However Maximum_At will propagate Constraint_Error if either of the bounds
> is No_Element. So the implementation would work.

Sure, but ideally we want the error we decided on for this situation.
Since the intent is to be generic, it's a shame to get one error with
some instantiations and a different one with others.

>> Second, if I try to use a Vector rather than an Ordered_Map, I am told
>> that:
>> test2.adb:97:05: error: instantiation error at line 12
>> test2.adb:97:05: error: no visible subprogram matches the specification for "<"
>> It would seem that vector cursors can't be compared using < (at least by
>> default). Maybe the installation needs more arguments.
>
> Vector has a proper index type. All you have to do is. Given
>
> package Integer_Vectors is
>
> Wrap Element into a function:
>
> V : Integer_Vectors.Vector;
> function Element (Index : Integer) return Integer is
> begin
> return V.Element (Index);
> end Element;
> ...
>
> and use the wrapper.

Sure, but the hope was to write something that does not need new
code for new situations. That's what makes it reusable.

>> Anyway, I am still not sure how to write a generic test for an empty
>> range.
>
> The problem is that the implementation of Cursor that breaks
> abstraction. The abstraction of an argument does not permit ideal
> non-values. Cursors and pointers have non-values. So if you want to test
> test for value validity to the abstraction:
>
> generic
> -- Ordered argument
> type Argument_Type is private;
> with function Valid (Value : Argument_Type) return Boolean is <>;
> ...
> package Generic_Arguments is
>
> Then you would pass Has_Element for it. For integers you would use wrapped
> X'Valid (there is no Integer'Valid, unfortunately. Only X'Valid where X is
> an object).

It's definitely getting what I call cumbersome.
The core of my Haskell solution is just a function decimalRepeatLength
that returns the repeat length given a divisor. But once I'd got the
answer (by applying it to 2 to 999 and getting the maximum) I wondered
what would happen if the numbers were not in a simple range. Is it easy
to write a `maximisedOver` function that finds the maximum of some
function over any ordered collection (technically, a "foldable" type in

Well, yes, it is easy:

function `maximisedOver` anything = maximum (fmap function anything)

so the solution to the project Euler problem is just

decimalRepeatLength `maximisedOver` [2..999]

but I can also find the maximum of this (or any other suitable) function
over an array, a hash map, a vector... whatever. No code changes
anywhere. It even works with arrays of any number of dimensions
regardless of the index bounds.

maximisedOver is genuinely generic and reusable.

I don't think this is incoherent. The Haskell libraries ensure that any
collection that is logically foldable is indeed foldable.

>> The bottom line is the last argument should be something very general
>> like the Period function.
>> A fix (though it's not really ideal) would be to use function
>> composition here (inventing . as the composition operator):
>> Map_Functions.Maximum_At (X.First, X.Last, Period'Access
>> . Element'Access)
>> but I don't think Ada has a function composition operator, does it?
>
> No as it would require closures.

What closure is required for a function composition? There is no
environment to "close over".

> So you can have a generic composition
> operator, no problem, but not a first-class one. However you can simply add
> Maximum_At with four arguments to the package.

This may be the closest we can get with Ada.
That's a lot just to use something that is supposed to be reusable.

>> You seem to be on your own as far as helping out is concerned!
>
> Because it started as a numeric puzzle. You should have asked directly

It only occurred to me after writing the non-generic solution. I
remember Ada as being something of a pioneer in it's attempt to provide
generic solutions, so I wondered how far things had come. I don't think
something really widely reusable is possible in this case.

--
Ben.

### G.B.

Sep 8, 2023, 2:09:59 AMSep 8
to
On 07.09.23 01:32, Ben Bacarisse wrote:

> A fix (though it's not really ideal) would be to use function
> composition here (inventing . as the composition operator):

Hm. A stateful, composed function that needs to be applied
in a certain way. Is that so different from calling interface
subprograms of a certain type?

to the commonalities. Considering the computational powers of
C++'s "hair-raising template metaprogramming" [14.4], the idea
of "Ada generics" = "functional style" is probably limited
in scope.

So, does type composition help?

[14.4]: A Tour of C++, 3rd ed.

### Dmitry A. Kazakov

Sep 8, 2023, 3:23:16 AMSep 8
to
On 2023-09-08 03:32, Ben Bacarisse wrote:
> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>
>> On 2023-09-07 01:32, Ben Bacarisse wrote:
>>> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>>>
>>>> On 2023-09-06 17:16, Ben Bacarisse wrote:
>>>>
>>> Second, if I try to use a Vector rather than an Ordered_Map, I am told
>>> that:
>>> test2.adb:97:05: error: instantiation error at line 12
>>> test2.adb:97:05: error: no visible subprogram matches the specification for "<"
>>> It would seem that vector cursors can't be compared using < (at least by
>>> default). Maybe the installation needs more arguments.
>>
>> Vector has a proper index type. All you have to do is. Given
>>
>> package Integer_Vectors is
>>
>> Wrap Element into a function:
>>
>> V : Integer_Vectors.Vector;
>> function Element (Index : Integer) return Integer is
>> begin
>> return V.Element (Index);
>> end Element;
>> ...
>>
>> and use the wrapper.
>
> Sure, but the hope was to write something that does not need new
> code for new situations. That's what makes it reusable.

Why should it be? You wanted to find maximum of a function. Vector is
not a function. It is in mathematical terms, but not in the language
terms. The abstraction for finding maximum in a container is just a
different abstraction.

>> Then you would pass Has_Element for it. For integers you would use wrapped
>> X'Valid (there is no Integer'Valid, unfortunately. Only X'Valid where X is
>> an object).
>
> It's definitely getting what I call cumbersome.

Yes, because you try too hard to make it work where it probably should not.

> I don't think this is incoherent. The Haskell libraries ensure that any
> collection that is logically foldable is indeed foldable.

Ada arrays and library containers do not share interfaces. [It is a long
discussion how they could be]. But similarly, there is no shared
interface between digits of a number in octal base and a container and a
string in UTF-16 encoding. Should there be? No. Should the language
possible in Ada in some very uncomfortable AKA cumbersome way, which is
why "finding maximum" is not a worthy abstraction in Ada.

>>> The bottom line is the last argument should be something very general
>>> like the Period function.
>>> A fix (though it's not really ideal) would be to use function
>>> composition here (inventing . as the composition operator):
>>> Map_Functions.Maximum_At (X.First, X.Last, Period'Access
>>> . Element'Access)
>>> but I don't think Ada has a function composition operator, does it?
>>
>> No as it would require closures.
>
> What closure is required for a function composition? There is no
> environment to "close over".

In Ada a function can use anything visible at its declaration point and
at the location of its body. You can even declare a function inside a
recursively called function and let it see local variables of each
recursive call, in effect having an infinite set of functions.

> That's a lot just to use something that is supposed to be reusable.

[rant on]
An Ada programmer would just write a loop. Abstractions are meant to
abstract the problem domain. If you starting abstract elementary
programming activities, then there might be something wrong with the
language or with you.

Then there is a point about readability. When I see a loop I say, aha
this is what the guy is going to do. When I see a pile of calls of a
dozen generic instances with arbitrary names, I begin to worry.

In my view it is a road to nowhere, for an imperative language at least.
The end of this road can be seen in modern C++. 20 years ago C++ was
severely crippled broken but sometimes enjoyable language. You could
*read* a C++ program. In these days with all libraries it became Forth
on steroids. There is no such thing as a C++ program anymore, just calls
upon calls.
[rant off]

> It only occurred to me after writing the non-generic solution. I
> remember Ada as being something of a pioneer in it's attempt to provide
> generic solutions, so I wondered how far things had come. I don't think
> something really widely reusable is possible in this case.

As I said you think in a wrong direction of abstracting the language
"finding maximum" rather than the problem space, e.g. generalization to
other bases, other mathematical structures etc.

### Ben Bacarisse

Sep 8, 2023, 5:02:41 PMSep 8
to
"G.B." <bau...@notmyhomepage.invalid> writes:

> On 07.09.23 01:32, Ben Bacarisse wrote:
>
>
>> A fix (though it's not really ideal) would be to use function
>> composition here (inventing . as the composition operator):
>
> Hm. A stateful, composed function that needs to be applied
> in a certain way. Is that so different from calling interface
> subprograms of a certain type?

There was nothing stateful (as I understand the term) in either function
being composed.

not see any fix other than passing a composed function which would, it
seems, have to be written afresh. Is that what your question refers to?
If so, then yes there is a small difference: writing a function (albeit
just a few lines) vs. applying an operator to two already written
functions.

> to the commonalities. Considering the computational powers of
> C++'s "hair-raising template metaprogramming" [14.4], the idea
> of "Ada generics" = "functional style" is probably limited
> in scope.
>
> So, does type composition help?

My turn to guess now: you are not being serious? I see no connection to
monads or type composition. And why bring C++ into it?

Having found the maximum of the function 'Period' over a range 2..999,
you might find yourself a week later wanting the maximum absolute value
of the numbers in an Ordered_Map. And then later the maximum of sine
squared over the elements of 2D array. You might want to have a
resuable "maximum of F over X" function, so I was curious about how
close one could get to this in Ada (or, more accurately, what the
restrictions on X and F might have to be).

--
Ben.

### Ben Bacarisse

Sep 8, 2023, 8:25:42 PMSep 8
to
I wanted the maximum of a function over a collection (range, array, map,
etc). In some languages, collections can be scanned so you don't need
to know where the data come from.

>>> Then you would pass Has_Element for it. For integers you would use wrapped
>>> X'Valid (there is no Integer'Valid, unfortunately. Only X'Valid where X is
>>> an object).
>> It's definitely getting what I call cumbersome.
>
> Yes, because you try too hard to make it work where it probably should
> not.

If you think a resuable Ada function that can find the maximum of some F
over some 'collection' X is possible, I'd like to see how it's done. I
can do it for some kinds of X but I have no idea how general it can be
general, or to make it very general is too much work, or that one should
not be trying in the first place.

(I put 'collection' in quotes because I know that's an Ada term but I
don't necessarily want to restrict the solution to how Ada uses the
term. For example, I don't think native arrays are collections in the

>> I don't think this is incoherent. The Haskell libraries ensure that any
>> collection that is logically foldable is indeed foldable.
>
> Ada arrays and library containers do not share interfaces.

I was pretty sure that was the case. Thanks for confirming. I think
that means there can be no truly generic solution. But maybe it's
possible at least for all container types in the library? (But I note
that if you think it /shouldn't/ be done, I won't expect you to show me
how.)

> Should the language allow adding
> ad-hoc interfaces to existing types. Yes, and this is possible in Ada in
> some very uncomfortable AKA cumbersome way, which is why "finding maximum"
> is not a worthy abstraction in Ada.

I suspected one might have to extend the interfaces. If a simple
abstraction (maximise F over X) does not have a simple representation,
it's not going to be worth it. Just write a slightly different empty
test and loop each time you need to do it.

>>>> A fix (though it's not really ideal) would be to use function
>>>> composition here (inventing . as the composition operator):
>>>> Map_Functions.Maximum_At (X.First, X.Last, Period'Access
>>>> . Element'Access)
>>>> but I don't think Ada has a function composition operator, does it?
>>>
>>> No as it would require closures.
>> What closure is required for a function composition? There is no
>> environment to "close over".
>
> In Ada a function can use anything visible at its declaration point and at
> the location of its body. You can even declare a function inside a
> recursively called function and let it see local variables of each
> recursive call, in effect having an infinite set of functions.

At the point where I want Period.Element I can write the (almost)
one-line function that takes a Cursor and returns Period(Element(C))
entirely mechanically. Can't the compiler do that?

Note I'm not asking if it /should/ (it may not be "Ada-like" to do
that). I'm just curious if there really is a technical reason it can't
be done.

>> That's a lot just to use something that is supposed to be reusable.
>
> [rant on]
> An Ada programmer would just write a loop.

Yes, that's fine. Different languages have different objectives. Just
write the empty range test and the loop you need for each kind of
collection. That was definitely the way things were done in the 80s.

>> It only occurred to me after writing the non-generic solution. I
>> remember Ada as being something of a pioneer in it's attempt to provide
>> generic solutions, so I wondered how far things had come. I don't think
>> something really widely reusable is possible in this case.
>
> As I said you think in a wrong direction of abstracting the language
> "finding maximum" rather than the problem space, e.g. generalization to
> other bases, other mathematical structures etc.

Generalising to an arbitrary base is local to the function that finds
the answer for one element. It's an entirely separate axis of
generalisation to that of where the elements come from.

It's interesting to me that you consider one simply wrong and the other
natural. In some languages the "wrong" one does not even merit
consideration as it's just there for free. You can concentrate on the
other bases and other structures without worrying if the program will be
able to maximise over the collection in which they are stored. (For
example, for polynomial residues, they can't come from a range like
2..999.)

I really do appreciate your help. I would not have got off the ground
Usenet is coming across people with very different ideas about
programming. In this case, it seems to be about what is worth
generalising and what isn't.

--
Ben.

### G.B.

Sep 9, 2023, 4:13:48 AMSep 9
to
On 08.09.23 23:02, Ben Bacarisse wrote:
> "G.B." <bau...@notmyhomepage.invalid> writes:
>
>> On 07.09.23 01:32, Ben Bacarisse wrote:
>>
>>
>>> A fix (though it's not really ideal) would be to use function
>>> composition here (inventing . as the composition operator):
>>
>> Hm. A stateful, composed function that needs to be applied
>> in a certain way. Is that so different from calling interface
>> subprograms of a certain type?
>
> There was nothing stateful (as I understand the term) in either function
> being composed.

The "apparatus" that the computation needs in order to remember
"max so far" looks like part of its state to me. Somehow
"the function" needs to operate this state and evaluate it.
Extend this to:
- find the maximum of [the maxima of] these n collections
- find the maximum in this stream at 10 seconds from now.

Is it possible, or practical, to define a pure function so that
calling it will remember the needed information, n >= 0
being arbitrary?

>> So, does type composition help?
>
> My turn to guess now: you are not being serious? I see no connection to

In the following sense:
There is an object of type So_Far that can remember
objects of any type T, them coming from collections
of type C-of-T.

> And why bring C++ into it?

It's already there, you mentioned the pair of iterators, and
there is std::max_element() which finds the greatest element
in any range based solely on these, and optionally using a generic
comparison.
There are similar things in Dmitry's packages. A key difference
seems to be that Ada's Cursors are tied to a specific collection.
I don't know of any convenient way around this, maybe because
type Cursor is just private in every Ada.Containers.Xyz and
there is no common type name for them, or for what some
algorithm might need them to have in common.

I'm not sure if the new Ada.Iterator_Interfaces (LRM 5.5.1)
could solve this, also because I really don't know that yet.
But it looks like I'd need instances of specific containers
for instantiation. (That being consistent with Ada's approach
to the STL, I think.)

### Dmitry A. Kazakov

Sep 9, 2023, 5:32:42 AMSep 9
to
On 2023-09-09 02:25, Ben Bacarisse wrote:
> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>
>> On 2023-09-08 03:32, Ben Bacarisse wrote:
>>> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>>>
>>>> On 2023-09-07 01:32, Ben Bacarisse wrote:
>>>>> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>>>>>
> I wanted the maximum of a function over a collection (range, array, map,
> etc). In some languages, collections can be scanned so you don't need
> to know where the data come from.

Hmm, the thing we discussed was a maximum element in array or map rather
than a maximum of a function over the *domain* set of array or map. In a
typed language array /= domain of array.

>>>> Then you would pass Has_Element for it. For integers you would use wrapped
>>>> X'Valid (there is no Integer'Valid, unfortunately. Only X'Valid where X is
>>>> an object).
>>> It's definitely getting what I call cumbersome.
>>
>> Yes, because you try too hard to make it work where it probably should
>> not.
>
> If you think a resuable Ada function that can find the maximum of some F
> over some 'collection' X is possible, I'd like to see how it's done.

To start with, no such function exists. Not in a typed language. Note
that a generic function is not a function. So instead we must consider
language constructs for the purpose. Generic instantiation is one of
them, some class might be another, but in Ada we just use loops. (And
yes, people liking writing programs while standing on their heads, may
use recursion... (:-))

> I
> can do it for some kinds of X but I have no idea how general it can be
> general, or to make it very general is too much work, or that one should
> not be trying in the first place.

The limits of generality are defined by the interfaces. In Ada types are
designed to implement needed interfaces upfront. If you want to do that
after the fact, you need some other adapter types to shove an existing
type into something it was not designed for.

>>> I don't think this is incoherent. The Haskell libraries ensure that any
>>> collection that is logically foldable is indeed foldable.
>>
>> Ada arrays and library containers do not share interfaces.
>
> I was pretty sure that was the case. Thanks for confirming. I think
> that means there can be no truly generic solution. But maybe it's
> possible at least for all container types in the library?

If a library is designed with this purpose in mind, that is trivial as
you just pointed out. All collection types in the library would
implement the required interface. End of story.

> (But I note
> that if you think it /shouldn't/ be done, I won't expect you to show me
> how.)

That is not a language question. It is a question of the library design.
What if the library did not follow the desired design? That would be a
language question and Ada offers some means, but not enough from my
point of view due to the limitation of its type system.

>> Should the language allow adding
>> ad-hoc interfaces to existing types. Yes, and this is possible in Ada in
>> some very uncomfortable AKA cumbersome way, which is why "finding maximum"
>> is not a worthy abstraction in Ada.
>
> I suspected one might have to extend the interfaces.

You cannot in a strongly typed language without breaking too much
things. You must create another type related to the old one and
implementing the new interface (superclass). That would do the trick.
Ada cannot this, so you go for the poor man's substitute: a mix-in. I.e.
you create a new type that references an object of the old type. E.g.
see array cursors example in my earlier post.

>>> What closure is required for a function composition? There is no
>>> environment to "close over".
>>
>> In Ada a function can use anything visible at its declaration point and at
>> the location of its body. You can even declare a function inside a
>> recursively called function and let it see local variables of each
>> recursive call, in effect having an infinite set of functions.
>
> At the point where I want Period.Element I can write the (almost)
> one-line function that takes a Cursor and returns Period(Element(C))
> entirely mechanically. Can't the compiler do that?

No.

(Ada indeed composes functions in some limited number of cases, e.g. an
explicit type conversion of [in] out arguments. But these are predefined.)

> Note I'm not asking if it /should/ (it may not be "Ada-like" to do
> that). I'm just curious if there really is a technical reason it can't
> be done.

Actually compositions might be useful in many cases and adapting
interfaces is one of them.

>>> That's a lot just to use something that is supposed to be reusable.
>>
>> [rant on]
>> An Ada programmer would just write a loop.
>
> Yes, that's fine. Different languages have different objectives. Just
> write the empty range test and the loop you need for each kind of
> collection.

You can loop in Ada over empty ranges, no problem.

> That was definitely the way things were done in the 80s.

Yes, before the Dark Ages of Computing...

>>> It only occurred to me after writing the non-generic solution. I
>>> remember Ada as being something of a pioneer in it's attempt to provide
>>> generic solutions, so I wondered how far things had come. I don't think
>>> something really widely reusable is possible in this case.
>>
>> As I said you think in a wrong direction of abstracting the language
>> "finding maximum" rather than the problem space, e.g. generalization to
>> other bases, other mathematical structures etc.
>
> Generalising to an arbitrary base is local to the function that finds
> the answer for one element. It's an entirely separate axis of
> generalisation to that of where the elements come from.
>
> It's interesting to me that you consider one simply wrong and the other
> natural.

Because one is a software design artifact and another is the result of
problem space analysis.

> In some languages the "wrong" one does not even merit

Being a part of design it has all possible merits to consider and then
reject it. That is in the position of a puzzle solver. Now in the
position of a library designer, the Ada standard library has an
[informal] interface that supports what you wanted:

1. Cursor
2. Key at the cursor
3. Element at the cursor
4. Iterate procedure

So, for the Ada standard library it might look like this:

generic
type Container_Type (<>) is limited private;
type Element_Type is private;
type Key_Type is private;
type Cursor_Type is private;
with function "<" (Left, Right : Element_Type) return Boolean is <>;
with function Key (Position : Cursor_Type) return Key_Type is <>;
with function Element
( Position : Cursor_Type
) return Element_Type is <>;
with procedure Iterate
( Container : Container_Type;
Process : not null access procedure
(Position : Cursor_Type)
) is <>;
function Generic_Container_Maximum_At (Container : Container_Type)
return Key_Type;

function Generic_Container_Maximum_At (Container : Container_Type)
return Key_Type is
Found : Boolean := False;
Max : Element_Type;
Result : Key_Type;
procedure Walker (Position : Cursor_Type) is
begin
if Found then
if Max < Element (Position) then
Result := Key (Position);
Max := Element (Position);
end if;
else
Result := Key (Position);
Max := Element (Position);
Found := True;
end if;
end Walker;
begin
Iterate (Container, Walker'Access);
if Found then
return Result;
else
raise Constraint_Error with "Empty container";
end if;
end Generic_Container_Maximum_At;

Instantiation:

package Integer_Maps is
use Integer_Maps;
function Integer_Map_Max is
new Generic_Container_Maximum_At (Map, Integer, Integer, Cursor);

### Ben Bacarisse

Sep 9, 2023, 5:04:39 PMSep 9
to
"G.B." <bau...@notmyhomepage.invalid> writes:

> On 08.09.23 23:02, Ben Bacarisse wrote:
>> "G.B." <bau...@notmyhomepage.invalid> writes:
>>
>>> On 07.09.23 01:32, Ben Bacarisse wrote:
>>>
>>>
>>>> A fix (though it's not really ideal) would be to use function
>>>> composition here (inventing . as the composition operator):
>>>
>>> Hm. A stateful, composed function that needs to be applied
>>> in a certain way. Is that so different from calling interface
>>> subprograms of a certain type?
>> There was nothing stateful (as I understand the term) in either function
>> being composed.
>
> The "apparatus" that the computation needs in order to remember
> "max so far" looks like part of its state to me.

The "max so far" function is not being composed.

> Somehow
> "the function" needs to operate this state and evaluate it.
> Extend this to:
> - find the maximum of [the maxima of] these n collections
> - find the maximum in this stream at 10 seconds from now.
>
> Is it possible, or practical, to define a pure function so that
> calling it will remember the needed information, n >= 0
> being arbitrary?

I am not sure how the discussion got here. Ada is an imperative
language so of course one would use "running" state to calculate a
maximum. The max_of_F_over_X function just loops like any other loop
from First_Of(X) to Last_Of(X) calculating F(This(X)), comparing that
with Max_So_Far.

These are invented names, of course, because I don't know how it should
be done, but the idea is plain imperative code. In fact, it's possible
that Ada has some entirely different syntax for this kind of imperative
loop.

The "fix" to use a composed function was because one proposed solution
found the maximum of Element(C) (where C was a cursor) because Element
was passed as F, but that of course is not what was wanted. To find the
maximum of F I speculated that one could pass F.Element.

>>> So, does type composition help?
>> My turn to guess now: you are not being serious? I see no connection to
>
> In the following sense:
> There is an object of type So_Far that can remember
> objects of any type T, them coming from collections
> of type C-of-T.

Given the above confusion about what is being composed, I can see the
connection with monads. But there is no reason to use the concept of a
monad in a language with modifiable state. The maximum should be found
as in the posted code with a simple loop.

> I'm not sure if the new Ada.Iterator_Interfaces (LRM 5.5.1)
> could solve this, also because I really don't know that yet.
> But it looks like I'd need instances of specific containers
> for instantiation. (That being consistent with Ada's approach
> to the STL, I think.)

Thanks for the pointer. I am not sure I have time to look in detail,
but it looks interesting.

--
Ben.

### Ben Bacarisse

Sep 9, 2023, 9:20:25 PMSep 9
to
"Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:

> On 2023-09-09 02:25, Ben Bacarisse wrote:
>> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:

>>> [rant on]
>>> An Ada programmer would just write a loop.
>> Yes, that's fine. Different languages have different objectives. Just
>> write the empty range test and the loop you need for each kind of
>> collection.
>
> You can loop in Ada over empty ranges, no problem.

Yes, but the problem in hand (maximum of F over X) should raise an error
on an empty X. I know there are other options, but you chose to
raise an error so that's the design I was talking about.

>> That was definitely the way things were done in the 80s.
>
> Yes, before the Dark Ages of Computing...

Eh? There have been repeated updates to the Ada language. Are they
taking Ada into the dark ages? If so, what was the golden age of Ada
when its design was perfect for numerical algorithms?

>>> As I said you think in a wrong direction of abstracting the language
>>> "finding maximum" rather than the problem space, e.g. generalization to
>>> other bases, other mathematical structures etc.
>> Generalising to an arbitrary base is local to the function that finds
>> the answer for one element. It's an entirely separate axis of
>> generalisation to that of where the elements come from.
>> It's interesting to me that you consider one simply wrong and the other
>> natural.
>
> Because one is a software design artifact and another is the result of
> problem space analysis.

Which one the wrong one?

>> In some languages the "wrong" one does not even merit
>
> Being a part of design it has all possible merits to consider and then
> reject it. That is in the position of a puzzle solver. Now in the position
> of a library designer, the Ada standard library has an [informal] interface
> that supports what you wanted:

Well, there has been some confusion over that, but from what I
understand of the code below, adding in a function to maximise would be
simple.
This is probably the closest we can get to a universal solution.
Vectors don't have a Key function but I am sure I could find out what
should be provided there.

Thanks.

I agree that is does not feel worth it. Just write the loop our each time.

--
Ben.

### Dmitry A. Kazakov

Sep 10, 2023, 4:46:07 AMSep 10
to
On 2023-09-10 03:20, Ben Bacarisse wrote:
> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>
>> On 2023-09-09 02:25, Ben Bacarisse wrote:
>>> "Dmitry A. Kazakov" <mai...@dmitry-kazakov.de> writes:
>
>>>> [rant on]
>>>> An Ada programmer would just write a loop.
>>> Yes, that's fine. Different languages have different objectives. Just
>>> write the empty range test and the loop you need for each kind of
>>> collection.
>>
>> You can loop in Ada over empty ranges, no problem.
>
> Yes, but the problem in hand (maximum of F over X) should raise an error
> on an empty X. I know there are other options, but you chose to
> raise an error so that's the design I was talking about.

It can be done by a Boolean flag.

>>> That was definitely the way things were done in the 80s.
>>
>> Yes, before the Dark Ages of Computing...
>
> Eh? There have been repeated updates to the Ada language. Are they
> taking Ada into the dark ages? If so, what was the golden age of Ada
> when its design was perfect for numerical algorithms?

I meant the state of computing as a whole.

(Ada is a niche language and "hordes of barbarians" largely missed its
existence... (:-))

>>>> As I said you think in a wrong direction of abstracting the language
>>>> "finding maximum" rather than the problem space, e.g. generalization to
>>>> other bases, other mathematical structures etc.
>>> Generalising to an arbitrary base is local to the function that finds
>>> the answer for one element. It's an entirely separate axis of
>>> generalisation to that of where the elements come from.
>>> It's interesting to me that you consider one simply wrong and the other
>>> natural.
>>
>> Because one is a software design artifact and another is the result of
>> problem space analysis.
>
> Which one the wrong one?

None automatically is. The point is avoiding overdesigning a numeric puzzle.

[...]
> This is probably the closest we can get to a universal solution.
> Vectors don't have a Key function but I am sure I could find out what
> should be provided there.

Vector has To_Index for Key.

In general, note that Ada does not require you to use any library. I
personally dislike cursors in particular because of their "functional"
style. I prefer plain element position and loop iteration of ordered
structures. A container library based on this paradigm would use othe