Can pure functions accept const parameters or only invariant
mastrost
titi.mastro at free.fr
Tue Dec 30 15:24:35 PST 2008
Denis Koroskin Wrote:
> On Tue, 30 Dec 2008 03:37:55 +0300, mastrost <titi.mastro at free.fr> wrote:
>
> > Christopher Wright Wrote:
> >
> >> mastrost wrote:
> >> > So why is this code accepted by the compiler?
> >>
> >> I'm not sure whether it's intentional, but a pure function is correct
> >> for mutable input as well as invariant input (barring threading issues),
> >> so this avoids code duplication.
> >
> > Yes maybe, but it creates strange stuffs... you could have a pure
> > function taking const inputs, another pure function taking invariant
> > inputs, and of course the first one could not call the second one, even
> > if it was called with invariant inputs.....I mean this would not be
> > allowed:
> >
> > pure int g(invariant A a){
> > return a.x;
> > }
> >
> > pure int f(const A a){
> > assert(is(typeof(a) == const(A))); //a is seen as const, even if a
> > is in fact invariant
> > return g(a); //error
> > }
> >
> > Wich means that it is possible that a pure function can not call another
> > one.
> >
>
> Does everyone still remember discussion we had some time ago about equivariant functions (http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=77729)?
>
> Perhaps, we could use a property of pure functions that they can accept all kind of input data (mutable, const and immutable) and still be correct and checked by compiler?
>
> Currently, we have to declare three distinct functions:
>
> pure invariant(char)[] trim(invariant(char)[] str);
> const(char)[] trim(const(char)[] str);
> char[] trim(char[] str);
>
> Could they be reduced to just one:
>
> pure char[] trim(char[] str); // ?
It is true that one should not duplicate code, but you can avoid that by using mixins.
If we use only one declaration, then what is the use of the 'pure' keyword ?
Anyway does anyone know what is the current behaviour in version 2.022 (why const is accepted in pure functions??) ?
More information about the Digitalmars-d
mailing list