Re: Questions about syntax decisions

2010-05-19 Thread Bill Baxter
On Wed, May 19, 2010 at 3:55 AM, bearophile bearophileh...@lycos.com wrote:

 As a side note, C++0x is going to add a new suffix operator to C++. This
 operator would be useful in its own right. Are there any plans to add a
 new opSuffix!(s) operator in D?

 Quite probably it will not become part of D, I think Andrei doesn't like 
 that. D has Foo!xxx(...) syntax.

It would also be chaos in D, since D lacks fine-grained control over namespaces.

D's module==namespace model means that every module has to be designed
with the idea that every publicly visible entity is likely to end up
in the global namespace.  That doesn't really play together nicely
with the notion of defining a bunch of what are essentially
single-letter functions.

--bb


Re: rebuild configuration

2010-05-18 Thread Bill Baxter
I recently ran into Gregor Richards unexpectedly outside the context of D.
It sounds like he's busy with grad school and not likely to turn back
to development of Rebuild/DSSS any time soon.

--bb

On Tue, May 18, 2010 at 1:45 PM, theambient tiaba...@gmail.com wrote:
 thanks.

 I've decided to quit rebuild too, besides I've found VisualD!!!

 --
 Ruslan Mullakhmetov

 Trass3r u...@known.com сообщил(а) в новостях
 следующее:op.vcwiqeux3nc...@enigma.fem.tu-ilmenau.de...

 I recommend not to use rebuild anymore.
 It's horribly outdated.

 xfBuild is quite neat.




Re: generic + numeric + literals = abomination

2010-03-27 Thread Bill Baxter
Note that 'real' is a built in type in D.  It's an 80-bit float on x86
procs and 64-bit elsewhere.
So .5L is like cast(real).5.  Not the solution you were looking for.

--bb

2010/3/27 so s...@so.do:
 On Sat, 27 Mar 2010 15:28:22 +0200, bearophile bearophileh...@lycos.com
 wrote:

 so:

 One thing i can think of now is adding another float literal, maybe 'r',
 for real!,

 See here, Unfortunately it's called L not r:
 http://www.digitalmars.com/d/2.0/lex.html

 FloatSuffix:
        f
        F

 RealSuffix:
        L

 bearophile

 Yes, it says :
 Floating literals with no suffix are of type double. Floats can be followed
 by one f, F, or L suffix. The f or F suffix means it is a float, and L means
 it is a real.

 Problem remains, i think you either lost me or just didn't read what i
 wrote,
 or well.. most probably i am still not clear enough.

 --
 Using Opera's revolutionary e-mail client: http://www.opera.com/mail/



Re: boolean over multiple variables

2010-01-26 Thread Bill Baxter
On Tue, Jan 26, 2010 at 1:21 PM, bearophile bearophileh...@lycos.com wrote:
 Nick Sabalausky:
 Aside from that being how Python does it, why do you see that as preferable?

 Because:
 1) linear searches in an array are damn common. I don't remember the results 
 of my benchmarks, but until your integer arrays is quite longer than 30-50 
 items, performing a linear search is faster than a lookup in an AA, on DMD. 
 On Tango this number is probably 70% higher
 1b) In Python if you perform a foo in barfoo the language doesn't perform 
 a linear search, it uses a much smarter search that has a complexity lower 
 than the product of the two lengths, using a custom algorithm. So in D you 
 can use the same syntax to search for substrings/subarrays. Where such 
 smarter search is not possible, D can use a naive search.
 2) It's really handy. I use isIn(item, items) to search on arrays in D, but 
 having a item in items is nicer.
 3) You can use the same syntax to search into anything that's lazily iterable 
 too (a Range). This is very handy.


 So having a single syntax work on the outputs for
 regular arrays, but then on the inputs for AAs, seems highly inconsistent
 and error-prone to me.

 I have followed many Python newbies personally, I am following the Python 
 newsgroups, and I have programmed for years in Python, and while I have seen 
 many different kinds of bugs, I have not seen a significant amount of bugs in 
 this. Python programmers just learn that dicts and lists are a little 
 different in this regard. At the same way they learn that a set and a dict 
 are different data structures, with different capabilities and usages.

It's not even really  inconsistent if you just think about these data
structures in terms of function rather than form.
An array is often used as a simple set of things.  O in Array means
is O in that set of things
An AA is a set of things that also have some associated data.  O in
AA means is O in that set of things (not the ancillary data)
If you have an actual set data structure for containing a set of of
things, then O in Set means, again, is O in that set of things.
(In fact the closest thing D has to a built-in set type is an AA with
don't care associated data, reinforcing the notion of AA as a set
plus extra data.)

--bb


Re: boolean over multiple variables

2010-01-26 Thread Bill Baxter
On Tue, Jan 26, 2010 at 6:16 PM, Nick Sabalausky a...@a.a wrote:
Bill Baxter wbax...@gmail.com wrote in message
news:mailman.34.1264542189.4461.digitalmars-d-le...@puremagic.com...
On Tue, Jan 26, 2010 at 1:21 PM, bearophile bearophileh...@lycos.com
wrote:
 Nick Sabalausky:
 Aside from that being how Python does it, why do you see that as
 preferable?

 Because:
 1) linear searches in an array are damn common. I don't remember the
 results of my benchmarks, but until your integer arrays is quite longer
 than 30-50 items, performing a linear search is faster than a lookup in
 an AA, on DMD. On Tango this number is probably 70% higher
 1b) In Python if you perform a foo in barfoo the language doesn't
 perform a linear search, it uses a much smarter search that has a
 complexity lower than the product of the two lengths, using a custom
 algorithm. So in D you can use the same syntax to search for
 substrings/subarrays. Where such smarter search is not possible, D can
 use a naive search.
 2) It's really handy. I use isIn(item, items) to search on arrays in D,
 but having a item in items is nicer.
 3) You can use the same syntax to search into anything that's lazily
 iterable too (a Range). This is very handy.


 So having a single syntax work on the outputs for
 regular arrays, but then on the inputs for AAs, seems highly
 inconsistent
 and error-prone to me.

 I have followed many Python newbies personally, I am following the Python
 newsgroups, and I have programmed for years in Python, and while I have
 seen many different kinds of bugs, I have not seen a significant amount
 of bugs in this. Python programmers just learn that dicts and lists are a
 little different in this regard. At the same way they learn that a set
 and a dict are different data structures, with different capabilities and
 usages.

It's not even really  inconsistent if you just think about these data
structures in terms of function rather than form.
An array is often used as a simple set of things.  O in Array means
is O in that set of things
An AA is a set of things that also have some associated data.  O in
AA means is O in that set of things (not the ancillary data)
If you have an actual set data structure for containing a set of of
things, then O in Set means, again, is O in that set of things.
(In fact the closest thing D has to a built-in set type is an AA with
don't care associated data, reinforcing the notion of AA as a set
plus extra data.)



 Even looking at function rather than form, I still think its innacurate to
 consider the keys to be the elements of an AA. In most uses of an AA, the
 key is primarily something convenient with which to look up data. They hold
 significance, but typically not as much as the data that is looked up with
 it. What you've described is very much like (and quite literally the same
 as, in the case of many dynamic languages) thinking of a variable's name as
 the actual data, and thinking of the value it holds merely as ancillary
 data.

 Keep in mind too, even with a regular array, the index can still hold
 significance as data. For instace, I could have an array of Foo's, declare
 that any element with an odd index has property 'A' and any with an even
 index has property 'B', and treat them as such. May seem strange at a
 glance, but such things are common in low-level, low-resoruce and
 performance-oriented code. Bottom line, though, is that Property 'A' or
 'B' is data that now been encoded in the array's index, but despite that,
 the indicies still aren't considered the array's elements. And the data they
 lookup still isn't considered ancillary data.

 And yes, a Hashed Set may likely be *implemented* as an AA with just keys,
 but that's just form, it doesn't imply a similarity in regard to function.
 The *function* of a HashSet is that of an unordered array that's been
 optimized for contains X / doesn't contain X on large data sets.

 Containers and their functions:
 - AA: Store A's with label B, A is fairly important, B may or may not be.
 - Array: Store A's with label B, A is fairly important, B may or may not be,
 B has certain restrictions, container overall has different performance
 characteristacs from an AA.
 - Hashed Set: Store A's.


All I am trying to say is that there are multiple ways of looking at
the functionality offered by different containers.
And there exists a way of looking at it where the Python-style 'in'
operator can be seen as behaving consistently.

You asserted it is inconsistent.  I'm just saying it's only
inconsistent if you insist that one particular way of looking at the
containers is the right way.

--bb


Re: Multidimensional foreach

2009-12-18 Thread Bill Baxter
On Fri, Dec 18, 2009 at 5:17 AM, Simen kjaeraas simen.kja...@gmail.com wrote:
 Simen kjaeraas simen.kja...@gmail.com wrote:

 I have a function that returns an N-dimensional array, where N is a
 template parameter. Now I want to run a foreach loop through each
 element of this array. Is there a known and tested way to do this,
 or should I write my own templates to do it?

 I wrote this implementation. Now, to get some meaningful indices
 out of it. Do D2's ranges even support that? Oh, and I probably
 need to rewrite it in terms of an index instead of slices to get
 that working. Bah.

 Ideas? Comments? Death threats?

I think you need to explain more what you are hoping to accomplish.
In general there are two ways to store multidimensional data:

1) jagged - with arrays of arrays.  This is the method directly
supported by D arrays.
With this accessing each element requires as many indirections as
there are dimensions.
But for large arrays, this is more friendly to memory use because
the data doesn't have to be in one huge contiguous chunk

2) rectangular - with indexing into a chunk of memory.  This method is
directly supported by some languages like C#, but not D.
Accessing each element requires just one indirection but a bit of
offset computation.
Very large arrays may have trouble fitting in available memory.
   (See this very old proposal for adding them to D:
http://homepages.uni-regensburg.de/~nen10015/documents/D-multidimarray.html)

Generally if your plan is to do math on these arrays, method 2 is
better supported by existing math libraries.
So what do you plan to do with these?  You may be better off
implementing a rectangular style multi-dim array type than trying to
use D's built-in.  Or look at the multi-dim array types written by
Fawzi or myself.

--bb


Re: static arrays in C functions

2009-12-08 Thread Bill Baxter
On Tue, Dec 8, 2009 at 2:08 AM, Lutger lutger.blijdest...@gmail.com wrote:
 Since a while some extern(C) functions which take arrays seem to be broken.
 Can anybody clarify /confirm how they should be declared?

 For example I stumbled upon this:

 import core.sys.posix.unistd, std.stdio;

 void main()
 {
    int[2] fd;
    writeln( pipe(fd) ); // failes with errno == EFAULT
 }

 In core.sys.posix.unistd, pipe is declared as: int pipe(int[2]);


 This works though:

 extern (C) { int pipe(int*); }

 void main()
 {
    int[2] fd;
    writeln( pipe(fd.ptr) );
 }

(Assuming you're talking about D2 here...)
A few releases ago fixed-size arrays changed to be pass-by-value.
But I guess there's still some logic in there to interpret int[2] as
int* when inside an extern(C) block.

It does seem like there's a bug there, though.  I think pipe(fd) in
the first case should fail to compile because it's attempting to pass
by value where a pointer is expected.

--bb


Re: Foo!(a).????? == `Foo!(a)`

2009-12-05 Thread Bill Baxter
On Sat, Dec 5, 2009 at 5:36 PM, Nick Sabalausky a...@a.a wrote:
 I don't suppose there's an easy general way to get the paramaters of a
 templated type just from the type itself? Ie, a way to get around this:

 class Foo(char[] str) {}
 static assert(Foo!(a).stringof != Foo!(b).stringof)
 // ^ fails because it evaluates to Foo != Foo

 I can probably work around it in my current case by sticking str into a
 const member of Foo and using that together with .stringof, but thought I'd
 see if there was a better way.

That should just be considered a bug I think.  I think what stringof
does is not detailed in the spec beyond provides a string
representation.  Clearly just returning the base name of the template
is not the most useful representation of a template type.  Stringof
clearly needs to have more thought put into it (as has been brought up
many times in the past).

--bb


Re: why can't structs implement interfaces?

2009-11-24 Thread Bill Baxter
On Tue, Nov 24, 2009 at 2:49 PM, Saaa em...@needmail.com wrote:
 bearophile wrote:
 Moritz Warning:

 If you only what a contract that certain functions are implemented,
 then it just need to be implemented in the compiler frontend.

 In the meantime this can be done with a template mixin, where the template
 statically asserts the presence of the functions/fields you want.

 Bye,
 bearophile

 I wanted to do something like this:

 class C : I {};
 struct S : I {};
 S s;
 I[] i =[new C(), s ];

Yeh, that's never going to work because that's acting as a dynamic
polymorphic interaface.  Referring polymorphically to a struct like
that pretty much makes it not a struct anymore, and requires having
the hidden pointer to a vtable that was mentioned.  That's what
classes are for.

In D2 you can use alias this inside a class to forward things to the
struct, though. Something like this:

class ClassWrapper(S) : I {
   S _impl;
   alias _impl this;
}

But I somehow doubt DMD will consider methods handled by S as being an
implementation of the interface.
So you'll need explicit forwarding.

--bb


Re: why can't structs implement interfaces?

2009-11-24 Thread Bill Baxter
On Tue, Nov 24, 2009 at 3:09 PM, Saaa em...@needmail.com wrote:

 I wanted to do something like this:

 class C : I {};
 struct S : I {};
 S s;
 I[] i =[new C(), s ];

 Yeh, that's never going to work because that's acting as a dynamic
 polymorphic interaface.  Referring polymorphically to a struct like
 that pretty much makes it not a struct anymore, and requires having
 the hidden pointer to a vtable that was mentioned.  That's what
 classes are for.
 Why is a hidden pointer necessary? (Just curious :)

 My simplistic view was like this:
 i[1] would just hold the location of s and s would be checked to have
 all it needs to be an I.

I think it could be done with a different implementation of interfaces
from the one D uses, one based on fat pointers.
With that design an I referring to an S would be a fat pointer, one
pointer pointing to the S and one pointing to S's table of function
pointers (vtable) for the I interface.

That's not how D does it AFAIR, but I don't actually recall how D does it.

--bb


Re: why can't structs implement interfaces?

2009-11-24 Thread Bill Baxter
On Tue, Nov 24, 2009 at 2:36 PM, bearophile bearophileh...@lycos.com wrote:
 Moritz Warning:

 If you only what a contract that certain functions are implemented,
 then it just need to be implemented in the compiler frontend.

 In the meantime this can be done with a template mixin, where the template 
 statically asserts the presence of the functions/fields you want.

I really think some kind of static interface (concept) support is
going to be necessary eventually.

In terms of functionality, static asserts and isInterfaceSupported()
methods are OK.  But the usability is not great.
In particular there's not a good way for the compiler to give good
error messages about why a concept is not satisfied by a particular
type.  I tried to come up with a way to do that given access to
compiler error messages, but the result looks rather like attempts to
do runtime inheritance in C.
The good thing is that since most of the machinery is there, the
actual compiler changes required would mostly be just rewrites of new
syntax in terms of existing functionality.

--bb


Re: why can't structs implement interfaces?

2009-11-24 Thread Bill Baxter
On Tue, Nov 24, 2009 at 4:38 PM, Daniel Keep
daniel.keep.li...@gmail.com wrote:

 (This is all off the top of my head.)


nice explanation snipped -- thanks

 Even then, there's a worse problem.  All interfaces can be cast to
 Object, and then upcast to any valid class.  This is done via the use of
 the first slot of the object's vtable, which contains the ClassInfo.

Well, except for those dreaded IUnknown COM interfaces.

 But if you allow structs as interfaces, you're suddenly in the position
 where you might not actually have an object at all.  If you tried to
 cast a struct to an Object, it might not actually fail; if you're lucky,
 you'll get a segfault.

Same as with IUnknown interfaces.

 The only solution there is to give structs a vtable.  At which point,
 congratulations, you've just re-invented classes.

 To allow structs to implement interfaces would require redesigning how
 interfaces are actually implemented.  You'd probably have to also
 redesign RTTI as well, object casting, etc.

But with good enough introspection, it should be possible to make
automatic class wrappers for structs that implement an interface by
forwarding to the struct.

That's probably mostly doable now, though probably with a frightening
assortment method signature string parsing and mixins.

--bb


Re: template type check syntax

2009-11-20 Thread Bill Baxter
2009/11/20 gzp ga...@freemail.hu:
 Which is the preferred form ? Shall I place the static assert into the in
 part or into the body directly ?

 Is there any difference ? Is there a way to toggle if the in part is
 executed/compiled or not ?  - Like in eifel it can be turned on and off by a
 compiler flag.

I think static asserts are always checked.
Regular asserts are turned off by the -release flag.


 template check1(T) {
        enum check1 = ...;
 }

 bool check2(T t) {
        return ...;
 }


 void foo(T)(ref T t)
 in {
        static assert( check1!(T) );
        assert(check2(t);
 }
 body {
        static assert( check1!(T) );
 ...
 }

 Or is there a form like (As i've seen mentioned with future coming opBinary)
 void foo(T)(ref T t) if check1!(T)
 {
        in {
                assert(check2(t);
        }
        body {
                ...
        }
 }

This form exists in D2 (with parens around the check1 part), but the
meaning is slightly different.

The static assert version allows the template to get instantiated but
causes a failure.

The latter form will pass over instantiation of that version of the
template if the if check1 fails.
It can then go on and try other forms of the template.

For instance you can have this:

void foo(T)(ref T t) if (isPrime!(T)) { ... }
void foo(T)(ref T t) if (!isPrime!(T)) { ... }

But not this:
void foo(T)(ref T t) {  static assert(isPrime!(T); ... }
void foo(T)(ref T t) {  static assert(!isPrime!(T); ... }

because you can't declare two identical templates.


--bb


Re: String Mixins Compile Time Evaluation

2009-11-17 Thread Bill Baxter
On Tue, Nov 17, 2009 at 2:07 AM, Don nos...@nospam.com wrote:
 Travis Boucher wrote:

 I've been playing with string mixins, and they are very powerful.

 One thing I can't figure out is what exactly can and cannot be evaluated
 at compile time.

 For example:

 
 char[] myFunc1() {
    return int a = 1;;
 }

 char[] myFunc2() {
    char[] myFunc3() {
        return int b = 2;;
    }
    return myFunc3();
 }

 void main() {
    mixin(myFunc1());
    mixin(myFunc2());
 }
 

 myFunc1() can be used as a string mixin.
 myFunc2() can't be.

 I think you're using an old version of DMD. It's been working since
 DMD1.047. Please upgrade to the latest version, you'll find it a lot less
 frustrating.
 The bottom of function.html in the spec gives the rules.
 Though it says nested functions aren't supported, but they are.

Ah, forgot about that list.  Good point.
But still Travis should know that the list is not exhaustive.
For instance the other day I found that this didn't work for some reason:

   while(i  a - b) { ... }

Instead I had to do

   int limit = a-b;
   while(i  limit) { ... }

--bb


Re: String Mixins Compile Time Evaluation

2009-11-17 Thread Bill Baxter
On Mon, Nov 16, 2009 at 8:25 PM, Travis Boucher
boucher.tra...@gmail.com wrote:
 Don wrote:

 Travis Boucher wrote:

 I've been playing with string mixins, and they are very powerful.

 One thing I can't figure out is what exactly can and cannot be evaluated
 at compile time.

 For example:

 
 char[] myFunc1() {
    return int a = 1;;
 }

 char[] myFunc2() {
    char[] myFunc3() {
        return int b = 2;;
    }
    return myFunc3();
 }

 void main() {
    mixin(myFunc1());
    mixin(myFunc2());
 }
 

 myFunc1() can be used as a string mixin.
 myFunc2() can't be.

 I think you're using an old version of DMD. It's been working since
 DMD1.047. Please upgrade to the latest version, you'll find it a lot less
 frustrating.
 The bottom of function.html in the spec gives the rules.
 Though it says nested functions aren't supported, but they are.

 Yeah, I am running 1.020 with gdc (freebsd default for gdc package).  I
 found a few work arounds, just trying to see what can be done.

O, well yeh, Don's been smashing CTFE bugs like crazy lately.  I
think the version you're using doesn't even have the useful error
message fix that tells you what can't be CTFE'd.

So definitely upgrade before you try to do anything serious with CTFE.

--bb


Re: One of us is crazy: Me or {function here}.stringof

2009-11-13 Thread Bill Baxter
On Fri, Nov 13, 2009 at 12:05 AM, Nick Sabalausky a...@a.a wrote:
 Nick Sabalausky a...@a.a wrote in message
 news:hdj3dk$1r5...@digitalmars.com...
 AKA .stringof strikes again, or .attackof.stringof...


 Ok, *now* I see all the reports of this on bugzilla, now that I searched for
 just stringof and dug through the pile of results, instead of searching
 for both stringof and function...Real pain for metaprogramming...

At any rate I think a single stringof for a function is not sufficient.
You might want any of:
foo
foo(int, int)
foo(int a, int b)
There should probably be some __traits functions for getting these
different things, if there aren't already.
--bb


Re: Possible?

2009-11-13 Thread Bill Baxter
On Fri, Nov 13, 2009 at 1:11 PM, Ary Borenszweig a...@esperanto.org.ar wrote:
 How can I know at compile time if all of the following are true for a given
 symbol s:
  1. s is a function
  2. the return type is a class that extends from class foo.Bar
  3. the function has three arguments and it is not variadic
  4. the first argument is an int
  5. the second argument is a struct
  6. the third argument is an associative array with char[] key and float
 value

For a question like that you should definitely specify whether you
want D1 or D2.

Also do you really want to know if s is a function?  Or if s is
something which can be called like a function.  If the latter then
you should test if call syntax compiles like Jacob suggested.  If not
then I think you use if(is(s == function)) like Simen said.

--bb


Re: CTFE and structs question

2009-11-08 Thread Bill Baxter
On Sat, Nov 7, 2009 at 10:40 PM, Don nos...@nospam.com wrote:
 You can create them without templates. std.metastrings was created before
 CTFE existed, it's rather outdated. It's intended for use with template
 metaprogramming, not for use with CTFE.

I posted about this the other day,  wouldn't it make sense to update
std.metastrings to be a set of functions useful for CTFE?  Because
that way they would be usable from either templates or other CTFE
functions.  And as CTFE capabilities of the compiler get better the
functions could be replaced with simple aliases to regular functions
in std.string.  But at the moment there's not much in std.string that
works for CTFE.

--bb


Re: Associative array trouble

2009-10-16 Thread Bill Baxter
You query presence of a key in an AA using 'in'

  if (id in symtab) {
 Symbol sym = symtab[id];
 ...
  } else {
  ..
  }

Or this avoids a double lookup if the symbol is present:

  Symbol* pSym = id in symtab;
  if (pSym !is null) {
 Symbol sym = *pSym;
 ...
  } else {
 ...
  }

--bb

On Fri, Oct 16, 2009 at 1:37 PM, Justin Johansson n...@spam.com wrote:
 What's wrong with this simple symbol table class?

 class Symbol
 {
   private char[] id;
   private static Symbol[char[]] symtab;

   private this( string id) {
      this.id = id;
   }

   static Symbol opCall( char[] id) {
      Symbol sym = symtab[id];  // *** ArrayBoundsError here

      if (sym is null) {
         sym = symtab[id] = new Symbol( id);
      }

      return sym;
   }
 }


 void main() {
  auto sym = Symbol( foo);
 }

 Running gives Error: ArrayBoundsError

 Does symtab need to be initialized in, say, a static if.
 The reference documentation on associative arrays does not suggest that it 
 needs to be.

 Thanks for all help.
 Justin





Re: Associative array trouble

2009-10-16 Thread Bill Baxter
On Fri, Oct 16, 2009 at 4:11 PM, Manfred_Nowak svv1...@hotmail.com wrote:
 Bill Baxter wrote:

   Symbol* pSym = id in symtab;

 shouldn't the compiler sort this out?

I'm not really sure what you mean, but I think the answer is that
there's a difference between an unset entry and one that's set to
null.

--bb


Re: How about macro == symbol for mixin statement? [was Re: Member functions C to D]

2009-10-08 Thread Bill Baxter
On Thu, Oct 8, 2009 at 1:06 AM, Don nos...@nospam.com wrote:
 Jarrett Billingsley wrote:

 On Wed, Oct 7, 2009 at 11:21 AM, Don nos...@nospam.com wrote:

 Steven Schveighoffer wrote:

 On Wed, 07 Oct 2009 09:17:59 -0400, Jarrett Billingsley
 jarrett.billings...@gmail.com wrote:

 It's also insanely kludgy and ugly. Bleh.

 Ugly, yes. Kludgy, I don't think so. It's only a syntax issue. The basic
 concept of passing meta-code to the compiler in the form of raw text is
 simple:

 mixin() if you want to insert something into the parse step.
  is(typeof()) if you want to catch it again after the syntax pass.
  stringof if you want to catch it again after the semantic pass.

 And that's all. The syntax is ugly, but the semantics are beautifully
 elegant.

 It'd be nice if they actually worked. is(typeof()) fails for *any*
 error, and it eats those errors too, so if your code fails to compile
 for some reason other than the one you're testing for, welp, good luck
 figuring that out. And don't even get me started on .stringof.

 Also, see my post on the get template and its instantiation
 parameters thread for my detailed opinion on them.

 By contrast, something like Nemerle macros are a kludge. The idea of
 providing a 'hook' into the compiler is a horrible hack. It exposes all
 kinds of compiler internals. Yes, it has nicer syntax.

 I.. don't even know how to begin to respond to that.

 Have you read the Nemerle extended macro tutorial? The compiler's internal
 structures are completely exposed. That's a hack.

It seems macros are implemented as compiler extensions.  You compile
your macros into DLLs first, that then get loaded into the compiler as
plugins.  On the plus side, doing things that way you really do have
access to any API you need at compile-time, using the same syntax as
run-time.  All of .NET can be used at compile-time in your macros.  No
more can't CTFE that gotchas.

But it does raise security concerns.  I wonder if they have some way
to prevent macros from running malicious code.  I guess you better run
your web-based compiler service in a tightly partitioned VM.

Overall it seems pretty nifty to me, really.  Giving macros access to
an actual compiler API seems less hackish than throwing in a
smattering of diverse functionality under the heading of __traits.
And less prone to gotchas than trying to create a separate
compile-time D interpreter that runs inside the D compiler.

What do you see as the down sides?  Just that some rogue macro might
mess up the AST?

--bb


Re: How about macro == symbol for mixin statement? [was Re: Member functions C to D]

2009-10-07 Thread Bill Baxter
 On Wed, Oct 7, 2009 at 11:21 AM, Don nos...@nospam.com wrote:

 By contrast, something like Nemerle macros are a kludge. The idea of
 providing a 'hook' into the compiler is a horrible hack. It exposes all
 kinds of compiler internals. Yes, it has nicer syntax.

Are you talking specifically about the ability to define new syntax?
Because it looks to me that one can use nemerle macros just fine
without defining new syntax.
I'm getting that from here: http://nemerle.org/Macros_tutorial

Here's just a simple macro that adds no new syntax from that page:

macro m () {
  Nemerle.IO.printf (compile-time\n);
  [ Nemerle.IO.printf (run-time\n) ];
}

module M {
  public Main () : void {
m ();
  }
}


That seems significantly more elegant to me than

string m() {
   pragma(msg, compile-time);
   return q{writefln(run-time);}
}
void main() {
   mixin(m());
}

So it looks to me like the mechanics of it are basically identical.
Just Nemerle's syntax is nicer.

If you want to condem Nemerle's ability to define new syntax, I think
that should be taken up as a separate matter.

--bb


Re: ref arguments

2009-09-21 Thread Bill Baxter
On Mon, Sep 21, 2009 at 12:53 PM, Jeremie Pelletier jerem...@gmail.com wrote:
 Right now the compiler makes a temporary copy of referenced parameters on
 the stack, calls the function with a pointer to the stack copy, and once the
 function returns copies the modified temporary back to its original
 location. This is quite considerable overhead.

 Are you sure this is true?  I don't have a d2 compiler right now, but that
 sounds like a *huge* step in the wrong direction.  D1 does not do this
 (tested dmd 1.046).

 Yeah I started a thread about that a few months ago in digitalmars.D, its
 something that's on the bugzilla I believe.

I think this is the only bugzilla bug about speed of reference parameters:
http://d.puremagic.com/issues/show_bug.cgi?id=2008

It does not mention the copying issue in D2 you talk about, only lack
of inlining in D1 and D2.  But I think the asm code posted there may
be doing that copying.  Not a big ASM guru though.

To anyone who thinks that poor optimization of ref args is an
important issue: please vote for the bug!

--bb


Re: alias foo.bar this?

2009-08-21 Thread Bill Baxter
On Fri, Aug 21, 2009 at 2:47 AM, Lutgerlutger.blijdest...@gmail.com wrote:
 The following doesn't compile, I was wondering whether this is a temporary
 limitation, bug or by design?

 struct Bar
 {
    int baz;
 }

 struct Foo
 {
    Bar bar;
    alias bar.baz this; // error
 }

Problem I would guess is that bar.baz is an expression and you can't
alias expressions in any context.
  alias bar.baz that;
doesn't work either.

--bb


Re: Template mixins: Why is the decision to mixin made at the call site?

2009-08-21 Thread Bill Baxter
On Fri, Aug 21, 2009 at 10:36 AM, div0d...@users.sourceforge.net wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 Chad J wrote:
 Regarding template mixins, I'm curious, why is the decision to mixin a
 template made at the call site and not at the declaration of the
 template/mixin?

 In other words, why do we write

       template foo()
       {
               // etc..
       }

       mixin foo!();

 instead of

       mixin foo()
       {
               // etc..
       }

       foo!();

 ??

 It seems to me like in most cases you determine whether or not you want
 to mixin based on the contents of the template, not based on the the
 calling code.  Not to mention, declaring as a mixin would allow us to
 omit that mixin keyword anytime we want to do something cool with
 template mixins.  So it seems odd to me as I reflect on it.

 Not sure what the original choice was based on, but what you suggest
 looks wrong to me. You aren't necessarily using a template in order to
 mix it in somewhere.

 With that syntax it looks like you can only use foo as a mixin. If you
 change 'mixin' to 'paste' your way round looks even more wrong.

At least for templates that are just a bunch of alias declarations, it
can be handy to be able to use directly or to mix in.  So there would
be little to be gained by forcing the developer to choose mixin or
regular template up front.

For example

template MeshTypes(MeshType) {
   alias MeshType mesh_type
   alias typeof(MeshType.vertices[0]) vert_type;
   alias typeof(MeshType.vertices[0].x)  float_type;
   const uint vert_dim = vert_type.length;
}

That's handy to use inline like   MeshTypes!(MyMesh).vert_type
Or you can mix it in to another class that uses mesh a lot to have all
those types defined inside your class too.

--bb


Re: Partial template function specialization

2009-08-20 Thread Bill Baxter
On Thu, Aug 20, 2009 at 7:22 AM, Peter
Alexanderpeter.alexander...@gmail.com wrote:
 Lars T. Kyllingstad Wrote:

 Disclaimer: You didn't say whether you use D1 or D2, but I use D2, so
 I'll give my answer in D2 code. It is highly likely it will also work in D1.

 I'm using neither :)  I'm just considering learning at the moment.


 First of all, I don't know how it is in C++, but in D you rarely write
 function declarations without definitions. So unless you have a very
 general function body for your general case, I'd simply drop it. If
 you have, the general case looks like this:

  snip

 For more info, check out http://www.digitalmars.com/d/2.0/template.html

 -Lars

 Excellent! Thanks a lot. I was hoping that D could overcome this problem.


 Ah, one (maybe) final question:

 Is there an equivalent to friends in D (didn't see any in the docs)? If so, 
 do they work with templates easily?

 In my style of programming, I very rarely use member functions (I think they 
 are an atrocity in language design), so I create global functions for almost 
 everything, and when they need to access to private members, I have the class 
 declare the function as a friend.

 Does D support my style of programming?

Instead of friend, in D everything within one file (==one module) has
access to everything else in that same file/module.

So you can use your style, as long as you put the global functions in
the same module as the classes operated on.

 Here's a concrete example of something I'd like to do (pseudocode):

 class Foo { private int x; friend globalFun; }
 class Bar { private int y; friend globalFun; }

 void globalFun(ref Foo foo, ref Bar bar) { foo.x = bar.y; }

 Is there anything like this in D? Export sounds like the right thing, but can 
 that be used in the example above, assuming that Foo and Bar are in separate 
 modules?

I don't think export has anything to do with it.

--bb


Re: CRTP in D?

2009-08-20 Thread Bill Baxter
On Thu, Aug 20, 2009 at 12:15 PM, div0d...@users.sourceforge.net wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 John C wrote:
 div0 Wrote:
 While we're on the subject, is it possible to mixin in a tuple?
 Doesn't seem like you can...

 class C(M...) {
  mixin M;
 }

 Doesn't work.

 import std.typetuple;

 class C(M...) {

   mixin TypeTuple!(M);

 }
 Unfortunately that doesn't work.

 It stops the immediate compile error, but the mixin doesn't
 do anything:

This doesn't work either:

class C(M) {
   mixin M;
}
template Foo() { void blarf() {} }

auto x = new C!(Foo);
x.blarf;

because a parameter that is itself a template needs to be an alias
template argument like so:

class C(alias M) { ... }

As far as I know you can't have an alias variadic argument or pass
template aliases to a regular variadic template arg.

--bb


Re: CRTP in D?

2009-08-19 Thread Bill Baxter
On Wed, Aug 19, 2009 at 2:59 PM, Saaaem...@needmail.com wrote:

 Mixins can be used to do a lot (most? all?) of things CRTP is used for:

 class Class(alias MixMe)
 {
   mixin MixMe impl;
   ...
   void doSomething {
         impl.doIt();
   }
 }


 where can I read about class parameters?

It's just a class template.  Short for

template Class(alias MixMe)  {
  class Class {
  
  }
}

See http://www.digitalmars.com/d/2.0/template.html under Class Templates.

--bb


Re: Semi Automated Object wrapping

2009-08-13 Thread Bill Baxter
On Thu, Aug 13, 2009 at 12:43 AM, Rory McGuirerjmcgu...@gmail.com wrote:
 On Wed, 12 Aug 2009 17:03:17 -0700, Bill Baxter wrote:

 On Wed, Aug 12, 2009 at 4:52 PM, Rory McGuirerjmcgu...@gmail.com
 wrote:
 Here is some code I wrote which enables wrapping a proxy around an
 object. I am using it for my serialization library. It works in
 D1(1.046) and D2 (2.031)

 Posting it here for reference by all before I add to much of the stuff
 specific to my use, should make it easier to follow.

 usage: new ProxyClass!(A, cast(string)getInt setInt getString); would
 implement the methods getInt setInt and getString from A in the new
 class.

 the code below will fail to compile but not before printing the
 generated code to stdout.

 Shin Fujishiro has made some new templates for D2 which will make it so
 I can get rid of the setInt getInt getString part which would make
 the usage for D2: new ProxyClass!A;
 which would be great!

 -Rory

  // author: Rory McGuire,
 rjmcgu...@gmail.com import std.stdio;
 import std.typetuple;
 import std.traits;
 import std.metastrings;

 //import serializer;

 // this CTF from somewhere on news.digitalmars.com string[]
 splitFuncs(string str) {
    string[] res;
    while (str.length  0) {
        while (str.length  0  (' ' == str[0] || ',' == str[0])) {
            str = str[1..$];
        }
        int to = 0;
        for (; to  str.length  str[to] != ' '  str[to] != ',';
        ++to)
 {}
        if (to  0) {
            res ~= str[0..to];
            str = str[to..$];
        }
    }
    return res;
 }

 string MethodTypeTuple_mixin(alias a)(string[] methods) {
        string ret = TypeTuple!(~
        typeof(C.init.~methods[0]~); foreach (method;
        methods[1..$]) {
                ret ~= ,typeof(C.init.~method~);
        }
        ret ~= );
        return ret;
 }



 // test case

 class A {
        int a;
        this(int a) {
                this.a = a;
        }
        int getInt(string intname) {
                return a;
        }

        void setInt(int i) {
                a = i;
        }
        string getString(string s) {
                return s ~1234;
        }
 }


 string ProxyMethods_mixin(alias C, string methodstr)() {
        string ret;
        foreach(i, t; mixin(MethodTypeTuple_mixin!(C)(splitFuncs
 (methodstr {
                // output function header
                ret ~= \t~ReturnType!(t).stringof ~ ~
                splitFuncs
 (methodstr)[i]~(;
                // output first arg
                ret ~= ParameterTypeTuple!(t)[0].stringof~
                arg; // output remainder of args
                foreach (j, t1; ParameterTypeTuple!(t)[1..$]) {
                        ret ~= ,~t1.stringof~
 arg~std.metastrings.ToString!(j);
                }
                // output body
                ret ~= ) {\n;
                // output serialization code
                // send method name
                ret ~= \t\twritefln(\serialize docall id\);
                // the
 method call byte id\n;
                ret ~= \t\tbuffer ~=
                serialize!(string)(\~splitFuncs
 (methodstr)[i]~\, s_state); /+ the method name +/\n;
                // send args
                ret ~= \t\tbuffer ~= serialize!(~
                ParameterTypeTuple!(t)
 [0].stringof~)(arg, s_state); /+ the first argument +/\n;
                foreach (j, t1; ParameterTypeTuple!(t)[1..$]) {
                        ret ~= \t\tbuffer ~= serialize!(~
                        t1.stringof
 ~)(arg~ToString!(j)~, s_state); /+ argument ~ToString!(j)~ +/\n;
                }
                // receive return type
                static if (!is(ReturnType!(t) == void)) {
                        ret ~= \t\treturn deserialize!(~
                        ReturnType!
 (t).stringof ~)(buffer, des_state);\n;
                }
                ret ~= \t}\n;
        }
        return ret;
 }


 class ProxyClass(alias C, string methodstr) {
                ubyte[] buffer;
                mixin(ProxyMethods_mixin!(C,methodstr)());
                pragma(msg, class ProxyClass!(~C.stringof~,
                \~
 methodstr ~\) {\n\tubyte[] buffer;\n  SerializerState s_state;\n
 DeserializerState des_state;\n  this() {s_state = new
 SerializerState(); des_state = new DeserializerState(); }\n\n~
 ProxyMethods_mixin! (C,methodstr)() ~\n}\n);

 }

 void main() {
        auto pc = new ProxyClass!(A, cast(string)getInt setInt
 getString);
        writefln(ProxyClass: ~ pc.getString(asdf));
 }


 That code is screaming for some macros. Or variable interpolation at
 least.

 --bb

 Where would you propose that one would use 'macro'?


It doesn't exist yet, so there's not much you can do about it.
Unfortunately code that generates code in D pretty much has to look
like what you wrote there.  I'm just saying it's not a lot of fun to
read such code.  Compare with Lisp macros that are almost as readable
as regular Lisp functions.

Or maybe instead of macros

Re: Semi Automated Object wrapping

2009-08-12 Thread Bill Baxter
On Wed, Aug 12, 2009 at 4:52 PM, Rory McGuirerjmcgu...@gmail.com wrote:
 Here is some code I wrote which enables wrapping a proxy around an object.
 I am using it for my serialization library. It works in D1(1.046) and D2
 (2.031)

 Posting it here for reference by all before I add to much of the stuff
 specific to my use, should make it easier to follow.

 usage: new ProxyClass!(A, cast(string)getInt setInt getString); would
 implement the methods getInt setInt and getString from A in the new class.

 the code below will fail to compile but not before printing the generated
 code to stdout.

 Shin Fujishiro has made some new templates for D2 which will make it so I
 can get rid of the setInt getInt getString part which would make the
 usage for D2: new ProxyClass!A;
 which would be great!

 -Rory

 
 // author: Rory McGuire, rjmcgu...@gmail.com
 import std.stdio;
 import std.typetuple;
 import std.traits;
 import std.metastrings;

 //import serializer;

 // this CTF from somewhere on news.digitalmars.com
 string[] splitFuncs(string str) {
    string[] res;
    while (str.length  0) {
        while (str.length  0  (' ' == str[0] || ',' == str[0])) {
            str = str[1..$];
        }
        int to = 0;
        for (; to  str.length  str[to] != ' '  str[to] != ','; ++to)
 {}
        if (to  0) {
            res ~= str[0..to];
            str = str[to..$];
        }
    }
    return res;
 }

 string MethodTypeTuple_mixin(alias a)(string[] methods) {
        string ret = TypeTuple!(~ typeof(C.init.~methods[0]~);
        foreach (method; methods[1..$]) {
                ret ~= ,typeof(C.init.~method~);
        }
        ret ~= );
        return ret;
 }



 // test case

 class A {
        int a;
        this(int a) {
                this.a = a;
        }
        int getInt(string intname) {
                return a;
        }

        void setInt(int i) {
                a = i;
        }
        string getString(string s) {
                return s ~1234;
        }
 }


 string ProxyMethods_mixin(alias C, string methodstr)() {
        string ret;
        foreach(i, t; mixin(MethodTypeTuple_mixin!(C)(splitFuncs
 (methodstr {
                // output function header
                ret ~= \t~ReturnType!(t).stringof ~ ~ splitFuncs
 (methodstr)[i]~(;
                // output first arg
                ret ~= ParameterTypeTuple!(t)[0].stringof~ arg;
                // output remainder of args
                foreach (j, t1; ParameterTypeTuple!(t)[1..$]) {
                        ret ~= ,~t1.stringof~
 arg~std.metastrings.ToString!(j);
                }
                // output body
                ret ~= ) {\n;
                // output serialization code
                // send method name
                ret ~= \t\twritefln(\serialize docall id\); // the
 method call byte id\n;
                ret ~= \t\tbuffer ~= serialize!(string)(\~splitFuncs
 (methodstr)[i]~\, s_state); /+ the method name +/\n;
                // send args
                ret ~= \t\tbuffer ~= serialize!(~ ParameterTypeTuple!(t)
 [0].stringof~)(arg, s_state); /+ the first argument +/\n;
                foreach (j, t1; ParameterTypeTuple!(t)[1..$]) {
                        ret ~= \t\tbuffer ~= serialize!(~ t1.stringof
 ~)(arg~ToString!(j)~, s_state); /+ argument ~ToString!(j)~ +/\n;
                }
                // receive return type
                static if (!is(ReturnType!(t) == void)) {
                        ret ~= \t\treturn deserialize!(~ ReturnType!
 (t).stringof ~)(buffer, des_state);\n;
                }
                ret ~= \t}\n;
        }
        return ret;
 }


 class ProxyClass(alias C, string methodstr) {
                ubyte[] buffer;
                mixin(ProxyMethods_mixin!(C,methodstr)());
                pragma(msg, class ProxyClass!(~C.stringof~, \~
 methodstr ~\) {\n\tubyte[] buffer;\n  SerializerState s_state;\n
 DeserializerState des_state;\n  this() {s_state = new SerializerState();
 des_state = new DeserializerState(); }\n\n~ ProxyMethods_mixin!
 (C,methodstr)() ~\n}\n);

 }

 void main() {
        auto pc = new ProxyClass!(A, cast(string)getInt setInt
 getString);
        writefln(ProxyClass: ~ pc.getString(asdf));
 }


That code is screaming for some macros.
Or variable interpolation at least.

--bb


Re: calling function templates

2009-08-09 Thread Bill Baxter
On Sun, Aug 9, 2009 at 9:30 AM, bearophilebearophileh...@lycos.com wrote:
 Jos van Uden:
 I'm not using the language. Just trying to learn it.

 To learn a programming language you have to use it some.


Most code examples I see, require D2.

 Then don't look at them, and do your own experiments, etc.


Aw come on.  I'd learn D2 if I were just getting into D now.  It's
where all the action is heading these days.
If you don't like dealing with the bleeding edge, then yeh, D1 is
better for now.   But there are reasons why a person might prefer to
learn either.

--bb


Re: How to search for an element in the array. D2 phobos.

2009-07-12 Thread Bill Baxter
On Sun, Jul 12, 2009 at 3:56 PM, bearophilebearophileh...@lycos.com wrote:
 Eldar Insafutdinov:
 I think I completely misunderstood how to use it.

 Yes, it's too much complex. It tries to do many different things in the most 
 efficient way possible, the result is a high complexity in usage. That's one 
 of the faults of Andrei's code, it's not tested by letting  average coders 
 use it.
 A solution for this problem is to offer simple functions (like you can find 
 in Tango. In my dlibs the situation is intermediate, I think) with a simple 
 API for the most common purposes.

Isn't that a matter of built-in arrays not yet sporting the range interface?
I assume if .empty is part of the range interface then arrays are
supposed to support it.

--bb


Re: help with c translation

2009-07-02 Thread Bill Baxter
On Thu, Jul 2, 2009 at 9:07 AM, BCSn...@anon.com wrote:
 Hello Ary,

 Well, it should work! const means, once a value is assigned to that
 variable, it never changes again. The compiler can do static analysis
 to verify this. And that's why it works. And that's why D should also
 work this way, IMHO.


 In D1, const is truly const, as in never changes, ever, not even from one
 run of the program to another. D2 keeps this idea but IIRC calls it
 something else.

That's what D2 uses enum for.

--bb


Re: How many people here use stackoverflow.com?

2009-05-23 Thread Bill Baxter
On Sat, May 23, 2009 at 11:36 AM, BCS n...@anon.com wrote:
 Hello Tim,

 On Sat, 23 May 2009 08:36:44 +1200, hasen hasan.alj...@gmail.com
 wrote:

 If I have some questions about D, should I ask on stackoverflow
 instead  of here? Are there enough D'ers there?

 I personally think that asking there would bring more public
 attention  to D, but it all depends on whether there are enough
 people there who  know about D.

 For instance, I might have a couple of question about gtkD, as I'm
 trying to play with it right now.

 So, do you regularly visit http://stackoverflow.com/ or no?

 http://stackoverflow.com/questions/tagged/d

 I remeber seeing a post on annoucements a long time ago about when you
 type d on the tags page here http://stackoverflow.com/tags you dont
 get  the d tag. IIRC that guy sent en email to jeff atwood about it
 but it is  still not working.


 declined (a.k.a. not now) twice

 http://stackoverflow.uservoice.com/pages/1722-general/suggestions/16008-bug-type-to-find-tags-will-fail-to-find-exact-match

 http://stackoverflow.uservoice.com/pages/1722-general/suggestions/159731-force-inclusion-of-exact-matches-in-tag-searches

Yeh, denied because search is really hard.

 http://stackoverflow.uservoice.com/pages/1722-general/suggestions/197730-tag-search-should-place-exact-match-first-

I would vote for it, but the login system is acting wonky.

--bb


Re: line drawing package?

2009-05-03 Thread Bill Baxter
SDL via Derelict is probably the easiest thing to get working quickly.
I think SDL has some kind of simple line drawing API.

SDL for opening the window with drawing done by GL wouldn't be hard
either, if you already know the GL api.

Neither will give you high-quality antialiased lines, though.

--bb

On Sat, May 2, 2009 at 6:29 PM, BCS n...@anon.com wrote:
 I find my self in need of a line drawing package. I need to pop a window and
 draw lines and points. Text would be nice but I can live without it. Most
 importantly, I need something that is dirt simple to get running. I don't
 have time to dink around with libs (if I did have time I'd be willing but
 I'm already way behind as it is).

 Windows XP, D1.0, Phobos

 I'd also be able to use an out of process solution as in: generate input
 file, call program if anyone knows of a windows program like that.





Re: line drawing package?

2009-05-03 Thread Bill Baxter
On Sun, May 3, 2009 at 5:15 AM, John C johnch_a...@hotmail.com wrote:
 BCS Wrote:

 I find my self in need of a line drawing package. I need to pop a window
 and draw lines and points. Text would be nice but I can live without it.
 Most importantly, I need something that is dirt simple to get running. I
 don't have time to dink around with libs (if I did have time I'd be willing
 but I'm already way behind as it is).

 Windows XP, D1.0, Phobos

 I'd also be able to use an out of process solution as in: generate input
 file, call program if anyone knows of a windows program like that.



 Had you ruled out CreateWindowEx, LineTo and DrawText from the Win32 API?

If there are bindings for GDI+ then that gets you nice antialiased lines too.

--bb


Re: Dear toolchain...

2009-03-10 Thread Bill Baxter
On Tue, Mar 10, 2009 at 10:45 AM, Simen Haugen si...@norstat.no wrote:
 I'm waist deep in problems, and have no idea how to get up.

 I have a program that uses d1, dmd, tango, ddbi, dwt and dwin. Some time ago
 I discovered that the program would no longer compile, and I have several
 features and bugfixes long overdue.

 It seems the problem happens during linking, but as I get no error what so
 ever it's a bit hard for me to track down. The project is about 30kloc.

 I've tried both dsss and rebuild. Dsss at least says rebuild exits with a
 status code 1, but still no hints on where the error might be.
 My guess is that this is a bug with lib.exe or link.exe, but I might be far
 off...

 I'm using D for several other programs, but don't keep a log for what
 versions I used when the projects last compiled... I've tried several
 different versions of both the compiler and the various libs, but as I said,
 I keep no log, so it's kind of a shot in the dark...

 I've spent at least 8 hours so far trying to locate the error with no luck.
 Does anyone have any good ideas how I can proceed?
 Or perhaps a pointer in the direction for narrowing down my search?

Some thoughts:
For the longest time DMD 1.037 was the most recent version that would
work for me and my DWT app.  So that might be a good version to try if
you haven't already.

One thing that bit me when I was trying to try out different compilers
-- the new directory layout is different, so you need to make sure
you're really using the compiler you think you're using.  If you set
up your path to have dmd/windows/bin on your path, but you install an
older compiler over top of an existing install, you'll still be using
the newer compiler because of your PATH setting.

Other than that, the only way to find these things is pretty much to
comment out chunks of your program until it compiles, and try to
narrow it down that way.

--bb


Re: Structuring a library project—best practi ces

2009-02-11 Thread Bill Baxter
On Thu, Feb 12, 2009 at 6:02 AM, Zarathustra adam.chrapkow...@gmail.com wrote:
 Hello Joel

 Maybe, you should look on the Helix Library.
 www.dsource.org/projects/helix

Well, I wouldn't recommend you copy their idea of having a single
top-level template that encloses all your types[1].  AFAIK, that
doesn't have any benefit over making each type templated individually,
and makes creating aliases for specific types more cumbersome, i.e.
their:
   alias LinearAlgebra!(float).Vector2 Vector2f;
vs just:
   alias Vector2!(float) Vector2f;

I think probably also forces instantiation of the entire template any
time you use any part of it, which means some unnecessary code bloat.

If you do want to do such grouping for some reason, it's probably
easier to go the other way and make things as individual types first,
then make the group template with all the component types as aliases.

Like
template LinearAlgebra(FloatT) {
   alias Vector2!(FloatT) Vector2;
   alias Vector3!(FloatT) Vector3;
   ... etc
}

--bb
[1]http://www.dsource.org/projects/openmeshd/browser/trunk/Helix/helix/linalgebra.d


Re: Learning by Doing: dimensioning units or geometric algebra?

2009-02-03 Thread Bill Baxter
On Wed, Feb 4, 2009 at 6:45 AM, Joel C. Salomon joelcsalo...@gmail.com wrote:
 Hello all,

 I'm a C programmer with some C++ experience (C with Classes+STL
 anyway; never did implement anything but the most trivial templates) and
 I'm looking to get stated with D. I figured a good way to do that would
 be to implement a template library, and it may as well be something I'll
 actually use. Here's what I'm thinking I could make:

 • a library for dimensional analysis, like boost::units, and/or

I always found this kind of thing boring, also I see it as kind of
useless overhead that I don't want in my calculations.  But it could
be a nice way to get your feet wet.

 • a set of classes for 2-dimensional Geometric Algebra (scalars,
 vectors, and pseudoscalars/imaginary numbers).

This would be very interesting.  The topic of GA did come up a few
weeks ago here.   From what I understand about GA, it's elegant from
the math point of view, but in terms of writing efficient code it
doesn't fare so well.  D can do a lot of stuff with ease at
compile-time that C++ couldn't even dream of, so it would be a great
showcase for D if someone could figure out how to make a GA lib that
rivals the performance of a classic mats  vecs approach.

I don't really know if it is possible.  Maybe the cost of the GA
abstractions cannot be automatically eliminated like that.  But if not
it would be interesting to know why.

 Should I start with D1 for now, or jump right in to D2?

D1 will give you the opportunity to build on more existing libraries.
D2 will give you the opportunity to use fancy new features that aren't
available in D1.  D2 will also likely break your code at some point as
the D2 language evolves.  D1 will not (should not anyway).

--bb


Re: casting int[] to bool[]

2009-01-28 Thread Bill Baxter
On Thu, Jan 29, 2009 at 10:20 AM, Saaa em...@needmail.com wrote:
  int[] a = [1,2,3,0];
  int[] aa = [0,1,0,1];
  bool[] b = cast(bool[])a.dup;
  bool[] bb = cast(bool[])aa.dup;
  writefln(a,`--`,b);
  writefln(aa,`--`,bb);

 --

 [1 2 3 0]--[true false false false true false false false true false false
 false false false false false]
 [0 1 0 1]--[false false false false true false false false false false
 false false true false false false]


 Why all this disagreeing?

bool is 1 byte under the hood.  Int is 4 bytes.
So what you are seeing is the 4 bytes of each int being treated as 4
separate bools in an ordering determined by the endian-ness of your
platform.

Casting arrays in this way is generally not a good idea.

You need to write a function that makes a fresh bool array out of your
int array.

--bb


Re: casting int[] to bool[]

2009-01-28 Thread Bill Baxter
On Thu, Jan 29, 2009 at 10:25 AM, Jarrett Billingsley
jarrett.billings...@gmail.com wrote:
 On Wed, Jan 28, 2009 at 8:25 PM, Bill Baxter wbax...@gmail.com wrote:
 On Thu, Jan 29, 2009 at 10:20 AM, Saaa em...@needmail.com wrote:
  int[] a = [1,2,3,0];
  int[] aa = [0,1,0,1];
  bool[] b = cast(bool[])a.dup;
  bool[] bb = cast(bool[])aa.dup;
  writefln(a,`--`,b);
  writefln(aa,`--`,bb);

 --

 [1 2 3 0]--[true false false false true false false false true false false
 false false false false false]
 [0 1 0 1]--[false false false false true false false false false false
 false false true false false false]


 Why all this disagreeing?

 bool is 1 byte under the hood.  Int is 4 bytes.
 So what you are seeing is the 4 bytes of each int being treated as 4
 separate bools in an ordering determined by the endian-ness of your
 platform.

 Casting arrays in this way is generally not a good idea.

 You need to write a function that makes a fresh bool array out of your
 int array.

 Stop beating me to things when I'm in the middle of typing!

Heh heh.  I sensed this one was gonna be a race.  :-P

--bb


Re: casting int[] to bool[]

2009-01-28 Thread Bill Baxter
On Thu, Jan 29, 2009 at 11:10 AM, Saaa em...@needmail.com wrote:
 :D

  dataIn[i][index] = cast(bool) t;

Jarrett?  You want to comment first?  :-D

--bb


Re: casting int[] to bool[]

2009-01-28 Thread Bill Baxter
On Thu, Jan 29, 2009 at 11:57 AM, Saaa em...@needmail.com wrote:
 Erm, anybody is fine to me..

 Is it the naming, still the casting or something else totally?

  dataIn[i][index] = cast(bool) t;

It's just that casting is a very blunt tool and should be avoided
whenever possible, because the compiler won't tell you if you're doing
something completely crazy.

Here you could use somethign like:

dataIn[i][index] = (t!=0);

instead of casting.

--bb


Re: casting int[] to bool[]

2009-01-28 Thread Bill Baxter
On Thu, Jan 29, 2009 at 12:04 PM, Jarrett Billingsley
jarrett.billings...@gmail.com wrote:
 On Wed, Jan 28, 2009 at 9:57 PM, Bill Baxter wbax...@gmail.com wrote:

 It's just that casting is a very blunt tool and should be avoided
 whenever possible, because the compiler won't tell you if you're doing
 something completely crazy.

 Here you could use somethign like:

dataIn[i][index] = (t!=0);

 instead of casting.

 Blunt?  Pfah!  cast(bool)int is well-defined.  ;)

Just you're more likely to catch an error if t changes from being an
int to something else later on.
I wish D had a tame and well-behaved casts only please kind of cast. :-(

--bb


Trick for teasing out static/constness of member in D1?

2009-01-26 Thread Bill Baxter
I'd like to do something like this:

static if (AType.length is a static constant ) {
  const  has_static_length = true;
}
else static if (AType.length exists but it's not a compile-time constant) {
  const  has_static_length = false;
}
else {
 // there is no .length at all
}


Anyone have a neat trick for this that works in D1?


--bb


Re: compile time output

2009-01-20 Thread Bill Baxter
On Wed, Jan 21, 2009 at 12:36 AM, Trass3r mrmoc...@gmx.de wrote:
 Is there any way to output information at compile time other than
 pragma(msg?
 pragma is driving me crazy, the following doesn't work:

 auto members = __traits(allMembers, typeof(this));
 foreach(m; members)
 {
pragma(msg, m);
 }

 - Error: string expected for message, not 'm'

 Though the docs clearly state:
 allMembers: An array of string literals is returned
 Also checked that, m is of type invariant(char)[].


 Any ideas? -.-

try indexing explicitly or using ref:

foreach(i,m; members)
{
pragma(msg, members[i]);
}

foreach(ref m; members)
{
pragma(msg, m);
}

Latter one may not be useful.  I can't recall.
--bb


Re: time measurement under linux?

2009-01-19 Thread Bill Baxter
On Tue, Jan 20, 2009 at 2:19 AM, Trass3r mrmoc...@gmx.de wrote:
 Daniel Keep schrieb:

 Check std.perf; it's documented, but sadly doesn't show up in the docs.

  -- Daniel

 Cool, is similar to my design. Though GetTickCount64 could be added.

That's odd.  I made some updates to std.perf a while back and my
understanding was that as a result of those Walter was going to put it
on the list of documented modules.  I guess he just forgot.

--bb


Re: time measurement under linux?

2009-01-19 Thread Bill Baxter
On Tue, Jan 20, 2009 at 4:47 AM, Jarrett Billingsley
jarrett.billings...@gmail.com wrote:
 On Mon, Jan 19, 2009 at 1:46 PM, Jason House
 jason.james.ho...@gmail.com wrote:
 Trass3r wrote:

 I wrote a module to ease time measurement in my projects.
 Does anyone know how to get elapsed milli- or nanoseconds under linux?
 Want to make it portable :)

 The difficulty of doing platform independent timing is one of the many 
 reasons that drove me to Tango...

 std.perf has been around for ages _  it's sad that it isn't documented.

That's a lot of what I did, actually.  A big reason it wasn't showing
up in the docs was because it didn't have ddoc comments.  So I wrote
those, and also did something about portability I think.  I don't
recall what I did exactly, but there were some code changes too in
addition to the ddoc changes.

--bb


Re: time measurement under linux?

2009-01-19 Thread Bill Baxter
On Tue, Jan 20, 2009 at 6:04 AM, Trass3r mrmoc...@gmx.de wrote:
 Jarrett Billingsley schrieb:

 On Mon, Jan 19, 2009 at 10:41 AM, Daniel Keep
 daniel.keep.li...@gmail.com wrote:

 Trass3r wrote:

 I wrote a module to ease time measurement in my projects.
 Does anyone know how to get elapsed milli- or nanoseconds under linux?
 Want to make it portable :)
 [snip]

 Check std.perf; it's documented, but sadly doesn't show up in the docs.

 Namely, PerformanceCounter is crossplatform.  (For some reason,
 HighPerformanceCounter only works on Windows, even though it uses the
 same mechanism as PerformanceCounter..)

 HighPerformanceCounter only exists in phobos1 and seems to be redundant
 anyway (as you said, uses same mechanism).

Oh yeh.  That's sounding familiar.  The phobos2 version of the file is
the one with my changes, and the one Walter was supposed to make
appear in the docs.

Here's what I wrote to walter about the changes I made:

I didn't end up changing the API.
But I did eliminate some classes which I think were dead weight:  the
ScopePerformanceCounter that just calls start() for you, and the
Windows-only HighPerformanceCounter.  On versions of Windows that have
QueryPerformanceCounter,  HighPerformanceCounter and
PerformanceCounter do exactly the same thing.  On platforms that don't
have it, PerformanceCounter uses a backup plan, while
HighPerformanceCounter just fails.  So there's pretty much no reason
to use HighPerformanceCounter, unless you just like code that fails on
particular versions of Windows.

I was thinking about adding an RDTSC-based timer, but after reading
about it a bit, it sounds like its use is discouraged these days,
since it is not so reliable on multicore machines.


---bb


Re: Getting line number where error occured?

2009-01-15 Thread Bill Baxter
On Fri, Jan 16, 2009 at 10:50 AM, Sergey Gromov snake.sc...@gmail.com wrote:
 Thu, 15 Jan 2009 13:08:35 -0500, Kagamin wrote:

 Bill Baxter Wrote:

 Nothing built-in for this,
 but there are the backtrace hacks: 
 http://team0xf.com/index.php?n=Site.Download
 Never tried those myself though.

 I use a debugger when I need a stack trace.
 http://ddbg.mainia.de/releases.html (Windows - on Linux I think you
 can use GDB).

 Weren't stack traces added to druntime some time ago?

 You're correct, I missed that.  Exception is derived from Throwable in
 druntime, and Throwable has a field 'info' of type TraceInfo with
 opApply in its interface.

 But it doesn't work, at least with DMD 2.023 on Windows.  Attempts to
 access this field cause object.Error: Access Violation.  I didn't try to
 investigate further though.

And also, D1 will not be moved to the new common druntime, so if
you're using D1 then backtrace hacks or a debugger are still your only
options I think.

--bb


Re: Questions regarding D

2009-01-14 Thread Bill Baxter
On Thu, Jan 15, 2009 at 7:35 AM, William Newbery wnewb...@hotmail.co.uk wrote:
 Jarrett Billingsley Wrote:

 On Wed, Jan 14, 2009 at 2:58 PM, William Newbery wnewb...@hotmail.co.uk 
 wrote:
  5)Support for classes in dynamic libaries, and the ability to dynamicaly 
  load these libaries.

 You're on Windows, so no.  Well, for the most part, no.  SOs on Linux
 work perfectly.  DLLs on Windows are not sufficient for what D needs
 to do proper dynamic linking.  Namely, there are issues with TypeInfo
 - the runtime type information that the D runtime uses to perform all
 sorts of useful things, like throwing exceptions and sorting arrays
 and doing downcasts.  What ends up happening is that the RTTI is
 duplicated in both the EXE and the DLL, and the runtime does no
 stitching up or removing of redundancy in those situations, leading
 to.. odd behavior.  The GC and DLLs also have strange interactions -
 it's entirely possible to set up the GC to collect data inside the
 DLL, but unloading the DLL sometimes results in a segfault for reasons
 behind my understanding.

 You do have options.  DDL is a project which aims to perform dynamic
 linking on Windows, and it works damn well.  It also has a lot of
 useful utility functions to i.e. look up symbols and types by name in
 the dynamic library.  There's also another project unrelated to D
 called EDLL which more or less does the same things that DDL does; I
 don't know if anyone has successfully used it with D.

 Is there some way around this, I dont really care if D needs to use its own 
 dynamic libary format rather than the windows dll, I just want some external 
 file that D can load and execute (ie it doesnt need to be able to contain 
 resources, or have its own HINSTANCE, or any of the other things dlls can 
 have beyond simply containing classes, functions, etc), and they dont have to 
 be compatible with anything outside of D at all.

Yes DDL is exactly that way to work around it.  See this very
interesting presentation about it here:
http://petermodzelewski.blogspot.com/2008/11/tango-conference-2008-ddl-talk.html

--bb


Re: using a typedefed variable with library classes

2009-01-12 Thread Bill Baxter
On Tue, Jan 13, 2009 at 1:48 AM, Sergey Gromov snake.sc...@gmail.com wrote:

 However, with a typedef, LocalType is a distinct type.  Yes it casts to
 int implicitly, but likewise it casts implicitly to char, short and
 long.  So compiler gets a whole load of File.write() functions matching
 with conversions, and fails because of the ambiguity.

 That's how the language works, and it's pretty consistent IMO.  What you
 can do is:

But the difference is LocalType can be converted to int exactly in all
cases.  Given a choice of int,char,short,etc.  clearly the conversion
to int is best choice.  It may be consistent with other cases
involving multiple legal conversions, but usually you don't have such
a single clearly preferred conversion.   It seems to significantly
reduce the utility of typedef.

--bb


Re: Foreach problem

2009-01-12 Thread Bill Baxter
On Tue, Jan 13, 2009 at 6:25 AM, Steven Schveighoffer
schvei...@yahoo.com wrote:

 because that's basically what a foreach does when using opApply: create an
 inner function and then pass a delegate pointing to that function to
 opApply.

 I think the difference between the two is that the compiler handles foreach
 on an array in a special manner without using an inner function/delegate.

That's an implementation detail and shouldn't effect the behavior
visible to the user.

--bb


Re: using a typedefed variable with library classes

2009-01-10 Thread Bill Baxter
On Sun, Jan 11, 2009 at 8:23 AM, Charles Hixson
charleshi...@earthlink.net wrote:
 Is it possible to use a typedefed variable with library classes?

 In particular, what I've done is:

 typedef  int  TestType;
 TestType  t;
 File  f;

 t = 42;
 f.write (t);

 And the response I get is the compiler asking whether I want to write bytes
 or a long.

 Am I doing something grossly wrong?  Or is typedef just broken?  Or is it
 really supposed to work that way for some not-understood reason?
 (alias works fine...but this seems to make typedef basically useless. Unless
 there's a way of adding functions to the library classes [like file] so that
 they'll understand how to cast the typedefed variable.)


I've never found a use for typedef myself.  I don't think it's used
much, so it could be that it's a special case that Andrei didn't
consider when re-writing write()  [at least I'm assuming you're
talking D2, based on the error message].  Or it could be that it is a
bug with the compiler.  But either way I think no one uses it, so it's
likely to flush out lots of corner cases.

--bb


Re: using a typedefed variable with library classes

2009-01-10 Thread Bill Baxter
On Sun, Jan 11, 2009 at 10:16 AM, bearophile bearophileh...@lycos.com wrote:
 Bill Baxter:
 I've never found a use for typedef myself.  I don't think it's used much,

 In Pascal (and its variant and children, like ObjectPascals, etc) there is a 
 section named Type where you define your typedefs. People used to program in 
 Pascal-like languages (ObjectPascals, Ada, Oberon, etc) may appreciate the 
 typedef of D and they may use it.
 I use typedef now and then, I presume it's mostly useful for imperative style 
 of programming and not much in OOP.

 A simple usage example: you have a procedural/functional program that has 
 several functions that process a matrix, the same matrix, for example a 
 float[12][7]. In such situation you may want to define:

 typedef float[12][7] FPfield;

 Then if you use FPField in function signatures like this:
 void foo(FPfield mat, ...) { ... }
 you gain some things:
 - The type name may be shorter, saving you some typing. And you don't need to 
 remember each time the size of the dimensions.
 - If you later want to FPfield into a matrix of doubles or the matrix you 
 have to change only one line. If your code uses a dynamic array this is less 
 important. But from coding a lot of programs in D I have seen programs up to 
 2-5-10 times faster when I use 3D/4D static arrays, mostly because lot of 
 address computations are done at compile time or partially optimized away 
 instead of run time, and because of higher cache coherence. I can show an 
 extreme example, if you want. D dynamic arrays can't replace all static 
 arrays where speed matters.
 - It's a way to document the code, because you aren't just giving a generic 
 matrix to foo, you are giving it a FPfield, this often has an important 
 semantic meaning.
 - It's type safe, so you don't risk giving the wrong matrix to foo. You can't 
 do this well with an alias. This is more useful in largish programs.

 If you use OOP or lot generic programming this becomes less important.


Actually it might be useful to me.  The first time I tried to use it
my thought was to do
  typedef Exception MyException;

To create a different exception type.  That doesn't work so I kinda
just said, eh whatever, this typedef stuff doesn't work yet.

But probably that's just because that's not the use case they were intended for.

Something I might be able to use it for is for index types.  Like this:

typedef size_t VertexHandle;
typedef size_t FaceHandle;

Now I can't accidentally assign a vertex handle to a face handle.
That could be useful.

--bb


Re: Foreach problem

2009-01-10 Thread Bill Baxter
On Sun, Jan 11, 2009 at 12:04 PM, Tim M a...@b.com wrote:
 On Sun, 11 Jan 2009 15:59:26 +1300, Tim M a...@b.com wrote:
 Why does it still work for some objects?


 This works:


 module test;

 class A
 {
this()
{
//
}
 }

 class B
 {
this()
{
//
}
int opApply (int delegate (inout B) dg)
{
return 1;
}
 }

 void main()
 {
A a;
B b;
foreach(a; b)
{
//
}
 }

Interesting.  But there the inner 'a' is actually a B.  So it
compiles, but there's no way it's using the outer 'a' as the counter
variable.

--bb


Re: Foreach problem

2009-01-10 Thread Bill Baxter
On Sun, Jan 11, 2009 at 12:15 PM, Tim M a...@b.com wrote:
 On Sun, 11 Jan 2009 16:10:39 +1300, Bill Baxter wbax...@gmail.com wrote:

 On Sun, Jan 11, 2009 at 12:04 PM, Tim M a...@b.com wrote:

 On Sun, 11 Jan 2009 15:59:26 +1300, Tim M a...@b.com wrote:

 Why does it still work for some objects?


 This works:


 module test;

 class A
 {
   this()
   {
   //
   }
 }

 class B
 {
   this()
   {
   //
   }
   int opApply (int delegate (inout B) dg)
   {
   return 1;
   }
 }

 void main()
 {
   A a;
   B b;
   foreach(a; b)
   {
   //
   }
 }

 Interesting.  But there the inner 'a' is actually a B.  So it
 compiles, but there's no way it's using the outer 'a' as the counter
 variable.

 --bb

 Sorry for my typo but change that line to:
 int opApply (int delegate (inout A) dg)

 and it still compiles.

'Still compiles or then it will compile?
Anyway, I'm curious if it's using the outer A or not.  Can you add a
line or two to actually modify 'a' in the loop?

--bb


Re: .bat file to help compile easier - dmd/build

2009-01-02 Thread Bill Baxter
On Sat, Jan 3, 2009 at 6:35 AM, Bill Baxter wbax...@gmail.com wrote:
 On Sat, Jan 3, 2009 at 4:17 AM, Michael P. baseball@gmail.com wrote:
 Okay, so right now, I'm making a small game(Mario) using DAllegro. I use 
 build, and every time, I have to type this in to compile my progress:

 build mario alleg.lib

 Now, I know it's not a lot of typing. But considering I type mario wrong 
 every so often, and I generally want to execute it after, assuming there is 
 not compiler errors, it takes time.
 In a .bat file right now, I have this:

 build mario alleg.lib
 mario

 But, mario will execute even if there are errors found by dmd.
 Is there anything that I can use to see if errors were found, and if there 
 isn't, execute it, and if there is, don't execute it?
 DMD1.036, Windows XP, Build/Bud 3.04

 build mario alleg.lib  mario

 Stops after the build if build returns a nonzero exit code.   That bit
 of the DOS shell is more or less just like a Unix shell.


Also, with that one-liner you can just use the up arrow instead of
typing it again or going to the trouble of putting it in a .bat file.

--bb


Re: .bat file to help compile easier - dmd/build

2009-01-02 Thread Bill Baxter
On Sat, Jan 3, 2009 at 7:20 AM, Jarrett Billingsley
jarrett.billings...@gmail.com wrote:
 On Fri, Jan 2, 2009 at 4:35 PM, Bill Baxter wbax...@gmail.com wrote:
 On Sat, Jan 3, 2009 at 4:17 AM, Michael P. baseball@gmail.com wrote:
 Okay, so right now, I'm making a small game(Mario) using DAllegro. I use 
 build, and every time, I have to type this in to compile my progress:

 build mario alleg.lib

 Now, I know it's not a lot of typing. But considering I type mario wrong 
 every so often, and I generally want to execute it after, assuming there is 
 not compiler errors, it takes time.
 In a .bat file right now, I have this:

 build mario alleg.lib
 mario

 But, mario will execute even if there are errors found by dmd.
 Is there anything that I can use to see if errors were found, and if there 
 isn't, execute it, and if there is, don't execute it?
 DMD1.036, Windows XP, Build/Bud 3.04

 build mario alleg.lib  mario

 I beat yo

Ah, didn't notice because gmail hid your response inside a click here
to see quoted message.

--bb


Re: How I can determine this is class or struct at compile time?

2008-12-27 Thread Bill Baxter
On Sat, Dec 27, 2008 at 4:14 PM, BCS a...@pathlink.com wrote:
 Reply to Weed,

 subj


 is(typeof(*this))?struct:class; // untested




if (is(typeof(this) == class)) {
// is class
} else {
//not
}


This page is your friend:
http://www.digitalmars.com/d/1.0/expression.html#IsExpression
Keep a copy under your pillow.

--bb


Re: distinguish between classes and structures

2008-12-15 Thread Bill Baxter
2008/12/15 Weed resume...@mail.ru:
 Bill Baxter пишет:

 On Mon, Dec 15, 2008 at 3:35 PM, Weed resume...@mail.ru wrote:

 Who can provide a link to an explanation about why in D has taken to
 distinguish between classes and structures?

 (Sorry for my bad English)


 The main justification is eliminating the slicing problem.

 http://cplusplusgems.blogspot.com/2005/10/what-is-slicing-problem-class-base.html

 D solves it by making it impossible to have a class instance as a value
 type.



 Why not disallow the casting for structs, leaving the possibility of up
 casting for the links and pointers to the structure?

I have to confess I don't really understand this question.  Can you
rephrase or give an example?

--bb


Re: distinguish between classes and structures

2008-12-15 Thread Bill Baxter
2008/12/15 Weed resume...@mail.ru:
 Weed пишет:

 Bill Baxter пишет:

 On Mon, Dec 15, 2008 at 3:35 PM, Weed resume...@mail.ru wrote:

 Who can provide a link to an explanation about why in D has taken to
 distinguish between classes and structures?

 (Sorry for my bad English)


 The main justification is eliminating the slicing problem.

 http://cplusplusgems.blogspot.com/2005/10/what-is-slicing-problem-class-base.html

 D solves it by making it impossible to have a class instance as a value
 type.



 Why not disallow the casting for structs, leaving the possibility of up
 casting for the links and pointers to the structure?

 What is the best place for such questions?

Here is fine.  digitalmars.d might be ok too.

This seems like a question that deserves a good answer on the rationale page:
http://www.digitalmars.com/d/2.0/rationale.html

I was just quoting to you the justification I've heard given before.
But I'm not necessarily convinced that it's a net win for the
language.  I find that it makes things simpler in some ways and more
complicated in other ways.  But the safety first argument says that
if it gets one potential bug (aka slicing), then its a net win.  I'm
not so sure.

--bb


Re: distinguish between classes and structures

2008-12-15 Thread Bill Baxter
2008/12/16 Weed resume...@mail.ru:
 Frits van Bommel пишет:

 Weed wrote:

 In C++, we had the problem - slicing objects.
 In D this problem is solved inability to inherit from structs.
 Without inheritance of structs many things are not possible, compared
 with C++.
 Why, instead of the complete inability to inherit, just do not make
 impossible to up casting struct type by value.

 like this:

 struct s1 {}
 struct s2 : s1 {}

 s1 base;
 s2 derr;

 s1* base_ptr = derr; // ok
 s1 val = derr; // error

 This is why:
  s1 val2 = *base_ptr; // error

 I do not understand that it is wrong?

The problem is that base_ptr isn't actually pointing to an s1.  So by
dereferencing it and assigning to an s1 you just sliced it.  Any extra
data derr had is lost.  Any method overrides it had are lost.  So to
avoid slicing you would need to disallow dereferencing struct
pointers, or disallow pointing to a struct of a different type.

Disallowing dereferencing a struct pointer seems like it might be
possible.  But then again that's also kinda what class gives you
already.  And then you'd be left with no way to create a pointer that
can be turned back into a value!  That doesn't sound so good.

--bb


Re: distinguish between classes and structures

2008-12-14 Thread Bill Baxter
On Mon, Dec 15, 2008 at 3:35 PM, Weed resume...@mail.ru wrote:
 Who can provide a link to an explanation about why in D has taken to
 distinguish between classes and structures?

 (Sorry for my bad English)


The main justification is eliminating the slicing problem.
http://cplusplusgems.blogspot.com/2005/10/what-is-slicing-problem-class-base.html

D solves it by making it impossible to have a class instance as a value type.

--bb


Re: Why is my code does not compile? (dmd 2.021 linux)

2008-12-12 Thread Bill Baxter
On Sat, Dec 13, 2008 at 5:45 AM, Weed resume...@mail.ru wrote:

 void main()
 {
int i;

ref int func()
{
  return i;
}

func() = 4;
 }

 lval.d(5): found 'ref' instead of statement
 lval.d(10): no identifier for declarator func
 lval.d(11): unrecognized declaration


 but code like this compiles:

 ref int func()
 {
  int* i = new int;
  return *i;
 }

 void main()
 {
func() = 4;
 }


Ref return values are a very new feature in D2.  I suspect its just a
bug that they don't work on inner functions yet.

--bb


Re: Why is my code does not compile? (dmd 2.021 linux)

2008-12-12 Thread Bill Baxter
2008/12/13 Weed resume...@mail.ru:
 Bill Baxter пишет:

 On Sat, Dec 13, 2008 at 5:45 AM, Weed resume...@mail.ru wrote:

 void main()
 {
   int i;

   ref int func()
   {
 return i;
   }

   func() = 4;
 }

 lval.d(5): found 'ref' instead of statement
 lval.d(10): no identifier for declarator func
 lval.d(11): unrecognized declaration


 but code like this compiles:

 ref int func()
 {
  int* i = new int;
  return *i;
 }

 void main()
 {
   func() = 4;
 }


 Ref return values are a very new feature in D2.  I suspect its just a
 bug that they don't work on inner functions yet.

 --bb

 message implies that the authors are aware of this limitation? report they
 do not need?

No, a report is probably needed.  There are lots of bugs with the new
const and ref features in D2.  Many have been reported, but there are
still many more to be discovered.  Returning refs in particular is
very new, so I would expect bugs a plenty with that, though I think
few have been reported so far.  I don't keep up with the bugs
newsgroup these days, though.  Certainly try to search for it in the
bug db before filing a new report, though.  D's bugzilla is here:
http://d.puremagic.com/issues/

--bb


Re: why the array bounds error

2008-12-07 Thread Bill Baxter
On Mon, Dec 8, 2008 at 11:22 AM, Michael P. [EMAIL PROTECTED] wrote:
 Michael P. Wrote:

 Okay, I'm getting an array bounds error, and I have no clue why. Here is the 
 code that affect it:

 //Constants
 const int SCREEN_WIDTH = 640;
 const int SCREEN_HEIGHT = 480;
 const int TILE_WIDTH = 20;
 const int TILE_HEIGHT = 20; //how big one tile is, in pixels
 const int NUMBER_OF_TILES_WIDTH = SCREEN_WIDTH / TILE_WIDTH;
 const int NUMBER_OF_TILES_HEIGHT = SCREEN_HEIGHT / TILE_HEIGHT;
 const int TYPES_OF_TILES = 4;

 //variables
 char[ NUMBER_OF_TILES_WIDTH ][ NUMBER_OF_TILES_HEIGHT ] tiles;
 //set all tiles to random
 for ( int i = 0; i  NUMBER_OF_TILES_WIDTH; i++ )
 {
   for ( int j = 0; j  NUMBER_OF_TILES_HEIGHT; j++ )
   {
   tiles[ i ][ j ] = cast( char )( rand()  TYPES_OF_TILES ); 
 //occurs here
   }
 }

 So, I'm not really sure why it's happening Anyone mind shedding some 
 light on why?

 -Michael P.

 I meant array bounds error, not array bounds array. :P

Your indices are backwards.

--bb


Re: why the array bounds array

2008-12-07 Thread Bill Baxter
On Mon, Dec 8, 2008 at 2:57 PM, BCS [EMAIL PROTECTED] wrote:
 Reply to Michael P.,

 rand()  TYPES_OF_TILES

 never use rand like that (the low order bit on many rands toggles every
 single time)
 better (I think):

 rand() / (TYPES_OF_TILES / RAND_MAX)

That's a divide by zero, so I don't think that's what you meant.

--bb


Re: custom opCmp for array sort

2008-12-01 Thread Bill Baxter
On Mon, Dec 1, 2008 at 7:23 PM, New [EMAIL PROTECTED] wrote:
 Thanks very much indeed for your help. The version posted does work. 
 Unfortunately I won't be able to use D for my project, this bug has scared 
 the management, D is still a moving target. I will have to wait until it is 
 more stable.

D1 is pretty stable, and I'm pretty sure that's what most folks are
using these days, actually.

--bb


 Cheers.


 Gide Nwawudu Wrote:

 On Fri, 28 Nov 2008 13:58:28 -0500, Kagamin [EMAIL PROTECTED] wrote:

 just found it accidentally
 http://d.puremagic.com/issues/show_bug.cgi?id=1309

 Yep, this issue prevents Path.opCmp from being called. The version
 below works.


 import std.string: find, cmp;
 import std.stdio: writefln;
 import std.algorithm : sort;

 struct Path {
 string thePath;

 int opCmp(Path other) {
   writefln(Path.opCmp);
 int pos;
 string a, b;

 pos = find(this.thePath, =);
 if (pos  -1)
 a = this.thePath[0 .. pos];
 else
 a = this.thePath;

 pos = find(other.thePath, =);
 if (pos  -1)
 b = other.thePath[0 .. pos];
 else
 b = other.thePath;

 return cmp(a, b);
 }
 }

 void main() {
 string[][Path] contents = [
 Path(/002=/other_dir): [aa,bb,cc,dd],
 Path(/001): [aa,bb,cc,dd],
 Path(/002=/hello) : [aa,bb,cc,dd]
 ];

 Path[] myPaths = contents.keys.dup;
 //myPaths.sort; // Does not call Path.opCmp
 sort(myPaths); // calls Path.opCmp

 foreach (item; myPaths)
 writefln(item.thePath);
 }




Re: tuple function parameters

2008-12-01 Thread Bill Baxter
On Tue, Dec 2, 2008 at 4:12 AM, llee [EMAIL PROTECTED] wrote:
 I defined a function that uses a tuple to define it's function parameters 
 like this:

 class Example (Signature ...)
 {
  void f (Signature) { ... }
 }

 I want to store the input parameters in an array, where the are is a data 
 member of the enclosing class.

 class Example (Signature ...)
 {
  ? array declaration here.

 Signature theData;

  void f (Signature) { ... }
 }

 Is this possible? If so, how would I do this?

Sure.  The above should work.

--bb


Comment highlighting in Descent plugin

2008-11-20 Thread Bill Baxter
Why is every word in every comment underlined with a red squiggle?
I see there's something called the D spell checker enabled.  Is it broken?
Disabling spell-checking makes the problem go away (but only after I
re-saved the file, which was rather unexpected... why should I have to
save the file for source code display styles to take effect?)

--bb


Re: Comment highlighting in Descent plugin

2008-11-20 Thread Bill Baxter
On Fri, Nov 21, 2008 at 1:13 PM, Robert Fraser
[EMAIL PROTECTED] wrote:
 Bill Baxter wrote:

 Why is every word in every comment underlined with a red squiggle?
 I see there's something called the D spell checker enabled.  Is it
 broken?
 Disabling spell-checking makes the problem go away (but only after I
 re-saved the file, which was rather unexpected... why should I have to
 save the file for source code display styles to take effect?)

 --bb

 If every word in the file (including keywords, var names, etc.) are being
 highlighted, you need to go to Window  Preferences  General  Editors 
 Text Editors  Spelling and change Default Spelling Engine to D Spelling
 Engine. This will make it only highlight spelling errors in comments 
 strings.

 If you got that part right, but every word is still being highlighted, it's
 likely because you are using non-English comments. In that case, you need to
 get a dictionary for whatever language you're using. Go to the same place
 (Window  Preferences  General  Editors  Text Editors  Spelling) and
 under User-defined dictionary, add a word list for your language (the format
 is just a list of words, one per line -- there's word lists like this all
 over the place for many different languages).

 If you have all that right  are using English comments, I'm not sure what
 the problem is (maybe an Eclipse version incompatibility...

Yeh I have all that right.  My Windows default system encoding is set
to Japanese, though.  Maybe that makes a difference?  The words its
flagging are all English words.

 what version are
 you using?).

Just downloaded both Eclipse and descent today.
eclipse-cpp-ganymede-SR1-win32 is the name of the zip file.

 As for why you have to save it, you need to get Eclipse to
 re-check the file. Generally, Eclipse does this either as you type, on a
 rebuild, or when you save, but to save a couple processor cycles it doesn't
 do this all the time.

I don't really care that much about spellcheck in comments, so I'll
just turn it off for now.

--bb


Re: Save/load data to a file

2008-11-17 Thread Bill Baxter
On Mon, Nov 17, 2008 at 11:07 PM, nobody [EMAIL PROTECTED] wrote:

 Bill Baxter [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
 On Mon, Nov 17, 2008 at 5:53 AM, Denis Koroskin [EMAIL PROTECTED] wrote:
 16.11.08 в 18:55 nobody в своём письме писал(а):

 I would like to be able to save and load a lot of data to/from a file.
 (in
 D1)
 For example a struct like this:

 struct Fruit
 {
int banana;
double[][] orange;
bool[] apple;
 }

 Practically all the examples that I've come across only deal with saving
 and
 loading text, so I'm having a hard time dealing with saving/loading
 arrays/floats/bools/etc.

 What would be a good way to do this?



 I know there is a doost.serializer
 (http://dsource.org/projects/doost/wiki/Serializer) but I never used it
 myself so I can't say whether it fill fit you.
 I am also prototyping another one at the moment, but I don't know how far
 will it take.


 team0xf has a library called xpose
 which does serialization to and from a binary format.

 Can be found here:
 http://team0xf.com:8080/xf/file/1eb43f0657ec/xpose/

 It's part of xf, which you can get using hg:
 hg clone http://team0xf.com:8080/xf


 --bb


 Oh, I've also used some other team0xf stuff, and that worked splendidly, so
 I'll check it out.
 Thanks.

I should mention that it's not quite done yet.  But many fairly tricky
things do work already.  For instance, I'm pretty sure that
de-serialization of subclasses was working properly last I tried it.
That is, if you write out a Derived, and then try to read back a Base,
the Base you get back will actually be a pointer to a Derived.   And
if you write out the same instance multiple times it only gets saved
once, and gets loaded back just once also, and the other N-1 copies
are just a  copy of the pointer to the one loaded instance.   I'm
pretty sure all that was working last time I tried it.  There was
something it couldn't do that I was wanting, but I don't quite recall
now...

On the down side, it's not exactly easy code to extend and/or debug.

--bb


Re: Cannot find link.exe

2008-11-09 Thread Bill Baxter
On Sun, Nov 9, 2008 at 8:52 PM, Rom [EMAIL PROTECTED] wrote:
 Hi pal,

  i also downloaded the dmc.zip. I extracted it and found link.exe there. I 
 tried
 to copy it on the dmd bin directory but i got a lots of error.

I'm not sure why it wouldn't work, but typically that stuff goes into
dm/bin, while the D stuff goes into dmd/bin.  Maybe the errors you got
were about copying over existing files?

--bb


Re: Cannot find link.exe

2008-11-09 Thread Bill Baxter
On Sun, Nov 9, 2008 at 10:52 PM, ore-sama [EMAIL PROTECTED] wrote:
 Rom Wrote:

 Hi pal,

  i also downloaded the dmc.zip. I extracted it and found link.exe there. I 
 tried
 to copy it on the dmd bin directory but i got a lots of error.

 you should extract whole dmc archive, also check dmd configuration.

The configuration is in dmd\bin\sc.ini.
There you can see it says:
[EMAIL PROTECTED]

Which means it expects link .exe to be in a dm\bin directory that's
parallel to the dmd\bin directory.

So yeh, it ain't gonna work copying link.exe to the dmd\bin directory.

--bb


Re: Array initialization with common base - Best way?

2008-11-09 Thread Bill Baxter
On Mon, Nov 10, 2008 at 6:47 AM, Ary Borenszweig [EMAIL PROTECTED] wrote:

 Can't the compiler try to set the array's component type to the most general
 type of it's elements, by combining the most general types by pairs?

 Hmmm... now that I think it, it's not that easy because of interfaces. Did
 this subject was ever discussed? If not, I'll try to think of an algorithm
 for this. (because if it was discussed, there must be a good reason for not
 doing this)

I'm not sure what the problem is.  I think Walter likes the current
scheme because it's simple for the compiler and simple to explain.
Unfortunately I think it is counter to naive expectations, which means
that even though it's simple to explain, it *has* to be explained to
the uninitiated.
NumPy works the way you suggest.  It picks the most generic type that
can hold the answer.  I'm not sure what the algorithm is but it seems
to give adhere much better to the principle of least surprise.   But
maybe the fact that NumPy only cares about numeric types makes the
problem easier.  But I should would like it if this worked
 auto foo = [1,1,1,0.5];
and gave me a double[].
Anyway, that behavior seems to do what most people expeect.  On the
other hand I've seen this topic of picking the first element's type
come up several times here, generally because people didn't expect
that behavior..

--bb