Difference between revisions of "Conceitos básicos: D"

From AdonaiMedrado.Pro.Br
Jump to: navigation, search
(Atribuição entre vetores)
(Referências)
 
(15 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
== Compiladores  & IDEs disponíveis ==
 +
 +
=== Compiladores ===
 +
==== Diginal Mars D ====
 +
Website: http://www.digitalmars.com/d/download.html
 +
 +
==== GDC ====
 +
Website: http://dgcc.sourceforge.net/.
 +
 +
=== IDEs ===
 +
==== Poseidon ====
 +
Website: http://dsource.org/projects/poseidon.
 +
 +
==== Descent (plugin para o Eclipse) ====
 +
Website: http://www.dsource.org/projects/descent.
 +
 +
==== Mais ====
 +
Veja em: http://www.prowiki.org/wiki4d/wiki.cgi?EditorSupport
 +
 
== Tipos básicos <ref name="dspecification">D Specification em http://www.prowiki.org/upload/duser/spec_DMD_1.00.pdf</ref> ==
 
== Tipos básicos <ref name="dspecification">D Specification em http://www.prowiki.org/upload/duser/spec_DMD_1.00.pdf</ref> ==
 
<code lang="d">
 
<code lang="d">
void no type -
+
void
 
bool = false
 
bool = false
 
byte (8 bits com sinal) = 0
 
byte (8 bits com sinal) = 0
Line 26: Line 45:
 
dchar (32 bits sem sinal - UTF-32) = 0x0000FFFF
 
dchar (32 bits sem sinal - UTF-32) = 0x0000FFFF
 
</code>
 
</code>
 +
 +
== Declaração<ref name="dspecification" /> ==
 +
=== Especificação ===
 +
<code lang="d">
 +
DeclarationStatement:
 +
    Declaration
 +
</code>
 +
 +
=== Exemplo ===
 +
<code lang="d">
 +
int a;            // declara a como um inteiro.
 +
struct S { }      // declara a estrutura S.
 +
alias int meuint; // declara meuint como um outro nome para o tipo int.
 +
</code>
 +
 +
== Bloco<ref name="dspecification" /> ==
 +
<code lang="d">
 +
BlockStatement:
 +
    { }
 +
    { StatementList }
 +
StatementList:
 +
    Statement
 +
    Statement StatementList
 +
</code>
 +
 +
== Escopo<ref name="dspecification" /> ==
 +
<code lang="d">
 +
ScopeBlockStatement:
 +
    BlockStatement
 +
</code>
 +
 +
== Função ==
 +
 +
== Classe ==
 +
  
 
== Vetores e matrizes <ref name="dspecification" /> ==
 
== Vetores e matrizes <ref name="dspecification" /> ==
Line 107: Line 161:
 
</code>
 
</code>
  
== Estruturas condicionais ==
+
== Estruturas condicionais<ref name="dspecification" /> ==
  
 
=== if ===
 
=== if ===
 +
 +
==== Especificação ====
 +
<code lang="d">
 +
IfStatement:
 +
    if ( IfCondition ) ThenStatement
 +
    if ( IfCondition ) ThenStatement else ElseStatement
 +
IfCondition:
 +
    Expression
 +
    auto Identifier = Expression
 +
    Declarator = Expression
 +
ThenStatement:
 +
    ScopeStatement
 +
ElseStatement:
 +
    ScopeStatement
 +
</code>
 +
 +
==== Exemplo ====
 +
<code lang="d">
 +
if (...)
 +
{
 +
    ...
 +
}
 +
else
 +
{
 +
    ...
 +
}
 +
</code>
  
 
=== switch ===
 
=== switch ===
 +
==== Especificação ====
 +
<code lang="d">
 +
SwitchStatement:
 +
    switch ( Expression ) ScopeStatement
 +
CaseStatement:
 +
    case ExpressionList : Statement
 +
DefaultStatement:
 +
default: Statement
 +
</code>
 +
==== Exemplo ====
 +
<code lang="d">
 +
switch (i)
 +
{
 +
    case 1:
 +
        x = 3;
 +
    case 2:
 +
        x = 4;
 +
        break;
 +
    case 3,4,5:
 +
        x = 5;
 +
        break;
 +
}
 +
</code>
  
 
=== ? : ===
 
=== ? : ===
 +
==== Especificação ====
 +
<code lang="d">
 +
ConditionalExpression:
 +
    OrOrExpression
 +
    OrOrExpression ? Expression : ConditionalExpression
 +
OrOrExpression:
 +
    AndAndExpression
 +
    OrOrExpression || AndAndExpression
 +
AndAndExpression:
 +
    OrExpression
 +
    AndAndExpression && OrExpression
 +
</code>
  
== Estrutura de repetição ==
+
== Estrutura de repetição<ref name="dspecification" /> ==
  
 
=== for ===
 
=== for ===
 +
==== Especificacão ====
 +
<code lang="d">
 +
ForStatement:
 +
    for (Initialize Test; Increment) ScopeStatement
 +
Initialize:
 +
    ;
 +
    NoScopeNonEmptyStatement
 +
Test:
 +
    empty
 +
    Expression
 +
Increment:
 +
    empty
 +
    Expression
 +
</code>
  
=== while ===
+
==== Exemplo ====
 +
<code lang="d">
 +
for (int i = 0; i < 10; i++)
 +
    foo(i);
 +
</code>
  
=== do...while ===
+
'''Atenção''':
 +
<code lang="d">
 +
for (int i = 0; i < 10; i++) ;  //isto não é permitido.
 +
for (int i = 0; i < 10; i++) {} //mas isto sim.
 +
</code>
  
== Declaração ==
+
=== foreach ===
  
=== Bloco ===
+
==== Especificação ====
 +
<code lang="c">
 +
ForeachStatement:
 +
    Foreach (ForeachTypeList; Aggregate) ScopeStatement
 +
Foreach:
 +
    foreach
 +
    foreach_reverse
 +
ForeachTypeList:
 +
    ForeachType
 +
    ForeachType , ForeachTypeList
 +
ForeachType:
 +
    inout Type Identifier
 +
    Type Identifier
 +
    inout Identifier
 +
    Identifier
 +
Aggregate:
 +
    Expression
 +
    Tuple
 +
</code>
  
=== Função ===
+
==== Exemplo 1 ====
 +
Exemplo também é válido para foreach_reverse.
 +
 
 +
<code lang="d">
 +
char[] a;
 +
...
 +
foreach (int i, char c; a)
 +
{
 +
    printf("a[%d] = '%c'\n", i, c);
 +
}
 +
</code>
 +
 
 +
==== Exemplo 2 ====
 +
Exemplo também é válido para foreach_reverse.
 +
 
 +
<code lang="d">
 +
foreach (char c; "ab")
 +
{
 +
    printf("'%c'\n", c);
 +
}
 +
</code>
 +
 
 +
==== Exemplo 3 ====
 +
Exemplo abaixo '''não''' é válido para foreach_reverse.
 +
 
 +
<code lang="d">
 +
double[char[]] a;
 +
...
 +
foreach (char[] s, double d; a)
 +
{
 +
    printf("a['%.*s'] = %g\n", s, d);
 +
}
 +
</code>
 +
 
 +
==== Exemplo 4 ====
 +
O segundo parâmetro de foreach ou foreach_reverse pode ser uma classe desde que ela implemente o operador opApply e/ou opApplyReverse respectivamente.
 +
 
 +
<code lang="d">
 +
class Foo
 +
{
 +
    uint array[2];
 +
    int opApply(int delegate(inout uint) dg)
 +
    {
 +
        int result = 0;
 +
        for (int i = 0; i < array.length; i++)
 +
        {
 +
            result = dg(array[i]);
 +
            if (result)
 +
                break;
 +
        }
 +
        return result;
 +
    }
 +
}
 +
void test()
 +
{
 +
    Foo a = new Foo();
 +
    a.array[0] = 73;
 +
    a.array[1] = 82;
 +
    foreach (uint u; a)
 +
    {
 +
        printf("%d\n", u);
 +
    }
 +
}
 +
</code>
 +
 
 +
=== while ===
 +
==== Especificação ====
 +
<code lang="d">
 +
WhileStatement:
 +
    while ( Expression ) ScopeStatement
 +
</code>
 +
 
 +
==== Exemplo ====
 +
<code lang="d">
 +
int i = 0;
 +
while (i < 10)
 +
{
 +
    foo(i);
 +
    i++;
 +
}
 +
</code>
 +
 
 +
=== do...while ===
 +
==== Especificação ====
 +
<code lang="d">
 +
DoStatement:
 +
    do ScopeStatement while ( Expression )
 +
</code>
 +
 
 +
==== Exemplo ====
 +
<code lang="d">
 +
int i = 0;
 +
do
 +
{
 +
    foo(i);
 +
} while (++i < 10);
 +
</code>
  
=== Classe ===
+
== Reportagens ==
 +
*[http://www.bitwisemag.com/copy/programming/d/opinion/d_programming_language.html D: C code done right...?].
  
 
== Referências ==
 
== Referências ==
 
<references />
 
<references />

Latest revision as of 01:03, 3 April 2009

Compiladores & IDEs disponíveis

Compiladores

Diginal Mars D

Website: http://www.digitalmars.com/d/download.html

GDC

Website: http://dgcc.sourceforge.net/.

IDEs

Poseidon

Website: http://dsource.org/projects/poseidon.

Descent (plugin para o Eclipse)

Website: http://www.dsource.org/projects/descent.

Mais

Veja em: http://www.prowiki.org/wiki4d/wiki.cgi?EditorSupport

Tipos básicos [1]

void
bool = false
byte (8 bits com sinal) = 0
ubyte (8 bits sem sinal) = 0
short (16 bits com sinal) = 0
ushort (16 bits sem sinal) = 0
int (32 bits com sinal) = 0
uint (32 bits sem sinal) 0
long (64 bits com sinal) = 0L
ulong (64 bits sem sinal) = 0L
cent (128 bits com sinal - reservado) = 0
ucent (128 bits sem sinal - reservado) = 0
float (ponto flutuante de 32 bits) = float.nan
double (ponto flutuante de 64 bits) = double.nan
real (maior ponto flutuante implementado pelo hardware) real.nan
ifloat (float imaginário) = float.nan * 1.0i
idouble (double imaginário) = double.nan * 1.0i
ireal (real imaginário) = real.nan * 1.0i
cfloat (número complexo com dois valores float) = float.nan + float.nan * 1.0i
cdouble (número complexo com dois valores double) = double.nan + double.nan * 1.0i
creal (número complexo com dois valores real) = real.nan + real.nan * 1.0i
char (8 bits sem sinal - UTF-8) = 0xFF
wchar (16 bits sem sinal - UTF-16) = 0xFFFF
dchar (32 bits sem sinal - UTF-32) = 0x0000FFFF

Declaração[1]

Especificação

DeclarationStatement:
    Declaration

Exemplo

int a;            // declara a como um inteiro.
struct S { }      // declara a estrutura S.
alias int meuint; // declara meuint como um outro nome para o tipo int.

Bloco[1]

BlockStatement:
    { }
    { StatementList }
StatementList:
    Statement
    Statement StatementList

Escopo[1]

ScopeBlockStatement:
    BlockStatement

Função

Classe

Vetores e matrizes [1]

Ponteiro

int *p;

Vetor estático

int[3] s;
int s[3];

Tamanho máximo: 16Mb.

Vetor dinâmico

int[] a;
int a[];

Vetor associado

int[char[]] x;

Ponteiro para vetor dinâmico

int[]* e;
int (*e)[];

Ponteiros para vetores

int*[]*[3] d;
int*[]* d[3];
int* (*d[3])[];

Matrizes estáticas

int[4][3] b;
int[4] b[3];
int b[3][4];

Matrizes dinâmicas

int[][5] c;
int[] c[5];
int c[5][];

Slicing

int[10] a;
int[] b;
 
b = a[1..3]; // a[1..3] representa um array de 2 elementos (a[1] and a[2]).

Atribuição

int[3] s;
int[3] t;
 
s[0..2] = t[1..3]; // mesmo que s[0] = t[1], s[1] = t[2].
s[] = 3;           // mesmo que s[0] = 3, s[1] = 3, s[2] = 3.
p[0..2] = 3;       // mesmo que p[0] = 3, p[1] = 3.

Concatenação

int[] a;
int[] b;
int[] c;
a = b ~ c; // cria um array resultado da concatenção d b com c.
a ~= b;    // concatena b ao array a.

Estruturas condicionais[1]

if

Especificação

IfStatement:
    if ( IfCondition ) ThenStatement
    if ( IfCondition ) ThenStatement else ElseStatement
IfCondition:
    Expression
    auto Identifier = Expression
    Declarator = Expression
ThenStatement:
    ScopeStatement
ElseStatement:
    ScopeStatement

Exemplo

if (...)
{
    ...
}
else
{
    ...
}

switch

Especificação

SwitchStatement:
    switch ( Expression ) ScopeStatement
CaseStatement:
    case ExpressionList : Statement
DefaultStatement:
default: Statement

Exemplo

switch (i)
{
    case 1:
        x = 3;
    case 2:
        x = 4;
        break;
    case 3,4,5:
        x = 5;
        break;
}

? :

Especificação

ConditionalExpression:
    OrOrExpression
    OrOrExpression ? Expression : ConditionalExpression
OrOrExpression:
    AndAndExpression
    OrOrExpression || AndAndExpression
AndAndExpression:
    OrExpression
    AndAndExpression && OrExpression

Estrutura de repetição[1]

for

Especificacão

ForStatement:
    for (Initialize Test; Increment) ScopeStatement
Initialize:
    ;
    NoScopeNonEmptyStatement
Test:
    empty
    Expression
Increment:
    empty
    Expression

Exemplo

for (int i = 0; i < 10; i++)
    foo(i);

Atenção:

for (int i = 0; i < 10; i++) ;  //isto não é permitido.
for (int i = 0; i < 10; i++) {} //mas isto sim.

foreach

Especificação

ForeachStatement:
    Foreach (ForeachTypeList; Aggregate) ScopeStatement
Foreach:
    foreach
    foreach_reverse
ForeachTypeList:
    ForeachType
    ForeachType , ForeachTypeList
ForeachType:
    inout Type Identifier
    Type Identifier
    inout Identifier
    Identifier
Aggregate:
    Expression
    Tuple

Exemplo 1

Exemplo também é válido para foreach_reverse.

char[] a;
...
foreach (int i, char c; a)
{
    printf("a[%d] = '%c'\n", i, c);
}

Exemplo 2

Exemplo também é válido para foreach_reverse.

foreach (char c; "ab")
{
    printf("'%c'\n", c);
}

Exemplo 3

Exemplo abaixo não é válido para foreach_reverse.

double[char[]] a;
...
foreach (char[] s, double d; a)
{
    printf("a['%.*s'] = %g\n", s, d);
}

Exemplo 4

O segundo parâmetro de foreach ou foreach_reverse pode ser uma classe desde que ela implemente o operador opApply e/ou opApplyReverse respectivamente.

class Foo
{
    uint array[2];
    int opApply(int delegate(inout uint) dg)
    { 
        int result = 0;
        for (int i = 0; i < array.length; i++)
        {
            result = dg(array[i]);
            if (result)
                break;
        }
        return result;
    }
}
void test()
{
    Foo a = new Foo();
    a.array[0] = 73;
    a.array[1] = 82;
    foreach (uint u; a)
    {
        printf("%d\n", u);
    }
}

while

Especificação

WhileStatement:
    while ( Expression ) ScopeStatement

Exemplo

int i = 0;
while (i < 10)
{
    foo(i);
    i++;
}

do...while

Especificação

DoStatement:
    do ScopeStatement while ( Expression )

Exemplo

int i = 0;
do
{
    foo(i);
} while (++i < 10);

Reportagens

Referências

  1. 1.0 1.1 1.2 1.3 1.4 1.5 1.6 D Specification em http://www.prowiki.org/upload/duser/spec_DMD_1.00.pdf