Re: Empty subexpressions captures in std.regex
Sorry about the lack of clarity in the last post. I actually commented out the call to the Regex.optimize in Regex.compile. auto r1 = regex( (a*)b ); r1.printProgram(); Prints out: printProgram() 0:REtestbit 98, 13 18:REparen len=15 n=0, pc=42 27:REnm len=2, n=0, m=4294967295, pc=42 40:REchar 'a' 42:REchar 'b' 44:REend With optimize(buf); commented out I get: printProgram() 0:REparen len=15 n=0, pc=24 9:REnm len=2, n=0, m=4294967295, pc=24 22:REchar 'a' 24:REchar 'b' 26:REend I don't understand why REtestbit is inserted at the start of the program by the optimize routine, but it will not match if there is no a at the start of the input (e.g. b). I think I need to spend some more time looking through the regex.d source to understand it better - Pete == Quote from Andrei Alexandrescu (seewebsiteforem...@erdani.org)'s article Hi PC, Thanks for your kind words. Regarding regex, we need to get a report into bugzilla so we keep track of the problem. When you say disable the call to optimize are you referring to the -O compiler flag? In that case it's a compiler problem (otherwise it might be a library issue). Could you please clarify? Thanks, Andrei On 07/11/2010 06:29 AM, PC wrote: Hi, I've been lurking in this group for a few months, have read through TDPL (which is great Andrei) and have started using D for some small programs. So far it's been a joy to use (you may have a C++ convert on your hands) and with the convenience of rdmd, I've been using it where I'd normally use a scripting language. It's been pretty good for this especially as Phobos has had almost everything I've wanted to do covered. I have run into some issues with std.regex matching empty subexpressions though (dmd 2.047, win32): auto r1 = regex( (a*)b ); auto m = match( b, r1 ); writefln( captures = %s, empty = %s, m.captures.length, m.empty ); = captures = 0, empty = true If I disable the call to optimize, it gives the expected results: = captures = 2, empty = false Also, with optimize disabled: auto r = regex(([^,]*),([^,]*),([^,]*)); m = match( ,,, r ); writefln( captures = %s, empty = %s, m.captures.length, m.empty ); = captures = 3, empty = false I noticed in Captures: @property size_t length() { foreach (i; 0 .. matches.length) { if (matches[i].startIdx= input.length) return i; } return matches.length; } In this case matches[3].startIdx = 2 and matches[3].endIdx=2. Should this line be: if (matches[i].startIdx input.length) return i; Anyway kudos to everyone involved with D, I'm certainly going to be using it a lot in the future.
Empty subexpressions captures in std.regex
Hi, I've been lurking in this group for a few months, have read through TDPL (which is great Andrei) and have started using D for some small programs. So far it's been a joy to use (you may have a C++ convert on your hands) and with the convenience of rdmd, I've been using it where I'd normally use a scripting language. It's been pretty good for this especially as Phobos has had almost everything I've wanted to do covered. I have run into some issues with std.regex matching empty subexpressions though (dmd 2.047, win32): auto r1 = regex( (a*)b ); auto m = match( b, r1 ); writefln( captures = %s, empty = %s, m.captures.length, m.empty ); = captures = 0, empty = true If I disable the call to optimize, it gives the expected results: = captures = 2, empty = false Also, with optimize disabled: auto r = regex(([^,]*),([^,]*),([^,]*)); m = match( ,,, r ); writefln( captures = %s, empty = %s, m.captures.length, m.empty ); = captures = 3, empty = false I noticed in Captures: @property size_t length() { foreach (i; 0 .. matches.length) { if (matches[i].startIdx = input.length) return i; } return matches.length; } In this case matches[3].startIdx = 2 and matches[3].endIdx=2. Should this line be: if (matches[i].startIdx input.length) return i; Anyway kudos to everyone involved with D, I'm certainly going to be using it a lot in the future.
pcnetsecur...@gmail.com Assistência Téc nica manutenção de computador es informatica Vitória-es 49518
Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com Planos a partir de R$ 250,00 . Assistência Técnica Prestamos assistência técnica nos computadores de sua empresa ou residência, e também possuímos uma equipe qualificada para fazer a manutenção no próprio local. - Contratos de Suporte e Manutenção Reduza os custos de sua empresa com solicitações de visitas técnicas para seus computadores, elaboramos um contrato de manutenção integrado para sua empresa onde disponibilizamos: técnicos, equipamentos de suporte e substituição, e atendimento no horário comercial ou plantão sob análise. - Redes Corporativas (Projetos e Instalações de Cabeamento Estruturado ou Wireless e parte Lógica em Geral) Projetamos e instalamos desde uma simples rede ponto a ponto, até uma rede de dados mais complexa e segura com compartilhamento de arquivos local e/ou remotamente, impressoras e Internet com Servidores 2003 ou 2008 Server. Disponibilizamos: TS (Terminal Server), VPN (Virtual Private Network) e FTP (File Tranfer Protocol), além de diversos serviços afins, como Backups automatizados entre outros. - Consultoria técnica em Hardware e Software Prestamos consultoria para melhorar os processos de sua empresa através da informática, otimizando assim o seu atendimento e o desenvolvimento da empresa. - Segurança. Protegemos sua empresa de vírus e invasões, o acesso aos dados dos usuários é feito de forma seletiva, ou seja, somente aqueles que tiverem permissões especiais terão essa possibilidade. Fazemos também um backup completo de todo o seu HD. Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com @ehncioy^+zbx%qYT)Mjf#mZ
pcnetsecur...@gmail.com Assistência Téc nica manutenção de computador es informatica Vitória-es 31527
Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com Planos a partir de R$ 250,00 . Assistência Técnica Prestamos assistência técnica nos computadores de sua empresa ou residência, e também possuímos uma equipe qualificada para fazer a manutenção no próprio local. - Contratos de Suporte e Manutenção Reduza os custos de sua empresa com solicitações de visitas técnicas para seus computadores, elaboramos um contrato de manutenção integrado para sua empresa onde disponibilizamos: técnicos, equipamentos de suporte e substituição, e atendimento no horário comercial ou plantão sob análise. - Redes Corporativas (Projetos e Instalações de Cabeamento Estruturado ou Wireless e parte Lógica em Geral) Projetamos e instalamos desde uma simples rede ponto a ponto, até uma rede de dados mais complexa e segura com compartilhamento de arquivos local e/ou remotamente, impressoras e Internet com Servidores 2003 ou 2008 Server. Disponibilizamos: TS (Terminal Server), VPN (Virtual Private Network) e FTP (File Tranfer Protocol), além de diversos serviços afins, como Backups automatizados entre outros. - Consultoria técnica em Hardware e Software Prestamos consultoria para melhorar os processos de sua empresa através da informática, otimizando assim o seu atendimento e o desenvolvimento da empresa. - Segurança. Protegemos sua empresa de vírus e invasões, o acesso aos dados dos usuários é feito de forma seletiva, ou seja, somente aqueles que tiverem permissões especiais terão essa possibilidade. Fazemos também um backup completo de todo o seu HD. Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com )lsoyVxfDt*xgLZSz$fX%?%u?
pcnetsecur...@gmail.com Assistência Téc nica manutenção de computador es informatica Vitória-es 40410
Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com Planos a partir de R$ 250,00 . Assistência Técnica Prestamos assistência técnica nos computadores de sua empresa ou residência, e também possuímos uma equipe qualificada para fazer a manutenção no próprio local. - Contratos de Suporte e Manutenção Reduza os custos de sua empresa com solicitações de visitas técnicas para seus computadores, elaboramos um contrato de manutenção integrado para sua empresa onde disponibilizamos: técnicos, equipamentos de suporte e substituição, e atendimento no horário comercial ou plantão sob análise. - Redes Corporativas (Projetos e Instalações de Cabeamento Estruturado ou Wireless e parte Lógica em Geral) Projetamos e instalamos desde uma simples rede ponto a ponto, até uma rede de dados mais complexa e segura com compartilhamento de arquivos local e/ou remotamente, impressoras e Internet com Servidores 2003 ou 2008 Server. Disponibilizamos: TS (Terminal Server), VPN (Virtual Private Network) e FTP (File Tranfer Protocol), além de diversos serviços afins, como Backups automatizados entre outros. - Consultoria técnica em Hardware e Software Prestamos consultoria para melhorar os processos de sua empresa através da informática, otimizando assim o seu atendimento e o desenvolvimento da empresa. - Segurança. Protegemos sua empresa de vírus e invasões, o acesso aos dados dos usuários é feito de forma seletiva, ou seja, somente aqueles que tiverem permissões especiais terão essa possibilidade. Fazemos também um backup completo de todo o seu HD. Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com PkHXRy+BYJyo/%...@vt@q+c*IN
pcnetsecur...@gmail.com Assistência Téc nica manutenção de computador es informatica Vitória-es 07457
Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com Planos a partir de R$ 250,00 . Assistência Técnica Prestamos assistência técnica nos computadores de sua empresa ou residência, e também possuímos uma equipe qualificada para fazer a manutenção no próprio local. - Contratos de Suporte e Manutenção Reduza os custos de sua empresa com solicitações de visitas técnicas para seus computadores, elaboramos um contrato de manutenção integrado para sua empresa onde disponibilizamos: técnicos, equipamentos de suporte e substituição, e atendimento no horário comercial ou plantão sob análise. - Redes Corporativas (Projetos e Instalações de Cabeamento Estruturado ou Wireless e parte Lógica em Geral) Projetamos e instalamos desde uma simples rede ponto a ponto, até uma rede de dados mais complexa e segura com compartilhamento de arquivos local e/ou remotamente, impressoras e Internet com Servidores 2003 ou 2008 Server. Disponibilizamos: TS (Terminal Server), VPN (Virtual Private Network) e FTP (File Tranfer Protocol), além de diversos serviços afins, como Backups automatizados entre outros. - Consultoria técnica em Hardware e Software Prestamos consultoria para melhorar os processos de sua empresa através da informática, otimizando assim o seu atendimento e o desenvolvimento da empresa. - Segurança. Protegemos sua empresa de vírus e invasões, o acesso aos dados dos usuários é feito de forma seletiva, ou seja, somente aqueles que tiverem permissões especiais terão essa possibilidade. Fazemos também um backup completo de todo o seu HD. Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com YWPCQE?/d...@=wct%p(_T(Qgvn
pcnetsecur...@gmail.com Assistência Téc nica manutenção de computador es informatica Vitória-es 52461
Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com Planos a partir de R$ 250,00 . Assistência Técnica Prestamos assistência técnica nos computadores de sua empresa ou residência, e também possuímos uma equipe qualificada para fazer a manutenção no próprio local. - Contratos de Suporte e Manutenção Reduza os custos de sua empresa com solicitações de visitas técnicas para seus computadores, elaboramos um contrato de manutenção integrado para sua empresa onde disponibilizamos: técnicos, equipamentos de suporte e substituição, e atendimento no horário comercial ou plantão sob análise. - Redes Corporativas (Projetos e Instalações de Cabeamento Estruturado ou Wireless e parte Lógica em Geral) Projetamos e instalamos desde uma simples rede ponto a ponto, até uma rede de dados mais complexa e segura com compartilhamento de arquivos local e/ou remotamente, impressoras e Internet com Servidores 2003 ou 2008 Server. Disponibilizamos: TS (Terminal Server), VPN (Virtual Private Network) e FTP (File Tranfer Protocol), além de diversos serviços afins, como Backups automatizados entre outros. - Consultoria técnica em Hardware e Software Prestamos consultoria para melhorar os processos de sua empresa através da informática, otimizando assim o seu atendimento e o desenvolvimento da empresa. - Segurança. Protegemos sua empresa de vírus e invasões, o acesso aos dados dos usuários é feito de forma seletiva, ou seja, somente aqueles que tiverem permissões especiais terão essa possibilidade. Fazemos também um backup completo de todo o seu HD. Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com BMtyrNkptdN$vxflMLn!#/^b
assitencia computadores enseada do sua vitoria-es 52395
Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com Assistência Técnica Prestamos assistência técnica nos computadores de sua empresa ou residência, e também possuímos uma equipe qualificada para fazer a manutenção no próprio local. - Contratos de Suporte e Manutenção Reduza os custos de sua empresa com solicitações de visitas técnicas para seus computadores, elaboramos um contrato de manutenção integrado para sua empresa onde disponibilizamos: técnicos, equipamentos de suporte e substituição, e atendimento no horário comercial ou plantão sob análise. - Redes Corporativas (Projetos e Instalações de Cabeamento Estruturado ou Wireless e parte Lógica em Geral) Projetamos e instalamos desde uma simples rede ponto a ponto, até uma rede de dados mais complexa e segura com compartilhamento de arquivos local e/ou remotamente, impressoras e Internet com Servidores 2003 ou 2008 Server. Disponibilizamos: TS (Terminal Server), VPN (Virtual Private Network) e FTP (File Tranfer Protocol), além de diversos serviços afins, como Backups automatizados entre outros. - Consultoria técnica em Hardware e Software Prestamos consultoria para melhorar os processos de sua empresa através da informática, otimizando assim o seu atendimento e o desenvolvimento da empresa. - Segurança. Protegemos sua empresa de vírus e invasões, o acesso aos dados dos usuários é feito de forma seletiva, ou seja, somente aqueles que tiverem permissões especiais terão essa possibilidade. Fazemos também um backup completo de todo o seu HD. Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com z?v...@hkfclo(tqM(i#+T#kF
Assistencia Tecnica windows jardim da penha vitoria 82612
Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com Assistência Técnica Prestamos assistência técnica nos computadores de sua empresa ou residência, e também possuímos uma equipe qualificada para fazer a manutenção no próprio local. - Contratos de Suporte e Manutenção Reduza os custos de sua empresa com solicitações de visitas técnicas para seus computadores, elaboramos um contrato de manutenção integrado para sua empresa onde disponibilizamos: técnicos, equipamentos de suporte e substituição, e atendimento no horário comercial ou plantão sob análise. - Redes Corporativas (Projetos e Instalações de Cabeamento Estruturado ou Wireless e parte Lógica em Geral) Projetamos e instalamos desde uma simples rede ponto a ponto, até uma rede de dados mais complexa e segura com compartilhamento de arquivos local e/ou remotamente, impressoras e Internet com Servidores 2003 ou 2008 Server. Disponibilizamos: TS (Terminal Server), VPN (Virtual Private Network) e FTP (File Tranfer Protocol), além de diversos serviços afins, como Backups automatizados entre outros. - Consultoria técnica em Hardware e Software Prestamos consultoria para melhorar os processos de sua empresa através da informática, otimizando assim o seu atendimento e o desenvolvimento da empresa. - Segurança. Protegemos sua empresa de vírus e invasões, o acesso aos dados dos usuários é feito de forma seletiva, ou seja, somente aqueles que tiverem permissões especiais terão essa possibilidade. Fazemos também um backup completo de todo o seu HD. Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com S+e/ybz?pW=ipB?+x_mPM%N
38842
Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com Assistência Técnica Prestamos assistência técnica nos computadores de sua empresa ou residência, e também possuímos uma equipe qualificada para fazer a manutenção no próprio local. - Contratos de Suporte e Manutenção Reduza os custos de sua empresa com solicitações de visitas técnicas para seus computadores, elaboramos um contrato de manutenção integrado para sua empresa onde disponibilizamos: técnicos, equipamentos de suporte e substituição, e atendimento no horário comercial ou plantão sob análise. - Redes Corporativas (Projetos e Instalações de Cabeamento Estruturado ou Wireless e parte Lógica em Geral) Projetamos e instalamos desde uma simples rede ponto a ponto, até uma rede de dados mais complexa e segura com compartilhamento de arquivos local e/ou remotamente, impressoras e Internet com Servidores 2003 ou 2008 Server. Disponibilizamos: TS (Terminal Server), VPN (Virtual Private Network) e FTP (File Tranfer Protocol), além de diversos serviços afins, como Backups automatizados entre outros. - Consultoria técnica em Hardware e Software Prestamos consultoria para melhorar os processos de sua empresa através da informática, otimizando assim o seu atendimento e o desenvolvimento da empresa. - Segurança. Protegemos sua empresa de vírus e invasões, o acesso aos dados dos usuários é feito de forma seletiva, ou seja, somente aqueles que tiverem permissões especiais terão essa possibilidade. Fazemos também um backup completo de todo o seu HD. Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com LwKH(vPB/y...@yyrttj.XUL$)
servicos especializados de informatica vitoria-es 99297
Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com Assistência Técnica Prestamos assistência técnica nos computadores de sua empresa ou residência, e também possuímos uma equipe qualificada para fazer a manutenção no próprio local. - Contratos de Suporte e Manutenção Reduza os custos de sua empresa com solicitações de visitas técnicas para seus computadores, elaboramos um contrato de manutenção integrado para sua empresa onde disponibilizamos: técnicos, equipamentos de suporte e substituição, e atendimento no horário comercial ou plantão sob análise. - Redes Corporativas (Projetos e Instalações de Cabeamento Estruturado ou Wireless e parte Lógica em Geral) Projetamos e instalamos desde uma simples rede ponto a ponto, até uma rede de dados mais complexa e segura com compartilhamento de arquivos local e/ou remotamente, impressoras e Internet com Servidores 2003 ou 2008 Server. Disponibilizamos: TS (Terminal Server), VPN (Virtual Private Network) e FTP (File Tranfer Protocol), além de diversos serviços afins, como Backups automatizados entre outros. - Consultoria técnica em Hardware e Software Prestamos consultoria para melhorar os processos de sua empresa através da informática, otimizando assim o seu atendimento e o desenvolvimento da empresa. - Segurança. Protegemos sua empresa de vírus e invasões, o acesso aos dados dos usuários é feito de forma seletiva, ou seja, somente aqueles que tiverem permissões especiais terão essa possibilidade. Fazemos também um backup completo de todo o seu HD. Contato: pcnetsecur...@gmail.com Contato: pcnetsecurity @ gmail.com Qz/w...@a+zybanqlbA/=+$UNc
Phobos, std.typecons: arrays of Rebindable
I had problems sorting an array of Rebindable!(..). Please see attached file. Am I completely missing the point or is this a bug? Also, a shown in the file, a hack to make this work may depend on a bug? in std.algoritm's swap function. But I am way over my head. Just trying to help.
Re: Phobos, std.typecons: arrays of Rebindable - with file
pc Wrote: I had problems sorting an array of Rebindable!(..). Please see attached file. Am I completely missing the point or is this a bug? Also, a shown in the file, a hack to make this work may depend on a bug? in std.algoritm's swap function. But I am way over my head. Just trying to help. import std.traits; import std.stdio, std.algorithm; class C1 { int x; this(int x){this.x = x;} int y() const { return x; } } alias Rebindable!(const(C1)) RC1; /*** Bugs?? -- Sorting and array of, say, Rebindable!(const(C1)) RC1; Possible typecons.d Bug Before I changed opAssign in a copy of Rebindable, below, test3 would not compile. I.e., Arrays of Rebindable appeared to fail for sorting because swap was not working. Possible algorithm.d Bug After the change to opAssign, everything worked just worked the change it just worked. But maybe it should not have worked so easily. I.e, after reading 1.8 of TDPL and looking breifly at the code in std.algorithm, I thought that I would have to ?overload? swap: void swap(ref RC1 a, ref RC1 b) { auto t = a; b = a; a = t; } But it worked without this. Is this correct behavior? */ void test3() { RC1[] aCs; aCs.length = 2; aCs[0] = new C1(9); aCs[1] = new C1(10); aCs ~= RC1(new C1(8)); sort!(a.x b.x)(aCs); foreach(ac; aCs) writeln(ac.y()); } // lifted from typecons.d // except for second opAssign template Rebindable(T) if (is(T : Object) || isArray!(T)) { static if (!is(T X == const(U), U) !is(T X == invariant(U), U)) { alias T Rebindable; } else static if (isArray!(T)) { alias const(ElementType!(T))[] Rebindable; } else { struct Rebindable { private union { T original; U stripped; } void opAssign(T another) { stripped = cast(U) another; } // comment out this opAssign and test3 will not compile void opAssign(Rebindable another) { stripped = another.stripped; } // - static Rebindable opCall(T initializer) { Rebindable result; result = initializer; return result; } alias original get; T opDot() { return original; } } } } void main(){ test3(); }
Re: Phobos, std.typecons: arrays of Rebindable - with DOS file
pc Wrote: pc Wrote: I had problems sorting an array of Rebindable!(..). Please see attached file. Am I completely missing the point or is this a bug? Also, a shown in the file, a hack to make this work may depend on a bug? in std.algoritm's swap function. But I am way over my head. Just trying to help. import std.traits; import std.stdio, std.algorithm; class C1 { int x; this(int x){this.x = x;} int y() const { return x; } } alias Rebindable!(const(C1)) RC1; /*** Bugs?? -- Sorting and array of, say, Rebindable!(const(C1)) RC1; Possible typecons.d Bug Before I changed opAssign in a copy of Rebindable, below, test3 would not compile. I.e., Arrays of Rebindable appeared to fail for sorting because swap was not working. Possible algorithm.d Bug After the change to opAssign, everything worked just worked the change it just worked. But maybe it should not have worked so easily. I.e, after reading 1.8 of TDPL and looking breifly at the code in std.algorithm, I thought that I would have to ?overload? swap: void swap(ref RC1 a, ref RC1 b) { auto t = a; b = a; a = t; } But it worked without this. Is this correct behavior? */ void test3() { RC1[] aCs; aCs.length = 2; aCs[0] = new C1(9); aCs[1] = new C1(10); aCs ~= RC1(new C1(8)); sort!(a.x b.x)(aCs); foreach(ac; aCs) writeln(ac.y()); } // lifted from typecons.d // except for second opAssign template Rebindable(T) if (is(T : Object) || isArray!(T)) { static if (!is(T X == const(U), U) !is(T X == invariant(U), U)) { alias T Rebindable; } else static if (isArray!(T)) { alias const(ElementType!(T))[] Rebindable; } else { struct Rebindable { private union { T original; U stripped; } void opAssign(T another) { stripped = cast(U) another; } // comment out this opAssign and test3 will not compile void opAssign(Rebindable another) { stripped = another.stripped; } // - static Rebindable opCall(T initializer) { Rebindable result; result = initializer; return result; } alias original get; T opDot() { return original; } } } } void main(){ test3(); } import std.traits; import std.stdio, std.algorithm; class C1 { int x; this(int x){this.x = x;} int y() const { return x; } } alias Rebindable!(const(C1)) RC1; /*** Bugs?? -- Sorting and array of, say, Rebindable!(const(C1)) RC1; Possible typecons.d Bug Before I changed opAssign in a copy of Rebindable, below, test3 would not compile. I.e., Arrays of Rebindable appeared to fail for sorting because swap was not working. Possible algorithm.d Bug After the change to opAssign, everything worked just worked the change it just worked. But maybe it should not have worked so easily. I.e, after reading 1.8 of TDPL and looking breifly at the code in std.algorithm, I thought that I would have to ?overload? swap: void swap(ref RC1 a, ref RC1 b) { auto t = a; b = a; a = t; } But it worked without this. Is this correct behavior? */ void test3() { RC1[] aCs; aCs.length = 2; aCs[0] = new C1(9); aCs[1] = new C1(10); aCs ~= RC1(new C1(8)); sort!(a.x b.x)(aCs); foreach(ac; aCs) writeln(ac.y()); } // lifted from typecons.d // except for second opAssign template Rebindable(T) if (is(T : Object) || isArray!(T)) { static if (!is(T X == const(U), U) !is(T X == invariant(U), U)) { alias T Rebindable; } else static if (isArray!(T)) { alias const(ElementType!(T))[] Rebindable; } else { struct Rebindable { private union { T original; U stripped; } void opAssign(T another) { stripped = cast(U) another; } // comment out this opAssign and test3 will not compile void opAssign(Rebindable another) { stripped = another.stripped; } // - static Rebindable opCall(T initializer) { Rebindable result; result = initializer; return result; } alias original get; T opDot() { return original; } } } } void main(){ test3(); }
Re: Phobos, std.typecons: arrays of Rebindable
Done. I am only up to chapter 6, but so far, IMHO, TDPL is a really great book. Thanks for writing it. I would like to see a chapter that introduces (to the extent not discussed in the context of generic functions and class), the template related concepts that are manifest in std.traits, std.typetuple, std.algortim, std.typecons, std.conv. Perhaps a second book - Phobos and D Tempates or the like is really what is needed. Even if you can't fit this in, a little more explanation on how to pick up imputed types like T and U in T[U], would be helpful. In any case, I was at a loss understanding the const(U), U in the following (from Rebindable in std.typecons) based on the description of is Expresions at 2.4.1.4.3. static if (!is(T X == const(U), U) !is(T X == invariant(U), U)) Granted, this example did not come from the book, and I know that you cannot possibly explain everything, but I have the feeling that this way of picking up U, as well as T, is fundamental and should not be left out of the book. Like I said, the book is great -- even in draft. Thanks again, pc
is(ulong : long) evaluates to true, is(int[] S) does not always compile
Per TDPL p. 66 is(ulong : long) should be false, but see below. is(int[] S) did no compile outside of static if Are these bugs? import std.stdio; void main(){ bool z = is(int[]); //ok //bool z = is(int[] AZ); //error only takes (T Sym) in static conditional static if (is(int[] AZ)) //ok writeln(typeid(AZ)); bool a = is(uint : int), b = is(ulong : long); writefln(%s %s,a,b); //== true true }
Re: std.string phobos
dsimcha Wrote: == Quote from pc (peng2che...@yahoo.com)'s article Is there a way to make the functions in std.string, such as replace, pure? Many pure functions are going to want to use these. Also, could some of them be executable at compile time? For me, using D2.032, this did not compile. pure string replaceXX(string str){ return replace(str,XX,X); } If I am missing something, help! For a function in D to pass the compiler checks for purity, it must only call functions that are *marked as* being pure. If a function is not marked as pure but is de facto pure, it won't work. For example: uint nPlus2(uint n) pure { return nPlus1( nPlus1( n)); // Not pure. } uint nPlus1(uint n) { return n + 1; } Many functions that are, in fact, pure, have not been annotated as such yet in Phobos, since pure was implemented fairly recently. If you want to help out, this is fairly low hanging fruit. Also, purity is very restrictive right now and is designed partly with thread safety in mind. A function that truly has no side effects from an observable behavior in a single thread point of view won't necessarily pass the compiler as pure: __gshared uint foo; /* wasteTime() is impure even though it has no observable side * effects in a single thread because it still (at least * temporarily) manipulates global state, and thus could * cause problems in multithreaded code. Furthermore, even if * it were thread safe, it would be hard to prove for all but * the simplest cases that functions like these have no * observable side effects.*/ void wasteTime() pure { // Won't compile. foo++; foo--; } Thank you for the helpful comments. Re helping out, I would like to help, but at this stage I feel that I need to learn much much more before I can be of any use. (I am a recently retired international income tax consultant). If I get up to speed, I will certainly help. I was thinking that it would be good if std.string was completely templated to work for char, wchar and dchar (My main hobby is learning Chinese, so I have an interest in unicode.) I also thought the functions should be pure. The first step in this direction, and to learn D2, was to write immutable(T)[][] csvSplit(T)(immutable(T)[], T sep=',', T quote=''); This worked out pretty well for string, wstring and dstring. (copy attached). I take no credit for anything clever in the code (its all based on a lisp program written by Alain Picard that is availble on the web -- it was by far the easiest to understand). Here's the catch -- I could not make csvSplit pure. The inner functions were referencing cvsSplits local variables. I think that the problem only occurs in templates. The following isolates the issue: import std.stdio; /* ATTEMPT TO USE NESTED PURE FUNCTIONS IN A TEMPLATE. All works fine unless you uncomment the third line in main. If you do, dmd 2.032 yeilds: pure.d(35): Error: pure nested function 'bar' cannot access mutable data 'fooState' pure.d(36): Error: pure nested function 'bar' cannot access mutable data 'y' pure.d(47): Error: template instance pure.fooPT!(char) error instantiating */ //pure inner function, with concrete types - ok pure string foo(string x, string y){ string fooState; string bar(string x){ fooState = hello ; return x ~ y; } return fooState ~ bar(x); } //potentially pure (?) templated version not labled as pure - ok immutable(T)[] fooT(T)(immutable(T)[] x, immutable(T)[] y){ immutable(T)[] fooState; immutable(T)[] bar(immutable(T)[] x){ fooState = hello ; return x ~ y; } return fooState ~ bar(x); } //attempt to make templated version pure - no dice pure immutable(T)[] fooPT(T)(immutable(T)[] x, immutable(T)[] y){ immutable(T)[] fooState; immutable(T)[] bar(immutable(T)[] x){ fooState = hello ; return x ~ y; } return fooState ~ bar(x); } void main(){ writeln(foo(p, c)); writeln(fooT(p, c)); //writeln(fooPT(p, c)); // Alain Picard -- the states // figure how to acknowledge // put in my string util module // module dcsv; import std.string; version(unittest){import std.conv;} private enum {OUTSIDE_FIELD, IN_FIELD, IN_QUOTED_FIELD, AFTER_ENDING_QUOTE} /* csvSplit * * Splits a line into its csv formatted fields * Strips leading and trailing whitespace from fields, unless quoted * The line can be string, wstring or dstring * */ public immutable(T)[][] csvSplit(T)(immutable(T)[] line, T fieldSepChar=',', T quoteChar = '') { alias immutable(T)[] tstring; immutable int EOL = -1; tstring nullField = ; int state; int fieldBeg; int charPos; tstring[] fields; bool fieldHasDoubleQuoteChars; int numTrailingWhitespaceChars; tstring reduceDoubles(T)(tstring str, T q){ tstring ret; bool afterQuote = false; foreach(T c;str){ if (c==q) { if (afterQuote){ afterQuote = false
std.string phobos
Is there a way to make the functions in std.string, such as replace, pure? Many pure functions are going to want to use these. Also, could some of them be executable at compile time? For me, using D2.032, this did not compile. pure string replaceXX(string str){ return replace(str,XX,X); } If I am missing something, help!
template FieldTypeTuple(S) in std.traits
1. Are the types guaranteed to be in the same order as the definition? struct S1 {int a; float f} can be intialized with S1(10, 10.5), implying a constructor that is based on the lexical order in the definition? Will FieldTypeTuple!(S1), always give me Tuple!(int, float)? Would the answer be the same if S1 were a class? 2. The description of Template RepresentationTypeTuple(T...) states: Get the primitive types of the fields of a struct or class, in topological order. Is this the lexical order in the code or how they are laid out when compiled or what? Thanks