From 2532d97bca71bdee8e2b340e53f802cb755922d0 Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 12:12:22 -0200 Subject: Translating brainfuck to pt-br --- pt-br/brainfuck-pt.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++ pt-br/brainfuck-pt.html.markdown~ | 84 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 168 insertions(+) create mode 100644 pt-br/brainfuck-pt.html.markdown create mode 100644 pt-br/brainfuck-pt.html.markdown~ diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/brainfuck-pt.html.markdown new file mode 100644 index 00000000..72c2cf6e --- /dev/null +++ b/pt-br/brainfuck-pt.html.markdown @@ -0,0 +1,84 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Suzane Sant Ana", "http://github.com/suuuzi"] +lang: pt-pt +--- + +Brainfuck (em letras minúsculas, eceto no início de frases) é uma linguagem de +programação Turing-completa extremamente simples com apenas 8 comandos. + +``` +Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. + +Brainfuck é representado por um vetor com 30 000 células inicializadas em zero +e um ponteiro de dados que aponta para a célula atual. + +Existem 8 comandos: ++ : Incrementa o vaor da célula atual em 1. +- : Decrementa o valor da célula atual em 1. +> : Move o ponteiro de dados para a célula seguinte (célula à direita). +< : Move o ponteiro de dados para a célula anterior (célula à esquerda). +. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A'). +, : Lê um único caractere para a célula atual. +[ : Se o valor da célula atual for zero, salta para o ] correspondente. + Caso contrário, passa para a instrução seguinte. +] : Se o valor da célula atual for zero, passa para a instrução seguinte. + Caso contrário, volta para a instrução relativa ao [ correspondente. + +[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. + +Vamos ver alguns exemplos básicos em brainfuck: + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. +A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se +o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10 +vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se +a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para +a célula #1 chegar a 0, momento em que se salta para o ] correspondente, +continuando com a instrução seguinte). + +Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2 +tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 +vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor +65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal. + +, [ > + < - ] > . + +Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é +iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na +célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente +decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser +igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de +dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a +célula #2 e imprimimos o valor em ASCII. + +Os espaços servem apenas para tornar o programa mais legível. Podemos escrever +o mesmo programa da seguinte maneira: + +,[>+<-]>. + +Tente descobrir o que este programa faz: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa lê dois números e os multiplica. + +Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um +ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados +para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula +#2, incrementando o valor da célula #3. Porém existe um problema, no final do +ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da +célula #4 é também incrementado e copiado para a célula #2. +``` + +E isto é brainfuck. Simples, não? Por divertimento você pode escrever os +seus próprios programas em brainfuck, ou então escrever um interpretador de +brainfuck em outra linguagem. O interpretador é relativamente fácil de se +implementar, mas caso você seja masoquista, tente escrever um interpretador de +brainfuck… em brainfuck. diff --git a/pt-br/brainfuck-pt.html.markdown~ b/pt-br/brainfuck-pt.html.markdown~ new file mode 100644 index 00000000..72c2cf6e --- /dev/null +++ b/pt-br/brainfuck-pt.html.markdown~ @@ -0,0 +1,84 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Suzane Sant Ana", "http://github.com/suuuzi"] +lang: pt-pt +--- + +Brainfuck (em letras minúsculas, eceto no início de frases) é uma linguagem de +programação Turing-completa extremamente simples com apenas 8 comandos. + +``` +Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. + +Brainfuck é representado por um vetor com 30 000 células inicializadas em zero +e um ponteiro de dados que aponta para a célula atual. + +Existem 8 comandos: ++ : Incrementa o vaor da célula atual em 1. +- : Decrementa o valor da célula atual em 1. +> : Move o ponteiro de dados para a célula seguinte (célula à direita). +< : Move o ponteiro de dados para a célula anterior (célula à esquerda). +. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A'). +, : Lê um único caractere para a célula atual. +[ : Se o valor da célula atual for zero, salta para o ] correspondente. + Caso contrário, passa para a instrução seguinte. +] : Se o valor da célula atual for zero, passa para a instrução seguinte. + Caso contrário, volta para a instrução relativa ao [ correspondente. + +[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. + +Vamos ver alguns exemplos básicos em brainfuck: + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. +A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se +o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10 +vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se +a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para +a célula #1 chegar a 0, momento em que se salta para o ] correspondente, +continuando com a instrução seguinte). + +Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2 +tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 +vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor +65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal. + +, [ > + < - ] > . + +Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é +iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na +célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente +decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser +igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de +dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a +célula #2 e imprimimos o valor em ASCII. + +Os espaços servem apenas para tornar o programa mais legível. Podemos escrever +o mesmo programa da seguinte maneira: + +,[>+<-]>. + +Tente descobrir o que este programa faz: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa lê dois números e os multiplica. + +Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um +ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados +para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula +#2, incrementando o valor da célula #3. Porém existe um problema, no final do +ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da +célula #4 é também incrementado e copiado para a célula #2. +``` + +E isto é brainfuck. Simples, não? Por divertimento você pode escrever os +seus próprios programas em brainfuck, ou então escrever um interpretador de +brainfuck em outra linguagem. O interpretador é relativamente fácil de se +implementar, mas caso você seja masoquista, tente escrever um interpretador de +brainfuck… em brainfuck. -- cgit v1.2.3 From f7c84056ff777caeaac165f935aa49b3b7cccd67 Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 12:13:16 -0200 Subject: Translating brainfuck to pt-br --- pt-br/brainfuck-pt.html.markdown~ | 84 --------------------------------------- 1 file changed, 84 deletions(-) delete mode 100644 pt-br/brainfuck-pt.html.markdown~ diff --git a/pt-br/brainfuck-pt.html.markdown~ b/pt-br/brainfuck-pt.html.markdown~ deleted file mode 100644 index 72c2cf6e..00000000 --- a/pt-br/brainfuck-pt.html.markdown~ +++ /dev/null @@ -1,84 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Suzane Sant Ana", "http://github.com/suuuzi"] -lang: pt-pt ---- - -Brainfuck (em letras minúsculas, eceto no início de frases) é uma linguagem de -programação Turing-completa extremamente simples com apenas 8 comandos. - -``` -Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. - -Brainfuck é representado por um vetor com 30 000 células inicializadas em zero -e um ponteiro de dados que aponta para a célula atual. - -Existem 8 comandos: -+ : Incrementa o vaor da célula atual em 1. -- : Decrementa o valor da célula atual em 1. -> : Move o ponteiro de dados para a célula seguinte (célula à direita). -< : Move o ponteiro de dados para a célula anterior (célula à esquerda). -. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A'). -, : Lê um único caractere para a célula atual. -[ : Se o valor da célula atual for zero, salta para o ] correspondente. - Caso contrário, passa para a instrução seguinte. -] : Se o valor da célula atual for zero, passa para a instrução seguinte. - Caso contrário, volta para a instrução relativa ao [ correspondente. - -[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. - -Vamos ver alguns exemplos básicos em brainfuck: - -++++++ [ > ++++++++++ < - ] > +++++ . - -Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. -A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se -o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10 -vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se -a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para -a célula #1 chegar a 0, momento em que se salta para o ] correspondente, -continuando com a instrução seguinte). - -Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2 -tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 -vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor -65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal. - -, [ > + < - ] > . - -Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é -iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na -célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente -decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser -igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de -dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a -célula #2 e imprimimos o valor em ASCII. - -Os espaços servem apenas para tornar o programa mais legível. Podemos escrever -o mesmo programa da seguinte maneira: - -,[>+<-]>. - -Tente descobrir o que este programa faz: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Este programa lê dois números e os multiplica. - -Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um -ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados -para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula -#2, incrementando o valor da célula #3. Porém existe um problema, no final do -ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da -célula #4 é também incrementado e copiado para a célula #2. -``` - -E isto é brainfuck. Simples, não? Por divertimento você pode escrever os -seus próprios programas em brainfuck, ou então escrever um interpretador de -brainfuck em outra linguagem. O interpretador é relativamente fácil de se -implementar, mas caso você seja masoquista, tente escrever um interpretador de -brainfuck… em brainfuck. -- cgit v1.2.3 From 37584056a09f93395d7079c0df5ac2b569638d4b Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 13:13:13 -0200 Subject: Translating Git to pt-br --- pt-br/git-pt.html.markdown | 312 +++++++++++++++++++++++---------------------- 1 file changed, 161 insertions(+), 151 deletions(-) diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index 6d2a55cd..b8cbd0a9 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -1,110 +1,119 @@ --- category: tool tool: git +lang: pt-pt +filename: LearnGit.txt contributors: - ["Jake Prather", "http://github.com/JakeHP"] translators: - - ["Miguel Araújo", "https://github.com/miguelarauj1o"] -lang: pt-br -filename: learngit-pt.txt + - ["Suzane Sant Ana", "http://github.com/suuuzi"] --- -Git é um sistema de controle de versão distribuído e de gerenciamento de código-fonte. +Git é um sistema distribuido de gestão para código fonte e controle de versões. -Ele faz isso através de uma série de momentos instantâneos de seu projeto, e ele funciona -com esses momentos para lhe fornecer a funcionalidade para a versão e -gerenciar o seu código-fonte. +Funciona através de uma série de registos de estado do projeto e usa esse +registo para permitir funcionalidades de versionamento e gestão de código +fonte. -## Versionando Conceitos +## Conceitos de versionamento -### O que é controle de versão? +### O que é controle de versão -O controle de versão é um sistema que registra alterações em um arquivo ou conjunto -de arquivos, ao longo do tempo. +Controle de versão (*source control*) é um processo de registo de alterações +a um arquivo ou conjunto de arquivos ao longo do tempo. -### Versionamento Centralizado VS Versionamento Distribuído +### Controle de versão: Centralizado VS Distribuído -* Controle de versão centralizado concentra-se na sincronização, controle e backup de arquivos. -* Controle de versão distribuído concentra-se na partilha de mudanças. Toda mudança tem um ID único. -* Sistemas Distribuídos não têm estrutura definida. Você poderia facilmente ter um estilo SVN, -sistema centralizado, com git. +* Controle de versão centralizado foca na sincronização, registo e *backup* +de arquivos. +* Controle de versão distribuído foca em compartilhar alterações. Cada +alteração é associada a um *id* único. +* Sistemas distribuídos não tem estrutura definida. É possivel ter um sistema +centralizado ao estilo SVN usando git. -[Informação Adicional](http://git-scm.com/book/en/Getting-Started-About-Version-Control) +[Informação adicional (EN)](http://git-scm.com/book/en/Getting-Started-About-Version-Control) -### Porque usar o Git? +### Por que usar git? -* Possibilidade de trabalhar offline -* Colaborar com os outros é fácil! -* Ramificação é fácil -* Mesclagem é fácil -* Git é rápido -* Git é flexível. +* Permite trabalhar offline. +* Colaborar com outros é fácil! +* Criar *branches* é fácil! +* Fazer *merge* é fácil! +* Git é rápido. +* Git é flexivel. + +## Git - Arquitetura -## Arquitetura Git ### Repositório -Um conjunto de arquivos, diretórios, registros históricos, cometes, e cabeças. Imagine-o -como uma estrutura de dados de código-fonte, com o atributo que cada "elemento" do -código-fonte dá-lhe acesso ao seu histórico de revisão, entre outras coisas. +Um conjunto de arquivos, diretórios, registos históricos, *commits* e +referências. Pode ser descrito como uma estrutura de dados de código fonte +com a particularidade de cada elemento do código fonte permitir acesso ao +histórico das suas alterações, entre outras coisas. -Um repositório git é composto do diretório git. e árvore de trabalho. +Um repositório git é constituido pelo diretório .git e a *working tree* ### Diretório .git (componente do repositório) -O diretório git. contém todas as configurações, registros, galhos, cabeça(HEAD) e muito mais. -[Lista Detalhada](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) +O repositório .git contém todas as configurações, *logs*, *branches*, +referências e outros. + +[Lista detalhada (EN)](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) -### Árvore de trabalho (componente do repositório) +### *Working Tree* (componente do repositório) -Esta é, basicamente, os diretórios e arquivos no seu repositório. Ele é muitas vezes referida -como seu diretório de trabalho. +A *Working Tree* é basicamente a listagem dos diretórios e arquivos do repositório. É chamada também de diretório do projeto. -### Índice (componente do diretório .git) +### *Index* (componente do diretório .git) -O Índice é a área de teste no git. É basicamente uma camada que separa a sua árvore de trabalho -a partir do repositório Git. Isso dá aos desenvolvedores mais poder sobre o que é enviado para o -repositório Git. +O *Index* é a camada da interface no git. É o elemento que separa +o diretório do projeto do repositório git. Isto permite aos programadores um +maior controle sobre o que é registado no repositório git. -### Comete (commit) +### *Commit* -A commit git é um instantâneo de um conjunto de alterações ou manipulações a sua árvore de trabalho. -Por exemplo, se você adicionou 5 imagens, e removeu outros dois, estas mudanças serão contidas -em um commit (ou instantâneo). Esta confirmação pode ser empurrado para outros repositórios, ou não! +Um *commit** de git é um registo de um cojunto de alterações ou manipulações nos arquivos do projeto. +Por exemplo, ao adicionar cinco arquivos e remover outros 2, estas alterações +serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado +para outros repositórios ou não! -### Ramo (branch) +### *Branch* -Um ramo é, essencialmente, um ponteiro que aponta para o último commit que você fez. Como -você se comprometer, este ponteiro irá atualizar automaticamente e apontar para o último commit. +Um *branch* é essencialmente uma referência que aponta para o último *commit* +efetuado. Na medida que são feitos novos commits, esta referência é atualizada +automaticamente e passa a apontar para o commit mais recente. -### Cabeça (HEAD) e cabeça (head) (componente do diretório .git) +### *HEAD* e *head* (componentes do diretório .git) -HEAD é um ponteiro que aponta para o ramo atual. Um repositório tem apenas 1 * ativo * HEAD. -head é um ponteiro que aponta para qualquer commit. Um repositório pode ter qualquer número de commits. +*HEAD* é a referência que aponta para o *branch* em uso. Um repositório só tem +uma *HEAD* activa. +*head* é uma referência que aponta para qualquer *commit*. Um repositório pode +ter um número indefinido de *heads* -### Recursos Conceituais +### Recursos conceituais (EN) -* [Git para Cientistas da Computação](http://eagain.net/articles/git-for-computer-scientists/) +* [Git para Cientistas de Computação](http://eagain.net/articles/git-for-computer-scientists/) * [Git para Designers](http://hoth.entp.com/output/git_for_designers.html) ## Comandos -### init +### *init* -Criar um repositório Git vazio. As configurações do repositório Git, informações armazenadas, -e mais são armazenados em um diretório (pasta) com o nome ". git". +Cria um repositório Git vazio. As definições, informação guardada e outros do +repositório git são guardados em uma pasta chamada ".git". ```bash $ git init ``` -### config +### *config* -Para configurar as definições. Quer seja para o repositório, o próprio sistema, ou -configurações globais. +Permite configurar as definições, sejam as definições do repositório, sistema +ou configurações globais. ```bash -# Impressão e definir algumas variáveis ​​de configuração básica (global) +# Imprime e define algumas variáveis de configuração básicas (global) $ git config --global user.email $ git config --global user.name @@ -112,22 +121,21 @@ $ git config --global user.email "MyEmail@Zoho.com" $ git config --global user.name "My Name" ``` -[Saiba mais sobre o git config.](http://git-scm.com/docs/git-config) +[Aprenda mais sobre git config. (EN)](http://git-scm.com/docs/git-config) ### help -Para lhe dar um acesso rápido a um guia extremamente detalhada de cada comando. ou -apenas dar-lhe um rápido lembrete de algumas semânticas. +Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da semântica. ```bash -# Rapidamente verificar os comandos disponíveis +# Ver rapidamente os comandos disponiveis $ git help -# Confira todos os comandos disponíveis +# Ver todos os comandos disponiveis $ git help -a -# Ajuda específica de comando - manual do usuário -# git help +# Usar o *help* para um comando especifico +# git help $ git help add $ git help commit $ git help init @@ -135,85 +143,89 @@ $ git help init ### status -Para mostrar as diferenças entre o arquivo de índice (basicamente o trabalho de -copiar/repo) e a HEAD commit corrente. +Apresenta as diferenças entre o arquivo *index* (a versão corrente +do repositório) e o *commit* da *HEAD* atual. + ```bash -# Irá exibir o ramo, os arquivos não monitorados, as alterações e outras diferenças +# Apresenta o *branch*, arquivos não monitorados, alterações e outras +# difereças $ git status -# Para saber outras "tid bits" sobre git status +# Para aprender mais detalhes sobre git *status* $ git help status ``` ### add -Para adicionar arquivos para a atual árvore/directory/repo trabalho. Se você não -der `git add` nos novos arquivos para o trabalhando árvore/diretório, eles não serão -incluídos em commits! +Adiciona arquivos ao repositório corrente. Se os arquivos novos não forem +adicionados através de `git add` ao repositório, então eles não serão +incluidos nos commits! ```bash -# Adicionar um arquivo no seu diretório de trabalho atual +# adiciona um arquivo no diretório do projeto atual $ git add HelloWorld.java -# Adicionar um arquivo em um diretório aninhado +# adiciona um arquivo num sub-diretório $ git add /path/to/file/HelloWorld.c -# Suporte a expressões regulares! +# permite usar expressões regulares! $ git add ./*.java ``` ### branch -Gerenciar seus ramos. Você pode visualizar, editar, criar, apagar ramos usando este comando. +Gerencia os *branches*. É possível ver, editar, criar e apagar branches com este +comando. ```bash -# Lista ramos e controles remotos existentes +# listar *branches* existentes e remotos $ git branch -a -# Criar um novo ramo +# criar um novo *branch* $ git branch myNewBranch -# Apagar um ramo +# apagar um *branch* $ git branch -d myBranch -# Renomear um ramo +# alterar o nome de um *branch* # git branch -m $ git branch -m myBranchName myNewBranchName -# Editar a descrição de um ramo +# editar a descrição de um *branch* $ git branch myBranchName --edit-description ``` ### checkout -Atualiza todos os arquivos na árvore de trabalho para corresponder à versão no -índice, ou árvore especificada. +Atualiza todos os arquivos no diretório do projeto para que fiquem iguais +à versão do index ou do *branch* especificado. ```bash -# Finalizar um repo - padrão de ramo mestre +# Checkout de um repositório - por padrão para o branch master $ git checkout -# Checa um ramo especificado +# Checkout de um branch especifico $ git checkout branchName -# Criar um novo ramo e mudar para ela, como: " git branch; git checkout " +# Cria um novo branch e faz checkout para ele. +# Equivalente a: "git branch ; git checkout " $ git checkout -b newBranch ``` ### clone -Clones, ou cópias, de um repositório existente para um novo diretório. Ele também adiciona -filiais remotas de rastreamento para cada ramo no repo clonado, que permite que você empurre -a um ramo remoto. +Clona ou copia um repositório existente para um novo diretório. Também +adiciona *branches* de monitoramento remoto para cada *branch* no repositório +clonado o que permite enviar alterações para um *branch* remoto. ```bash -# Clone learnxinyminutes-docs +# Clona learnxinyminutes-docs $ git clone https://github.com/adambard/learnxinyminutes-docs.git ``` ### commit -Armazena o conteúdo atual do índice em um novo "commit". Este commit contém -as alterações feitas e uma mensagem criada pelo utilizador. +Guarda o conteudo atual do index num novo *commit*. Este *commit* contém +as alterações feitas e a mensagem criada pelo usuário. ```bash # commit com uma mensagem @@ -222,170 +234,170 @@ $ git commit -m "Added multiplyNumbers() function to HelloWorld.c" ### diff -Mostra as diferenças entre um arquivo no diretório, o índice de trabalho e commits. +Apresenta as diferenças entre um arquivo no repositório do projeto, *index* +e *commits* ```bash -# Mostrar diferença entre o seu diretório de trabalho e o índice. +# Apresenta a diferença entre o diretório atual e o index $ git diff -# Mostrar diferenças entre o índice e o commit mais recente. +# Apresenta a diferença entre o index e os commits mais recentes $ git diff --cached -# Mostrar diferenças entre o seu diretório de trabalho e o commit mais recente. +# Apresenta a diferença entre o diretório atual e o commit mais recente $ git diff HEAD ``` ### grep -Permite procurar rapidamente um repositório. +Permite procurar facilmente num repositório Configurações opcionais: ```bash -# Obrigado ao Travis Jeffery por isto -# Configure os números de linha a serem mostrados nos resultados de busca grep +# Define a apresentação de números de linha nos resultados do grep $ git config --global grep.lineNumber true -# Fazer resultados de pesquisa mais legível, incluindo agrupamento +# Agrupa os resultados da pesquisa para facilitar a leitura $ git config --global alias.g "grep --break --heading --line-number" ``` ```bash -# Procure por "variableName" em todos os arquivos java +# Pesquisa por "variableName" em todos os arquivos java $ git grep 'variableName' -- '*.java' -# Procure por uma linha que contém "arrayListName" e "adicionar" ou "remover" -$ git grep -e 'arrayListName' --and \( -e add -e remove \) +# Pesquisa por uma linha que contém "arrayListName" e "add" ou "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) ``` -Google é seu amigo; para mais exemplos -[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) +O Google é seu amigo; para mais exemplos: +[Git Grep Ninja (EN)](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) ### log -Mostrar commits para o repositório. +Apresenta commits do repositório. ```bash -# Mostrar todos os commits +# Apresenta todos os commits $ git log -# Mostrar um número X de commits +# Apresenta X commits $ git log -n 10 -# Mostrar somente commits mesclados +# Apresenta apenas commits de merge $ git log --merges ``` ### merge -"Merge" em mudanças de commits externos no branch atual. +"Merge" junta as alterações de commits externos com o *branch* atual. ```bash -# Mesclar o ramo especificado para o atual. +# Junta o branch especificado com o atual $ git merge branchName -# Gera sempre uma mesclagem commit ao mesclar +# Para gerar sempre um commit ao juntar os branches $ git merge --no-ff branchName ``` ### mv -Renomear ou mover um arquivo +Alterar o nome ou mover um arquivo. ```bash -# Renomear um arquivo +# Alterar o nome de um arquivo $ git mv HelloWorld.c HelloNewWorld.c # Mover um arquivo $ git mv HelloWorld.c ./new/path/HelloWorld.c -# Força renomear ou mover -# "ExistingFile" já existe no diretório, será substituído +# Forçar a alteração de nome ou mudança local +# "existingFile" já existe no directório, será sobrescrito. $ git mv -f myFile existingFile ``` ### pull -Puxa de um repositório e se funde com outro ramo. +Puxa alterações de um repositório e as junta com outro branch ```bash -# Atualize seu repo local, através da fusão de novas mudanças -# A partir da "origem" remoto e ramo "master (mestre)". +# Atualiza o repositório local, juntando as novas alterações +# do repositório remoto 'origin' e branch 'master' # git pull -# git pull => implícito por padrão => git pull origin master +# git pull => aplica a predefinição => git pull origin master $ git pull origin master -# Mesclar em mudanças de ramo remoto e rebase -# Ramo commita em seu repo local, como: "git pull , git rebase " +# Juntar alterações do branch remote e fazer rebase commits do branch +# no repositório local, como: "git pull , git rebase " $ git pull origin master --rebase ``` ### push -Empurre e mesclar as alterações de uma ramificação para uma remota e ramo. +Enviar e juntar alterações de um branch para o seu branch correspondente +num repositório remoto. ```bash -# Pressione e mesclar as alterações de um repo local para um -# Chamado remoto "origem" e ramo de "mestre". +# Envia e junta as alterações de um repositório local +# para um remoto denominado "origin" no branch "master". # git push -# git push => implícito por padrão => git push origin master +# git push => aplica a predefinição => git push origin master $ git push origin master - -# Para ligar atual filial local com uma filial remota, bandeira add-u: -$ git push -u origin master -# Agora, a qualquer hora que você quer empurrar a partir desse mesmo ramo local, uso de atalho: -$ git push ``` -### rebase (CAUTELA) +### rebase (cautela!) -Tire todas as alterações que foram commitadas em um ramo, e reproduzi-las em outro ramo. -* Não rebase commits que você tenha empurrado a um repo público *. +Pega em todas as alterações que foram registadas num branch e volta a +aplicá-las em outro branch. +*Não deve ser feito rebase de commits que foram enviados para um repositório +público* ```bash -# Rebase experimentBranch para mestre +# Faz Rebase de experimentBranch para master # git rebase $ git rebase master experimentBranch ``` -[Leitura Adicional.](http://git-scm.com/book/en/Git-Branching-Rebasing) +[Leitura adicional (EN).](http://git-scm.com/book/en/Git-Branching-Rebasing) -### reset (CAUTELA) +### reset (cuidado!) -Repor o atual HEAD de estado especificado. Isto permite-lhe desfazer fusões (merge), -puxa (push), commits, acrescenta (add), e muito mais. É um grande comando, mas também -perigoso se não saber o que se está fazendo. +Restabelece a HEAD atual ao estado definido. Isto permite reverter *merges*, +*pulls*, *commits*, *adds* e outros. É um comando muito poderoso mas também +perigoso quando não há certeza do que se está fazendo. ```bash -# Repor a área de teste, para coincidir com o último commit (deixa diretório inalterado) +# Restabelece a camada intermediária de registo para o último +# commit (o directório fica sem alterações) $ git reset -# Repor a área de teste, para coincidir com o último commit, e substituir diretório trabalhado +# Restabelece a camada intermediária de registo para o último commit, e +# sobrescreve o projeto atual $ git reset --hard -# Move a ponta ramo atual para o especificado commit (deixa diretório inalterado) -# Todas as alterações ainda existem no diretório. +# Move a head do branch atual para o commit especificado, sem alterar o projeto. +# todas as alterações ainda existem no projeto $ git reset 31f2bb1 -# Move a ponta ramo atual para trás, para o commit especificado -# E faz o jogo dir trabalho (exclui mudanças não commitadas e todos os commits -# Após o commit especificado). +# Inverte a head do branch atual para o commit especificado +# fazendo com que este esteja em sintonia com o diretório do projeto +# Remove alterações não registadas e todos os commits após o commit especificado $ git reset --hard 31f2bb1 ``` ### rm -O oposto do git add, git rm remove arquivos da atual árvore de trabalho. +O oposto de git add, git rm remove arquivos do branch atual. ```bash # remove HelloWorld.c $ git rm HelloWorld.c -# Remove um arquivo de um diretório aninhado +# Remove um arquivo de um sub-directório $ git rm /pather/to/the/file/HelloWorld.c ``` -# # Mais informações +## Informação complementar (EN) * [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) @@ -398,5 +410,3 @@ $ git rm /pather/to/the/file/HelloWorld.c * [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) * [GitGuys](http://www.gitguys.com/) - -* [Git - guia prático](http://rogerdudler.github.io/git-guide/index.pt_BR.html) \ No newline at end of file -- cgit v1.2.3 From a3318599c8514b970a18148e687fae6a69d8f81e Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 13:15:42 -0200 Subject: Fixing some typos in Git pt-pt translation --- pt-pt/git-pt.html.markdown | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/pt-pt/git-pt.html.markdown b/pt-pt/git-pt.html.markdown index 66cda07f..a85c9704 100644 --- a/pt-pt/git-pt.html.markdown +++ b/pt-pt/git-pt.html.markdown @@ -74,8 +74,7 @@ maior controlo sobre o que é registado no repositório git. ### *Commit* -Um *commit** de git é um registo de um cojunto de alterações ou manipulações -no nos ficheiros do projecto. +Um *commit** de git é um registo de um cojunto de alterações ou manipulações nos ficheiros do projecto. Por exemplo, ao adicionar cinco ficheiros e remover outros 2, estas alterações serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado para outros repositórios ou não! @@ -83,7 +82,7 @@ para outros repositórios ou não! ### *Branch* Um *branch* é essencialmente uma referência que aponta para o último *commit* -efetuado. à medida que são feitos novos commits, esta referência é atualizada +efetuado. À medida que são feitos novos commits, esta referência é atualizada automaticamente e passa a apontar para o commit mais recente. ### *HEAD* e *head* (componentes do directório .git) @@ -115,7 +114,7 @@ Permite configurar as definições, sejam as definições do repositório, siste ou configurações globais. ```bash -# Imprime & Define Algumas Variáveis de Configuração Básicas (Global) +# Imprime e define algumas variáveis de configuração básicas (global) $ git config --global user.email $ git config --global user.name @@ -123,7 +122,7 @@ $ git config --global user.email "MyEmail@Zoho.com" $ git config --global user.name "My Name" ``` -[Aprenda Mais Sobre git config. (EN)](http://git-scm.com/docs/git-config) +[Aprenda mais sobre git config. (EN)](http://git-scm.com/docs/git-config) ### help @@ -166,7 +165,7 @@ adicionados através de `git add` ao repositório, então eles não serão incluidos nos commits! ```bash -# adiciona um ficheiro no directório do project atual +# adiciona um ficheiro no directório do projecto atual $ git add HelloWorld.java # adiciona um ficheiro num sub-directório @@ -371,7 +370,7 @@ Restabelece a HEAD atual ao estado definido. Isto permite reverter *merges*, perigoso se não há certeza quanto ao que se está a fazer. ```bash -# Restabelece a camada intermediária dr registo para o último +# Restabelece a camada intermediária de registo para o último # commit (o directório fica sem alterações) $ git reset -- cgit v1.2.3 From f4bd1bc8b462e09330ae22ae89a72c11354aa8ac Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 15:32:55 -0200 Subject: Python 3: Changing 'the other tutorial' to a link refering the other tutorial --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index 6b1d3156..0293d7d2 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -13,7 +13,7 @@ executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] -Note: This article applies to Python 3 specifically. Check out the other tutorial if you want to learn the old Python 2.7 +Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/python/) if you want to learn the old Python 2.7 ```python -- cgit v1.2.3 From 22a0f44e64e6c7ac969556b9648ebcfca4bad187 Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 15:36:20 -0200 Subject: Refering Python3 tutorial link --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index da04d381..478804cd 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -14,7 +14,7 @@ executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial. +to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). ```python -- cgit v1.2.3 From 8858382c044e6be744811a80a479de7304fcb3da Mon Sep 17 00:00:00 2001 From: Wincent Balin Date: Sat, 14 Feb 2015 22:26:14 +0100 Subject: Update go-de.html.markdown Fixed many, many grammar mistakes. --- de-de/go-de.html.markdown | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index ca27fdc7..4b50112e 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -5,34 +5,34 @@ contributors: - ["Joseph Adams", "https://github.com/jcla1"] lang: de-de --- -Go wurde entwickelt um probleme zu lösen. Sie ist zwar nicht der neuste Trend in -der Informatik, aber sie ist eine der neusten und schnellsten Wege um Aufgabe in +Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in +der Informatik, aber sie ist einer der neuesten und schnellsten Wege, um Aufgabe in der realen Welt zu lösen. -Sie hat vertraute Elemente von imperativen Sprachen mit statisher Typisierung +Sie hat vertraute Elemente von imperativen Sprachen mit statischer Typisierung und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große Programmierprojekte. -Außerdem beinhaltet Go eine gut ausgestattete standard bibliothek und hat eine -aktive community. +Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine +aktive Community. ```go // Einzeiliger Kommentar /* Mehr- zeiliger Kommentar */ -// Eine jede Quelldatei beginnt mit einer Packet-Klausel. -// "main" ist ein besonderer Packetname, da er ein ausführbares Programm +// Eine jede Quelldatei beginnt mit einer Paket-Klausel. +// "main" ist ein besonderer Pkaetname, da er ein ausführbares Programm // einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek // deklariert. package main -// Ein "import" wird verwendet um Packte zu deklarieren, die in dieser +// Ein "import" wird verwendet, um Pakete zu deklarieren, die in dieser // Quelldatei Anwendung finden. import ( - "fmt" // Ein Packet in der Go standard Bibliothek + "fmt" // Ein Paket in der Go Standardbibliothek "net/http" // Ja, ein Webserver. "strconv" // Zeichenkettenmanipulation ) @@ -42,10 +42,10 @@ import ( // Programms. Vergessen Sie nicht die geschweiften Klammern! func main() { // Println gibt eine Zeile zu stdout aus. - // Der Prefix "fmt" bestimmt das Packet aus welchem die Funktion stammt. + // Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt. fmt.Println("Hello world!") - // Aufruf einer weiteren Funktion definiert innerhalb dieses Packets. + // Aufruf einer weiteren Funktion definiert innerhalb dieses Pakets. beyondHello() } @@ -217,7 +217,7 @@ func learnInterfaces() { // Aufruf der String Methode von i, gleiche Ausgabe wie zuvor. fmt.Println(i.String()) - // Funktionen des fmt-Packets rufen die String() Methode auf um eine + // Funktionen des fmt-Pakets rufen die String() Methode auf um eine // druckbare variante des Empfängers zu erhalten. fmt.Println(p) // gleiche Ausgabe wie zuvor fmt.Println(i) // und wieder die gleiche Ausgabe wie zuvor @@ -287,7 +287,7 @@ func learnConcurrency() { learnWebProgramming() // Go kann es und Sie hoffentlich auch bald. } -// Eine einzige Funktion aus dem http-Packet kann einen Webserver starten. +// Eine einzige Funktion aus dem http-Paket kann einen Webserver starten. func learnWebProgramming() { // Der erste Parameter von "ListenAndServe" ist eine TCP Addresse an die // sich angeschlossen werden soll. -- cgit v1.2.3 From b7c25da54c006a3aa885ebcbf7bfe7b8ff2ccc1e Mon Sep 17 00:00:00 2001 From: Wincent Balin Date: Sun, 15 Feb 2015 00:46:06 +0100 Subject: Update go-de.html.markdown More fixes. --- de-de/go-de.html.markdown | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 4b50112e..83d59c8b 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -54,7 +54,7 @@ func main() { func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. x = 3 // Zuweisung eines Werts. - // Kurze Deklaration: Benutzen Sie ":=" um die Typisierung automatisch zu + // Kurze Deklaration: Benutzen Sie ":=", um die Typisierung automatisch zu // folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen. y := 4 @@ -70,7 +70,7 @@ func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Wiedergabe zweier Werte } -// Überblick ueber einige eingebaute Typen und Literale. +// Überblick über einige eingebaute Typen und Literale. func learnTypes() { // Kurze Deklarationen sind die Norm. s := "Lernen Sie Go!" // Zeichenketten-Typ @@ -111,7 +111,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ m["eins"] = 1 // Ungebrauchte Variablen sind Fehler in Go - // Der Unterstrich wird verwendet um einen Wert zu verwerfen. + // Der Unterstrich wird verwendet, um einen Wert zu verwerfen. _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs // Die Ausgabe zählt natürlich auch als Gebrauch fmt.Println(s, c, a4, s3, d2, m) @@ -142,7 +142,7 @@ func learnFlowControl() { if true { fmt.Println("hab's dir ja gesagt!") } - // Die Formattierung ist durch den Befehl "go fmt" standardisiert + // Die Formatierung ist durch den Befehl "go fmt" standardisiert if false { // nicht hier } else { @@ -170,7 +170,7 @@ func learnFlowControl() { continue // wird nie ausgeführt } - // Wie bei for, bedeutet := in einer Bedingten Anweisung zunächst die + // Wie bei for, bedeutet := in einer bedingten Anweisung zunächst die // Zuweisung und erst dann die Überprüfung der Bedingung. if y := expensiveComputation(); y > x { x = y @@ -218,7 +218,7 @@ func learnInterfaces() { fmt.Println(i.String()) // Funktionen des fmt-Pakets rufen die String() Methode auf um eine - // druckbare variante des Empfängers zu erhalten. + // druckbare Variante des Empfängers zu erhalten. fmt.Println(p) // gleiche Ausgabe wie zuvor fmt.Println(i) // und wieder die gleiche Ausgabe wie zuvor @@ -244,18 +244,18 @@ func learnErrorHandling() { learnConcurrency() } -// c ist ein Kannal, ein sicheres Kommunikationsmedium. +// c ist ein Kanal, ein sicheres Kommunikationsmedium. func inc(i int, c chan int) { - c <- i + 1 // <- ist der "send" Operator, wenn ein Kannal auf der Linken ist + c <- i + 1 // <- ist der "send" Operator, wenn ein Kanal auf der Linken ist } // Wir verwenden "inc" um Zahlen parallel zu erhöhen. func learnConcurrency() { // Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für - // maps, slices und Kannäle. + // maps, slices und Kanäle. c := make(chan int) // Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently) - // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kannal. + // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kanal. go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine go inc(10, c) go inc(-805, c) @@ -269,16 +269,16 @@ func learnConcurrency() { // Start einer neuen Goroutine, nur um einen Wert zu senden go func() { c <- 84 }() - go func() { cs <- "wortreich" }() // schon wider, diesmal für + go func() { cs <- "wortreich" }() // schon wieder, diesmal für // "select" hat eine Syntax wie ein switch Statement, aber jeder Fall ist - // eine Kannaloperation. Es wählt eine Fall zufällig aus allen die - // kommunikationsbereit sind aus. + // eine Kanaloperation. Es wählt einen Fall zufällig aus allen, die + // kommunikationsbereit sind, aus. select { case i := <-c: // der empfangene Wert kann einer Variable zugewiesen werden fmt.Printf("es ist ein: %T", i) case <-cs: // oder der Wert kann verworfen werden fmt.Println("es ist eine Zeichenkette!") - case <-cc: // leerer Kannal, nicht bereit für den Empfang + case <-cc: // leerer Kanal, nicht bereit für den Empfang fmt.Println("wird nicht passieren.") } // Hier wird eine der beiden Goroutines fertig sein, die andere nicht. @@ -289,14 +289,14 @@ func learnConcurrency() { // Eine einzige Funktion aus dem http-Paket kann einen Webserver starten. func learnWebProgramming() { - // Der erste Parameter von "ListenAndServe" ist eine TCP Addresse an die + // Der erste Parameter von "ListenAndServe" ist eine TCP Addresse, an die // sich angeschlossen werden soll. // Der zweite Parameter ist ein Interface, speziell: ein http.Handler err := http.ListenAndServe(":8080", pair{}) fmt.Println(err) // Fehler sollte man nicht ignorieren! } -// Wir lassen "pair" das http.Handler Interface erfüllen indem wir seine einzige +// Wir lassen "pair" das http.Handler Interface erfüllen, indem wir seine einzige // Methode implementieren: ServeHTTP func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Senden von Daten mit einer Methode des http.ResponseWriter @@ -313,6 +313,6 @@ Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/). Gut documentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil -verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktions- -Namen in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). +verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen +in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). -- cgit v1.2.3 From 79170764a1b5069e648bb3764f95fbc3043e851b Mon Sep 17 00:00:00 2001 From: Wincent Balin Date: Tue, 3 Mar 2015 12:20:57 +0100 Subject: Update python-de.html.markdown Fixed typos. --- de-de/python-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 5ddb6f4b..ae29d6f9 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -149,7 +149,7 @@ li[0] #=> 1 # Das letzte Element ansehen li[-1] #=> 3 -# Bei Zugriffen außerhal der Liste kommt es jedoch zu einem IndexError +# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError li[4] # Raises an IndexError # Wir können uns Ranges mit Slice-Syntax ansehen @@ -188,7 +188,7 @@ tup[:2] #=> (1, 2) # Wir können Tupel (oder Listen) in Variablen entpacken a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 -# Tuple werden standardmäßig erstellt, wenn wir uns die Klammern sparen +# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen d, e, f = 4, 5, 6 # Es ist kinderleicht zwei Werte zu tauschen e, d = d, e # d is now 5 and e is now 4 -- cgit v1.2.3 From 7c3de408077a494d644ad926a198fc7e31f7ab82 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sat, 14 Mar 2015 12:42:52 +0800 Subject: [c++/cn] translation started. --- zh-cn/c++-cn.html.markdown | 579 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 579 insertions(+) create mode 100644 zh-cn/c++-cn.html.markdown diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown new file mode 100644 index 00000000..f1bdf158 --- /dev/null +++ b/zh-cn/c++-cn.html.markdown @@ -0,0 +1,579 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] +translators: + - ["Arnie97", "https://github.com/Arnie97"] +lang: zh-cn +--- + +C++是一種系統編程語言。用它的發明者, +[Bjarne Stroustrup的話](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)來說,C++的設計目標是: + +- 成爲「更好的C語言」 +- 支持數據的抽象與封裝 +- 支持面向對象編程 +- 支持泛型編程 + +C++提供了對硬件的緊密控制(正如C語言一樣), +能夠編譯爲機器語言,由處理器直接執行。 +與此同時,它也提供了泛型、異常和類等高層功能。 +雖然C++的語法可能比某些出現較晚的語言更複雜,它仍然得到了人們的青睞—— +功能與速度的平衡使C++成爲了目前應用最廣泛的系統編程語言之一。 + +```c++ +//////////////// +// 與C語言的比較 +//////////////// + +// C++_幾乎_是C語言的一個超集,它與C語言的基本語法有許多相同之處, +// 例如變量和函數的聲明,原生數據類型等等。 + +// 和C語言一樣,在C++中,你的程序會從main()開始執行, +// 該函數的返回值應當爲int型,這個返回值會作爲程序的退出狀態值。 +// 不過,大多數的編譯器(gcc,clang等)也接受 void main() 的函數原型。 +// (參見 http://en.wikipedia.org/wiki/Exit_status 來獲取更多信息) +int main(int argc, char** argv) +{ + // 和C語言一樣,命令行參數通過argc和argv傳遞。 + // argc代表命令行參數的數量, + // 而argv是一個包含“C語言風格字符串”(char *)的數組, + // 其中每個字符串代表一個命令行參數的內容, + // 首個命令行參數是調用該程序時所使用的名稱。 + // 如果你不關心命令行參數的值,argc和argv可以被忽略。 + // 此時,你可以用int main()作爲函數原型。 + + // 退出狀態值爲0時,表示程序執行成功 + return 0; +} + +// 然而,C++和C語言也有一些區別: + +// 在C++中,字符字面量的大小是一個字節。 +sizeof('c') == 1 + +// 在C語言中,字符字面量的大小與int相同。 +sizeof('c') == sizeof(10) + + +// C++的函數原型與函數定義是嚴格匹配的 +void func(); // 這個函數不能接受任何參數 + +// 而在C語言中 +void func(); // 這個函數能接受任意數量的參數 + +// 在C++中,用nullptr代替C語言中的NULL +int* ip = nullptr; + +// C++也可以使用C語言的標準頭文件, +// 但是需要加上前綴“c”並去掉末尾的“.h”。 +#include + +int main() +{ + printf("Hello, world!\n"); + return 0; +} + +/////////// +// 函數重載 +/////////// + +// C++支持函數重載,provided each function takes different parameters. + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("My int is %d", myInt); +} + +int main() +{ + print("Hello"); // 解析爲 void print(const char*) + print(15); // 解析爲 void print(int) +} + +/////////////////// +// 函數參數的默認值 +/////////////////// + +// 你可以爲函數的參數指定默認值, +// 它們將會在調用者沒有提供相應參數時被使用。 + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // 對兩個參數進行一些操作 +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// 默認參數必須放在所有的常規參數之後。 + +void invalidDeclaration(int a = 1, int b) // 這是錯誤的! +{ +} + + +/////////// +// 命名空間 +/////////// + +// 命名空間爲變量、函數和其他聲明提供了【separate】的作用域。 +// 命名空間可以嵌套使用。 + +namespace First { + namespace Nested { + void foo() + { + printf("This is First::Nested::foo\n"); + } + } // end namespace Nested +} // end namespace First + +namespace Second { + void foo() + { + printf("This is Second::foo\n") + } +} + +void foo() +{ + printf("This is global foo\n"); +} + +int main() +{ + // 如果沒有特別指定,所有【對象】都使用【取自】"Second"中的【聲明】。 + using namespace Second; + + foo(); // 顯示 "This is Second::foo" + First::Nested::foo(); // 顯示 "This is First::Nested::foo" + ::foo(); // 顯示 "This is global foo" +} + +//////////// +// 輸入/輸出 +//////////// + +// C++使用“流”來輸入輸出。 +// cin、cout、和cerr分別代表stdin(標準輸入)、stdout(標準輸出)和stderr(標準錯誤)。 +// <<是流的插入運算符,>>是流提取運算符。 + +#include // Include for I/O streams + +using namespace std; // 輸入輸出流在std命名空間(也就是標準庫)中。 + +int main() +{ + int myInt; + + // 在標準輸出(終端/顯示器)中顯示 + cout << "Enter your favorite number:\n"; + // 從標準輸入(鍵盤)獲得一個值 + cin >> myInt; + + // cout can also be formatted + cout << "Your favorite number is " << myInt << "\n"; + // 顯示 "Your favorite number is " + + cerr << "Used for error messages"; +} + +///////// +// 字符串 +///////// + +// C++中的字符串是對象,它們有很多成員函數 +#include + +using namespace std; // 字符串也在std命名空間(標準庫)中。 + +string myString = "Hello"; +string myOtherString = " World"; + +// + 可以用於連接字符串。 +cout << myString + myOtherString; // "Hello World" + +cout << myString + " You"; // "Hello You" + +// C++中的字符串是可變的,具有“值語義”。 +myString.append(" Dog"); +cout << myString; // "Hello Dog" + + +///////////// +// 引用 +///////////// + +// 除了支持C語言中的指針類型以外,C++還提供了_引用_。 +// 引用是一種特殊的指針類型,一旦被定義就不能重新賦值,並且引用不能被設置爲空值。 +// 使用引用時的語法與原變量相同: +// 也就是說,對引用類型進行解引用時,不需要使用*; +// 賦值時也不需要用&來取地址。 + +using namespace std; + +string foo = "I am foo"; +string bar = "I am bar"; + + +string& fooRef = foo; // 建立了一個對foo的引用。 +fooRef += ". Hi!"; // 通過引用來修改foo的值 +cout << fooRef; // "I am foo. Hi!" + +// 這句話的並不會改變fooRef的指向,其效果與“foo = bar”相同。 +// 也就是說,在執行這條語句之後,foo == "I am bar"。 +fooRef = bar; + +const string& barRef = bar; // 建立指向bar的【const ref】。 +// 和C語言中一樣,聲明爲常數的值(包括指針和引用)不能被修改。 +barRef += ". Hi!"; // 這是錯誤的,【const ref】不能被修改。 + +/////////////////// +// 類與面向對象編程 +/////////////////// + +// 有關類的第一個示例 +#include + +// 聲明一個類。 +// 類通常在頭文件(.h或.hpp)中聲明。 +class Dog { + // 成員變量和成員函數默認情況下是私有(private)的。 + std::string name; + int weight; + +// 在這個標籤之後,所有聲明都是公有(public)的, +// 直到重新指定“private:”(私有繼承)或“protected:”(保護繼承)爲止 +public: + + // 默認的構造器 + Dog(); + + // Member function declarations (implementations to follow) + // Note that we use std::string here instead of placing + // using namespace std; + // above. + // Never put a "using namespace" statement in a header. + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + + // Functions that do not modify the state of the object + // should be marked as const. + // This allows you to call them if given a const reference to the object. + // Also note the functions must be explicitly declared as _virtual_ + // in order to be overridden in derived classes. + // Functions are not virtual by default for performance reasons. + virtual void print() const; + + // 函數也可以在class body內部定義。 + // 這樣定義的函數會自動成爲內聯函數。 + void bark() const { std::cout << name << " barks!\n" } + + // 除了構造器以外,C++還提供了析構器。 + // These are called when an object is deleted or falls out of scope. + // 這使得如同下文中的RAII這樣的強大範式成爲可能。 + // Destructors must be virtual to allow classes to be derived from this one. + virtual ~Dog(); + +}; // 在類的定義後必須加一個分號 + +// 類的成員函數通常在.cpp文件中實現。 +void Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} + +// 對象(例如字符串)應當以引用的形式傳遞, +// 不需要修改的對象則應當作爲【const ref】。 +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// Notice that "virtual" is only needed in the declaration, not the definition. +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +void Dog::~Dog() +{ + cout << "Goodbye " << name << "\n"; +} + +int main() { + Dog myDog; // 此時顯示“A dog has been constructed” + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.printDog(); // 顯示“Dog is Barkley and weighs 10 kg” + return 0; +} // 顯示“Goodbye Barkley” + +// 繼承: + +// 這個類繼承了Dog類中的公有(public)和保護(protected)對象 +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner) + + // 重寫OwnedDogs類的print方法。 + // 如果你不熟悉子類多態的話,可以參考這個頁面中的概述: + // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + + // override關鍵字是可選的,它確保你是在重寫基類中的方法。 + void print() const override; + +private: + std::string owner; +}; + +// 與此同時,在對應的.cpp文件裏: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // 調用基類Dog中的print方法 + // "Dog is and weights " + + std::cout << "Dog is owned by " << owner << "\n"; + // "Dog is owned by " +} + +///////////////////// +// 初始化與運算符重載 +///////////////////// + +// 在C++中,你可以重載+、-、*、/等運算符的行爲。 +// This is done by defining a function +// which is called whenever the operator is used. + +#include +using namespace std; + +class Point { +public: + // 可以以這樣的方式爲成員變量設置默認值。 + double x = 0; + double y = 0; + + // Define a default constructor which does nothing + // but initialize the Point to the default value (0, 0) + Point() { }; + + // The following syntax is known as an initialization list + // and is the proper way to initialize class member values + Point (double a, double b) : + x(a), + y(b) + { /* Do nothing except initialize the values */ } + + // 重載 + 運算符 + Point operator+(const Point& rhs) const; + + // 重載 += 運算符 + Point& operator+=(const Point& rhs); + + // 增加 - 和 -= 運算符也是有意義的,這裏不再贅述。 +}; + +Point Point::operator+(const Point& rhs) const +{ + // Create a new point that is the sum of this one and rhs. + return Point(x + rhs.x, y + rhs.y); +} + +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // 這裏調用了Point類型的運算符“+” + // 調用up(Point類型)的“+”方法,並以right作爲函數的參數 + Point result = up + right; + // 顯示“Result is upright (1,1)” + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +/////////// +// 異常處理 +/////////// + +// 標準庫中提供了a few exception types +// (參見http://en.cppreference.com/w/cpp/error/exception) +// but any type can be thrown an as exception +#include + +// All exceptions thrown inside the _try_ block can be caught by subsequent +// _catch_ handlers. +try { + // Do not allocate exceptions on the heap using _new_. + throw std::exception("A problem occurred"); +} +// Catch exceptions by const reference if they are objects +catch (const std::exception& ex) +{ + std::cout << ex.what(); +// Catches any exception not caught by previous _catch_ blocks +} catch (...) +{ + std::cout << "Unknown exception caught"; + throw; // Re-throws the exception +} + +/////// +// RAII +/////// + +// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization)。 +// It is often considered the most powerful paradigm in C++, +// and is the simple concept that a constructor for an object +// acquires that object's resources and the destructor releases them. + +// 爲了理解這一範式的用處,讓我們考慮某個函數使用文件句柄時的情況: +void doSomethingWithAFile(const char* filename) +{ + // 首先,讓我們假設一切都會順利進行。 + + FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // 關閉文件句柄 +} + +// 不幸的是,隨着錯誤處理機制的引入,事情會變得複雜。 +// 假設fopen有可能執行失敗, +// 而doSomethingWithTheFile和doSomethingElseWithIt會在失敗時返回錯誤代碼。 +// (雖然【Exceptions】是處理錯誤的推薦方式, +// 但是某些程序員,尤其是有C語言背景的,並不認可【exceptions】的效用)。 +// 現在,我們必須檢查每個函數調用是否成功執行,並在問題發生的時候關閉文件句柄。 +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 + if (fh == nullptr) // 當執行失敗是,返回的指針是nullptr + return false; // 向調用者彙報錯誤 + + // 假設每個函數會在執行失敗時返回false + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // 反饋錯誤 + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // 反饋錯誤 + } + + fclose(fh); // Close the file handle so it doesn't leak. + return true; // 指示函數已成功執行 +} + +// C語言的程序員通常會借助goto語句簡化上面的代碼: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + return false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // 關閉文件 + return true; // 執行成功 + +failure: + fclose(fh); + return false; // 反饋錯誤 +} + +// If the functions indicate errors using exceptions, +// things are a little cleaner, but still sub-optimal. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 + if (fh == nullptr) + throw std::exception("Could not open the file."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // 保證出錯的時候文件被正確關閉 + throw; // Then re-throw the exception. + } + + fclose(fh); // 關閉文件 + // 所有工作順利完成 +} + +// Compare this to the use of C++'s file stream class (fstream) +// fstream利用自己的析構器來關閉文件句柄。 +// Recall from above that destructors are automatically called +// whenver an object falls out of scope. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream is short for input file stream + std::ifstream fh(filename); // Open the file + + // 對文件進行一些操作 + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // 文件已經被析構器自動關閉 + +// 與上面幾種方式相比,這種方式有着_明顯_的優勢: +// 1. 無論發生了什麼情況,資源(此例當中是文件句柄)都會被正確關閉。 +// 只要你正確使用了析構器,就_不會_因爲忘記關閉句柄,造成資源的泄漏。 +// 2. Note that the code is much cleaner. +// The destructor handles closing the file behind the scenes +// without you having to worry about it. +// 3. The code is exception safe. +// An exception can be thrown anywhere in the function and cleanup +// will still occur. + +// All idiomatic C++ code uses RAII extensively for all resources. +// Additional examples include +// - Memory using unique_ptr and shared_ptr +// - Containers - the standard library linked list, +// vector (i.e. self-resizing array), hash maps, and so on +// all automatically destroy their contents when they fall out of scope. +// - Mutexes using lock_guard and unique_lock +``` +擴展閱讀: + + 提供了最新的語法參考。 + +可以在 找到一些補充資料。 -- cgit v1.2.3 From b3d7a178e729c142eb6890a815c13137d4d35314 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sat, 14 Mar 2015 13:16:34 +0800 Subject: [c++/cn] mark all parts still in progress. --- zh-cn/c++-cn.html.markdown | 117 ++++++++++++++++++++++----------------------- 1 file changed, 57 insertions(+), 60 deletions(-) diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index f1bdf158..9a952d85 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -39,7 +39,7 @@ int main(int argc, char** argv) { // 和C語言一樣,命令行參數通過argc和argv傳遞。 // argc代表命令行參數的數量, - // 而argv是一個包含“C語言風格字符串”(char *)的數組, + // 而argv是一個包含「C語言風格字符串」(char *)的數組, // 其中每個字符串代表一個命令行參數的內容, // 首個命令行參數是調用該程序時所使用的名稱。 // 如果你不關心命令行參數的值,argc和argv可以被忽略。 @@ -68,7 +68,7 @@ void func(); // 這個函數能接受任意數量的參數 int* ip = nullptr; // C++也可以使用C語言的標準頭文件, -// 但是需要加上前綴“c”並去掉末尾的“.h”。 +// 但是需要加上前綴「c」並去掉末尾的「.h」。 #include int main() @@ -81,7 +81,7 @@ int main() // 函數重載 /////////// -// C++支持函數重載,provided each function takes different parameters. +// C++支持函數重載,【provided each function takes different parameters.】 void print(char const* myString) { @@ -138,8 +138,8 @@ namespace First { { printf("This is First::Nested::foo\n"); } - } // end namespace Nested -} // end namespace First + } // 結束嵌套的命名空間Nested +} // 結束命名空間First namespace Second { void foo() @@ -155,23 +155,23 @@ void foo() int main() { - // 如果沒有特別指定,所有【對象】都使用【取自】"Second"中的【聲明】。 + // 如果沒有特別指定,就從「Second」中取得所需的內容。 using namespace Second; - foo(); // 顯示 "This is Second::foo" - First::Nested::foo(); // 顯示 "This is First::Nested::foo" - ::foo(); // 顯示 "This is global foo" + foo(); // 顯示「This is Second::foo」 + First::Nested::foo(); // 顯示「This is First::Nested::foo」 + ::foo(); // 顯示「This is global foo」 } //////////// // 輸入/輸出 //////////// -// C++使用“流”來輸入輸出。 +// C++使用「流」來輸入輸出。 // cin、cout、和cerr分別代表stdin(標準輸入)、stdout(標準輸出)和stderr(標準錯誤)。 // <<是流的插入運算符,>>是流提取運算符。 -#include // Include for I/O streams +#include // 引入包含輸入/輸出流的頭文件 using namespace std; // 輸入輸出流在std命名空間(也就是標準庫)中。 @@ -184,9 +184,9 @@ int main() // 從標準輸入(鍵盤)獲得一個值 cin >> myInt; - // cout can also be formatted + // cout也提供了格式化功能 cout << "Your favorite number is " << myInt << "\n"; - // 顯示 "Your favorite number is " + // 顯示「Your favorite number is 」 cerr << "Used for error messages"; } @@ -208,7 +208,7 @@ cout << myString + myOtherString; // "Hello World" cout << myString + " You"; // "Hello You" -// C++中的字符串是可變的,具有“值語義”。 +// C++中的字符串是可變的,具有「值語義」。 myString.append(" Dog"); cout << myString; // "Hello Dog" @@ -218,7 +218,7 @@ cout << myString; // "Hello Dog" ///////////// // 除了支持C語言中的指針類型以外,C++還提供了_引用_。 -// 引用是一種特殊的指針類型,一旦被定義就不能重新賦值,並且引用不能被設置爲空值。 +// 引用是一種特殊的指針類型,一旦被定義就不能重新賦值,並且不能被設置爲空值。 // 使用引用時的語法與原變量相同: // 也就是說,對引用類型進行解引用時,不需要使用*; // 賦值時也不需要用&來取地址。 @@ -233,7 +233,7 @@ string& fooRef = foo; // 建立了一個對foo的引用。 fooRef += ". Hi!"; // 通過引用來修改foo的值 cout << fooRef; // "I am foo. Hi!" -// 這句話的並不會改變fooRef的指向,其效果與“foo = bar”相同。 +// 這句話的並不會改變fooRef的指向,其效果與「foo = bar」相同。 // 也就是說,在執行這條語句之後,foo == "I am bar"。 fooRef = bar; @@ -256,13 +256,13 @@ class Dog { int weight; // 在這個標籤之後,所有聲明都是公有(public)的, -// 直到重新指定“private:”(私有繼承)或“protected:”(保護繼承)爲止 +// 直到重新指定「private:」(私有繼承)或「protected:」(保護繼承)爲止 public: // 默認的構造器 Dog(); - // Member function declarations (implementations to follow) + // 【Member function declarations (implementations to follow) // Note that we use std::string here instead of placing // using namespace std; // above. @@ -271,7 +271,7 @@ public: void setWeight(int dogsWeight); - // Functions that do not modify the state of the object + // 【Functions that do not modify the state of the object // should be marked as const. // This allows you to call them if given a const reference to the object. // Also note the functions must be explicitly declared as _virtual_ @@ -284,12 +284,12 @@ public: void bark() const { std::cout << name << " barks!\n" } // 除了構造器以外,C++還提供了析構器。 - // These are called when an object is deleted or falls out of scope. - // 這使得如同下文中的RAII這樣的強大範式成爲可能。 - // Destructors must be virtual to allow classes to be derived from this one. + // 當一個對象被刪除或者【falls out of scope】時,它的析構器會被調用。 + // 這使得RAII這樣的強大範式(參見下文)成爲可能。 + // 析構器【must be virtual to allow classes to be derived from this one. virtual ~Dog(); -}; // 在類的定義後必須加一個分號 +}; // 在類的定義之後,要加一個分號 // 類的成員函數通常在.cpp文件中實現。 void Dog::Dog() @@ -309,7 +309,7 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// Notice that "virtual" is only needed in the declaration, not the definition. +// 【Notice that "virtual" is only needed in the declaration, not the definition. void Dog::print() const { std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; @@ -321,12 +321,12 @@ void Dog::~Dog() } int main() { - Dog myDog; // 此時顯示“A dog has been constructed” + Dog myDog; // 此時顯示「A dog has been constructed」 myDog.setName("Barkley"); myDog.setWeight(10); - myDog.printDog(); // 顯示“Dog is Barkley and weighs 10 kg” + myDog.printDog(); // 顯示「Dog is Barkley and weighs 10 kg」 return 0; -} // 顯示“Goodbye Barkley” +} // 顯示「Goodbye Barkley」 // 繼承: @@ -367,7 +367,7 @@ void OwnedDog::print() const ///////////////////// // 在C++中,你可以重載+、-、*、/等運算符的行爲。 -// This is done by defining a function +// 【This is done by defining a function // which is called whenever the operator is used. #include @@ -379,16 +379,16 @@ public: double x = 0; double y = 0; - // Define a default constructor which does nothing + // 【Define a default constructor which does nothing // but initialize the Point to the default value (0, 0) Point() { }; - // The following syntax is known as an initialization list + // 【The following syntax is known as an initialization list // and is the proper way to initialize class member values Point (double a, double b) : x(a), y(b) - { /* Do nothing except initialize the values */ } + { /* 【Do nothing except initialize the values */ } // 重載 + 運算符 Point operator+(const Point& rhs) const; @@ -401,7 +401,7 @@ public: Point Point::operator+(const Point& rhs) const { - // Create a new point that is the sum of this one and rhs. + // 【Create a new point that is the sum of this one and rhs. return Point(x + rhs.x, y + rhs.y); } @@ -415,10 +415,10 @@ Point& Point::operator+=(const Point& rhs) int main () { Point up (0,1); Point right (1,0); - // 這裏調用了Point類型的運算符“+” - // 調用up(Point類型)的“+”方法,並以right作爲函數的參數 + // 這裏調用了Point類型的運算符「+」 + // 調用up(Point類型)的「+」方法,並以right作爲函數的參數 Point result = up + right; - // 顯示“Result is upright (1,1)” + // 顯示「Result is upright (1,1)」 cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; return 0; } @@ -429,32 +429,31 @@ int main () { // 標準庫中提供了a few exception types // (參見http://en.cppreference.com/w/cpp/error/exception) -// but any type can be thrown an as exception +// 【but any type can be thrown an as exception #include -// All exceptions thrown inside the _try_ block can be caught by subsequent -// _catch_ handlers. +// 在_try_代碼塊中拋出的異常可以被隨後的_catch_捕獲。 try { - // Do not allocate exceptions on the heap using _new_. + // 【Do not allocate exceptions on the heap using _new_. throw std::exception("A problem occurred"); } -// Catch exceptions by const reference if they are objects +// 【Catch exceptions by const reference if they are objects catch (const std::exception& ex) { std::cout << ex.what(); -// Catches any exception not caught by previous _catch_ blocks +// 捕獲尚未被_catch_處理的所有錯誤 } catch (...) { std::cout << "Unknown exception caught"; - throw; // Re-throws the exception + throw; // 重新拋出異常 } /////// // RAII /////// -// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization)。 -// It is often considered the most powerful paradigm in C++, +// RAII指的是「资源获取就是初始化」(Resource Allocation Is Initialization)。 +// 【It is often considered the most powerful paradigm in C++, // and is the simple concept that a constructor for an object // acquires that object's resources and the destructor releases them. @@ -472,10 +471,10 @@ void doSomethingWithAFile(const char* filename) } // 不幸的是,隨着錯誤處理機制的引入,事情會變得複雜。 -// 假設fopen有可能執行失敗, +// 假設fopen函數有可能執行失敗, // 而doSomethingWithTheFile和doSomethingElseWithIt會在失敗時返回錯誤代碼。 -// (雖然【Exceptions】是處理錯誤的推薦方式, -// 但是某些程序員,尤其是有C語言背景的,並不認可【exceptions】的效用)。 +// (雖然異常是C++中處理錯誤的推薦方式, +// 但是某些程序員,尤其是有C語言背景的,並不認可異常捕獲機制的作用)。 // 現在,我們必須檢查每個函數調用是否成功執行,並在問題發生的時候關閉文件句柄。 bool doSomethingWithAFile(const char* filename) { @@ -518,7 +517,7 @@ failure: return false; // 反饋錯誤 } -// If the functions indicate errors using exceptions, +// 【If the functions indicate errors using exceptions, // things are a little cleaner, but still sub-optimal. void doSomethingWithAFile(const char* filename) { @@ -539,13 +538,13 @@ void doSomethingWithAFile(const char* filename) // 所有工作順利完成 } -// Compare this to the use of C++'s file stream class (fstream) +// 【Compare this to the use of C++'s file stream class (fstream) // fstream利用自己的析構器來關閉文件句柄。 -// Recall from above that destructors are automatically called +// 【Recall from above that destructors are automatically called // whenver an object falls out of scope. void doSomethingWithAFile(const std::string& filename) { - // ifstream is short for input file stream + // ifstream是輸入文件流(input file stream)的簡稱 std::ifstream fh(filename); // Open the file // 對文件進行一些操作 @@ -557,20 +556,18 @@ void doSomethingWithAFile(const std::string& filename) // 與上面幾種方式相比,這種方式有着_明顯_的優勢: // 1. 無論發生了什麼情況,資源(此例當中是文件句柄)都會被正確關閉。 // 只要你正確使用了析構器,就_不會_因爲忘記關閉句柄,造成資源的泄漏。 -// 2. Note that the code is much cleaner. +// 2. 【Note that the code is much cleaner. // The destructor handles closing the file behind the scenes // without you having to worry about it. -// 3. The code is exception safe. +// 3. 【The code is exception safe. // An exception can be thrown anywhere in the function and cleanup // will still occur. -// All idiomatic C++ code uses RAII extensively for all resources. -// Additional examples include -// - Memory using unique_ptr and shared_ptr -// - Containers - the standard library linked list, -// vector (i.e. self-resizing array), hash maps, and so on -// all automatically destroy their contents when they fall out of scope. -// - Mutexes using lock_guard and unique_lock +// 地道的C++代碼應當把RAII的使用擴展到所有類型的資源上,包括: +// - 用unique_ptr和shared_ptr管理的內存 +// - 容器,例如標準庫中的鏈表、向量(容量自動擴展的數組)、散列表等; +// 【all automatically destroy their contents when they fall out of scope. +// - 用lock_guard和unique_lock實現的互斥 ``` 擴展閱讀: -- cgit v1.2.3 From 4e00fa4734bd39436f3336b4ce1034b65c265657 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Mon, 16 Mar 2015 21:09:17 +0200 Subject: Update haskell.html.markdown. Wrong explanation about '$' operator --- haskell.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 79fbf09f..d5dfd122 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -202,9 +202,9 @@ foo = (*5) . (+10) foo 5 -- 75 -- fixing precedence --- Haskell has another function called `$`. This changes the precedence --- so that everything to the left of it gets computed first and then applied --- to everything on the right. You can use `$` (often in combination with `.`) +-- Haskell has another function called `$`. Anything appearing after it will +-- take precedence over anything that comes before. +-- You can use `$` (often in combination with `.`) -- to get rid of a lot of parentheses: -- before -- cgit v1.2.3 From 9fb21f1ce4c02e8cad50046f90d026ccab284626 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Mon, 16 Mar 2015 21:24:21 +0200 Subject: Haskell.html.markdown. Wrong result of an expression. The seventh Fibonacci number is 13 (odd number), so the result of 'even 13' is false. --- haskell.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index d5dfd122..f1025d44 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -208,13 +208,13 @@ foo 5 -- 75 -- to get rid of a lot of parentheses: -- before -(even (fib 7)) -- true +(even (fib 7)) -- false -- after -even . fib $ 7 -- true +even . fib $ 7 -- false -- equivalently -even $ fib 7 -- true +even $ fib 7 -- false ---------------------------------------------------- -- 5. Type signatures -- cgit v1.2.3 From abce4e0a2fd8598a2768bcef86623a02e5f572e5 Mon Sep 17 00:00:00 2001 From: Jean-Philippe Monette Date: Tue, 17 Mar 2015 20:25:44 +0000 Subject: Adding Go French translation --- fr-fr/go-fr.html.markdown | 430 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 430 insertions(+) create mode 100644 fr-fr/go-fr.html.markdown diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown new file mode 100644 index 00000000..1d2b656b --- /dev/null +++ b/fr-fr/go-fr.html.markdown @@ -0,0 +1,430 @@ +--- +name: Go +category: language +language: Go +filename: learngo.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Jean-Philippe Monette", "http://blogue.jpmonette.net/"] +--- + +Go a été créé dans l'optique de déveloper de façcon efficace. Ce n'est pas la +dernière tendance en ce qui au développement, mais c'est la nouvelle façon de +régler des défis réels de façcon rapide. + +Le langage possède des concepts familiers à la programmation impérative avec +typage. Il est rapide à compiler et exécuter, ajoute une concurrence facile à +comprendre pour les processeurs multi coeurs d'aujourd'hui et apporte des +fonctionnalités facilitant le développement à grande échelle. + +Développer avec Go, c'est bénéficier d'une riche librairie standard et d'une +communauté active. + +```go +// Commentaire ligne simple +/* Commentaire + multiligne */ + +// Un paquet débute avec une clause "package" +// "Main" est un nom spécial déclarant un paquet de type exécutable plutôt +// qu'une librairie +package main + +// "Import" déclare les paquets référencés dans ce fichier. +import ( + "fmt" // Un paquet dans la librairie standard. + "io/ioutil" // Implémente des fonctions utilitaires I/O. + m "math" // Librairie mathématique utilisant un alias local "m". + "net/http" // Un serveur Web! + "strconv" // Librairie pour convertir les chaînes de caractères. +) + +// Une définition de fonction. La fonction "main" est spéciale - c'est le point +// d'entrée du binaire. Celle-ci est encapsulée par des accolades. +func main() { + // Println retourne une ligne à stdout. + // Associez la fonction avec son paquet respectif, fmt. + fmt.Println("Hello world!") + + // Appelez une fonction différente à partir de ce paquet. + beyondHello() +} + +// Les fonctions ont des paramètres entre parenthèses. +// Les parenthèses sont nécessaires avec ou sans paramètre. +func beyondHello() { + var x int // Déclaration de variable. Les variables doivent être déclarées + // avant leur utilisation. + x = 3 // Assignation de valeur. + // Les déclarations courtes utilisent := pour inférer le type, déclarer et + // assigner. + y := 4 + sum, prod := learnMultiple(x, y) // La fonction retourne deux valeurs. + fmt.Println("sum:", sum, "prod:", prod) // Affichage simple. + learnTypes() // < y minutes, en savoir plus! +} + +// Les fonctions peuvent avoir des paramètres et plusieurs valeurs retournées. +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // Deux valeurs retournées. +} + +// Quelques types inclus et littéraux. +func learnTypes() { + // Déclaration courte produit généralement le type désiré. + str := "Learn Go!" // Type string. + + s2 := `Une chaîne de caractères peut contenir des +sauts de ligne.` // Chaîne de caractère. + + // Littéral non-ASCII. Les sources Go utilisent le charset UTF-8. + g := 'Σ' // type rune, un alias pour le type int32, contenant un caractère + // unicode. + + f := 3.14195 // float64, un nombre flottant IEEE-754 de 64-bit. + c := 3 + 4i // complex128, représenté à l'interne par deux float64. + + // Syntaxe "var" avec une valeur d'initialisation. + var u uint = 7 // Non signé, mais la taille dépend selon l'entier. + var pi float32 = 22. / 7 + + // Conversion avec syntaxe courte. + n := byte('\n') // byte est un alias du type uint8. + + // Les tableaux ont des tailles fixes à la compilation. + var a4 [4]int // Un tableau de 4 ints, tous initialisés à 0. + a3 := [...]int{3, 1, 5} // Un tableau initialisé avec une taille fixe de 3 + // éléments, contenant les valeurs 3, 1 et 5. + + // Les slices ont des tailles dynamiques. Les tableaux et slices ont chacun + // des avantages, mais les usages des slices sont plus communs. + s3 := []int{4, 5, 9} // Comparable à a3. + s4 := make([]int, 4) // Alloue un slice de 4 ints, initialisés à 0. + var d2 [][]float64 // Déclaration seulement, sans allocation de mémoire. + bs := []byte("a slice") // Conversion d'une chaîne en slice de bytes. + + // Parce qu'elles sont dynamiques, les slices peuvent être jointes sur + // demande. Pour joindre un élément à une slice, la fonction standard append() + // est utilisée. Le premier argument est la slice à utiliser. Habituellement, + // la variable tableau est mise à jour sur place, voir ci-bas. + s := []int{1, 2, 3} // Le résultat est une slice de taille 3. + s = append(s, 4, 5, 6) // Ajout de 3 valeurs. La taille est de 6. + fmt.Println(s) // La valeur est maintenant de [1 2 3 4 5 6] + // Pour ajouter une autre slice, au lieu d'utiliser une liste de valeurs + // atomiques, il est possible de mettre en argument une référence de + // slice littérale de cette façon, avec des points de suspension, signifiant + // qu'il faut prendre les éléments de la slice et les ajouter à la slice s. + s = append(s, []int{7, 8, 9}...) // Le deuxième argument est une slice + // littérale. + fmt.Println(s) // La slice contient [1 2 3 4 5 6 7 8 9] + + p, q := learnMemory() // Déclare p, q comme étant des pointeurs de type int. + fmt.Println(*p, *q) // * suit un pointeur. Ceci retourne deux ints. + + // Les maps sont des tableaux associatifs de taille dynamique, comme les + // hash ou les types dictionnaires de certains langages. + m := map[string]int{"trois": 3, "quatre": 4} + m["un"] = 1 + + // Les valeurs inutilisées sont des erreurs en Go. + // Un tiret bas permet d'utiliser une variable, mais d'en jeter la valeur. + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // L'affichage est considéré comme une utilisation de la variable. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // De retour dans le flux. +} + +// Il est possible, à l'opposée de plusieurs autres langages, à des fonctions +// en go d'avoir des valeurs retournées avec nom. +// Assigner un nom à un type retourné par une fonction permet de retrouver sa +// valeur ainsi que d'utiliser le mot-clé "return" uniquement, sans plus. +func learnNamedReturns(x, y int) (z int) { + z = x * y + return // z est implicite, car la variable a été définie précédemment. +} + +// La récupération de la mémoire est automatique en Go. Le langage possède des +// pointeurs, mais aucun pointeur arithmétique. Vous pouvez faire une erreur +// avec un pointeur nil, mais pas en incrémentant un pointeur. +func learnMemory() (p, q *int) { + // Les valeurs retournées définies p et q ont le type pointeur int. + p = new(int) // Fonction standard "new" alloue la mémoire. + // Le int alloué est initialisé à 0, p n'est plus nil. + s := make([]int, 20) // Alloue 20 ints en un seul bloc de mémoire. + s[3] = 7 // Assigne l'un des entiers. + r := -2 // Déclare une autre variable locale. + return &s[3], &r // & retourne l'adresse d'un objet. +} + +func expensiveComputation() float64 { + return m.Exp(10) +} + +func learnFlowControl() { + // Bien que les "if" requiert des accolades, les parenthèses ne le sont pas. + if true { + fmt.Println("voilà!") + } + // Le formate est standardisé par la commande shell "go fmt." + if false { + // bing. + } else { + // bang. + } + // Utilisez "switch" au lieu des "if" en chaîne + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Les "case" n'ont pas besoin de "break;". + case 43: + // Non-exécuté. + } + // Comme les "if", "for" n'utilise pas de parenthèses. + // Les variables déclarées dans "for" et "if" sont locales à leur portée. + for x := 0; x < 3; x++ { // ++ est une incrémentation. + fmt.Println("itération ", x) + } + // x == 42 ici. + + // "For" est le seul type de boucle en Go, mais possède différentes formes. + for { // Boucle infinie + break // C'est une farce + continue // Non atteint. + } + + // Vous pouvez utiliser un "range" pour itérer dans un tableau, une slice, une + // chaîne, une map ou un channel. Les "range" retournent un canal ou deux + // valeurs (tableau, slice, chaîne et map). + for key, value := range map[string]int{"une": 1, "deux": 2, "trois": 3} { + // pour chaque pair dans une map, affichage de la valeur et clé + fmt.Printf("clé=%s, valeur=%d\n", key, value) + } + + // À l'opposé du "for", := dans un "if" signifie la déclaration et + // l'assignation y en premier, et ensuite y > x + if y := expensiveComputation(); y > x { + x = y + } + // Les fonctions littérales est une fermeture (closure). + xBig := func() bool { + return x > 10000 // Réfère à la variable x déclarée en haut du "switch". + } + fmt.Println("xBig:", xBig()) // true (la valeur e^10 a été assignée à x). + x = 1.3e3 // Ceci fait x == 1300 + fmt.Println("xBig:", xBig()) // Maintenant false. + + // De plus, les fonctions littérales peuvent être définies et appelée + // sur la même ligne, agissant comme argument de fonctions, tant que: + // a) la fonction littérale est appelée suite à (), + // b) le résultat correspond au type de l'argument. + fmt.Println("Ajoute + multiplie deux nombres: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Appelé avec les arguments 10 et 2 + // => Ajoute + double deux nombres: 24 + + // Quand vous en aurez besoin, vous allez l'adorer. + goto love +love: + + learnFunctionFactory() // func retournant func correspond à fun(3)(3). + learnDefer() // Un survol de cette instruction important. + learnInterfaces() // Incontournable! +} + +func learnFunctionFactory() { + // Les deux syntaxes sont identiques, bien que la seconde est plus pratique. + fmt.Println(sentenceFactory("été")("Une matinée d'", "agréable!")) + + d := sentenceFactory("été") + fmt.Println(d("Une matinée d'", "agréable!")) + fmt.Println(d("Une soirée d'", "relaxante!")) +} + +// Le décorateur est un patron de conception commun dans d'autres langages. +// Il est possible de faire de même en Go avec des fonctions littérales +// acceptant des arguments. +func sentenceFactory(mystring string) func(before, after string) string { + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // nouvelle chaîne + } +} + +func learnDefer() (ok bool) { + // Les déclarations différées sont exécutées avant la sortie d'une fonction. + defer fmt.Println("les déclarations différées s'exécutent en ordre LIFO.") + defer fmt.Println("\nCette ligne est affichée en premier parce que") + // Les déclarations différées sont utilisées fréquemment pour fermer un + // fichier, afin que la fonction ferme le fichier en fin d'exécution. + return true +} + +// Défini Stringer comme étant une interface avec une méthode, String. +type Stringer interface { + String() string +} + +// Défini pair comme étant une structure contenant deux entiers, x et y. +type pair struct { + x, y int +} + +// Défini une méthode associée au type pair. Pair implémente maintenant Stringer +func (p pair) String() string { // p s'appelle le "destinataire" + // Sprintf est une autre fonction publique dans le paquet fmt. + // La syntaxe avec point permet de faire référence aux valeurs de p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // La syntaxe avec accolade défini une "structure littérale". Ceci s'évalue + // comme étant une strucutre. La syntaxe := déclare et initialise p comme + // étant cette structure. + p := pair{3, 4} + fmt.Println(p.String()) // Appelle la méthode String de p, de type pair. + var i Stringer // Déclare i de l'interface de type Stringer. + i = p // Valide, car pair implémente Stringer. + // Appelle la méthode String de i, de type Stringer. Retourne la même valeur + // que ci-haut. + fmt.Println(i.String()) + + // Les fonctions dans le paquet fmt appellent la méthode String, demandant + // aux objets d'afficher une représentation de leur structure. + fmt.Println(p) // Affiche la même chose que ci-haut. Println appelle la + // méthode String. + fmt.Println(i) // Affiche la même chose que ci-haut. + + learnVariadicParams("apprentissage", "génial", "ici!") +} + +// Les fonctions peuvent avoir des paramètres variables. +func learnVariadicParams(myStrings ...interface{}) { + // Itère chaque valeur du paramètre variable. + // Le tiret bas sert à ignorer l'index retourné du tableau. + for _, param := range myStrings { + fmt.Println("paramètre:", param) + } + + // Passe une valeur variadique comme paramètre variadique. + fmt.Println("paramètres:", fmt.Sprintln(myStrings...)) + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" expression utilisée pour définir si quelque chose a fonctionné ou + // non. + m := map[int]string{3: "trois", 4: "quatre"} + if x, ok := m[1]; !ok { // ok sera faux, car 1 n'est pas dans la map. + fmt.Println("inexistant") + } else { + fmt.Print(x) // x serait la valeur, si elle se trouvait dans la map. + } + // Une erreur ne retourne qu'un "ok", mais également plus d'information + // par rapport à un problème survenu. + if _, err := strconv.Atoi("non-int"); err != nil { // _ discarte la valeur + // retourne: 'strconv.ParseInt: parsing "non-int": invalid syntax' + fmt.Println(err) + } + // Nous réviserons les interfaces un peu plus tard. Maintenant, + learnConcurrency() +} + +// c est un canal, un objet permettant de communiquer en simultané de façon +// sécuritaire. +func inc(i int, c chan int) { + c <- i + 1 // <- est l'opérateur "destination" quand un canal apparaît à + // gauche. +} + +// Nous utiliserons inc pour incrémenter des nombres en même temps. +func learnConcurrency() { + // La fonction "make" utilisée précédemment pour générer un slice. Elle + // alloue et initialise les slices, maps et les canaux. + c := make(chan int) + // Démarrage de trois goroutines simultanées. Les nombres seront incrémentés + // simultanément, peut-être en paralèle si la machine le permet et configurée + // correctement. Les trois utilisent le même canal. + go inc(0, c) // go est une déclaration démarrant une nouvelle goroutine. + go inc(10, c) + go inc(-805, c) + // Lis et affiche trois résultats du canal - impossible de savoir dans quel + // ordre! + fmt.Println(<-c, <-c, <-c) // Canal à droite, <- est l'opérateur de + // "réception". + + cs := make(chan string) // Un autre canal, celui-ci gère des chaînes. + ccs := make(chan chan string) // Un canal de canaux de chaînes. + go func() { c <- 84 }() // Démarre une nouvelle goroutine, pour + // envoyer une valeur. + go func() { cs <- "wordy" }() // De nouveau, pour cs cette fois-ci. + // Select possède une syntaxe similaire au switch, mais chaque cas requiert + // une opération impliquant un canal. Il sélectionne un cas aléatoirement + // prêt à communiquer. + select { + case i := <-c: // La valeur reçue peut être assignée à une variable, + fmt.Printf("c'est un %T", i) + case <-cs: // ou la valeur reçue peut être discartée. + fmt.Println("c'est une chaîne") + case <-ccs: // Un canal vide, indisponible à la communication. + fmt.Println("ne surviendra pas.") + } + // À ce point, une valeur a été prise de c ou cs. L'une des deux goroutines + // démarrée plus haut a complété, la seconde restera bloquée. + + learnWebProgramming() // Go permet la programmation Web. +} + +// Une seule fonction du paquet http démarre un serveur Web. +func learnWebProgramming() { + + // Le premier paramètre de ListenAndServe is une adresse TCP à écouter. + // Le second est une interface, de type http.Handler. + go func() { + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // n'ignorez pas les erreurs! + }() + + requestServer() +} + +// Fait de pair un http.Handler en implémentant sa seule méthode: ServeHTTP. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Répondez à une requête à l'aide de la méthode http.ResponseWriter. + w.Write([]byte("Vous avez appris Go en Y minutes!")) +} + +func requestServer() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nLe serveur Web a dit: `%s`", string(body)) +} +``` + +## En savoir plus + +La référence Go se trouve sur [le site officiel de Go](http://golang.org/). +Vous pourrez y suivre le tutoriel interactif et en apprendre beaucoup plus. + +Une lecture de la documentation du langage est grandement conseillée. C'est +facile à lire et très court (comparé aux autres langages). + +Vous pouvez exécuter modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. + +Sur la liste de lecteur des étudiants de Go se trouve le [code source de la +librairie standard](http://golang.org/src/pkg/). Bien documentée, elle démontre +le meilleur de la clarté de Go, le style ainsi que ses expressions. Sinon, vous +pouvez cliquer sur le nom d'une fonction dans [la +documentation](http://golang.org/pkg/) et le code source apparaît! + +Une autre excellente ressource pour apprendre est [Go par l'exemple](https://gobyexample.com/). -- cgit v1.2.3 From 290c0956d00ddfe23a8cad9ce17f2eaed3a099c0 Mon Sep 17 00:00:00 2001 From: Jean-Philippe Monette Date: Tue, 17 Mar 2015 20:29:01 +0000 Subject: updating translators information --- fr-fr/go-fr.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 1d2b656b..31e1e92b 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -2,7 +2,7 @@ name: Go category: language language: Go -filename: learngo.go +filename: learngo-fr.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] @@ -10,7 +10,9 @@ contributors: - ["Quint Guvernator", "https://github.com/qguv"] - ["Jose Donizetti", "https://github.com/josedonizetti"] - ["Alexej Friesen", "https://github.com/heyalexej"] +translators: - ["Jean-Philippe Monette", "http://blogue.jpmonette.net/"] +lang: fr-fr --- Go a été créé dans l'optique de déveloper de façcon efficace. Ce n'est pas la -- cgit v1.2.3 From 9922336a9df1359b57695bd5df538d98b8ab2dc0 Mon Sep 17 00:00:00 2001 From: Jean-Philippe Monette Date: Tue, 17 Mar 2015 23:17:50 +0000 Subject: Updating French translation Thanks vendethiel for all the suggestions! --- fr-fr/go-fr.html.markdown | 140 ++++++++++++++++++++++++---------------------- 1 file changed, 73 insertions(+), 67 deletions(-) diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 31e1e92b..2ff5902f 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -2,7 +2,7 @@ name: Go category: language language: Go -filename: learngo-fr.go +filename: learngo.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] @@ -10,21 +10,19 @@ contributors: - ["Quint Guvernator", "https://github.com/qguv"] - ["Jose Donizetti", "https://github.com/josedonizetti"] - ["Alexej Friesen", "https://github.com/heyalexej"] -translators: - ["Jean-Philippe Monette", "http://blogue.jpmonette.net/"] -lang: fr-fr --- -Go a été créé dans l'optique de déveloper de façcon efficace. Ce n'est pas la -dernière tendance en ce qui au développement, mais c'est la nouvelle façon de -régler des défis réels de façcon rapide. +Go a été créé dans l'optique de développer de façon efficace. Ce n'est pas la +dernière tendance en ce qui est au développement, mais c'est la nouvelle façon +de régler des défis réels de façon rapide. Le langage possède des concepts familiers à la programmation impérative avec typage. Il est rapide à compiler et exécuter, ajoute une concurrence facile à -comprendre pour les processeurs multi coeurs d'aujourd'hui et apporte des +comprendre, pour les processeurs multi coeurs d'aujourd'hui et apporte des fonctionnalités facilitant le développement à grande échelle. -Développer avec Go, c'est bénéficier d'une riche librairie standard et d'une +Développer avec Go, c'est bénéficier d'une riche bibliothèque standard et d'une communauté active. ```go @@ -34,22 +32,22 @@ communauté active. // Un paquet débute avec une clause "package" // "Main" est un nom spécial déclarant un paquet de type exécutable plutôt -// qu'une librairie +// qu'une bibliothèque package main // "Import" déclare les paquets référencés dans ce fichier. import ( - "fmt" // Un paquet dans la librairie standard. + "fmt" // Un paquet dans la bibliothèque standard. "io/ioutil" // Implémente des fonctions utilitaires I/O. - m "math" // Librairie mathématique utilisant un alias local "m". + m "math" // Bibliothèque mathématique utilisant un alias local "m". "net/http" // Un serveur Web! - "strconv" // Librairie pour convertir les chaînes de caractères. + "strconv" // Bibliothèque pour convertir les chaînes de caractères. ) // Une définition de fonction. La fonction "main" est spéciale - c'est le point -// d'entrée du binaire. Celle-ci est encapsulée par des accolades. +// d'entrée du binaire. func main() { - // Println retourne une ligne à stdout. + // Println retournera la valeur à la console. // Associez la fonction avec son paquet respectif, fmt. fmt.Println("Hello world!") @@ -78,7 +76,7 @@ func learnMultiple(x, y int) (sum, prod int) { // Quelques types inclus et littéraux. func learnTypes() { - // Déclaration courte produit généralement le type désiré. + // Une déclaration courte infère généralement le type désiré. str := "Learn Go!" // Type string. s2 := `Une chaîne de caractères peut contenir des @@ -89,7 +87,7 @@ sauts de ligne.` // Chaîne de caractère. // unicode. f := 3.14195 // float64, un nombre flottant IEEE-754 de 64-bit. - c := 3 + 4i // complex128, représenté à l'interne par deux float64. + c := 3 + 4i // complex128, considéré comme deux float64 par le compilateur. // Syntaxe "var" avec une valeur d'initialisation. var u uint = 7 // Non signé, mais la taille dépend selon l'entier. @@ -98,13 +96,13 @@ sauts de ligne.` // Chaîne de caractère. // Conversion avec syntaxe courte. n := byte('\n') // byte est un alias du type uint8. - // Les tableaux ont des tailles fixes à la compilation. + // Les tableaux ont une taille fixe déclarée à la compilation. var a4 [4]int // Un tableau de 4 ints, tous initialisés à 0. a3 := [...]int{3, 1, 5} // Un tableau initialisé avec une taille fixe de 3 // éléments, contenant les valeurs 3, 1 et 5. // Les slices ont des tailles dynamiques. Les tableaux et slices ont chacun - // des avantages, mais les usages des slices sont plus communs. + // des avantages, mais les cas d'utilisation des slices sont plus fréquents. s3 := []int{4, 5, 9} // Comparable à a3. s4 := make([]int, 4) // Alloue un slice de 4 ints, initialisés à 0. var d2 [][]float64 // Déclaration seulement, sans allocation de mémoire. @@ -114,13 +112,13 @@ sauts de ligne.` // Chaîne de caractère. // demande. Pour joindre un élément à une slice, la fonction standard append() // est utilisée. Le premier argument est la slice à utiliser. Habituellement, // la variable tableau est mise à jour sur place, voir ci-bas. - s := []int{1, 2, 3} // Le résultat est une slice de taille 3. + s := []int{1, 2, 3} // Le résultat est une slice de taille 3. s = append(s, 4, 5, 6) // Ajout de 3 valeurs. La taille est de 6. - fmt.Println(s) // La valeur est maintenant de [1 2 3 4 5 6] - // Pour ajouter une autre slice, au lieu d'utiliser une liste de valeurs + fmt.Println(s) // La valeur est de [1 2 3 4 5 6] + + // Pour ajouter une slice à une autre, au lieu d'utiliser une liste de valeurs // atomiques, il est possible de mettre en argument une référence de - // slice littérale de cette façon, avec des points de suspension, signifiant - // qu'il faut prendre les éléments de la slice et les ajouter à la slice s. + // slice littérale grâce aux points de suspension. s = append(s, []int{7, 8, 9}...) // Le deuxième argument est une slice // littérale. fmt.Println(s) // La slice contient [1 2 3 4 5 6 7 8 9] @@ -133,17 +131,19 @@ sauts de ligne.` // Chaîne de caractère. m := map[string]int{"trois": 3, "quatre": 4} m["un"] = 1 - // Les valeurs inutilisées sont des erreurs en Go. - // Un tiret bas permet d'utiliser une variable, mais d'en jeter la valeur. + // Les valeurs inutilisées sont considérées comme des erreurs en Go. + // Un tiret bas permet d'ignorer une valeur inutilisée, évitant une erreur. _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs - // L'affichage est considéré comme une utilisation de la variable. + + // Cependant, son affichage en console est considéré comme une utilisation, + // ce qui ne sera pas considéré comme une erreur à la compilation. fmt.Println(s, c, a4, s3, d2, m) learnFlowControl() // De retour dans le flux. } -// Il est possible, à l'opposée de plusieurs autres langages, à des fonctions -// en go d'avoir des valeurs retournées avec nom. +// Il est possible, à l'opposé de plusieurs autres langages, de retourner des +// variables par leur nom à partir de fonctions. // Assigner un nom à un type retourné par une fonction permet de retrouver sa // valeur ainsi que d'utiliser le mot-clé "return" uniquement, sans plus. func learnNamedReturns(x, y int) (z int) { @@ -152,10 +152,11 @@ func learnNamedReturns(x, y int) (z int) { } // La récupération de la mémoire est automatique en Go. Le langage possède des -// pointeurs, mais aucun pointeur arithmétique. Vous pouvez faire une erreur -// avec un pointeur nil, mais pas en incrémentant un pointeur. +// pointeurs, mais aucune arithmétique des pointeurs (*(a + b) en C). Vous +// pouvez produire une erreur avec un pointeur nil, mais pas en incrémentant un +// pointeur. func learnMemory() (p, q *int) { - // Les valeurs retournées définies p et q ont le type pointeur int. + // Les valeurs retournées p et q auront le type pointeur int. p = new(int) // Fonction standard "new" alloue la mémoire. // Le int alloué est initialisé à 0, p n'est plus nil. s := make([]int, 20) // Alloue 20 ints en un seul bloc de mémoire. @@ -169,11 +170,12 @@ func expensiveComputation() float64 { } func learnFlowControl() { - // Bien que les "if" requiert des accolades, les parenthèses ne le sont pas. + // Bien que les "if" requièrent des accolades, les parenthèses ne sont pas + // nécessaires pour contenir le test booléen. if true { fmt.Println("voilà!") } - // Le formate est standardisé par la commande shell "go fmt." + // Le formatage du code est standardisé par la commande shell "go fmt." if false { // bing. } else { @@ -189,8 +191,9 @@ func learnFlowControl() { case 43: // Non-exécuté. } - // Comme les "if", "for" n'utilise pas de parenthèses. - // Les variables déclarées dans "for" et "if" sont locales à leur portée. + // Comme les "if", les "for" n'utilisent pas de parenthèses. + // Les variables déclarées dans les "for" et les "if" sont locales à leur + // portée. for x := 0; x < 3; x++ { // ++ est une incrémentation. fmt.Println("itération ", x) } @@ -202,8 +205,8 @@ func learnFlowControl() { continue // Non atteint. } - // Vous pouvez utiliser un "range" pour itérer dans un tableau, une slice, une - // chaîne, une map ou un channel. Les "range" retournent un canal ou deux + // Vous pouvez utiliser une "range" pour itérer dans un tableau, une slice, une + // chaîne, une map ou un canal. Les "range" retournent un canal ou deux // valeurs (tableau, slice, chaîne et map). for key, value := range map[string]int{"une": 1, "deux": 2, "trois": 3} { // pour chaque pair dans une map, affichage de la valeur et clé @@ -215,35 +218,35 @@ func learnFlowControl() { if y := expensiveComputation(); y > x { x = y } - // Les fonctions littérales est une fermeture (closure). + // Les fonctions littérales sont des fermetures. xBig := func() bool { - return x > 10000 // Réfère à la variable x déclarée en haut du "switch". + return x > 10000 } fmt.Println("xBig:", xBig()) // true (la valeur e^10 a été assignée à x). x = 1.3e3 // Ceci fait x == 1300 fmt.Println("xBig:", xBig()) // Maintenant false. - // De plus, les fonctions littérales peuvent être définies et appelée - // sur la même ligne, agissant comme argument de fonctions, tant que: + // De plus, les fonctions littérales peuvent être définies et appelées + // sur la même ligne, agissant comme argument à cette fonction, tant que: // a) la fonction littérale est appelée suite à (), // b) le résultat correspond au type de l'argument. - fmt.Println("Ajoute + multiplie deux nombres: ", + fmt.Println("Ajoute + multiplie deux nombres : ", func(a, b int) int { return (a + b) * 2 - }(10, 2)) // Appelé avec les arguments 10 et 2 - // => Ajoute + double deux nombres: 24 + }(10, 2)) // Appelle la fonction avec les arguments 10 et 2 + // => Ajoute + double deux nombres : 24 // Quand vous en aurez besoin, vous allez l'adorer. goto love love: - learnFunctionFactory() // func retournant func correspond à fun(3)(3). - learnDefer() // Un survol de cette instruction important. - learnInterfaces() // Incontournable! + learnFunctionFactory() // func retournant func correspondant à fun(3)(3). + learnDefer() // Un survol de cette instruction importante. + learnInterfaces() // Incontournable ! } func learnFunctionFactory() { - // Les deux syntaxes sont identiques, bien que la seconde est plus pratique. + // Les deux syntaxes sont identiques, bien que la seconde soit plus pratique. fmt.Println(sentenceFactory("été")("Une matinée d'", "agréable!")) d := sentenceFactory("été") @@ -287,12 +290,12 @@ func (p pair) String() string { // p s'appelle le "destinataire" } func learnInterfaces() { - // La syntaxe avec accolade défini une "structure littérale". Ceci s'évalue - // comme étant une strucutre. La syntaxe := déclare et initialise p comme - // étant cette structure. + // La syntaxe avec accolade défini une "structure littérale". Celle-ci + // s'évalue comme étant une structure. La syntaxe := déclare et initialise p + // comme étant une instance. p := pair{3, 4} fmt.Println(p.String()) // Appelle la méthode String de p, de type pair. - var i Stringer // Déclare i de l'interface de type Stringer. + var i Stringer // Déclare i instance de l'interface Stringer. i = p // Valide, car pair implémente Stringer. // Appelle la méthode String de i, de type Stringer. Retourne la même valeur // que ci-haut. @@ -307,9 +310,11 @@ func learnInterfaces() { learnVariadicParams("apprentissage", "génial", "ici!") } -// Les fonctions peuvent avoir des paramètres variables. +// Les fonctions peuvent être définie de façon à accepter un ou plusieurs +// paramètres grâce aux points de suspension, offrant une flexibilité lors de +// son appel. func learnVariadicParams(myStrings ...interface{}) { - // Itère chaque valeur du paramètre variable. + // Itère chaque paramètre dans la range. // Le tiret bas sert à ignorer l'index retourné du tableau. for _, param := range myStrings { fmt.Println("paramètre:", param) @@ -322,8 +327,8 @@ func learnVariadicParams(myStrings ...interface{}) { } func learnErrorHandling() { - // ", ok" expression utilisée pour définir si quelque chose a fonctionné ou - // non. + // ", ok" idiome utilisée pour définir si l'opération s'est déroulée avec + // succès ou non m := map[int]string{3: "trois", 4: "quatre"} if x, ok := m[1]; !ok { // ok sera faux, car 1 n'est pas dans la map. fmt.Println("inexistant") @@ -336,14 +341,14 @@ func learnErrorHandling() { // retourne: 'strconv.ParseInt: parsing "non-int": invalid syntax' fmt.Println(err) } - // Nous réviserons les interfaces un peu plus tard. Maintenant, + // Nous réviserons les interfaces un peu plus tard. Pour l'instant, learnConcurrency() } // c est un canal, un objet permettant de communiquer en simultané de façon -// sécuritaire. +// sécurisée. func inc(i int, c chan int) { - c <- i + 1 // <- est l'opérateur "destination" quand un canal apparaît à + c <- i + 1 // <- est l'opérateur "envoi" quand un canal apparaît à // gauche. } @@ -355,11 +360,11 @@ func learnConcurrency() { // Démarrage de trois goroutines simultanées. Les nombres seront incrémentés // simultanément, peut-être en paralèle si la machine le permet et configurée // correctement. Les trois utilisent le même canal. - go inc(0, c) // go est une déclaration démarrant une nouvelle goroutine. + go inc(0, c) // go est une instruction démarrant une nouvelle goroutine. go inc(10, c) go inc(-805, c) // Lis et affiche trois résultats du canal - impossible de savoir dans quel - // ordre! + // ordre ! fmt.Println(<-c, <-c, <-c) // Canal à droite, <- est l'opérateur de // "réception". @@ -374,13 +379,13 @@ func learnConcurrency() { select { case i := <-c: // La valeur reçue peut être assignée à une variable, fmt.Printf("c'est un %T", i) - case <-cs: // ou la valeur reçue peut être discartée. + case <-cs: // ou la valeur reçue peut être ignorée. fmt.Println("c'est une chaîne") case <-ccs: // Un canal vide, indisponible à la communication. fmt.Println("ne surviendra pas.") } // À ce point, une valeur a été prise de c ou cs. L'une des deux goroutines - // démarrée plus haut a complété, la seconde restera bloquée. + // démarrée plus haut a complétée, la seconde restera bloquée. learnWebProgramming() // Go permet la programmation Web. } @@ -388,17 +393,18 @@ func learnConcurrency() { // Une seule fonction du paquet http démarre un serveur Web. func learnWebProgramming() { - // Le premier paramètre de ListenAndServe is une adresse TCP à écouter. + // Le premier paramètre de ListenAndServe est une adresse TCP à écouter. // Le second est une interface, de type http.Handler. go func() { err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // n'ignorez pas les erreurs! + fmt.Println(err) // n'ignorez pas les erreurs ! }() requestServer() } -// Fait de pair un http.Handler en implémentant sa seule méthode: ServeHTTP. +// Implémente la méthode ServeHTTP de http.Handler à pair, la rendant compatible +// avec les opérations utilisant l'interface http.Handler. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Répondez à une requête à l'aide de la méthode http.ResponseWriter. w.Write([]byte("Vous avez appris Go en Y minutes!")) @@ -421,7 +427,7 @@ Vous pourrez y suivre le tutoriel interactif et en apprendre beaucoup plus. Une lecture de la documentation du langage est grandement conseillée. C'est facile à lire et très court (comparé aux autres langages). -Vous pouvez exécuter modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. +Vous pouvez exécuter et modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. Sur la liste de lecteur des étudiants de Go se trouve le [code source de la librairie standard](http://golang.org/src/pkg/). Bien documentée, elle démontre -- cgit v1.2.3 From cfb4d5922d485f68b9ed3ba7a9e2f1add14cba3c Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Thu, 19 Mar 2015 00:31:33 +0800 Subject: Complete most parts of translation. --- zh-cn/c++-cn.html.markdown | 92 ++++++++++++++++++++++++++-------------------- 1 file changed, 53 insertions(+), 39 deletions(-) diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index 9a952d85..24d2a1b8 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -167,9 +167,9 @@ int main() // 輸入/輸出 //////////// -// C++使用「流」來輸入輸出。 -// cin、cout、和cerr分別代表stdin(標準輸入)、stdout(標準輸出)和stderr(標準錯誤)。 -// <<是流的插入運算符,>>是流提取運算符。 +// C++使用「流」來輸入輸出。<<是流的插入運算符,>>是流提取運算符。 +// cin、cout、和cerr分別代表 +// stdin(標準輸入)、stdout(標準輸出)和stderr(標準錯誤)。 #include // 引入包含輸入/輸出流的頭文件 @@ -237,9 +237,9 @@ cout << fooRef; // "I am foo. Hi!" // 也就是說,在執行這條語句之後,foo == "I am bar"。 fooRef = bar; -const string& barRef = bar; // 建立指向bar的【const ref】。 -// 和C語言中一樣,聲明爲常數的值(包括指針和引用)不能被修改。 -barRef += ". Hi!"; // 這是錯誤的,【const ref】不能被修改。 +const string& barRef = bar; // 建立指向bar的常量引用。 +// 和C語言中一樣,(指針和引用)聲明爲常量時,對應的值不能被修改。 +barRef += ". Hi!"; // 這是錯誤的,不能修改一個常量引用的值。 /////////////////// // 類與面向對象編程 @@ -262,21 +262,19 @@ public: // 默認的構造器 Dog(); - // 【Member function declarations (implementations to follow) - // Note that we use std::string here instead of placing - // using namespace std; - // above. - // Never put a "using namespace" statement in a header. + // 這裏是成員函數聲明的一個例子。 + // 可以注意到,我們在此處使用了std::string,而不是using namespace std + // 語句using namespace絕不應當出現在頭文件當中。 void setName(const std::string& dogsName); void setWeight(int dogsWeight); - // 【Functions that do not modify the state of the object - // should be marked as const. - // This allows you to call them if given a const reference to the object. - // Also note the functions must be explicitly declared as _virtual_ - // in order to be overridden in derived classes. - // Functions are not virtual by default for performance reasons. + // 如果一個函數不對對象的狀態進行修改, + // 應當在聲明中加上const。 + // 這樣,你就可以對一個以常量方式引用的對象執行該操作。 + // 同時可以注意到,當父類的成員函數需要被子類重寫時, + // 父類中的函數必須被顯式聲明爲_虛函數(virtual)_。 + // 考慮到性能方面的因素,函數默認情況下不會被聲明爲虛函數。 virtual void print() const; // 函數也可以在class body內部定義。 @@ -284,13 +282,15 @@ public: void bark() const { std::cout << name << " barks!\n" } // 除了構造器以外,C++還提供了析構器。 - // 當一個對象被刪除或者【falls out of scope】時,它的析構器會被調用。 + // 當一個對象被刪除或者脫離其定義域時時,它的析構函數會被調用。 // 這使得RAII這樣的強大範式(參見下文)成爲可能。 - // 析構器【must be virtual to allow classes to be derived from this one. + // 爲了衍生出子類來,基類的析構函數必須定義爲虛函數。 virtual ~Dog(); }; // 在類的定義之後,要加一個分號 +}; // 記住,在類的定義之後,要加一個分號! + // 類的成員函數通常在.cpp文件中實現。 void Dog::Dog() { @@ -298,7 +298,7 @@ void Dog::Dog() } // 對象(例如字符串)應當以引用的形式傳遞, -// 不需要修改的對象則應當作爲【const ref】。 +// 對於不需要修改的對象,最好使用常量引用。 void Dog::setName(const std::string& dogsName) { name = dogsName; @@ -309,7 +309,23 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// 【Notice that "virtual" is only needed in the declaration, not the definition. +// 虛函數的virtual關鍵字只需要在聲明時使用,不需要在定義時出現 +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +void Dog::~Dog() +{ + cout << "Goodbye " << name << "\n"; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// 虛函數的virtual關鍵字只需要在聲明時使用,不需要在定義時重複 void Dog::print() const { std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; @@ -427,17 +443,17 @@ int main () { // 異常處理 /////////// -// 標準庫中提供了a few exception types +// 標準庫中提供了一些基本的異常類型 // (參見http://en.cppreference.com/w/cpp/error/exception) -// 【but any type can be thrown an as exception +// 但是,其他任何類型也可以作爲一個異常被拋出 #include // 在_try_代碼塊中拋出的異常可以被隨後的_catch_捕獲。 try { - // 【Do not allocate exceptions on the heap using _new_. + // 不要用 _new_關鍵字在堆上爲異常分配空間。 throw std::exception("A problem occurred"); } -// 【Catch exceptions by const reference if they are objects +// 如果拋出的異常是一個對象,可以用常量引用來捕獲它 catch (const std::exception& ex) { std::cout << ex.what(); @@ -452,10 +468,10 @@ catch (const std::exception& ex) // RAII /////// -// RAII指的是「资源获取就是初始化」(Resource Allocation Is Initialization)。 -// 【It is often considered the most powerful paradigm in C++, -// and is the simple concept that a constructor for an object -// acquires that object's resources and the destructor releases them. +// RAII指的是「资源获取就是初始化」(Resource Allocation Is Initialization), +// 它被視作C++中最強大的編程範式之一。 +// 簡單說來,它指的是,用構造函數來獲取一個對象的資源, +// 相應的,借助析構函數來釋放對象的資源。 // 爲了理解這一範式的用處,讓我們考慮某個函數使用文件句柄時的情況: void doSomethingWithAFile(const char* filename) @@ -517,8 +533,8 @@ failure: return false; // 反饋錯誤 } -// 【If the functions indicate errors using exceptions, -// things are a little cleaner, but still sub-optimal. +// 如果用異常捕獲機制來指示錯誤的話, +// 代碼會變得清晰一些,但是仍然有優化的餘地。 void doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 @@ -556,17 +572,15 @@ void doSomethingWithAFile(const std::string& filename) // 與上面幾種方式相比,這種方式有着_明顯_的優勢: // 1. 無論發生了什麼情況,資源(此例當中是文件句柄)都會被正確關閉。 // 只要你正確使用了析構器,就_不會_因爲忘記關閉句柄,造成資源的泄漏。 -// 2. 【Note that the code is much cleaner. -// The destructor handles closing the file behind the scenes -// without you having to worry about it. +// 2. 可以注意到,通過這種方式寫出來的代碼十分簡潔。 +// 析構器會在後臺關閉文件句柄,不再需要你來操心這些瑣事。 // 3. 【The code is exception safe. -// An exception can be thrown anywhere in the function and cleanup -// will still occur. +// 無論在函數中的何處拋出異常,都不會阻礙對文件資源的釋放。 -// 地道的C++代碼應當把RAII的使用擴展到所有類型的資源上,包括: +// 地道的C++代碼應當把RAII的使用擴展到各種類型的資源上,包括: // - 用unique_ptr和shared_ptr管理的內存 -// - 容器,例如標準庫中的鏈表、向量(容量自動擴展的數組)、散列表等; -// 【all automatically destroy their contents when they fall out of scope. +// - 各種數據容器,例如標準庫中的鏈表、向量(容量自動擴展的數組)、散列表等; +// 當它們脫離作用域時,析構器會自動釋放其中儲存的內容。 // - 用lock_guard和unique_lock實現的互斥 ``` 擴展閱讀: -- cgit v1.2.3 From cfe726561dd27cf74aaf966eae4cf6f5b5556812 Mon Sep 17 00:00:00 2001 From: yukirock Date: Thu, 19 Mar 2015 18:36:10 +1100 Subject: Improve zh-ch translation. --- zh-cn/haskell-cn.html.markdown | 234 ++++++++++++++++++++--------------------- 1 file changed, 116 insertions(+), 118 deletions(-) diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index cb7ccdee..fae8a456 100644 --- a/zh-cn/haskell-cn.html.markdown +++ b/zh-cn/haskell-cn.html.markdown @@ -5,24 +5,24 @@ contributors: - ["Adit Bhargava", "http://adit.io"] translators: - ["Peiyong Lin", ""] + - ["chad luo", "http://yuki.rocks"] lang: zh-cn --- -Haskell 被设计成一种实用的纯函数式编程语言。它因为 monads 及其类型系统而出名,但是我回归到它本身因为。Haskell 使得编程对于我而言是一种真正的快乐。 +Haskell 是一门实用的函数式编程语言,因其 Monads 与类型系统而闻名。而我使用它则是因为它异常优雅。用 Haskell 编程令我感到非常快乐。 ```haskell --- 单行注释以两个破折号开头 -{- 多行注释像这样 - 被一个闭合的块包围 +-- 单行注释以两个减号开头 +{- 多行注释像这样被一个闭合的块包围 -} ---------------------------------------------------- -- 1. 简单的数据类型和操作符 ---------------------------------------------------- --- 你有数字 +-- 数字 3 -- 3 --- 数学计算就像你所期待的那样 +-- 数学计算 1 + 1 -- 2 8 - 1 -- 7 10 * 2 -- 20 @@ -34,7 +34,7 @@ Haskell 被设计成一种实用的纯函数式编程语言。它因为 monads -- 整除 35 `div` 4 -- 8 --- 布尔值也简单 +-- 布尔值 True False @@ -45,73 +45,80 @@ not False -- True 1 /= 1 -- False 1 < 10 -- True --- 在上述的例子中,`not` 是一个接受一个值的函数。 --- Haskell 不需要括号来调用函数。。。所有的参数 --- 都只是在函数名之后列出来。因此,通常的函数调用模式是: +-- 在上面的例子中,`not` 是一个接受一个参数的函数。 +-- Haskell 不需要括号来调用函数。所有的参数都只是在函数名之后列出来。 +-- 因此,通常的函数调用模式是: -- func arg1 arg2 arg3... --- 查看关于函数的章节以获得如何写你自己的函数的相关信息。 +-- 你可以查看函数部分了解如何自行编写。 -- 字符串和字符 -"This is a string." +"This is a string." -- 字符串 'a' -- 字符 '对于字符串你不能使用单引号。' -- 错误! --- 连结字符串 +-- 连接字符串 "Hello " ++ "world!" -- "Hello world!" -- 一个字符串是一系列字符 +['H', 'e', 'l', 'l', 'o'] -- "Hello" "This is a string" !! 0 -- 'T' ---------------------------------------------------- --- 列表和元组 +-- 数组和元组 ---------------------------------------------------- --- 一个列表中的每一个元素都必须是相同的类型 --- 下面两个列表一样 +-- 一个数组中的每一个元素都必须是相同的类型 +-- 下面两个数组等价: [1, 2, 3, 4, 5] [1..5] --- 在 Haskell 你可以拥有含有无限元素的列表 -[1..] -- 一个含有所有自然数的列表 +-- 区间也可以这样 +['A'..'F'] -- "ABCDEF" --- 因为 Haskell 有“懒惰计算”,所以无限元素的列表可以正常运作。这意味着 --- Haskell 可以只在它需要的时候计算。所以你可以请求 --- 列表中的第1000个元素,Haskell 会返回给你 +-- 你可以在区间中指定步进 +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- 这样不行,因为 Haskell 默认递增 +[5,4..1] -- [5, 4, 3, 2, 1] + +-- 数组下标 +[0..] !! 5 -- 5 + +-- 在 Haskell 你可以使用无限数组 +[1..] -- 一个含有所有自然数的数组 + +-- 无限数组的原理是,Haskell 有“惰性求值”。 +-- 这意味着 Haskell 只在需要时才会计算。 +-- 所以当你获取数组的第 1000 项元素时,Haskell 会返回给你: [1..] !! 999 -- 1000 --- Haskell 计算了列表中 1 - 1000 个元素。。。但是 --- 这个无限元素的列表中剩下的元素还不存在! Haskell 不会 --- 真正地计算它们知道它需要。 +-- Haskell 计算了数组中第 1 至 1000 项元素,但这个无限数组中剩下的元素还不存在。 +-- Haskell 只有在需要时才会计算它们。 -- 连接两个列表 +-- 连接两个数组 [1..5] ++ [6..10] --- 往列表头增加元素 +-- 往数组头增加元素 0:[1..5] -- [0, 1, 2, 3, 4, 5] --- 列表中的下标 -[0..] !! 5 -- 5 - --- 更多列表操作 +-- 其它数组操作 head [1..5] -- 1 tail [1..5] -- [2, 3, 4, 5] init [1..5] -- [1, 2, 3, 4] last [1..5] -- 5 --- 列表推导 +-- 数组推导 [x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] -- 附带条件 [x*2 | x <-[1..5], x*2 > 4] -- [6, 8, 10] --- 元组中的每一个元素可以是不同类型的,但是一个元组 --- 的长度是固定的 +-- 元组中的每一个元素可以是不同类型,但是一个元组的长度是固定的 -- 一个元组 ("haskell", 1) --- 获取元组中的元素 +-- 获取元组中的元素(例如,一个含有 2 个元素的元祖) fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 @@ -121,31 +128,28 @@ snd ("haskell", 1) -- 1 -- 一个接受两个变量的简单函数 add a b = a + b --- 注意,如果你使用 ghci (Hakell 解释器) --- 你将需要使用 `let`,也就是 +-- 注意,如果你使用 ghci (Hakell 解释器),你需要使用 `let`,也就是 -- let add a b = a + b --- 使用函数 +-- 调用函数 add 1 2 -- 3 --- 你也可以把函数放置在两个参数之间 --- 附带倒引号: +-- 你也可以使用反引号中置函数名: 1 `add` 2 -- 3 --- 你也可以定义不带字符的函数!这使得 --- 你定义自己的操作符!这里有一个操作符 --- 来做整除 +-- 你也可以定义不带字母的函数名,这样你可以定义自己的操作符 +-- 这里有一个做整除的操作符 (//) a b = a `div` b 35 // 4 -- 8 --- 守卫:一个简单的方法在函数里做分支 +-- Guard:一个在函数中做条件判断的简单方法 fib x | x < 2 = x | otherwise = fib (x - 1) + fib (x - 2) --- 模式匹配是类型的。这里有三种不同的 fib --- 定义。Haskell 将自动调用第一个 --- 匹配值的模式的函数。 +-- 模式匹配与 Guard 类似 +-- 这里给出了三个不同的 fib 定义 +-- Haskell 会自动调用第一个符合参数模式的声明 fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) @@ -153,76 +157,76 @@ fib x = fib (x - 1) + fib (x - 2) -- 元组的模式匹配: foo (x, y) = (x + 1, y + 2) --- 列表的模式匹配。这里 `x` 是列表中第一个元素, --- 并且 `xs` 是列表剩余的部分。我们可以写 --- 自己的 map 函数: +-- 数组的模式匹配 +-- 这里 `x` 是列表中第一个元素,`xs` 是列表剩余的部分 +-- 我们可以实现自己的 map 函数: myMap func [] = [] myMap func (x:xs) = func x:(myMap func xs) --- 编写出来的匿名函数带有一个反斜杠,后面跟着 --- 所有的参数。 +-- 匿名函数带有一个反斜杠,后面跟着所有的参数。 myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] --- 使用 fold (在一些语言称为`inject`)随着一个匿名的 --- 函数。foldl1 意味着左折叠(fold left), 并且使用列表中第一个值 --- 作为累加器的初始化值。 +-- 在 fold(在一些语言称 为`inject`)中使用匿名函数 +-- foldl1 意味着左折叠 (fold left), 并且使用列表中第一个值作为累加器的初始值 foldl1 (\acc x -> acc + x) [1..5] -- 15 ---------------------------------------------------- --- 4. 更多的函数 +-- 4. 其它函数 ---------------------------------------------------- --- 柯里化(currying):如果你不传递函数中所有的参数, --- 它就变成“柯里化的”。这意味着,它返回一个接受剩余参数的函数。 - +-- 部分调用: +-- 如果你调用函数时没有给出所有参数,它就被“部分调用” +-- 它将返回一个接受余下参数的函数 add a b = a + b foo = add 10 -- foo 现在是一个接受一个数并对其加 10 的函数 foo 5 -- 15 --- 另外一种方式去做同样的事 +-- 另一种等价写法 foo = (+10) foo 5 -- 15 -- 函数组合 -- (.) 函数把其它函数链接到一起 --- 举个列子,这里 foo 是一个接受一个值的函数。它对接受的值加 10, --- 并对结果乘以 5,之后返回最后的值。 +-- 例如,这里 foo 是一个接受一个值的函数。 +-- 它对接受的值加 10,并对结果乘以 5,之后返回最后的值。 foo = (*5) . (+10) -- (5 + 10) * 5 = 75 foo 5 -- 75 --- 修复优先级 --- Haskell 有另外一个函数称为 `$`。它改变优先级 --- 使得其左侧的每一个操作先计算然后应用到 --- 右侧的每一个操作。你可以使用 `.` 和 `$` 来除去很多 --- 括号: +-- 修正优先级 +-- Haskell 有另外一个函数 `$` 可以改变优先级 +-- `$` 使得 Haskell 先计算其右边的部分,然后调用左边的部分 +-- 你可以使用 `$` 来移除多余的括号 --- before +-- 修改前 (even (fib 7)) -- true --- after +-- 修改后 even . fib $ 7 -- true +-- 等价地 +even $ fib 7 -- true + ---------------------------------------------------- --- 5. 类型签名 +-- 5. 类型声明 ---------------------------------------------------- --- Haskell 有一个非常强壮的类型系统,一切都有一个类型签名。 +-- Haskell 有一个非常强大的类型系统,一切都有一个类型声明。 -- 一些基本的类型: 5 :: Integer "hello" :: String True :: Bool --- 函数也有类型。 +-- 函数也有类型 -- `not` 接受一个布尔型返回一个布尔型: -- not :: Bool -> Bool -- 这是接受两个参数的函数: -- add :: Integer -> Integer -> Integer --- 当你定义一个值,在其上写明它的类型是一个好实践: +-- 当你定义一个值,声明其类型是一个好做法: double :: Integer -> Integer double x = x * 2 @@ -230,29 +234,30 @@ double x = x * 2 -- 6. 控制流和 If 语句 ---------------------------------------------------- --- if 语句 +-- if 语句: haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" --- if 语句也可以有多行,缩进是很重要的 +-- if 语句也可以有多行,注意缩进: haskell = if 1 == 1 then "awesome" else "awful" --- case 语句:这里是你可以怎样去解析命令行参数 +-- case 语句 +-- 解析命令行参数: case args of "help" -> printHelp "start" -> startProgram _ -> putStrLn "bad args" --- Haskell 没有循环因为它使用递归取代之。 --- map 应用一个函数到一个数组中的每一个元素 +-- Haskell 没有循环,它使用递归 +-- map 对一个数组中的每一个元素调用一个函数: map (*2) [1..5] -- [2, 4, 6, 8, 10] --- 你可以使用 map 来编写 for 函数 +-- 你可以使用 map 来编写 for 函数: for array func = map func array --- 然后使用它 +-- 调用: for [0..5] $ \i -> show i -- 我们也可以像这样写: @@ -262,36 +267,32 @@ for [0..5] show -- foldl foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 --- 这和下面是一样的 +-- 等价于: (2 * (2 * (2 * 4 + 1) + 2) + 3) --- foldl 是左手边的,foldr 是右手边的- +-- foldl 从左开始,foldr 从右: foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 --- 这和下面是一样的 +-- 现在它等价于: (2 * 3 + (2 * 2 + (2 * 1 + 4))) ---------------------------------------------------- -- 7. 数据类型 ---------------------------------------------------- --- 这里展示在 Haskell 中你怎样编写自己的数据类型 - +-- 在 Haskell 中声明你自己的数据类型: data Color = Red | Blue | Green -- 现在你可以在函数中使用它: - - say :: Color -> String say Red = "You are Red!" say Blue = "You are Blue!" say Green = "You are Green!" -- 你的数据类型也可以有参数: - data Maybe a = Nothing | Just a --- 类型 Maybe 的所有 +-- 这些都是 Maybe 类型: Just "hello" -- of type `Maybe String` Just 1 -- of type `Maybe Int` Nothing -- of type `Maybe a` for any `a` @@ -300,58 +301,54 @@ Nothing -- of type `Maybe a` for any `a` -- 8. Haskell IO ---------------------------------------------------- --- 虽然在没有解释 monads 的情况下 IO不能被完全地解释, --- 着手解释到位并不难。 - --- 当一个 Haskell 程序被执行,函数 `main` 就被调用。 --- 它必须返回一个类型 `IO ()` 的值。举个列子: +-- 虽然不解释 Monads 就无法完全解释 IO,但大致了解并不难。 +-- 当执行一个 Haskell 程序时,函数 `main` 就被调用。 +-- 它必须返回一个类型 `IO ()` 的值。例如: main :: IO () main = putStrLn $ "Hello, sky! " ++ (say Blue) --- putStrLn has type String -> IO () +-- putStrLn 的类型是 String -> IO () --- 如果你能实现你的程序依照函数从 String 到 String,那样编写 IO 是最简单的。 +-- 如果你的程序输入 String 返回 String,那样编写 IO 是最简单的。 -- 函数 -- interact :: (String -> String) -> IO () --- 输入一些文本,在其上运行一个函数,并打印出输出 +-- 输入一些文本,对其调用一个函数,并打印输出。 countLines :: String -> String countLines = show . length . lines main' = interact countLines --- 你可以考虑一个 `IO()` 类型的值,当做一系列计算机所完成的动作的代表, --- 就像一个以命令式语言编写的计算机程序。我们可以使用 `do` 符号来把动作链接到一起。 +-- 你可以认为一个 `IO ()` 类型的值是表示计算机做的一系列操作,类似命令式语言。 +-- 我们可以使用 `do` 声明来把动作连接到一起。 -- 举个列子: - sayHello :: IO () sayHello = do putStrLn "What is your name?" - name <- getLine -- this gets a line and gives it the name "input" + name <- getLine -- 这里接受一行输入并绑定至 "name" putStrLn $ "Hello, " ++ name -- 练习:编写只读取一行输入的 `interact` -- 然而,`sayHello` 中的代码将不会被执行。唯一被执行的动作是 `main` 的值。 --- 为了运行 `sayHello`,注释上面 `main` 的定义,并代替它: +-- 为了运行 `sayHello`,注释上面 `main` 的定义,替换为: -- main = sayHello --- 让我们来更好地理解刚才所使用的函数 `getLine` 是怎样工作的。它的类型是: +-- 让我们来更进一步理解刚才所使用的函数 `getLine` 是怎样工作的。它的类型是: -- getLine :: IO String --- 你可以考虑一个 `IO a` 类型的值,代表一个当被执行的时候 --- 将产生一个 `a` 类型的值的计算机程序(除了它所做的任何事之外)。我们可以保存和重用这个值通过 `<-`。 --- 我们也可以写自己的 `IO String` 类型的动作: - +-- 你可以认为一个 `IO a` 类型的值代表了一个运行时会生成一个 `a` 类型值的程序(可能还有其它行为)。 +-- 我们可以通过 `<-` 保存和重用这个值。 +-- 我们也可以实现自己的 `IO String` 类型函数: action :: IO String action = do putStrLn "This is a line. Duh" input1 <- getLine input2 <- getLine - -- The type of the `do` statement is that of its last line. - -- `return` is not a keyword, but merely a function + -- `do` 语句的类型是它的最后一行 + -- `return` 不是关键字,只是一个普通函数 return (input1 ++ "\n" ++ input2) -- return :: String -> IO String --- 我们可以使用这个动作就像我们使用 `getLine`: +-- 我们可以像调用 `getLine` 一样调用它: main'' = do putStrLn "I will echo two lines!" @@ -359,18 +356,19 @@ main'' = do putStrLn result putStrLn "This was all, folks!" --- `IO` 类型是一个 "monad" 的例子。Haskell 使用一个 monad 来做 IO的方式允许它是一门纯函数式语言。 --- 任何与外界交互的函数(也就是 IO) 都在它的类型签名处做一个 `IO` 标志 --- 着让我们推出 什么样的函数是“纯洁的”(不与外界交互,不修改状态) 和 什么样的函数不是 “纯洁的” +-- `IO` 类型是一个 "Monad" 的例子。 +-- Haskell 通过使用 Monad 使得其本身为纯函数式语言。 +-- 任何与外界交互的函数(即 IO)都在它的类型声明中标记为 `IO` +-- 这告诉我们什么样的函数是“纯洁的”(不与外界交互,不修改状态) ,什么样的函数不是 “纯洁的” --- 这是一个强有力的特征,因为并发地运行纯函数是简单的;因此,Haskell 中并发是非常简单的。 +-- 这个功能非常强大,因为纯函数并发非常容易,由此在 Haskell 中做并发非常容易。 ---------------------------------------------------- --- 9. The Haskell REPL +-- 9. Haskell REPL ---------------------------------------------------- --- 键入 `ghci` 开始 repl。 +-- 键入 `ghci` 开始 REPL。 -- 现在你可以键入 Haskell 代码。 -- 任何新值都需要通过 `let` 来创建: @@ -390,7 +388,7 @@ Hello, Friend! ``` -还有很多关于 Haskell,包括类型类和 monads。这些是使得编码 Haskell 是如此有趣的主意。我用一个最后的 Haskell 例子来结束:一个 Haskell 的快排实现: +Haskell 还有许多内容,包括类型类 (typeclasses) 与 Monads。这些都是令 Haskell 编程非常有趣的好东西。我们最后给出 Haskell 的一个例子,一个快速排序的实现: ```haskell qsort [] = [] @@ -399,9 +397,9 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater greater = filter (>= p) xs ``` -安装 Haskell 是简单的。你可以从[这里](http://www.haskell.org/platform/)获得它。 +安装 Haskell 很简单。你可以[从这里获得](http://www.haskell.org/platform/)。 你可以从优秀的 [Learn you a Haskell](http://learnyouahaskell.com/) 或者 [Real World Haskell](http://book.realworldhaskell.org/) -找到优雅不少的入门介绍。 +找到更平缓的入门介绍。 -- cgit v1.2.3 From 1b1d10e2d9b7493039382f0f6020e82d317d0c52 Mon Sep 17 00:00:00 2001 From: Rahil Momin Date: Thu, 19 Mar 2015 15:37:42 +0530 Subject: add include? method on arrays --- ruby.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 1883d1ad..800f0445 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -169,6 +169,9 @@ array[1..3] #=> [2, 3, 4] # Add to an array like this array << 6 #=> [1, 2, 3, 4, 5, 6] +# Check if an item exists in an array +array.include?(1) #=> true + # Hashes are Ruby's primary dictionary with keys/value pairs. # Hashes are denoted with curly braces: hash = { 'color' => 'green', 'number' => 5 } -- cgit v1.2.3 From 37c00223d013da83d847767fbab6a3c4f960ad1a Mon Sep 17 00:00:00 2001 From: Rahil Momin Date: Thu, 19 Mar 2015 15:38:16 +0530 Subject: add has_key? and has_value? methods on hashes --- ruby.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 800f0445..8c9d8fc5 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -191,6 +191,10 @@ new_hash = { defcon: 3, action: true } new_hash.keys #=> [:defcon, :action] +# Check existence of keys and values in hash +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true + # Tip: Both Arrays and Hashes are Enumerable # They share a lot of useful methods such as each, map, count, and more -- cgit v1.2.3 From 1246edea3f83063b24c97240a10246025831843d Mon Sep 17 00:00:00 2001 From: Rahil Momin Date: Thu, 19 Mar 2015 15:38:27 +0530 Subject: add to ruby contributors --- ruby.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 8c9d8fc5..792c9c95 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -11,6 +11,7 @@ contributors: - ["Ariel Krakowski", "http://www.learneroo.com"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] --- -- cgit v1.2.3 From 7243f13fc6462e9fee8d463e13446ab7339e9d67 Mon Sep 17 00:00:00 2001 From: ronaldxs Date: Fri, 20 Mar 2015 16:40:25 -0400 Subject: thrice .... gather ^3 counts three times "0 1 2" not 5 Probably just a paste-o mistake. Want to count 3 times not 5. --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 85ab1d79..1b320028 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -963,7 +963,7 @@ say join ',', gather if False { # But consider: constant thrice = gather for ^3 { say take $_ }; # Doesn't print anything # versus: -constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2 3 4 +constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2 # - `lazy` - Defer actual evaluation until value is fetched (forces lazy context) # Not yet implemented !! -- cgit v1.2.3 From f94fd7356adcf034f97256d2ce575f240a50d4b8 Mon Sep 17 00:00:00 2001 From: chadluo Date: Mon, 23 Mar 2015 01:54:46 +1100 Subject: fixed translation --- zh-cn/haskell-cn.html.markdown | 117 ++++++++++++++++++++--------------------- 1 file changed, 56 insertions(+), 61 deletions(-) diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index fae8a456..8904970f 100644 --- a/zh-cn/haskell-cn.html.markdown +++ b/zh-cn/haskell-cn.html.markdown @@ -13,7 +13,8 @@ Haskell 是一门实用的函数式编程语言,因其 Monads 与类型系统 ```haskell -- 单行注释以两个减号开头 -{- 多行注释像这样被一个闭合的块包围 +{- 多行注释像这样 + 被一个闭合的块包围 -} ---------------------------------------------------- @@ -46,9 +47,9 @@ not False -- True 1 < 10 -- True -- 在上面的例子中,`not` 是一个接受一个参数的函数。 --- Haskell 不需要括号来调用函数。所有的参数都只是在函数名之后列出来。 +-- Haskell 不需要括号来调用函数,所有的参数都只是在函数名之后列出来 -- 因此,通常的函数调用模式是: --- func arg1 arg2 arg3... +-- func arg1 arg2 arg3... -- 你可以查看函数部分了解如何自行编写。 -- 字符串和字符 @@ -65,11 +66,11 @@ not False -- True ---------------------------------------------------- --- 数组和元组 +-- 列表和元组 ---------------------------------------------------- --- 一个数组中的每一个元素都必须是相同的类型 --- 下面两个数组等价: +-- 一个列表中的每一个元素都必须是相同的类型。 +-- 下面两个列表等价 [1, 2, 3, 4, 5] [1..5] @@ -81,34 +82,32 @@ not False -- True [5..1] -- 这样不行,因为 Haskell 默认递增 [5,4..1] -- [5, 4, 3, 2, 1] --- 数组下标 +-- 列表下标 [0..] !! 5 -- 5 --- 在 Haskell 你可以使用无限数组 -[1..] -- 一个含有所有自然数的数组 +-- 在 Haskell 你可以使用无限列表 +[1..] -- 一个含有所有自然数的列表 --- 无限数组的原理是,Haskell 有“惰性求值”。 +-- 无限列表的原理是,Haskell 有“惰性求值”。 -- 这意味着 Haskell 只在需要时才会计算。 --- 所以当你获取数组的第 1000 项元素时,Haskell 会返回给你: - +-- 所以当你获取列表的第 1000 项元素时,Haskell 会返回给你: [1..] !! 999 -- 1000 - --- Haskell 计算了数组中第 1 至 1000 项元素,但这个无限数组中剩下的元素还不存在。 +-- Haskell 计算了列表中第 1 至 1000 项元素,但这个无限列表中剩下的元素还不存在。 -- Haskell 只有在需要时才会计算它们。 --- 连接两个数组 +-- 连接两个列表 [1..5] ++ [6..10] --- 往数组头增加元素 +-- 往列表头增加元素 0:[1..5] -- [0, 1, 2, 3, 4, 5] --- 其它数组操作 +-- 其它列表操作 head [1..5] -- 1 tail [1..5] -- [2, 3, 4, 5] init [1..5] -- [1, 2, 3, 4] last [1..5] -- 5 --- 数组推导 +-- 列表推导 (list comprehension) [x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] -- 附带条件 @@ -125,6 +124,7 @@ snd ("haskell", 1) -- 1 ---------------------------------------------------- -- 3. 函数 ---------------------------------------------------- + -- 一个接受两个变量的简单函数 add a b = a + b @@ -137,7 +137,7 @@ add 1 2 -- 3 -- 你也可以使用反引号中置函数名: 1 `add` 2 -- 3 --- 你也可以定义不带字母的函数名,这样你可以定义自己的操作符 +-- 你也可以定义不带字母的函数名,这样你可以定义自己的操作符。 -- 这里有一个做整除的操作符 (//) a b = a `div` b 35 // 4 -- 8 @@ -147,36 +147,36 @@ fib x | x < 2 = x | otherwise = fib (x - 1) + fib (x - 2) --- 模式匹配与 Guard 类似 --- 这里给出了三个不同的 fib 定义 +-- 模式匹配与 Guard 类似。 +-- 这里给出了三个不同的 fib 定义。 -- Haskell 会自动调用第一个符合参数模式的声明 fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) --- 元组的模式匹配: +-- 元组的模式匹配 foo (x, y) = (x + 1, y + 2) --- 数组的模式匹配 --- 这里 `x` 是列表中第一个元素,`xs` 是列表剩余的部分 +-- 列表的模式匹配 +-- 这里 `x` 是列表中第一个元素,`xs` 是列表剩余的部分。 -- 我们可以实现自己的 map 函数: myMap func [] = [] myMap func (x:xs) = func x:(myMap func xs) --- 匿名函数带有一个反斜杠,后面跟着所有的参数。 +-- 匿名函数带有一个反斜杠,后面跟着所有的参数 myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] -- 在 fold(在一些语言称 为`inject`)中使用匿名函数 --- foldl1 意味着左折叠 (fold left), 并且使用列表中第一个值作为累加器的初始值 +-- foldl1 意味着左折叠 (fold left), 并且使用列表中第一个值作为累加器的初始值。 foldl1 (\acc x -> acc + x) [1..5] -- 15 ---------------------------------------------------- -- 4. 其它函数 ---------------------------------------------------- --- 部分调用: --- 如果你调用函数时没有给出所有参数,它就被“部分调用” --- 它将返回一个接受余下参数的函数 +-- 部分调用 +-- 如果你调用函数时没有给出所有参数,它就被“部分调用”。 +-- 它将返回一个接受余下参数的函数。 add a b = a + b foo = add 10 -- foo 现在是一个接受一个数并对其加 10 的函数 foo 5 -- 15 @@ -185,8 +185,8 @@ foo 5 -- 15 foo = (+10) foo 5 -- 15 --- 函数组合 --- (.) 函数把其它函数链接到一起 +-- 函列表合 +-- (.) 函数把其它函数链接到一起。 -- 例如,这里 foo 是一个接受一个值的函数。 -- 它对接受的值加 10,并对结果乘以 5,之后返回最后的值。 foo = (*5) . (+10) @@ -195,9 +195,9 @@ foo = (*5) . (+10) foo 5 -- 75 -- 修正优先级 --- Haskell 有另外一个函数 `$` 可以改变优先级 --- `$` 使得 Haskell 先计算其右边的部分,然后调用左边的部分 --- 你可以使用 `$` 来移除多余的括号 +-- Haskell 有另外一个函数 `$` 可以改变优先级。 +-- `$` 使得 Haskell 先计算其右边的部分,然后调用左边的部分。 +-- 你可以使用 `$` 来移除多余的括号。 -- 修改前 (even (fib 7)) -- true @@ -220,13 +220,13 @@ even $ fib 7 -- true True :: Bool -- 函数也有类型 --- `not` 接受一个布尔型返回一个布尔型: +-- `not` 接受一个布尔型返回一个布尔型 -- not :: Bool -> Bool --- 这是接受两个参数的函数: +-- 这是接受两个参数的函数 -- add :: Integer -> Integer -> Integer --- 当你定义一个值,声明其类型是一个好做法: +-- 当你定义一个值,声明其类型是一个好做法 double :: Integer -> Integer double x = x * 2 @@ -250,30 +250,29 @@ case args of _ -> putStrLn "bad args" -- Haskell 没有循环,它使用递归 --- map 对一个数组中的每一个元素调用一个函数: - +-- map 对一个列表中的每一个元素调用一个函数 map (*2) [1..5] -- [2, 4, 6, 8, 10] --- 你可以使用 map 来编写 for 函数: +-- 你可以使用 map 来编写 for 函数 for array func = map func array --- 调用: +-- 调用 for [0..5] $ \i -> show i --- 我们也可以像这样写: +-- 我们也可以像这样写 for [0..5] show -- 你可以使用 foldl 或者 foldr 来分解列表 -- foldl foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 --- 等价于: +-- 等价于 (2 * (2 * (2 * 4 + 1) + 2) + 3) --- foldl 从左开始,foldr 从右: +-- foldl 从左开始,foldr 从右 foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 --- 现在它等价于: +-- 现在它等价于 (2 * 3 + (2 * 2 + (2 * 1 + 4))) ---------------------------------------------------- @@ -293,9 +292,9 @@ say Green = "You are Green!" data Maybe a = Nothing | Just a -- 这些都是 Maybe 类型: -Just "hello" -- of type `Maybe String` -Just 1 -- of type `Maybe Int` -Nothing -- of type `Maybe a` for any `a` +Just "hello" -- `Maybe String` 类型 +Just 1 -- `Maybe Int` 类型 +Nothing -- 对任意 `a` 为 `Maybe a` 类型 ---------------------------------------------------- -- 8. Haskell IO @@ -321,7 +320,7 @@ main' = interact countLines -- 你可以认为一个 `IO ()` 类型的值是表示计算机做的一系列操作,类似命令式语言。 -- 我们可以使用 `do` 声明来把动作连接到一起。 --- 举个列子: +-- 举个列子 sayHello :: IO () sayHello = do putStrLn "What is your name?" @@ -336,7 +335,8 @@ sayHello = do -- 让我们来更进一步理解刚才所使用的函数 `getLine` 是怎样工作的。它的类型是: -- getLine :: IO String --- 你可以认为一个 `IO a` 类型的值代表了一个运行时会生成一个 `a` 类型值的程序(可能还有其它行为)。 +-- 你可以认为一个 `IO a` 类型的值代表了一个运行时会生成一个 `a` 类型值的程序。 +-- (可能伴随其它行为) -- 我们可以通过 `<-` 保存和重用这个值。 -- 我们也可以实现自己的 `IO String` 类型函数: action :: IO String @@ -348,8 +348,7 @@ action = do -- `return` 不是关键字,只是一个普通函数 return (input1 ++ "\n" ++ input2) -- return :: String -> IO String --- 我们可以像调用 `getLine` 一样调用它: - +-- 我们可以像调用 `getLine` 一样调用它 main'' = do putStrLn "I will echo two lines!" result <- action @@ -358,29 +357,25 @@ main'' = do -- `IO` 类型是一个 "Monad" 的例子。 -- Haskell 通过使用 Monad 使得其本身为纯函数式语言。 --- 任何与外界交互的函数(即 IO)都在它的类型声明中标记为 `IO` --- 这告诉我们什么样的函数是“纯洁的”(不与外界交互,不修改状态) ,什么样的函数不是 “纯洁的” - +-- 任何与外界交互的函数(即 IO)都在它的类型声明中标记为 `IO`。 +-- 这告诉我们什么样的函数是“纯洁的”(不与外界交互,不修改状态) , +-- 什么样的函数不是 “纯洁的”。 -- 这个功能非常强大,因为纯函数并发非常容易,由此在 Haskell 中做并发非常容易。 - ---------------------------------------------------- -- 9. Haskell REPL ---------------------------------------------------- -- 键入 `ghci` 开始 REPL。 -- 现在你可以键入 Haskell 代码。 --- 任何新值都需要通过 `let` 来创建: - +-- 任何新值都需要通过 `let` 来创建 let foo = 5 --- 你可以查看任何值的类型,通过命令 `:t`: - +-- 你可以通过命令 `:t` 查看任何值的类型 >:t foo foo :: Integer -- 你也可以运行任何 `IO ()`类型的动作 - > sayHello What is your name? Friend! -- cgit v1.2.3 From f1159951711a45c6f52b78ec247634c18f7de0b5 Mon Sep 17 00:00:00 2001 From: Dan Korostelev Date: Tue, 24 Mar 2015 01:19:13 +0300 Subject: Use "haxe" highlighting instead of C# --- haxe.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 8599de8d..b8e6a265 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -11,7 +11,7 @@ Haxe author). Note that this guide is for Haxe version 3. Some of the guide may be applicable to older versions, but it is recommended to use other references. -```csharp +```haxe /* Welcome to Learn Haxe 3 in 15 minutes. http://www.haxe.org This is an executable tutorial. You can compile and run it using the haxe -- cgit v1.2.3 From 0e118934db0c6813482cee606ce15cec681a9ae0 Mon Sep 17 00:00:00 2001 From: Dan Korostelev Date: Tue, 24 Mar 2015 01:21:28 +0300 Subject: [haxe] some additions and fixes (closes #489) --- haxe.html.markdown | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index b8e6a265..e57c46a8 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -3,6 +3,7 @@ language: haxe filename: LearnHaxe3.hx contributors: - ["Justin Donaldson", "https://github.com/jdonaldson/"] + - ["Dan Korostelev", "https://github.com/nadako/"] --- Haxe is a web-oriented language that provides platform support for C++, C#, @@ -34,16 +35,20 @@ references. /* This is your first actual haxe code coming up, it's declaring an empty package. A package isn't necessary, but it's useful if you want to create a - namespace for your code (e.g. org.module.ClassName). + namespace for your code (e.g. org.yourapp.ClassName). + + Omitting package declaration is the same as declaring empty package. */ package; // empty package, no namespace. /* - Packages define modules for your code. Each module (e.g. org.module) must - be lower case, and should exist as a folder structure containing the class. - Class (and type) names must be capitalized. E.g, the class "org.module.Foo" - should have the folder structure org/module/Foo.hx, as accessible from the - compiler's working directory or class path. + Packages are directories that contain modules. Each module is a .hx file + that contains types defined in a package. Package names (e.g. org.yourapp) + must be lower case while module names are capitalized. A module contain one + or more types whose names are also capitalized. + + E.g, the class "org.yourapp.Foo" should have the folder structure org/module/Foo.hx, + as accessible from the compiler's working directory or class path. If you import code from other files, it must be declared before the rest of the code. Haxe provides a lot of common default classes to get you started: @@ -53,6 +58,12 @@ import haxe.ds.ArraySort; // you can import many classes/modules at once with "*" import haxe.ds.*; +// you can import static fields +import Lambda.array; + +// you can also use "*" to import all static fields +import Math.*; + /* You can also import classes in a special way, enabling them to extend the functionality of other classes like a "mixin". More on 'using' later. @@ -172,7 +183,8 @@ class LearnHaxe3{ Regexes are also supported, but there's not enough space to go into much detail. */ - trace((~/foobar/.match('foo')) + " is the value for (~/foobar/.match('foo')))"); + var re = ~/foobar/; + trace(re.match('foo') + " is the value for (~/foobar/.match('foo')))"); /* Arrays are zero-indexed, dynamic, and mutable. Missing values are @@ -383,11 +395,7 @@ class LearnHaxe3{ */ // if statements - var k = if (true){ - 10; - } else { - 20; - } + var k = if (true) 10 else 20; trace("K equals ", k); // outputs 10 @@ -628,6 +636,7 @@ enum ComplexEnum{ ComplexEnumEnum(c:ComplexEnum); } // Note: The enum above can include *other* enums as well, including itself! +// Note: This is what called *Algebraic data type* in some other languages. class ComplexEnumTest{ public static function example(){ -- cgit v1.2.3 From 20d612ce5c8e1fe8ea23c15ff937142ef53f5034 Mon Sep 17 00:00:00 2001 From: Fatih Erikli Date: Tue, 24 Mar 2015 11:11:14 +0200 Subject: Add brainfuck-visualizer link --- brainfuck.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown index 27ac6921..aa1fcc40 100644 --- a/brainfuck.html.markdown +++ b/brainfuck.html.markdown @@ -8,6 +8,8 @@ contributors: Brainfuck (not capitalized except at the start of a sentence) is an extremely minimal Turing-complete programming language with just 8 commands. +You can try brainfuck on your browser with brainfuck-visualizer. + ``` Any character not "><+-.,[]" (excluding quotation marks) is ignored. -- cgit v1.2.3 From 03398877482f08c017e6774665f2c3b6e206ed34 Mon Sep 17 00:00:00 2001 From: Dan Korostelev Date: Tue, 24 Mar 2015 12:37:49 +0300 Subject: [haxe] polishing --- haxe.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index e57c46a8..c807d2d7 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -12,7 +12,7 @@ Haxe author). Note that this guide is for Haxe version 3. Some of the guide may be applicable to older versions, but it is recommended to use other references. -```haxe +```csharp /* Welcome to Learn Haxe 3 in 15 minutes. http://www.haxe.org This is an executable tutorial. You can compile and run it using the haxe @@ -37,7 +37,7 @@ references. package. A package isn't necessary, but it's useful if you want to create a namespace for your code (e.g. org.yourapp.ClassName). - Omitting package declaration is the same as declaring empty package. + Omitting package declaration is the same as declaring an empty package. */ package; // empty package, no namespace. @@ -636,7 +636,7 @@ enum ComplexEnum{ ComplexEnumEnum(c:ComplexEnum); } // Note: The enum above can include *other* enums as well, including itself! -// Note: This is what called *Algebraic data type* in some other languages. +// Note: This is what's called *Algebraic data type* in some other languages. class ComplexEnumTest{ public static function example(){ -- cgit v1.2.3 From 7e7a60d47ce0113e1a5b4ee8642984c60a08f569 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Tue, 24 Mar 2015 12:29:01 +0200 Subject: Update python3.html.markdown. Changes to spacing and online resources 1. Some changes related to spacing 2. Added an online resource --- python3.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 0293d7d2..e8913267 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -276,7 +276,7 @@ empty_set = set() # Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} -#Can set new variables to a set +# Can set new variables to a set filled_set = some_set # Add one more item to the set @@ -394,7 +394,6 @@ our_iterator.__next__() # Raises StopIteration list(filled_dict.keys()) #=> Returns ["one", "two", "three"] - #################################################### ## 4. Functions #################################################### @@ -410,7 +409,6 @@ add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 # Another way to call functions is with keyword arguments add(y=6, x=5) # Keyword arguments can arrive in any order. - # You can define functions that take a variable number of # positional arguments def varargs(*args): @@ -418,7 +416,6 @@ def varargs(*args): varargs(1, 2, 3) # => (1, 2, 3) - # You can define functions that take a variable number of # keyword arguments, as well def keyword_args(**kwargs): @@ -636,6 +633,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) ### Dead Tree -- cgit v1.2.3 From 44c37d5531d42a73b0bde49525e586b413489caf Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Tue, 24 Mar 2015 19:26:19 +0200 Subject: [python3.html.mardown] Added a short statement about magic methods Terminology related to Python special functions --- python3.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index e8913267..56126ad3 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -498,7 +498,9 @@ class Human(object): # Basic initializer, this is called when this class is instantiated. # Note that the double leading and trailing underscores denote objects # or attributes that are used by python but that live in user-controlled - # namespaces. You should not invent such names on your own. + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called magic methods (or sometimes called dunder methods) + # You should not invent such names on your own. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name -- cgit v1.2.3 From c7a9731b07071c2380a5383ab976592df970aa50 Mon Sep 17 00:00:00 2001 From: Fatih Erikli Date: Tue, 24 Mar 2015 22:24:49 +0200 Subject: Change link format --- brainfuck.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown index aa1fcc40..a76169c8 100644 --- a/brainfuck.html.markdown +++ b/brainfuck.html.markdown @@ -8,7 +8,7 @@ contributors: Brainfuck (not capitalized except at the start of a sentence) is an extremely minimal Turing-complete programming language with just 8 commands. -You can try brainfuck on your browser with brainfuck-visualizer. +You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). ``` Any character not "><+-.,[]" (excluding quotation marks) is ignored. -- cgit v1.2.3 From 2f43da109ffab5a4d3dd582cc51a7c3d95dd4987 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Wed, 25 Mar 2015 18:08:32 +0200 Subject: [haskell.html.markdown] Changed explanation for Haskell '$' operator --- haskell.html.markdown | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index f1025d44..6bdc78e0 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -202,10 +202,12 @@ foo = (*5) . (+10) foo 5 -- 75 -- fixing precedence --- Haskell has another function called `$`. Anything appearing after it will --- take precedence over anything that comes before. --- You can use `$` (often in combination with `.`) --- to get rid of a lot of parentheses: +-- Haskell has another operator called `$`. This operator applies a function +-- to a given parameter. In contrast to standard function application, which +-- has highest possible priority of 10 and is left-associative, the `$` operator +-- has priority of 0 and is right-associative. Such a low priority means that +-- all other operators on both sides of `$` will be evaluated before applying +-- the `$`. -- before (even (fib 7)) -- false -- cgit v1.2.3 From c5c8004450567a4be4c814e3c18725688c1601b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Wed, 25 Mar 2015 19:50:46 +0200 Subject: Primitive Datatypes and Operators --- tr-tr/python3-tr.html.markdown | 645 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 645 insertions(+) create mode 100644 tr-tr/python3-tr.html.markdown diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown new file mode 100644 index 00000000..d815e4f9 --- /dev/null +++ b/tr-tr/python3-tr.html.markdown @@ -0,0 +1,645 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Eray AYDIN", "http://erayaydin.me/"] +lang: tr-tr +filename: learnpython3-tr.py +--- + +Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur. + +Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/python/) kontrol edebilirsiniz. + +```python + +# Single line comments start with a number symbol. + +""" Multiline strings can be written + using three "s, and are often used + as comments +""" + +#################################################### +## 1. Primitive Datatypes and Operators +#################################################### + +# You have numbers +3 # => 3 + +# Math is what you would expect +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Except division which returns floats by default +35 / 5 # => 7.0 + +# Result of integer division truncated down both for positive and negative. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# When you use a float, results are floats +3 * 2.0 # => 6.0 + +# Modulo operation +7 % 3 # => 1 + +# Exponentiation (x to the yth power) +2**4 # => 16 + +# Enforce precedence with parentheses +(1 + 3) * 2 # => 8 + +# Boolean values are primitives +True +False + +# negate with not +not True # => False +not False # => True + +# Boolean Operators +# Note "and" and "or" are case-sensitive +True and False #=> False +False or True #=> True + +# Note using Bool operators with ints +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Equality is == +1 == 1 # => True +2 == 1 # => False + +# Inequality is != +1 != 1 # => False +2 != 1 # => True + +# More comparisons +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Comparisons can be chained! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Strings are created with " or ' +"This is a string." +'This is also a string.' + +# Strings can be added too! But try not to do this. +"Hello " + "world!" # => "Hello world!" + +# A string can be treated like a list of characters +"This is a string"[0] # => 'T' + +# .format can be used to format strings, like this: +"{} can be {}".format("strings", "interpolated") + +# You can repeat the formatting arguments to save some typing. +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# You can use keywords if you don't want to count. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" + +# If your Python 3 code also needs to run on Python 2.5 and below, you can also +# still use the old style of formatting: +"%s can be %s the %s way" % ("strings", "interpolated", "old") + + +# None is an object +None # => None + +# Don't use the equality "==" symbol to compare objects to None +# Use "is" instead. This checks for equality of object identity. +"etc" is None # => False +None is None # => True + +# None, 0, and empty strings/lists/dicts all evaluate to False. +# All other values are True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variables and Collections +#################################################### + +# Python has a print function +print("I'm Python. Nice to meet you!") + +# No need to declare variables before assigning to them. +# Convention is to use lower_case_with_underscores +some_var = 5 +some_var # => 5 + +# Accessing a previously unassigned variable is an exception. +# See Control Flow to learn more about exception handling. +some_unknown_var # Raises a NameError + +# Lists store sequences +li = [] +# You can start with a prefilled list +other_li = [4, 5, 6] + +# Add stuff to the end of a list with append +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# Remove from the end with pop +li.pop() # => 3 and li is now [1, 2, 4] +# Let's put it back +li.append(3) # li is now [1, 2, 4, 3] again. + +# Access a list like you would any array +li[0] # => 1 +# Look at the last element +li[-1] # => 3 + +# Looking out of bounds is an IndexError +li[4] # Raises an IndexError + +# You can look at ranges with slice syntax. +# (It's a closed/open range for you mathy types.) +li[1:3] # => [2, 4] +# Omit the beginning +li[2:] # => [4, 3] +# Omit the end +li[:3] # => [1, 2, 4] +# Select every second entry +li[::2] # =>[1, 4] +# Revert the list +li[::-1] # => [3, 4, 2, 1] +# Use any combination of these to make advanced slices +# li[start:end:step] + +# Remove arbitrary elements from a list with "del" +del li[2] # li is now [1, 2, 3] + +# You can add lists +# Note: values for li and for other_li are not modified. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatenate lists with "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Check for existence in a list with "in" +1 in li # => True + +# Examine the length with "len()" +len(li) # => 6 + + +# Tuples are like lists but are immutable. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Raises a TypeError + +# You can do all those list thingies on tuples too +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# You can unpack tuples (or lists) into variables +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# Tuples are created by default if you leave out the parentheses +d, e, f = 4, 5, 6 +# Now look how easy it is to swap two values +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionaries store mappings +empty_dict = {} +# Here is a prefilled dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys as a list with "keys()". +# We need to wrap the call in list() because we are getting back an iterable. We'll talk about those later. +# Note - Dictionary key ordering is not guaranteed. +# Your results might not match this exactly. +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable. +# Note - Same as above regarding key ordering. +list(filled_dict.values()) # => [3, 2, 1] + + +# Check for existence of keys in a dictionary with "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Looking up a non-existing key is a KeyError +filled_dict["four"] # KeyError + +# Use "get()" method to avoid the KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# The get method supports a default argument when the value is missing +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" inserts into a dictionary only if the given key isn't present +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + +# Adding to a dictionary +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 #another way to add to dict + +# Remove keys from a dictionary with del +del filled_dict["one"] # Removes the key "one" from filled dict + + +# Sets store ... well sets +empty_set = set() +# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# Can set new variables to a set +filled_set = some_set + +# Add one more item to the set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Do set intersection with & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Do set union with | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Do set difference with - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Check for existence in a set with in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Control Flow and Iterables +#################################################### + +# Let's just make a variable +some_var = 5 + +# Here is an if statement. Indentation is significant in python! +# prints "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # This elif clause is optional. + print("some_var is smaller than 10.") +else: # This is optional too. + print("some_var is indeed 10.") + + +""" +For loops iterate over lists +prints: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use format() to interpolate formatted strings + print("{} is a mammal".format(animal)) + +""" +"range(number)" returns a list of numbers +from zero to the given number +prints: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +While loops go until a condition is no longer met. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Shorthand for x = x + 1 + +# Handle exceptions with a try/except block +try: + # Use "raise" to raise an error + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. +except (TypeError, NameError): + pass # Multiple exceptions can be handled together, if required. +else: # Optional clause to the try/except block. Must follow all except blocks + print("All good!") # Runs only if the code in try raises no exceptions + +# Python offers a fundamental abstraction called the Iterable. +# An iterable is an object that can be treated as a sequence. +# The object returned the range function, is an iterable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface + +# We can loop over it. +for i in our_iterable: + print(i) # Prints one, two, three + +# However we cannot address elements by index. +our_iterable[1] # Raises a TypeError + +# An iterable is an object that knows how to create an iterator. +our_iterator = iter(our_iterable) + +# Our iterator is an object that can remember the state as we traverse through it. +# We get the next object by calling the __next__ function. +our_iterator.__next__() #=> "one" + +# It maintains state as we call __next__. +our_iterator.__next__() #=> "two" +our_iterator.__next__() #=> "three" + +# After the iterator has returned all of its data, it gives you a StopIterator Exception +our_iterator.__next__() # Raises StopIteration + +# You can grab all the elements of an iterator by calling list() on it. +list(filled_dict.keys()) #=> Returns ["one", "two", "three"] + + +#################################################### +## 4. Functions +#################################################### + +# Use "def" to create new functions +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # Return values with a return statement + +# Calling functions with parameters +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 + +# Another way to call functions is with keyword arguments +add(y=6, x=5) # Keyword arguments can arrive in any order. + +# You can define functions that take a variable number of +# positional arguments +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# You can define functions that take a variable number of +# keyword arguments, as well +def keyword_args(**kwargs): + return kwargs + +# Let's call it to see what happens +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# You can do both at once, if you like +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# When calling functions, you can do the opposite of args/kwargs! +# Use * to expand tuples and use ** to expand kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalent to foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) + + +# Function Scope +x = 5 + +def setX(num): + # Local var x not the same as global variable x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # global var x is now set to 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python has first class functions +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# There are also anonymous functions +(lambda x: x > 2)(3) # => True + +# TODO - Fix for iterables +# There are built-in higher order functions +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# We can use list comprehensions for nice maps and filters +# List comprehension stores the output as a list which can itself be a nested list +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# We subclass from object to get a class. +class Human(object): + + # A class attribute. It is shared by all instances of this class + species = "H. sapiens" + + # Basic initializer, this is called when this class is instantiated. + # Note that the double leading and trailing underscores denote objects + # or attributes that are used by python but that live in user-controlled + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called magic methods (or sometimes called dunder methods) + # You should not invent such names on your own. + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # An instance method. All methods take "self" as the first argument + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # A class method is shared among all instances + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # A static method is called without a class or instance reference + @staticmethod + def grunt(): + return "*grunt*" + + +# Instantiate a class +i = Human(name="Ian") +print(i.say("hi")) # prints out "Ian: hi" + +j = Human("Joel") +print(j.say("hello")) # prints out "Joel: hello" + +# Call our class method +i.get_species() # => "H. sapiens" + +# Change the shared attribute +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Call the static method +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# You can import modules +import math +print(math.sqrt(16)) # => 4 + +# You can get specific functions from a module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modules are just ordinary python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + + +#################################################### +## 7. Advanced +#################################################### + +# Generators help you make lazy code +def double_numbers(iterable): + for i in iterable: + yield i + i + +# A generator creates values on the fly. +# Instead of generating and returning all values at once it creates one in each +# iteration. This means values bigger than 15 wont be processed in +# double_numbers. +# Note range is a generator too. Creating a list 1-900000000 would take lot of +# time to be made +# We use a trailing underscore in variable names when we want to use a name that +# would normally collide with a python keyword +range_ = range(1, 900000000) +# will double all numbers until a result >=30 found +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decorators +# in this example beg wraps say +# Beg will call say. If say_please is True then it will change the returned +# message +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) + +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + -- cgit v1.2.3 From 46273c1ffe60c581968c9b43d1fb603a881823e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Wed, 25 Mar 2015 20:34:27 +0200 Subject: Variables and Collections --- tr-tr/python3-tr.html.markdown | 297 ++++++++++++++++++++--------------------- 1 file changed, 148 insertions(+), 149 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index d815e4f9..4939f219 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -17,119 +17,119 @@ Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [bur ```python -# Single line comments start with a number symbol. +# Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır. -""" Multiline strings can be written - using three "s, and are often used - as comments +""" Çok satırlı olmasını istediğiniz yorumlar + üç adet tırnak(") işareti ile + yapılmaktadır """ #################################################### -## 1. Primitive Datatypes and Operators +## 1. Temel Veri Türleri ve Operatörler #################################################### -# You have numbers +# Sayılar 3 # => 3 -# Math is what you would expect +# Tahmin edebileceğiniz gibi matematik 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 -# Except division which returns floats by default +# Bölme işlemi varsayılan olarak onluk döndürür 35 / 5 # => 7.0 -# Result of integer division truncated down both for positive and negative. +# Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar 5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too +5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 -# When you use a float, results are floats +# Onluk kullanırsanız, sonuç da onluk olur 3 * 2.0 # => 6.0 -# Modulo operation +# Kalan operatörü 7 % 3 # => 1 -# Exponentiation (x to the yth power) +# Üs (2 üzeri 4) 2**4 # => 16 -# Enforce precedence with parentheses +# Parantez ile önceliği değiştirebilirsiniz (1 + 3) * 2 # => 8 -# Boolean values are primitives +# Boolean(Doğru-Yanlış) değerleri standart True False -# negate with not +# 'değil' ile terse çevirme not True # => False not False # => True -# Boolean Operators -# Note "and" and "or" are case-sensitive +# Boolean Operatörleri +# "and" ve "or" büyük küçük harf duyarlıdır True and False #=> False False or True #=> True -# Note using Bool operators with ints +# Bool operatörleri ile sayı kullanımı 0 and 2 #=> 0 -5 or 0 #=> -5 0 == False #=> True 2 == True #=> False 1 == True #=> True -# Equality is == +# Eşitlik kontrolü == 1 == 1 # => True 2 == 1 # => False -# Inequality is != +# Eşitsizlik Kontrolü != 1 != 1 # => False 2 != 1 # => True -# More comparisons +# Diğer karşılaştırmalar 1 < 10 # => True 1 > 10 # => False 2 <= 2 # => True 2 >= 2 # => True -# Comparisons can be chained! +# Zincirleme şeklinde karşılaştırma da yapabilirsiniz! 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# Strings are created with " or ' -"This is a string." -'This is also a string.' +# Yazı(Strings) " veya ' işaretleri ile oluşturulabilir +"Bu bir yazı." +'Bu da bir yazı.' -# Strings can be added too! But try not to do this. -"Hello " + "world!" # => "Hello world!" +# Yazılar da eklenebilir! Fakat bunu yapmanızı önermem. +"Merhaba " + "dünya!" # => "Merhaba dünya!" -# A string can be treated like a list of characters -"This is a string"[0] # => 'T' +# Bir yazı(string) karakter listesi gibi işlenebilir +"Bu bir yazı"[0] # => 'B' -# .format can be used to format strings, like this: -"{} can be {}".format("strings", "interpolated") +# .format ile yazıyı biçimlendirebilirsiniz, şu şekilde: +"{} da ayrıca {}".format("yazılar", "işlenebilir") -# You can repeat the formatting arguments to save some typing. -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" +# Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz. +"{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu") +#=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir" -# You can use keywords if you don't want to count. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" +# Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz. +"{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor" -# If your Python 3 code also needs to run on Python 2.5 and below, you can also -# still use the old style of formatting: -"%s can be %s the %s way" % ("strings", "interpolated", "old") +# Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız, +# eski stil formatlamayı kullanabilirsiniz: +"%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir") -# None is an object +# Hiçbir şey(none) da bir objedir None # => None -# Don't use the equality "==" symbol to compare objects to None -# Use "is" instead. This checks for equality of object identity. -"etc" is None # => False +# Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın +# Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir. +"vb" is None # => False None is None # => True -# None, 0, and empty strings/lists/dicts all evaluate to False. -# All other values are True +# None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü. +# Diğer veriler ise True değeri döndürür bool(0) # => False bool("") # => False bool([]) #=> False @@ -137,164 +137,163 @@ bool({}) #=> False #################################################### -## 2. Variables and Collections +## 2. Değişkenler ve Koleksiyonlar #################################################### -# Python has a print function -print("I'm Python. Nice to meet you!") +# Python bir yazdırma fonksiyonuna sahip +print("Ben Python. Tanıştığıma memnun oldum!") -# No need to declare variables before assigning to them. -# Convention is to use lower_case_with_underscores -some_var = 5 -some_var # => 5 +# Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok. +# Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin +bir_degisken = 5 +bir_degisken # => 5 -# Accessing a previously unassigned variable is an exception. -# See Control Flow to learn more about exception handling. -some_unknown_var # Raises a NameError +# Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır. +# Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz. +bir_bilinmeyen_degisken # NameError hatası oluşturur -# Lists store sequences +# Listeler ile sıralamaları tutabilirsiniz li = [] -# You can start with a prefilled list -other_li = [4, 5, 6] - -# Add stuff to the end of a list with append -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# Remove from the end with pop -li.pop() # => 3 and li is now [1, 2, 4] -# Let's put it back -li.append(3) # li is now [1, 2, 4, 3] again. - -# Access a list like you would any array +# Önceden doldurulmuş listeler ile başlayabilirsiniz +diger_li = [4, 5, 6] + +# 'append' ile listenin sonuna ekleme yapabilirsiniz +li.append(1) # li artık [1] oldu +li.append(2) # li artık [1, 2] oldu +li.append(4) # li artık [1, 2, 4] oldu +li.append(3) # li artık [1, 2, 4, 3] oldu +# 'pop' ile listenin son elementini kaldırabilirsiniz +li.pop() # => 3 ve li artık [1, 2, 4] +# Çıkarttığımız tekrardan ekleyelim +li.append(3) # li yeniden [1, 2, 4, 3] oldu. + +# Dizi gibi listeye erişim sağlayın li[0] # => 1 -# Look at the last element +# Son elemente bakın li[-1] # => 3 -# Looking out of bounds is an IndexError -li[4] # Raises an IndexError +# Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur +li[4] # IndexError hatası oluşturur -# You can look at ranges with slice syntax. -# (It's a closed/open range for you mathy types.) +# Bir kısmını almak isterseniz. li[1:3] # => [2, 4] -# Omit the beginning +# Başlangıç belirtmezseniz li[2:] # => [4, 3] -# Omit the end +# Sonu belirtmesseniz li[:3] # => [1, 2, 4] -# Select every second entry +# Her ikişer objeyi seçme li[::2] # =>[1, 4] -# Revert the list +# Listeyi tersten almak li[::-1] # => [3, 4, 2, 1] -# Use any combination of these to make advanced slices -# li[start:end:step] +# Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz +# li[baslangic:son:adim] -# Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] +# "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz +del li[2] # li artık [1, 2, 3] oldu -# You can add lists -# Note: values for li and for other_li are not modified. -li + other_li # => [1, 2, 3, 4, 5, 6] +# Listelerde de ekleme yapabilirsiniz +# Not: değerler üzerinde değişiklik yapılmaz. +li + diger_li # => [1, 2, 3, 4, 5, 6] -# Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] +# Listeleri birbirine bağlamak için "extend()" kullanılabilir +li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu -# Check for existence in a list with "in" +# Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir 1 in li # => True -# Examine the length with "len()" +# Uzunluğu öğrenmek için "len()" kullanılabilir len(li) # => 6 -# Tuples are like lists but are immutable. +# Tüpler listeler gibidir fakat değiştirilemez. tup = (1, 2, 3) tup[0] # => 1 -tup[0] = 3 # Raises a TypeError +tup[0] = 3 # TypeError hatası oluşturur -# You can do all those list thingies on tuples too +# Diğer liste işlemlerini tüplerde de uygulayabilirsiniz len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True -# You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -# Tuples are created by default if you leave out the parentheses +# Tüpleri(veya listeleri) değişkenlere açabilirsiniz +a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3 +# Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur d, e, f = 4, 5, 6 -# Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 +# 2 değeri birbirine değiştirmek bu kadar kolay +e, d = d, e # 'd' artık 5 ve 'e' artık 4 -# Dictionaries store mappings -empty_dict = {} -# Here is a prefilled dictionary -filled_dict = {"one": 1, "two": 2, "three": 3} +# Sözlükler anahtar kodlarla verileri tutar +bos_sozl = {} +# Önceden doldurulmuş sözlük oluşturma +dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} -# Look up values with [] -filled_dict["one"] # => 1 +# Değere bakmak için [] kullanalım +dolu_sozl["bir"] # => 1 -# Get all keys as a list with "keys()". -# We need to wrap the call in list() because we are getting back an iterable. We'll talk about those later. -# Note - Dictionary key ordering is not guaranteed. -# Your results might not match this exactly. -list(filled_dict.keys()) # => ["three", "two", "one"] +# Bütün anahtarları almak için "keys()" kullanılabilir. +# Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz. +# Not - Sözlük anahtarlarının sıralaması kesin değildir. +# Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir. +list(dolu_sozl.keys()) # => ["uc", "iki", "bir"] -# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable. -# Note - Same as above regarding key ordering. -list(filled_dict.values()) # => [3, 2, 1] +# Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor +# Not - Sıralama değişebilir. +list(dolu_sozl.values()) # => [3, 2, 1] -# Check for existence of keys in a dictionary with "in" -"one" in filled_dict # => True -1 in filled_dict # => False +# Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz +"bir" in dolu_sozl # => True +1 in dolu_sozl # => False -# Looking up a non-existing key is a KeyError -filled_dict["four"] # KeyError +# Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır. +dolu_sozl["dort"] # KeyError hatası oluşturur -# Use "get()" method to avoid the KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# The get method supports a default argument when the value is missing -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 +# "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz +dolu_sozl.get("bir") # => 1 +dolu_sozl.get("dort") # => None +# "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz. +dolu_sozl.get("bir", 4) # => 1 +dolu_sozl.get("dort", 4) # => 4 -# "setdefault()" inserts into a dictionary only if the given key isn't present -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 +# "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır +dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip +dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip -# Adding to a dictionary -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 #another way to add to dict +# Sözlüğe ekleme +dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4} +#dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu -# Remove keys from a dictionary with del -del filled_dict["one"] # Removes the key "one" from filled dict +# Sözlükten anahtar silmek için 'del' kullanılabilir +del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir -# Sets store ... well sets -empty_set = set() -# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} +# Setler ... set işte :D +bos_set = set() +# Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm. +bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4} -# Can set new variables to a set -filled_set = some_set +# Sete yeni setler ekleyebilirsiniz +dolu_set = bir_set -# Add one more item to the set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} +# Sete bir diğer öğe ekleme +dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu -# Do set intersection with & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} +# Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz +diger_set = {3, 4, 5, 6} +dolu_set & diger_set # => {3, 4, 5} -# Do set union with | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} +# '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz +dolu_set | diger_set # => {1, 2, 3, 4, 5, 6} -# Do set difference with - +# Farklılıkları almak için "-" kullanabilirsiniz {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} -# Check for existence in a set with in -2 in filled_set # => True -10 in filled_set # => False +# Bir değerin olup olmadığının kontrolü için "in" kullanılabilir +2 in dolu_set # => True +10 in dolu_set # => False #################################################### -- cgit v1.2.3 From 1ab0a6eb5e73079393844719da067c37e84b8fef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Wed, 25 Mar 2015 21:05:25 +0200 Subject: Control Flow and Iterables --- tr-tr/python3-tr.html.markdown | 109 ++++++++++++++++++++--------------------- 1 file changed, 54 insertions(+), 55 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index 4939f219..b1806e7b 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -297,37 +297,37 @@ dolu_set | diger_set # => {1, 2, 3, 4, 5, 6} #################################################### -## 3. Control Flow and Iterables +## 3. Kontrol Akışları ve Temel Soyutlandırma #################################################### -# Let's just make a variable -some_var = 5 +# Bir değişken oluşturalım +bir_degisken = 5 -# Here is an if statement. Indentation is significant in python! -# prints "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # This elif clause is optional. - print("some_var is smaller than 10.") -else: # This is optional too. - print("some_var is indeed 10.") +# Burada bir "if" ifadesi var. Girinti(boşluk,tab) python için önemlidir! +# çıktı olarak "bir_degisken 10 dan küçük" yazar +if bir_degisken > 10: + print("bir_degisken 10 dan büyük") +elif bir_degisken < 10: # Bu 'elif' ifadesi zorunlu değildir. + print("bir_degisken 10 dan küçük") +else: # Bu ifade de zorunlu değil. + print("bir_degisken değeri 10") """ -For loops iterate over lists -prints: - dog is a mammal - cat is a mammal - mouse is a mammal +Döngülerle lsiteleri döngüye alabilirsiniz +çıktı: + köpek bir memeli hayvandır + kedi bir memeli hayvandır + fare bir memeli hayvandır """ -for animal in ["dog", "cat", "mouse"]: - # You can use format() to interpolate formatted strings - print("{} is a mammal".format(animal)) +for hayvan in ["köpek", "kedi, "fare"]: + # format ile kolayca yazıyı biçimlendirelim + print("{} bir memeli hayvandır".format(hayvan)) """ -"range(number)" returns a list of numbers -from zero to the given number -prints: +"range(sayi)" bir sayı listesi döndür +0'dan belirttiğiniz sayıyıa kadar +çıktı: 0 1 2 @@ -337,8 +337,8 @@ for i in range(4): print(i) """ -While loops go until a condition is no longer met. -prints: +'While' döngüleri koşul çalıştıkça işlemleri gerçekleştirir. +çıktı: 0 1 2 @@ -347,50 +347,49 @@ prints: x = 0 while x < 4: print(x) - x += 1 # Shorthand for x = x + 1 + x += 1 # Uzun hali x = x + 1 -# Handle exceptions with a try/except block +# Hataları kontrol altına almak için try/except bloklarını kullanabilirsiniz try: - # Use "raise" to raise an error - raise IndexError("This is an index error") + # Bir hata oluşturmak için "raise" kullanabilirsiniz + raise IndexError("Bu bir index hatası") except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. + pass # Önemsiz, devam et. except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks - print("All good!") # Runs only if the code in try raises no exceptions + pass # Çoklu bir şekilde hataları kontrol edebilirsiniz, tabi gerekirse. +else: # İsteğe bağlı bir kısım. Eğer hiçbir hata kontrol mekanizması desteklemiyorsa bu blok çalışacaktır + print("Her şey iyi!") # IndexError, TypeError ve NameError harici bir hatada bu blok çalıştı -# Python offers a fundamental abstraction called the Iterable. -# An iterable is an object that can be treated as a sequence. -# The object returned the range function, is an iterable. +# Temel Soyutlandırma, bir objenin işlenmiş halidir. +# Aşağıdaki örnekte; Obje, range fonksiyonuna temel soyutlandırma gönderdi. -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface +dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} +temel_soyut = dolu_sozl.keys() +print(temel_soyut) #=> range(1,10). Bu obje temel soyutlandırma arayüzü ile oluşturuldu -# We can loop over it. -for i in our_iterable: - print(i) # Prints one, two, three +# Temel Soyutlandırılmış objeyi döngüye sokabiliriz. +for i in temel_soyut: + print(i) # Çıktısı: bir, iki, uc -# However we cannot address elements by index. -our_iterable[1] # Raises a TypeError +# Fakat, elementin anahtarına değerine. +temel_soyut[1] # TypeError hatası! -# An iterable is an object that knows how to create an iterator. -our_iterator = iter(our_iterable) +# 'iterable' bir objenin nasıl temel soyutlandırıldığıdır. +iterator = iter(temel_soyut) -# Our iterator is an object that can remember the state as we traverse through it. -# We get the next object by calling the __next__ function. -our_iterator.__next__() #=> "one" +# 'iterator' o obje üzerinde yaptığımız değişiklikleri hatırlayacaktır +# Bir sonraki objeyi almak için __next__ fonksiyonunu kullanabilirsiniz. +iterator.__next__() #=> "bir" -# It maintains state as we call __next__. -our_iterator.__next__() #=> "two" -our_iterator.__next__() #=> "three" +# Bir önceki __next__ fonksiyonumuzu hatırlayıp bir sonraki kullanımda bu sefer ondan bir sonraki objeyi döndürecektir +iterator.__next__() #=> "iki" +iterator.__next__() #=> "uc" -# After the iterator has returned all of its data, it gives you a StopIterator Exception -our_iterator.__next__() # Raises StopIteration +# Bütün nesneleri aldıktan sonra bir daha __next__ kullanımınızda, StopIterator hatası oluşturacaktır. +iterator.__next__() # StopIteration hatası -# You can grab all the elements of an iterator by calling list() on it. -list(filled_dict.keys()) #=> Returns ["one", "two", "three"] +# iterator'deki tüm nesneleri almak için list() kullanabilirsiniz. +list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"] #################################################### -- cgit v1.2.3 From 71d688379641a91f6247920962a005d9af635a70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Wed, 25 Mar 2015 21:26:00 +0200 Subject: Functions --- tr-tr/python3-tr.html.markdown | 100 ++++++++++++++++++++--------------------- 1 file changed, 48 insertions(+), 52 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index b1806e7b..6babb7d0 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -393,93 +393,89 @@ list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"] #################################################### -## 4. Functions +## 4. Fonksiyonlar #################################################### -# Use "def" to create new functions -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # Return values with a return statement +# "def" ile yeni fonksiyonlar oluşturabilirsiniz +def topla(x, y): + print("x = {} ve y = {}".format(x, y)) + return x + y # Değer döndürmek için 'return' kullanmalısınız -# Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 +# Fonksiyonu parametleri ile çağırıyoruz +topla(5, 6) # => çıktı "x = 5 ve y = 6" ve değer olarak 11 döndürür -# Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. +# Bir diğer fonksiyon çağırma yöntemi de anahtar değerleri ile belirtmek +topla(y=6, x=5) # Anahtar değeri belirttiğiniz için parametre sıralaması önemsiz. -# You can define functions that take a variable number of -# positional arguments -def varargs(*args): - return args +# Sınırsız sayıda argüman da alabilirsiniz +def argumanlar(*argumanlar): + return argumanlar -varargs(1, 2, 3) # => (1, 2, 3) +argumanlar(1, 2, 3) # => (1, 2, 3) -# You can define functions that take a variable number of -# keyword arguments, as well -def keyword_args(**kwargs): - return kwargs +# Parametrelerin anahtar değerlerini almak isterseniz +def anahtar_par(**anahtarlar): + return anahtar -# Let's call it to see what happens -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} +# Çalıştırdığımızda +anahtar_par(anah1="deg1", anah2="deg2") # => {"anah1": "deg1", "anah2": "deg2"} -# You can do both at once, if you like -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) +# İsterseniz, bu ikisini birden kullanabilirsiniz +def tum_argumanlar(*argumanlar, **anahtarla): + print(argumanlar) + print(anahtarla) """ -all_the_args(1, 2, a=3, b=4) prints: +tum_argumanlar(1, 2, a=3, b=4) çıktı: (1, 2) {"a": 3, "b": 4} """ -# When calling functions, you can do the opposite of args/kwargs! -# Use * to expand tuples and use ** to expand kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +# Fonksiyonu çağırırken de aynısını kullanabilirsiniz +argumanlar = (1, 2, 3, 4) +anahtarla = {"a": 3, "b": 4} +tum_argumanlar(*argumanlar) # = foo(1, 2, 3, 4) +tum_argumanlar(**anahtarla) # = foo(a=3, b=4) +tum_argumanlar(*argumanlar, **anahtarla) # = foo(1, 2, 3, 4, a=3, b=4) -# Function Scope +# Fonksiyonlarda kullanacağımız bir değişken oluşturalım x = 5 -def setX(num): - # Local var x not the same as global variable x - x = num # => 43 +def belirleX(sayi): + # Fonksiyon içerisindeki x ile global tanımladığımız x aynı değil + x = sayi # => 43 print (x) # => 43 -def setGlobalX(num): +def globalBelirleX(sayi): global x print (x) # => 5 - x = num # global var x is now set to 6 + x = sayi # global olan x değişkeni artık 6 print (x) # => 6 -setX(43) -setGlobalX(6) +belirleX(43) +globalBelirleX(6) -# Python has first class functions -def create_adder(x): - def adder(y): +# Sınıf fonksiyonları oluşturma +def toplama_olustur(x): + def topla(y): return x + y - return adder + return topla -add_10 = create_adder(10) -add_10(3) # => 13 +ekle_10 = toplama_olustur(10) +ekle_10(3) # => 13 -# There are also anonymous functions +# Bilinmeyen fonksiyon (lambda x: x > 2)(3) # => True # TODO - Fix for iterables -# There are built-in higher order functions -map(add_10, [1, 2, 3]) # => [11, 12, 13] +# Belirli sayıdan yükseğini alma fonksiyonu +map(ekle_10, [1, 2, 3]) # => [11, 12, 13] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] -# We can use list comprehensions for nice maps and filters -# List comprehension stores the output as a list which can itself be a nested list -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +# Filtreleme işlemi için liste comprehensions da kullanabiliriz +[ekle_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### -- cgit v1.2.3 From e34c67290a311c32a208793f44e5d0d51bf37bc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Wed, 25 Mar 2015 21:36:52 +0200 Subject: Classes --- tr-tr/python3-tr.html.markdown | 68 ++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 35 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index 6babb7d0..ee858fb6 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -479,59 +479,57 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### -## 5. Classes +## 5. Sınıflar #################################################### -# We subclass from object to get a class. -class Human(object): +# Sınıf oluşturmak için objeden alt sınıf oluşturacağız. +class Insan(obje): - # A class attribute. It is shared by all instances of this class - species = "H. sapiens" + # Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir + tur = "H. sapiens" - # Basic initializer, this is called when this class is instantiated. - # Note that the double leading and trailing underscores denote objects - # or attributes that are used by python but that live in user-controlled - # namespaces. Methods(or objects or attributes) like: __init__, __str__, - # __repr__ etc. are called magic methods (or sometimes called dunder methods) - # You should not invent such names on your own. - def __init__(self, name): - # Assign the argument to the instance's name attribute - self.name = name + # Basit başlatıcı, Sınıf çağrıldığında tetiklenecektir. + # Dikkat edin, iki adet alt çizgi(_) bulunmakta. Bunlar + # python tarafından tanımlanan isimlerdir. + # Kendinize ait bir fonksiyon oluştururken __fonksiyon__ kullanmayınız! + def __init__(self, isim): + # Parametreyi sınıfın değerine atayalım + self.isim = isim - # An instance method. All methods take "self" as the first argument - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) + # Bir metot. Bütün metotlar ilk parametre olarak "self "alır. + def soyle(self, mesaj): + return "{isim}: {mesaj}".format(isim=self.name, mesaj=mesaj) - # A class method is shared among all instances - # They are called with the calling class as the first argument + # Bir sınıf metotu bütün nesnelere paylaştırılır + # İlk parametre olarak sınıf alırlar @classmethod - def get_species(cls): - return cls.species + def getir_tur(snf): + return snf.tur - # A static method is called without a class or instance reference + # Bir statik metot, sınıf ve nesnesiz çağrılır @staticmethod def grunt(): return "*grunt*" -# Instantiate a class -i = Human(name="Ian") -print(i.say("hi")) # prints out "Ian: hi" +# Sınıfı çağıralım +i = Insan(isim="Ahmet") +print(i.soyle("merhaba")) # çıktı "Ahmet: merhaba" -j = Human("Joel") -print(j.say("hello")) # prints out "Joel: hello" +j = Insan("Ali") +print(j.soyle("selam")) # çıktı "Ali: selam" -# Call our class method -i.get_species() # => "H. sapiens" +# Sınıf metodumuzu çağıraim +i.getir_tur() # => "H. sapiens" -# Change the shared attribute -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" +# Paylaşılan değeri değiştirelim +Insan.tur = "H. neanderthalensis" +i.getir_tur() # => "H. neanderthalensis" +j.getir_tur() # => "H. neanderthalensis" -# Call the static method -Human.grunt() # => "*grunt*" +# Statik metodumuzu çağıralım +Insan.grunt() # => "*grunt*" #################################################### -- cgit v1.2.3 From 965d7972d1ef7dfbfc9c07de72bbce81898eb703 Mon Sep 17 00:00:00 2001 From: Jeff Erickson Date: Wed, 25 Mar 2015 16:53:46 -0400 Subject: Minor typo: fixed curly bracket direction (} -> {) --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 1b320028..f0ef6600 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -560,7 +560,7 @@ subset VeryBigInteger of Int where * > 500; multi sub sayit(Int $n) { # note the `multi` keyword here say "Number: $n"; } -multi sayit(Str $s) } # a multi is a `sub` by default +multi sayit(Str $s) { # a multi is a `sub` by default say "String: $s"; } sayit("foo"); # prints "String: foo" -- cgit v1.2.3 From 4d74369df3a33f22442ce5938768500d55e9fa94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Thu, 26 Mar 2015 15:23:45 +0200 Subject: Modules --- tr-tr/python3-tr.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index ee858fb6..83ce892d 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -533,32 +533,32 @@ Insan.grunt() # => "*grunt*" #################################################### -## 6. Modules +## 6. Moduller #################################################### -# You can import modules +# Modülleri içe aktarabilirsiniz import math print(math.sqrt(16)) # => 4 -# You can get specific functions from a module +# Modülden belirli bir fonksiyonları alabilirsiniz from math import ceil, floor print(ceil(3.7)) # => 4.0 print(floor(3.7)) # => 3.0 -# You can import all functions from a module. -# Warning: this is not recommended +# Modüldeki tüm fonksiyonları içe aktarabilirsiniz +# Dikkat: bunu yapmanızı önermem. from math import * -# You can shorten module names +# Modül isimlerini değiştirebilirsiniz. +# Not: Modül ismini kısaltmanız çok daha iyi olacaktır import math as m math.sqrt(16) == m.sqrt(16) # => True -# Python modules are just ordinary python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. +# Python modulleri aslında birer python dosyalarıdır. +# İsterseniz siz de yazabilir ve içe aktarabilirsiniz Modulün +# ismi ile dosyanın ismi aynı olacaktır. -# You can find out which functions and attributes -# defines a module. +# Moduldeki fonksiyon ve değerleri öğrenebilirsiniz. import math dir(math) -- cgit v1.2.3 From fde928afa6ef076087acf6c2dbfde0b53ba46e99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Thu, 26 Mar 2015 15:36:05 +0200 Subject: Advanced --- tr-tr/python3-tr.html.markdown | 62 ++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index 83ce892d..fcd57229 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -564,56 +564,54 @@ dir(math) #################################################### -## 7. Advanced +## 7. Gelişmiş #################################################### -# Generators help you make lazy code -def double_numbers(iterable): - for i in iterable: +# Oluşturucular uzun uzun kod yazmamanızı sağlayacak ve yardımcı olacaktır +def kare_sayilar(nesne): + for i in nesne: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# Note range is a generator too. Creating a list 1-900000000 would take lot of -# time to be made -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword +# Bir oluşturucu(generator) değerleri anında oluşturur. +# Bir seferde tüm değerleri oluşturup göndermek yerine teker teker her oluşumdan +# sonra geri döndürür. Bu demektir ki, kare_sayilar fonksiyonumuzda 15'ten büyük +# değerler işlenmeyecektir. +# Not: range() da bir oluşturucu(generator)dur. 1-900000000 arası bir liste yapmaya çalıştığınızda +# çok fazla vakit alacaktır. +# Python tarafından belirlenen anahtar kelimelerden kaçınmak için basitçe alt çizgi(_) kullanılabilir. range_ = range(1, 900000000) -# will double all numbers until a result >=30 found -for i in double_numbers(range_): +# kare_sayilar'dan dönen değer 30'a ulaştığında durduralım +for i in kare_sayilar(range_): print(i) if i >= 30: break -# Decorators -# in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned -# message +# Dekoratörler +# Bu örnekte, +# Eğer lutfen_soyle True ise dönen değer değişecektir. from functools import wraps -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg +def yalvar(hedef_fonksiyon): + @wraps(hedef_fonksiyon) + def metot(*args, **kwargs): + msj, lutfen_soyle = hedef_fonksiyon(*args, **kwargs) + if lutfen_soyle: + return "{} {}".format(msj, "Lütfen! Artık dayanamıyorum :(") + return msj - return wrapper + return metot -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please +@yalvar +def soyle(lutfen_soyle=False): + msj = "Bana soda alır mısın?" + return msj, lutfen_soyle -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +print(soyle()) # Bana soda alır mısın? +print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :( ``` ## Ready For More? -- cgit v1.2.3 From c26eb3384b7c1201d903acfdee67b1709696c249 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Thu, 26 Mar 2015 15:36:45 +0200 Subject: Ready To More? --- tr-tr/python3-tr.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index fcd57229..2477c5da 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -614,9 +614,9 @@ print(soyle()) # Bana soda alır mısın? print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :( ``` -## Ready For More? +## Daha Fazlasına Hazır Mısınız? -### Free Online +### Ücretsiz Online * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) @@ -627,7 +627,7 @@ print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayana * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [Python Course](http://www.python-course.eu/index.php) -### Dead Tree +### Kitaplar * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From e8a1ee8912d1c9bb0145c2afbdc530463fc612b7 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Fri, 27 Mar 2015 15:25:33 +0200 Subject: [haskell.html.markdown] Explanation for Haskell '$' operator with support from @geoffliu --- haskell.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 6bdc78e0..6c98c2b6 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -205,9 +205,8 @@ foo 5 -- 75 -- Haskell has another operator called `$`. This operator applies a function -- to a given parameter. In contrast to standard function application, which -- has highest possible priority of 10 and is left-associative, the `$` operator --- has priority of 0 and is right-associative. Such a low priority means that --- all other operators on both sides of `$` will be evaluated before applying --- the `$`. +-- has priority of 0 and is right-associative. Such a low priority means that +-- the expression on its right is applied as the parameter to the function on its left. -- before (even (fib 7)) -- false -- cgit v1.2.3 From e267eed62caf49d6d2b0d91c60d30b700d08729f Mon Sep 17 00:00:00 2001 From: Max Filippov Date: Mon, 30 Mar 2015 10:08:30 +0300 Subject: c.html: fix #1021 (bitwise negation and shifting into the sign bit) 0x0f is of type int, for 32-bit int the result is 0xfffffff0. 31'st bit is the sign bit of a 32-bit wide int. --- c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 1696d28f..d3f20eda 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -234,7 +234,7 @@ int main() { // same with j-- and --j // Bitwise operators! - ~0x0F; // => 0xF0 (bitwise negation, "1's complement") + ~0x0F; // => 0xFFFFFFF0 (bitwise negation, "1's complement", example result for 32-bit int) 0x0F & 0xF0; // => 0x00 (bitwise AND) 0x0F | 0xF0; // => 0xFF (bitwise OR) 0x04 ^ 0x0F; // => 0x0B (bitwise XOR) @@ -242,7 +242,7 @@ int main() { 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) // Be careful when shifting signed integers - the following are undefined: - // - shifting into the sign bit of a signed integer (int a = 1 << 32) + // - shifting into the sign bit of a signed integer (int a = 1 << 31) // - left-shifting a negative number (int a = -1 << 2) // - shifting by an offset which is >= the width of the type of the LHS: // int a = 1 << 32; // UB if int is 32 bits wide -- cgit v1.2.3 From 8823c084ecf33db212635c2e6c635f6294ec4e89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andre=20Polykanine=20A=2EK=2EA=2E=20Menelion=20Elens=C3=BA?= =?UTF-8?q?l=C3=AB?= Date: Mon, 30 Mar 2015 13:24:30 +0300 Subject: [javascript/ru] Multiline comments correction, fixes #1023 --- ru-ru/javascript-ru.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index e7398c88..79844565 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -22,8 +22,8 @@ Google Chrome, становится все более популярной. ```js // Си-подобные комментарии. Однострочные комментарии начинаются с двух символов слэш, -/* а многострочные комментарии начинаются с звёздочка-слэш - и заканчиваются символами слэш-звёздочка */ +/* а многострочные комментарии начинаются с последовательности слэш-звёздочка + и заканчиваются символами звёздочка-слэш */ // Инструкции могут заканчиваться точкой с запятой ; doStuff(); -- cgit v1.2.3 From 3c565a5535d7f6fb788b2a7b719262dd1a88720b Mon Sep 17 00:00:00 2001 From: nomatteus Date: Mon, 30 Mar 2015 16:13:26 -0400 Subject: Fix syntax error: Remove semicolon from last branch of erlang if-expression. http://erlang.org/doc/reference_manual/expressions.html#id78310 --- erlang.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index 04086aeb..a7390c3e 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -206,7 +206,7 @@ max(X, Y) -> if X > Y -> X; X < Y -> Y; - true -> nil; + true -> nil end. % Warning: at least one of the guards in the `if` expression must evaluate to true; -- cgit v1.2.3 From 212ba8301419923cffb82fa4d4ef7c91832b6096 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Mon, 30 Mar 2015 21:26:26 +0000 Subject: Markdown tr-tr language --- tr-tr/markdown-tr.html.markdown | 251 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 251 insertions(+) create mode 100644 tr-tr/markdown-tr.html.markdown diff --git a/tr-tr/markdown-tr.html.markdown b/tr-tr/markdown-tr.html.markdown new file mode 100644 index 00000000..bac8f6fc --- /dev/null +++ b/tr-tr/markdown-tr.html.markdown @@ -0,0 +1,251 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Eray AYDIN", "http://erayaydin.me/"] +lang: tr-tr +filename: markdown-tr.md +--- + +Markdown, 2004 yılında John Gruber tarafından oluşturuldu. Asıl amacı kolay okuma ve yazmayı sağlamakla beraber kolayca HTML (artık bir çok diğer formatlara) dönüşüm sağlamaktır. + + +```markdown + + + + + + +# Bu bir

+## Bu bir

+### Bu bir

+#### Bu bir

+##### Bu bir

+###### Bu bir
+ + +Bu bir h1 +========= + +Bu bir h2 +--------- + + + +*Bu yazı italik.* +_Bu yazı da italik._ + +**Bu yazı kalın.** +__Bu yazı da kalın.__ + +***Bu yazı hem kalın hem italik.*** +**_Bu da öyle!_** +*__Hatta bu bile!__* + + +~~Bu yazı üstü çizili olarak gözükecek.~~ + + + +Bu bir paragraf. Paragrafın içeriğine devam ediyorum, eğlenceli değil mi? + +Şimdi 2. paragrafıma geçtim. +Hala 2. paragraftayım, çünkü boş bir satır bırakmadım. + +Bu da 3. paragrafım! + + + +Bu yazının sonunda 2 boşluk var (bu satırı seçerek kontrol edebilirsiniz). + +Bir üst satırda
etiketi var! + + + +> Bu bir blok etiketi. Satırlara ayırmak için +> her satırın başında `>` karakter yerleştirmeli veya tek satırda bütün içeriği yazabilirsiniz. +> Satır `>` karakteri ile başladığı sürece sorun yok. + +> Ayrıca alt alta da blok elementi açabilirsiniz +>> iç içe yani +> düzgün değil mi ? + + + + +* Nesne +* Nesne +* Bir başka nesne + +veya + ++ Nesne ++ Nesne ++ Bir başka nesne + +veya + +- Nesne +- Nesne +- Son bir nesne + + + +1. İlk nesne +2. İkinci nesne +3. Üçüncü nesne + + + +1. İlk nesne +1. İkinci nesne +1. Üçüncü nesne + + + + + +1. İlk nesne +2. İkinci nesne +3. Üçüncü nesne + * Alt nesne + * Alt nesne +4. Dördüncü nesne + + +Kutunun içerisinde `x` yoksa eğer seçim kutusu boş olacaktır. +- [ ] Yapılacak ilk görev. +- [ ] Yapılması gereken bir başka görev +Aşağıdaki seçim kutusu ise içi dolu olacaktır. +- [x] Bu görev başarıyla yapıldı + + + + + Bu bir kod + öyle mi? + + + + my_array.each do |item| + puts item + end + + + +Ahmet `go_to()` fonksiyonun ne yaptığını bilmiyor! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + + + + + + +*** +--- +- - - +**************** + + + + +[Bana tıkla!](http://test.com) + + + +[Bana tıkla!](http://test.com "Test.com'a gider") + + +[Müzik dinle](/muzik/). + + + +[Bu linke tıklayarak][link1] daha detaylı bilgi alabilirsiniz! +[Ayrıca bu linki de inceleyin][foobar] tabi istiyorsanız. + +[link1]: http://test.com/ "harika!" +[foobar]: http://foobar.biz/ "okey!" + + + + + +[Bu][] bir link. +[bu]: http://bubirlink.com + + + + + +![Bu alt etiketine gelecek içerik](http://imgur.com/resmim.jpg "Bu da isteğe bağlı olan bir başlık") + + +![Bu alt etiketi.][resmim] + +[resmim]: bagil/linkler/de/calisiyor.jpg "Başlık isterseniz buraya girebilirsiniz" + + + + + ile +[http://testwebsite.com/](http://testwebsite.com) aynı şeyler + + + + + + + +Bu yazının *yıldızlar arasında gözükmesini* istiyorum fakat italik olmamasını istiyorum, +bunun için, şu şekilde: \*bu yazı italik değil, yıldızlar arasında\*. + + + + +| Sütun1 | Sütun 2 | Sütün 3 | +| :----------- | :------: | ------------: | +| Sola dayalı | Ortalı | Sağa dayalı | +| test | test | test | + + + +Sütun 1 | Sütun 2 | Sütun 3 +:-- | :-: | --: +Çok çirkin göözüküyor | değil | mi? + + + +``` + +Daha detaylı bilgi için, John Gruber'in resmi söz dizimi yazısını [buradan](http://daringfireball.net/projects/markdown/syntax) veya Adam Pritchard'ın mükemmel hatırlatma kağıdını [buradan](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) inceleyebilirsiniz. -- cgit v1.2.3 From 5e79da614c98070cfbf908af1c7be9b6abf3b2ed Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 31 Mar 2015 15:46:34 -0700 Subject: Added lang tag to go-fr --- fr-fr/go-fr.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 2ff5902f..16558e7e 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -2,6 +2,7 @@ name: Go category: language language: Go +lang: fr-fr filename: learngo.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] -- cgit v1.2.3 From 4c46a456bd5e33aec2a3cab7b7c33a375d5a97ed Mon Sep 17 00:00:00 2001 From: Philippe Bricout Date: Wed, 1 Apr 2015 15:13:59 +0200 Subject: Update perl6.html.markdown ($_.chars > 50) ~~ True : this is always True. --- perl6.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index f0ef6600..8404f9f8 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -253,7 +253,9 @@ given "foo bar" { when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True, # so you can also put "normal" conditionals. # This when is equivalent to this `if`: - # if ($_.chars > 50) ~~ True {...} + # if $_ ~~ ($_.chars > 50) {...} + # Which means: + # if $_.chars > 50 {...} say "Quite a long string !"; } default { # same as `when *` (using the Whatever Star) -- cgit v1.2.3 From 145ede1f98fed18bbdfc1d1e807551d62deb1154 Mon Sep 17 00:00:00 2001 From: Suzane Sant Ana Date: Sun, 5 Apr 2015 11:24:10 -0300 Subject: Update brainfuck-pt.html.markdown fixing bug: pt-pt instead of pt-br --- pt-br/brainfuck-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/brainfuck-pt.html.markdown index 72c2cf6e..c7ce55ee 100644 --- a/pt-br/brainfuck-pt.html.markdown +++ b/pt-br/brainfuck-pt.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Suzane Sant Ana", "http://github.com/suuuzi"] -lang: pt-pt +lang: pt-br --- Brainfuck (em letras minúsculas, eceto no início de frases) é uma linguagem de -- cgit v1.2.3 From e6b77595f2669d66ac7be43c6e6083cbff80a9a7 Mon Sep 17 00:00:00 2001 From: Suzane Sant Ana Date: Sun, 5 Apr 2015 11:24:34 -0300 Subject: fixing bug: pt-pt instead of pt-br fixing bug: pt-pt instead of pt-br --- pt-br/git-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index b8cbd0a9..981da503 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -1,7 +1,7 @@ --- category: tool tool: git -lang: pt-pt +lang: pt-br filename: LearnGit.txt contributors: - ["Jake Prather", "http://github.com/JakeHP"] -- cgit v1.2.3 From dac116d322ca587647cff5576e3534c33e6e30e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D1=82=D1=8E=D0=BA=20=D0=94=D0=BC=D0=B8=D1=82?= =?UTF-8?q?=D1=80=D0=B8=D0=B9?= Date: Tue, 7 Apr 2015 12:30:52 +0300 Subject: Update python3-ru.html.markdown Typo fix --- ru-ru/python3-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown index fd95c876..2a7b3f7b 100644 --- a/ru-ru/python3-ru.html.markdown +++ b/ru-ru/python3-ru.html.markdown @@ -593,7 +593,7 @@ def double_numbers(iterable): range_ = range(1, 900000000) # Будет удваивать все числа, пока результат не превысит 30 -for i in double_numbers(xrange_): +for i in double_numbers(range_): print(i) if i >= 30: break -- cgit v1.2.3 From cb69cff1be0b22942a29a076d7cabec3fbb5467f Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sat, 11 Apr 2015 12:31:11 +0800 Subject: [c++/cn] Complete the whole translation. --- zh-cn/c++-cn.html.markdown | 410 ++++++++++++++++++++++----------------------- 1 file changed, 205 insertions(+), 205 deletions(-) diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index 24d2a1b8..cbf89c38 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -9,66 +9,66 @@ translators: lang: zh-cn --- -C++是一種系統編程語言。用它的發明者, -[Bjarne Stroustrup的話](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)來說,C++的設計目標是: +C++是一种系统编程语言。用它的发明者, +[Bjarne Stroustrup的话](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)来说,C++的设计目标是: -- 成爲「更好的C語言」 -- 支持數據的抽象與封裝 -- 支持面向對象編程 -- 支持泛型編程 +- 成为“更好的C语言” +- 支持数据的抽象与封装 +- 支持面向对象编程 +- 支持泛型编程 -C++提供了對硬件的緊密控制(正如C語言一樣), -能夠編譯爲機器語言,由處理器直接執行。 -與此同時,它也提供了泛型、異常和類等高層功能。 -雖然C++的語法可能比某些出現較晚的語言更複雜,它仍然得到了人們的青睞—— -功能與速度的平衡使C++成爲了目前應用最廣泛的系統編程語言之一。 +C++提供了对硬件的紧密控制(正如C语言一样), +能够编译为机器语言,由处理器直接执行。 +与此同时,它也提供了泛型、异常和类等高层功能。 +虽然C++的语法可能比某些出现较晚的语言更复杂,它仍然得到了人们的青睞—— +功能与速度的平衡使C++成为了目前应用最广泛的系统编程语言之一。 ```c++ //////////////// -// 與C語言的比較 +// 与C语言的比较 //////////////// -// C++_幾乎_是C語言的一個超集,它與C語言的基本語法有許多相同之處, -// 例如變量和函數的聲明,原生數據類型等等。 +// C++_几乎_是C语言的一个超集,它与C语言的基本语法有许多相同之处, +// 例如变量和函数的声明,原生数据类型等等。 -// 和C語言一樣,在C++中,你的程序會從main()開始執行, -// 該函數的返回值應當爲int型,這個返回值會作爲程序的退出狀態值。 -// 不過,大多數的編譯器(gcc,clang等)也接受 void main() 的函數原型。 -// (參見 http://en.wikipedia.org/wiki/Exit_status 來獲取更多信息) +// 和C语言一样,在C++中,你的程序会从main()开始执行, +// 该函数的返回值应当为int型,这个返回值会作为程序的退出状态值。 +// 不过,大多数的编译器(gcc,clang等)也接受 void main() 的函数原型。 +// (参见 http://en.wikipedia.org/wiki/Exit_status 来获取更多信息) int main(int argc, char** argv) { - // 和C語言一樣,命令行參數通過argc和argv傳遞。 - // argc代表命令行參數的數量, - // 而argv是一個包含「C語言風格字符串」(char *)的數組, - // 其中每個字符串代表一個命令行參數的內容, - // 首個命令行參數是調用該程序時所使用的名稱。 - // 如果你不關心命令行參數的值,argc和argv可以被忽略。 - // 此時,你可以用int main()作爲函數原型。 - - // 退出狀態值爲0時,表示程序執行成功 + // 和C语言一样,命令行参数通过argc和argv传递。 + // argc代表命令行参数的数量, + // 而argv是一个包含“C语言风格字符串”(char *)的数组, + // 其中每个字符串代表一个命令行参数的内容, + // 首个命令行参数是调用该程序时所使用的名称。 + // 如果你不关心命令行参数的值,argc和argv可以被忽略。 + // 此时,你可以用int main()作为函数原型。 + + // 退出状态值为0时,表示程序执行成功 return 0; } -// 然而,C++和C語言也有一些區別: +// 然而,C++和C语言也有一些区别: -// 在C++中,字符字面量的大小是一個字節。 +// 在C++中,字符字面量的大小是一个字节。 sizeof('c') == 1 -// 在C語言中,字符字面量的大小與int相同。 +// 在C语言中,字符字面量的大小与int相同。 sizeof('c') == sizeof(10) -// C++的函數原型與函數定義是嚴格匹配的 -void func(); // 這個函數不能接受任何參數 +// C++的函数原型与函数定义是严格匹配的 +void func(); // 这个函数不能接受任何参数 -// 而在C語言中 -void func(); // 這個函數能接受任意數量的參數 +// 而在C语言中 +void func(); // 这个函数能接受任意数量的参数 -// 在C++中,用nullptr代替C語言中的NULL +// 在C++中,用nullptr代替C语言中的NULL int* ip = nullptr; -// C++也可以使用C語言的標準頭文件, -// 但是需要加上前綴「c」並去掉末尾的「.h」。 +// C++也可以使用C语言的标准头文件, +// 但是需要加上前缀“c”并去掉末尾的“.h”。 #include int main() @@ -78,10 +78,10 @@ int main() } /////////// -// 函數重載 +// 函数重载 /////////// -// C++支持函數重載,【provided each function takes different parameters.】 +// C++支持函数重载,你可以定义一组名称相同而参数不同的函数。 void print(char const* myString) { @@ -95,20 +95,20 @@ void print(int myInt) int main() { - print("Hello"); // 解析爲 void print(const char*) - print(15); // 解析爲 void print(int) + print("Hello"); // 解析为 void print(const char*) + print(15); // 解析为 void print(int) } /////////////////// -// 函數參數的默認值 +// 函数参数的默认值 /////////////////// -// 你可以爲函數的參數指定默認值, -// 它們將會在調用者沒有提供相應參數時被使用。 +// 你可以为函数的参数指定默认值, +// 它们将会在调用者没有提供相应参数时被使用。 void doSomethingWithInts(int a = 1, int b = 4) { - // 對兩個參數進行一些操作 + // 对两个参数进行一些操作 } int main() @@ -118,19 +118,19 @@ int main() doSomethingWithInts(20, 5); // a = 20, b = 5 } -// 默認參數必須放在所有的常規參數之後。 +// 默认参数必须放在所有的常规参数之后。 -void invalidDeclaration(int a = 1, int b) // 這是錯誤的! +void invalidDeclaration(int a = 1, int b) // 这是错误的! { } /////////// -// 命名空間 +// 命名空间 /////////// -// 命名空間爲變量、函數和其他聲明提供了【separate】的作用域。 -// 命名空間可以嵌套使用。 +// 命名空间为变量、函数和其他声明提供了分离的的作用域。 +// 命名空间可以嵌套使用。 namespace First { namespace Nested { @@ -138,8 +138,8 @@ namespace First { { printf("This is First::Nested::foo\n"); } - } // 結束嵌套的命名空間Nested -} // 結束命名空間First + } // 结束嵌套的命名空间Nested +} // 结束命名空间First namespace Second { void foo() @@ -155,38 +155,38 @@ void foo() int main() { - // 如果沒有特別指定,就從「Second」中取得所需的內容。 + // 如果没有特别指定,就从“Second”中取得所需的内容。 using namespace Second; - foo(); // 顯示「This is Second::foo」 - First::Nested::foo(); // 顯示「This is First::Nested::foo」 - ::foo(); // 顯示「This is global foo」 + foo(); // 显示“This is Second::foo” + First::Nested::foo(); // 显示“This is First::Nested::foo” + ::foo(); // 显示“This is global foo” } //////////// -// 輸入/輸出 +// 输入/输出 //////////// -// C++使用「流」來輸入輸出。<<是流的插入運算符,>>是流提取運算符。 -// cin、cout、和cerr分別代表 -// stdin(標準輸入)、stdout(標準輸出)和stderr(標準錯誤)。 +// C++使用“流”来输入输出。<<是流的插入运算符,>>是流提取运算符。 +// cin、cout、和cerr分别代表 +// stdin(标准输入)、stdout(标准输出)和stderr(标准错误)。 -#include // 引入包含輸入/輸出流的頭文件 +#include // 引入包含输入/输出流的头文件 -using namespace std; // 輸入輸出流在std命名空間(也就是標準庫)中。 +using namespace std; // 输入输出流在std命名空间(也就是标准库)中。 int main() { int myInt; - // 在標準輸出(終端/顯示器)中顯示 + // 在标准输出(终端/显示器)中显示 cout << "Enter your favorite number:\n"; - // 從標準輸入(鍵盤)獲得一個值 + // 从标准输入(键盘)获得一个值 cin >> myInt; // cout也提供了格式化功能 cout << "Your favorite number is " << myInt << "\n"; - // 顯示「Your favorite number is 」 + // 显示“Your favorite number is ” cerr << "Used for error messages"; } @@ -195,20 +195,20 @@ int main() // 字符串 ///////// -// C++中的字符串是對象,它們有很多成員函數 +// C++中的字符串是对象,它们有很多成员函数 #include -using namespace std; // 字符串也在std命名空間(標準庫)中。 +using namespace std; // 字符串也在std命名空间(标准库)中。 string myString = "Hello"; string myOtherString = " World"; -// + 可以用於連接字符串。 +// + 可以用于连接字符串。 cout << myString + myOtherString; // "Hello World" cout << myString + " You"; // "Hello You" -// C++中的字符串是可變的,具有「值語義」。 +// C++中的字符串是可变的,具有“值语义”。 myString.append(" Dog"); cout << myString; // "Hello Dog" @@ -217,11 +217,11 @@ cout << myString; // "Hello Dog" // 引用 ///////////// -// 除了支持C語言中的指針類型以外,C++還提供了_引用_。 -// 引用是一種特殊的指針類型,一旦被定義就不能重新賦值,並且不能被設置爲空值。 -// 使用引用時的語法與原變量相同: -// 也就是說,對引用類型進行解引用時,不需要使用*; -// 賦值時也不需要用&來取地址。 +// 除了支持C语言中的指针类型以外,C++还提供了_引用_。 +// 引用是一种特殊的指针类型,一旦被定义就不能重新赋值,并且不能被设置为空值。 +// 使用引用时的语法与原变量相同: +// 也就是说,对引用类型进行解引用时,不需要使用*; +// 赋值时也不需要用&来取地址。 using namespace std; @@ -229,76 +229,76 @@ string foo = "I am foo"; string bar = "I am bar"; -string& fooRef = foo; // 建立了一個對foo的引用。 -fooRef += ". Hi!"; // 通過引用來修改foo的值 +string& fooRef = foo; // 建立了一个对foo的引用。 +fooRef += ". Hi!"; // 通过引用来修改foo的值 cout << fooRef; // "I am foo. Hi!" -// 這句話的並不會改變fooRef的指向,其效果與「foo = bar」相同。 -// 也就是說,在執行這條語句之後,foo == "I am bar"。 +// 这句话的并不会改变fooRef的指向,其效果与“foo = bar”相同。 +// 也就是说,在执行这条语句之后,foo == "I am bar"。 fooRef = bar; const string& barRef = bar; // 建立指向bar的常量引用。 -// 和C語言中一樣,(指針和引用)聲明爲常量時,對應的值不能被修改。 -barRef += ". Hi!"; // 這是錯誤的,不能修改一個常量引用的值。 +// 和C语言中一样,(指针和引用)声明为常量时,对应的值不能被修改。 +barRef += ". Hi!"; // 这是错误的,不能修改一个常量引用的值。 /////////////////// -// 類與面向對象編程 +// 类与面向对象编程 /////////////////// -// 有關類的第一個示例 +// 有关类的第一个示例 #include -// 聲明一個類。 -// 類通常在頭文件(.h或.hpp)中聲明。 +// 声明一个类。 +// 类通常在头文件(.h或.hpp)中声明。 class Dog { - // 成員變量和成員函數默認情況下是私有(private)的。 + // 成员变量和成员函数默认情况下是私有(private)的。 std::string name; int weight; -// 在這個標籤之後,所有聲明都是公有(public)的, -// 直到重新指定「private:」(私有繼承)或「protected:」(保護繼承)爲止 +// 在这个标签之后,所有声明都是公有(public)的, +// 直到重新指定“private:”(私有继承)或“protected:”(保护继承)为止 public: - // 默認的構造器 + // 默认的构造器 Dog(); - // 這裏是成員函數聲明的一個例子。 - // 可以注意到,我們在此處使用了std::string,而不是using namespace std - // 語句using namespace絕不應當出現在頭文件當中。 + // 这里是成员函数声明的一个例子。 + // 可以注意到,我们在此处使用了std::string,而不是using namespace std + // 语句using namespace绝不应当出现在头文件当中。 void setName(const std::string& dogsName); void setWeight(int dogsWeight); - // 如果一個函數不對對象的狀態進行修改, - // 應當在聲明中加上const。 - // 這樣,你就可以對一個以常量方式引用的對象執行該操作。 - // 同時可以注意到,當父類的成員函數需要被子類重寫時, - // 父類中的函數必須被顯式聲明爲_虛函數(virtual)_。 - // 考慮到性能方面的因素,函數默認情況下不會被聲明爲虛函數。 + // 如果一个函数不对对象的状态进行修改, + // 应当在声明中加上const。 + // 这样,你就可以对一个以常量方式引用的对象执行该操作。 + // 同时可以注意到,当父类的成员函数需要被子类重写时, + // 父类中的函数必须被显式声明为_虚函数(virtual)_。 + // 考虑到性能方面的因素,函数默认情况下不会被声明为虚函数。 virtual void print() const; - // 函數也可以在class body內部定義。 - // 這樣定義的函數會自動成爲內聯函數。 + // 函数也可以在class body内部定义。 + // 这样定义的函数会自动成为内联函数。 void bark() const { std::cout << name << " barks!\n" } - // 除了構造器以外,C++還提供了析構器。 - // 當一個對象被刪除或者脫離其定義域時時,它的析構函數會被調用。 - // 這使得RAII這樣的強大範式(參見下文)成爲可能。 - // 爲了衍生出子類來,基類的析構函數必須定義爲虛函數。 + // 除了构造器以外,C++还提供了析构器。 + // 当一个对象被删除或者脱离其定义域时时,它的析构函数会被调用。 + // 这使得RAII这样的强大范式(参见下文)成为可能。 + // 为了衍生出子类来,基类的析构函数必须定义为虚函数。 virtual ~Dog(); -}; // 在類的定義之後,要加一個分號 +}; // 在类的定义之后,要加一个分号 -}; // 記住,在類的定義之後,要加一個分號! +}; // 记住,在类的定义之后,要加一个分号! -// 類的成員函數通常在.cpp文件中實現。 +// 类的成员函数通常在.cpp文件中实现。 void Dog::Dog() { std::cout << "A dog has been constructed\n"; } -// 對象(例如字符串)應當以引用的形式傳遞, -// 對於不需要修改的對象,最好使用常量引用。 +// 对象(例如字符串)应当以引用的形式传递, +// 对于不需要修改的对象,最好使用常量引用。 void Dog::setName(const std::string& dogsName) { name = dogsName; @@ -309,7 +309,7 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// 虛函數的virtual關鍵字只需要在聲明時使用,不需要在定義時出現 +// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时出现 void Dog::print() const { std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; @@ -325,7 +325,7 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// 虛函數的virtual關鍵字只需要在聲明時使用,不需要在定義時重複 +// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复 void Dog::print() const { std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; @@ -337,32 +337,32 @@ void Dog::~Dog() } int main() { - Dog myDog; // 此時顯示「A dog has been constructed」 + Dog myDog; // 此时显示“A dog has been constructed” myDog.setName("Barkley"); myDog.setWeight(10); - myDog.printDog(); // 顯示「Dog is Barkley and weighs 10 kg」 + myDog.printDog(); // 显示“Dog is Barkley and weighs 10 kg” return 0; -} // 顯示「Goodbye Barkley」 +} // 显示“Goodbye Barkley” -// 繼承: +// 继承: -// 這個類繼承了Dog類中的公有(public)和保護(protected)對象 +// 这个类继承了Dog类中的公有(public)和保护(protected)对象 class OwnedDog : public Dog { void setOwner(const std::string& dogsOwner) - // 重寫OwnedDogs類的print方法。 - // 如果你不熟悉子類多態的話,可以參考這個頁面中的概述: + // 重写OwnedDogs类的print方法。 + // 如果你不熟悉子类多态的话,可以参考这个页面中的概述: // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping - // override關鍵字是可選的,它確保你是在重寫基類中的方法。 + // override关键字是可选的,它确保你所重写的是基类中的方法。 void print() const override; private: std::string owner; }; -// 與此同時,在對應的.cpp文件裏: +// 与此同时,在对应的.cpp文件里: void OwnedDog::setOwner(const std::string& dogsOwner) { @@ -371,7 +371,7 @@ void OwnedDog::setOwner(const std::string& dogsOwner) void OwnedDog::print() const { - Dog::print(); // 調用基類Dog中的print方法 + Dog::print(); // 调用基类Dog中的print方法 // "Dog is and weights " std::cout << "Dog is owned by " << owner << "\n"; @@ -379,45 +379,46 @@ void OwnedDog::print() const } ///////////////////// -// 初始化與運算符重載 +// 初始化与运算符重载 ///////////////////// -// 在C++中,你可以重載+、-、*、/等運算符的行爲。 -// 【This is done by defining a function -// which is called whenever the operator is used. +// 在C++中,通过定义一些特殊名称的函数, +// 你可以重载+、-、*、/等运算符的行为。 +// 当运算符被使用时,这些特殊函数会被调用,从而实现运算符重载。 #include using namespace std; class Point { public: - // 可以以這樣的方式爲成員變量設置默認值。 + // 可以以这样的方式为成员变量设置默认值。 double x = 0; double y = 0; - // 【Define a default constructor which does nothing - // but initialize the Point to the default value (0, 0) + // 定义一个默认的构造器。 + // 除了将Point初始化为(0, 0)以外,这个函数什么都不做。 Point() { }; - // 【The following syntax is known as an initialization list - // and is the proper way to initialize class member values + // 下面使用的语法称为初始化列表, + // 这是初始化类中成员变量的正确方式。 Point (double a, double b) : x(a), y(b) - { /* 【Do nothing except initialize the values */ } + { /* 除了初始化成员变量外,什么都不做 */ } - // 重載 + 運算符 + // 重载 + 运算符 Point operator+(const Point& rhs) const; - // 重載 += 運算符 + // 重载 += 运算符 Point& operator+=(const Point& rhs); - // 增加 - 和 -= 運算符也是有意義的,這裏不再贅述。 + // 增加 - 和 -= 运算符也是有意义的,但这里不再赘述。 }; Point Point::operator+(const Point& rhs) const { - // 【Create a new point that is the sum of this one and rhs. + // 创建一个新的点, + // 其横纵坐标分别为这个点与另一点在对应方向上的坐标之和。 return Point(x + rhs.x, y + rhs.y); } @@ -431,88 +432,88 @@ Point& Point::operator+=(const Point& rhs) int main () { Point up (0,1); Point right (1,0); - // 這裏調用了Point類型的運算符「+」 - // 調用up(Point類型)的「+」方法,並以right作爲函數的參數 + // 这里使用了Point类型的运算符“+” + // 调用up(Point类型)的“+”方法,并以right作为函数的参数 Point result = up + right; - // 顯示「Result is upright (1,1)」 + // 显示“Result is upright (1,1)” cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; return 0; } /////////// -// 異常處理 +// 异常处理 /////////// -// 標準庫中提供了一些基本的異常類型 -// (參見http://en.cppreference.com/w/cpp/error/exception) -// 但是,其他任何類型也可以作爲一個異常被拋出 +// 标准库中提供了一些基本的异常类型 +// (参见http://en.cppreference.com/w/cpp/error/exception) +// 但是,其他任何类型也可以作为一个异常被拋出 #include -// 在_try_代碼塊中拋出的異常可以被隨後的_catch_捕獲。 +// 在_try_代码块中拋出的异常可以被随后的_catch_捕获。 try { - // 不要用 _new_關鍵字在堆上爲異常分配空間。 + // 不要用 _new_关键字在堆上为异常分配空间。 throw std::exception("A problem occurred"); } -// 如果拋出的異常是一個對象,可以用常量引用來捕獲它 +// 如果拋出的异常是一个对象,可以用常量引用来捕获它 catch (const std::exception& ex) { std::cout << ex.what(); -// 捕獲尚未被_catch_處理的所有錯誤 +// 捕获尚未被_catch_处理的所有错误 } catch (...) { std::cout << "Unknown exception caught"; - throw; // 重新拋出異常 + throw; // 重新拋出异常 } /////// // RAII /////// -// RAII指的是「资源获取就是初始化」(Resource Allocation Is Initialization), -// 它被視作C++中最強大的編程範式之一。 -// 簡單說來,它指的是,用構造函數來獲取一個對象的資源, -// 相應的,借助析構函數來釋放對象的資源。 +// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization), +// 它被视作C++中最强大的编程范式之一。 +// 简单说来,它指的是,用构造函数来获取一个对象的资源, +// 相应的,借助析构函数来释放对象的资源。 -// 爲了理解這一範式的用處,讓我們考慮某個函數使用文件句柄時的情況: +// 为了理解这一范式的用处,让我们考虑某个函数使用文件句柄时的情况: void doSomethingWithAFile(const char* filename) { - // 首先,讓我們假設一切都會順利進行。 + // 首先,让我们假设一切都会顺利进行。 - FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 + FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); - fclose(fh); // 關閉文件句柄 + fclose(fh); // 关闭文件句柄 } -// 不幸的是,隨着錯誤處理機制的引入,事情會變得複雜。 -// 假設fopen函數有可能執行失敗, -// 而doSomethingWithTheFile和doSomethingElseWithIt會在失敗時返回錯誤代碼。 -// (雖然異常是C++中處理錯誤的推薦方式, -// 但是某些程序員,尤其是有C語言背景的,並不認可異常捕獲機制的作用)。 -// 現在,我們必須檢查每個函數調用是否成功執行,並在問題發生的時候關閉文件句柄。 +// 不幸的是,随着错误处理机制的引入,事情会变得复杂。 +// 假设fopen函数有可能执行失败, +// 而doSomethingWithTheFile和doSomethingElseWithIt会在失败时返回错误代码。 +// (虽然异常是C++中处理错误的推荐方式, +// 但是某些程序员,尤其是有C语言背景的,并不认可异常捕获机制的作用)。 +// 现在,我们必须检查每个函数调用是否成功执行,并在问题发生的时候关闭文件句柄。 bool doSomethingWithAFile(const char* filename) { - FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 - if (fh == nullptr) // 當執行失敗是,返回的指針是nullptr - return false; // 向調用者彙報錯誤 + FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 + if (fh == nullptr) // 当执行失败是,返回的指针是nullptr + return false; // 向调用者汇报错误 - // 假設每個函數會在執行失敗時返回false + // 假设每个函数会在执行失败时返回false if (!doSomethingWithTheFile(fh)) { - fclose(fh); // Close the file handle so it doesn't leak. - return false; // 反饋錯誤 + fclose(fh); // 关闭文件句柄,避免造成内存泄漏。 + return false; // 反馈错误 } if (!doSomethingElseWithIt(fh)) { - fclose(fh); // Close the file handle so it doesn't leak. - return false; // 反饋錯誤 + fclose(fh); // 关闭文件句柄 + return false; // 反馈错误 } - fclose(fh); // Close the file handle so it doesn't leak. - return true; // 指示函數已成功執行 + fclose(fh); // 关闭文件句柄 + return true; // 指示函数已成功执行 } -// C語言的程序員通常會借助goto語句簡化上面的代碼: +// C语言的程序员通常会借助goto语句简化上面的代码: bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); @@ -525,19 +526,19 @@ bool doSomethingWithAFile(const char* filename) if (!doSomethingElseWithIt(fh)) goto failure; - fclose(fh); // 關閉文件 - return true; // 執行成功 + fclose(fh); // 关闭文件 + return true; // 执行成功 failure: fclose(fh); - return false; // 反饋錯誤 + return false; // 反馈错误 } -// 如果用異常捕獲機制來指示錯誤的話, -// 代碼會變得清晰一些,但是仍然有優化的餘地。 +// 如果用异常捕获机制来指示错误的话, +// 代码会变得清晰一些,但是仍然有优化的餘地。 void doSomethingWithAFile(const char* filename) { - FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 + FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 if (fh == nullptr) throw std::exception("Could not open the file."); @@ -546,45 +547,44 @@ void doSomethingWithAFile(const char* filename) doSomethingElseWithIt(fh); } catch (...) { - fclose(fh); // 保證出錯的時候文件被正確關閉 + fclose(fh); // 保证出错的时候文件被正确关闭 throw; // Then re-throw the exception. } - fclose(fh); // 關閉文件 - // 所有工作順利完成 + fclose(fh); // 关闭文件 + // 所有工作顺利完成 } -// 【Compare this to the use of C++'s file stream class (fstream) -// fstream利用自己的析構器來關閉文件句柄。 -// 【Recall from above that destructors are automatically called -// whenver an object falls out of scope. +// 相比之下,使用C++中的文件流类(fstream)时, +// fstream会利用自己的析构器来关闭文件句柄。 +// 只要离开了某一对象的定义域,它的析构函数就会被自动调用。 void doSomethingWithAFile(const std::string& filename) { - // ifstream是輸入文件流(input file stream)的簡稱 - std::ifstream fh(filename); // Open the file + // ifstream是输入文件流(input file stream)的简称 + std::ifstream fh(filename); // 打开一个文件 - // 對文件進行一些操作 + // 对文件进行一些操作 doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); -} // 文件已經被析構器自動關閉 - -// 與上面幾種方式相比,這種方式有着_明顯_的優勢: -// 1. 無論發生了什麼情況,資源(此例當中是文件句柄)都會被正確關閉。 -// 只要你正確使用了析構器,就_不會_因爲忘記關閉句柄,造成資源的泄漏。 -// 2. 可以注意到,通過這種方式寫出來的代碼十分簡潔。 -// 析構器會在後臺關閉文件句柄,不再需要你來操心這些瑣事。 -// 3. 【The code is exception safe. -// 無論在函數中的何處拋出異常,都不會阻礙對文件資源的釋放。 - -// 地道的C++代碼應當把RAII的使用擴展到各種類型的資源上,包括: -// - 用unique_ptr和shared_ptr管理的內存 -// - 各種數據容器,例如標準庫中的鏈表、向量(容量自動擴展的數組)、散列表等; -// 當它們脫離作用域時,析構器會自動釋放其中儲存的內容。 -// - 用lock_guard和unique_lock實現的互斥 +} // 文件已经被析构器自动关闭 + +// 与上面几种方式相比,这种方式有着_明显_的优势: +// 1. 无论发生了什么情况,资源(此例当中是文件句柄)都会被正确关闭。 +// 只要你正确使用了析构器,就_不会_因为忘记关闭句柄,造成资源的泄漏。 +// 2. 可以注意到,通过这种方式写出来的代码十分简洁。 +// 析构器会在后臺关闭文件句柄,不再需要你来操心这些琐事。 +// 3. 这种方式的代码具有异常安全性。 +// 无论在函数中的何处拋出异常,都不会阻碍对文件资源的释放。 + +// 地道的C++代码应当把RAII的使用扩展到各种类型的资源上,包括: +// - 用unique_ptr和shared_ptr管理的内存 +// - 各种数据容器,例如标准库中的链表、向量(容量自动扩展的数组)、散列表等; +// 当它们脱离作用域时,析构器会自动释放其中储存的内容。 +// - 用lock_guard和unique_lock实现的互斥 ``` -擴展閱讀: +扩展阅读: - 提供了最新的語法參考。 + 提供了最新的语法参考。 -可以在 找到一些補充資料。 +可以在 找到一些补充资料。 -- cgit v1.2.3 From c38d8d93135561e8c0afbe20a5b16b39917ee06c Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sat, 11 Apr 2015 12:40:47 +0800 Subject: [c++/cn] Update the translated file name. --- zh-cn/c++-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index cbf89c38..eed20721 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -1,6 +1,6 @@ --- language: c++ -filename: learncpp.cpp +filename: learncpp-cn.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] -- cgit v1.2.3 From 299f3de0eacfe4e3d1303135716ad14a09bb0118 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sat, 11 Apr 2015 12:52:23 +0800 Subject: [c++/en] Fix spelling --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 1978d183..1a84efa4 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -555,7 +555,7 @@ void doSomethingWithAFile(const char* filename) // Compare this to the use of C++'s file stream class (fstream) // fstream uses its destructor to close the file. // Recall from above that destructors are automatically called -// whenver an object falls out of scope. +// whenever an object falls out of scope. void doSomethingWithAFile(const std::string& filename) { // ifstream is short for input file stream -- cgit v1.2.3 From b95c6b0dae6b91d1c88c337863e8fe182e326b4e Mon Sep 17 00:00:00 2001 From: yejinchang Date: Wed, 15 Apr 2015 15:54:53 +0800 Subject: translate scala doc into chinese --- zh-cn/scala-cn.html.markdown | 553 +++++++++++++++++++++++++++++-------------- 1 file changed, 378 insertions(+), 175 deletions(-) diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 58f5cd47..5d5d93c7 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -4,8 +4,10 @@ filename: learnscala-zh.scala contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] translators: - ["Peiyong Lin", ""] + - ["Jinchang Ye", "http://github.com/alwayswithme"] lang: zh-cn --- @@ -17,23 +19,31 @@ Scala - 一门可拓展性的语言 自行设置: 1) 下载 Scala - http://www.scala-lang.org/downloads - 2) unzip/untar 到你喜欢的地方,放在路径中的 bin 目录下 - 3) 在终端输入 scala,开启 Scala 的 REPL,你会看到提示符: + 2) unzip/untar 到您喜欢的地方,并把 bin 子目录添加到 path 环境变量 + 3) 在终端输入 scala,启动 Scala 的 REPL,您会看到提示符: scala> - 这就是所谓的 REPL,你现在可以在其中运行命令,让我们做到这一点: + 这就是所谓的 REPL (读取-求值-输出循环,英语: Read-Eval-Print Loop), + 您可以在其中输入合法的表达式,结果会被打印。 + 在教程中我们会进一步解释 Scala 文件是怎样的,但现在先了解一点基础。 */ -println(10) // 打印整数 10 -println("Boo!") // 打印字符串 "BOO!" +///////////////////////////////////////////////// +// 1. 基础 +///////////////////////////////////////////////// +// 单行注释开始于两个斜杠 -// 一些基础 +/* + 多行注释,如您之前所见,看起来像这样 +*/ // 打印并强制换行 println("Hello world!") +println(10) + // 没有强制换行的打印 print("Hello world") @@ -41,13 +51,19 @@ print("Hello world") // val 声明是不可变的,var 声明是可修改的。不可变性是好事。 val x = 10 // x 现在是 10 x = 20 // 错误: 对 val 声明的变量重新赋值 -var x = 10 -x = 20 // x 现在是 20 +var y = 10 +y = 20 // y 现在是 20 -// 单行注释开始于两个斜杠 -/* -多行注释看起来像这样。 +/* + Scala 是静态语言,但注意上面的声明方式,我们没有指定类型。 + 这是因为类型推导的语言特性。大多数情况, Scala 编译器可以推测变量的类型, + 所以您不需要每次都输入。可以像这样明确声明变量类型: */ +val z: Int = 10 +val a: Double = 1.0 + +// 注意从 Int 到 Double 的自动转型,结果是 10.0, 不是 10 +val b: Double = 10 // 布尔值 true @@ -64,9 +80,11 @@ true == false // false 2 - 1 // 1 5 * 3 // 15 6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 -// 在 REPL 计算一个命令会返回给你结果的类型和值 +// 在 REPL 计算一个表达式会返回给您结果的类型和值 1 + 7 @@ -77,58 +95,190 @@ true == false // false 这意味着计算 1 + 7 的结果是一个 Int 类型的对象,其值为 8 - 1+7 的结果是一样的 + 注意 "res29" 是一个连续生成的变量名,用以存储您输入的表达式结果, + 您看到的输入可能不一样。 */ +"Scala strings are surrounded by double quotes" +'a' // Scala 的字符 +// '不存在单引号字符串' <= 这会导致错误 -// 包括函数在内,每一个事物都是对象。在 REPL 中输入: +// 字符串定义了常见的 Java 方法 +"hello world".length +"hello world".substring(2, 6) +"hello world".replace("C", "3") -7 // 结果 res30: Int = 7 (res30 是一个生成的结果的 var 命名) +// 也有一些额外的 Scala 方法,另请参见:scala.collection.immutable.StringOps +"hello world".take(5) +"hello world".drop(5) -// 下一行给你一个接收一个 Int 类型并返回该数的平方的函数 -(x:Int) => x * x +// 字符串改写:留意前缀 "s" +val n = 45 +s"We have $n apples" // => "We have 45 apples" -// 你可以分配给函数一个标识符,像这样: -val sq = (x:Int) => x * x +// 在要改写的字符串中使用表达式也是可以的 +val a = Array(11, 9, 6) +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" -/* 上面的例子说明 - - sq: Int => Int = +// 添加 "f" 前缀对要改写的字符串进行格式化 +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" - 意味着这次我们给予了 sq 这样一个显式的名字给一个接受一个 Int 类型值并返回 一个 Int 类型值的函数 +// 未处理的字符串,忽略特殊字符。 +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." - sq 可以像下面那样被执行: -*/ +// 一些字符需要转义,比如字符串中的双引号 +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" -sq(10) // 返回给你:res33: Int = 100. +// 三个双引号可以使字符串跨越多行,并包含引号 +val html = """
+

Press belo', Joe

+ +
""" -// Scala 允许方法和函数返回或者接受其它的函数或者方法作为参数。 -val add10: Int => Int = _ + 10 // 一个接受一个 Int 类型参数并返回一个 Int 类型值的函数 -List(1, 2, 3) map add10 // List(11, 12, 13) - add10 被应用到每一个元素 +///////////////////////////////////////////////// +// 2. 函数 +///////////////////////////////////////////////// + +// 函数可以这样定义: +// +// def functionName(args...): ReturnType = { body... } +// +// 如果您以前学习过传统的编程语言,注意 return 关键字的省略。 +// 在 Scala 中, 函数代码块最后一条表达式就是返回值。 +def sumOfSquares(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} -// 匿名函数可以被使用来代替有命名的函数: -List(1, 2, 3) map (x => x + 10) +// 如果函数体是单行表达式,{ } 可以省略: +def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y -// 下划线标志,如果匿名函数只有一个参数可以被使用来表示该参数变量 -List(1, 2, 3) map (_ + 10) +// 函数调用的语法是熟知的: +sumOfSquares(3, 4) // => 25 -// 如果你所应用的匿名块和匿名函数都接受一个参数,那么你甚至可以省略下划线 -List("Dom", "Bob", "Natalia") foreach println +// 在多数情况下 (递归函数是需要注意的例外), 函数返回值可以省略, +// 变量所用的类型推导一样会应用到函数返回值中: +def sq(x: Int) = x * x // 编译器会推断得知返回值是 Int + +// 函数可以有默认参数 +def addWithDefault(x: Int, y: Int = 5) = x + y +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 + + +// 匿名函数是这样的: +(x:Int) => x * x + +// 和 def 不同,如果语义清晰,匿名函数的输入类型也可以省略。 +// 类型 "Int => Int" 意味着这个函数接收一个 Int 并返回一个 Int。 +val sq: Int => Int = x => x * x + +// 匿名函数的调用也是类似的: +sq(10) // => 100 + +// 如果您的匿名函数有一到两个参数,每一个参数仅使用一次, +// Scala 提供一个更简洁的方式来定义他们。这样的匿名函数极为常见, +// 在数据结构部分会明显可见。 +val addOne: Int => Int = _ + 1 +val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) + +addOne(5) // => 6 +weirdSum(2, 4) // => 16 + + +// return 关键字是存在的,但它从最里面包裹了 return 的 def 函数中返回。 +// 警告: 在 Scala 中使用 return 容易出错,应该避免使用。 +// 在匿名函数中没有效果,例如: +def foo(x: Int): Int = { + val anonFunc: Int => Int = { z => + if (z > 5) + return z // 这一行令 z 成为 foo 函数的返回值! + else + z + 2 // 这一行是 anonFunc 函数的返回值 + } + anonFunc(x) // 这一行是 foo 函数的返回值 +} + +/* + * 译者注:此处是指匿名函数中的 return z 成为最后执行的语句, + * 在 anonFunc(x) 下面的表达式(假设存在)不再执行。如果 anonFunc + * 是用 def 定义的函数, return z 仅返回到 anonFunc(x) , + * 在 anonFunc(x) 下面的表达式(假设存在)会继续执行。 + */ +///////////////////////////////////////////////// +// 3. 控制语句 +///////////////////////////////////////////////// -// 数据结构 +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// 留意: Scala 对点和括号的要求比较宽松,对这些规则加以区分。 +// 这有助于写出读起来像英语的 DSL(领域特定语言) 和 API(应用编程接口)。 + +(5 to 1 by -1) foreach ( println ) + +// while 循环 +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // 没错,再执行一次,发生了什么?为什么? + +i // 显示 i 的值。注意 while 是经典的循环方式,它连续执行并改变循环中的变量。 + // while 执行很快,比 Java 的循环快,但像上面所看到的那样用组合子和推导式 + // 更易于理解和并行化。 + +// do while 循环 +do { + println("x is still less than 10"); + x += 1 +} while (x < 10) + +// Scala 中尾递归是一种符合语言习惯的递归方式。 +// 递归函数需要清晰的返回类型,编译器不能推断得知。 +// 这是一个 Unit。 +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} +showNumbersInRange(1,14) + + +// 条件语句 + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nay") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + + +///////////////////////////////////////////////// +// 4. 数据结构 +///////////////////////////////////////////////// val a = Array(1, 2, 3, 5, 8, 13) a(0) a(3) -a(21) // 这会抛出一个异常 +a(21) // 抛出异常 val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") m("fork") m("spoon") -m("bottle") // 这会抛出一个异常 +m("bottle") // 抛出异常 val safeM = m.withDefaultValue("no lo se") safeM("bottle") @@ -137,9 +287,9 @@ val s = Set(1, 3, 7) s(0) s(1) -/* 查看 map 的文档 - * 点击[这里](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map) - * 确保你可以读它 +/* 这里查看 map 的文档 - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * 并确保你会阅读 */ @@ -157,7 +307,7 @@ s(1) val divideInts = (x:Int, y:Int) => (x / y, x % y) -divideInts(10,3) // 函数 divideInts 返回你结果和余数 +divideInts(10,3) // 函数 divideInts 返回您结果和余数 // 要读取元组的元素,使用 _._n,n是从1开始的元素索引 @@ -168,234 +318,287 @@ d._1 d._2 +///////////////////////////////////////////////// +// 5. 面向对象编程 +///////////////////////////////////////////////// -// 选择器 - -s.map(sq) - -val sSquared = s. map(sq) - -sSquared.filter(_ < 10) +/* + 旁白: 教程中到现在为止我们所做的一切只是简单的表达式(值,函数等)。 + 这些表达示可以输入到命令行解释器中作为快速测试,但它们无法单一的存在于 Scala + 文件。举个例子,您不能在 Scala 文件上简单的写上 "val x = 5"。而 Scala 允许存 + 在的顶级结构是: -sSquared.reduce (_+_) + - objects + - classes + - case classes + - traits -// filter 函数接受一个预测(一个函数,形式为 A -> Boolean) 并选择出所有的元素满足这个预测 + 现在来解释这些是什么。 +*/ -List(1, 2, 3) filter (_ > 2) // List(3) -List( - Person(name = "Dom", age = 23), - Person(name = "Bob", age = 30) -).filter(_.age > 25) // List(Person("Bob", 30)) +// 类和其他语言的类相似,构造器参数在类名后声明,初始化在类结构体中完成。 +class Dog(br: String) { + // 构造器代码在此 + var breed: String = br + // 定义名为 bark 的方法,返回字符串 + def bark = "Woof, woof!" -// Scala 的 foreach 方法定义在特定的接受一个类型的集合上 -// 返回 Unit(一个 void 方法) -aListOfNumbers foreach (x => println(x)) -aListOfNumbers foreach println + // 值和方法作用域假定为 public。"protected" 和 "private" 关键字也是可用的。 + private def sleep(hours: Int) = + println(s"I'm sleeping for $hours hours") + // 抽象方法是没有方法体的方法。如果取消下面那行注释,Dog 类需要被声明为 abstract + // abstract class Dog(...) { ... } + // def chaseAfter(what: String): String +} +val mydog = new Dog("greyhound") +println(mydog.breed) // => "greyhound" +println(mydog.bark) // => "Woof, woof!" -// For 包含 +// "object" 关键字创造一种类型和该类型的单例。 +// Scala 的 class 常常也含有一个 “伴生对象”,class 中包含每个实例的行为,所有实例 +// 共用的行为则放入 object 中。两者的区别和其他语言中方法和静态方法类似。 +// 请注意 object 和 class 可以同名。 +object Dog { + def allKnownBreeds = List("pitbull", "shepherd", "retriever") + def createDog(breed: String) = new Dog(breed) +} -for { n <- s } yield sq(n) -val nSquared2 = for { n <- s } yield sq(n) +// Case 类是有额外内建功能的类。Scala 初学者常遇到的问题之一便是何时用类 +// 和何时用 case 类。界线比较模糊,但通常类倾向于封装,多态和行为。类中的值 +// 的作用域一般为 private , 只有方向是暴露的。case 类的主要目的是放置不可变 +// 数据。它们通常只有几个方法,且方法几乎没有副作用。 +case class Person(name: String, phoneNumber: String) -for { n <- nSquared2 if n < 10 } yield n +// 创造新实例,注意 case 类不需要 "new" 关键字 +val george = Person("George", "1234") +val kate = Person("Kate", "4567") -for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared +// 使用 case 类,您可以轻松得到一些功能,像 getters: +george.phoneNumber // => "1234" -/* 注意:这些不是 for 循环. 一个 for 循环的语义是 '重复'('repeat'), - 然而,一个 for-包含 定义了一个两个数据结合间的关系 */ +// 每个字段的相等性(无需覆盖 .equals) +Person("George", "1234") == Person("Kate", "1236") // => false +// 简单的拷贝方式 +// otherGeorge == Person("george", "9876") +val otherGeorge = george.copy(phoneNumber = "9876") +// 还有很多。case 类同时可以用于模式匹配,接下来会看到。 -// 循环和迭代 -1 to 5 -val r = 1 to 5 -r.foreach( println ) +// 敬请期待 Traits ! -r foreach println -// 注意:Scala 是相当宽容的当它遇到点和括号 - 分别地学习这些规则。 -// 这帮助你编写读起来像英语的 DSLs 和 APIs -(5 to 1 by -1) foreach ( println ) +///////////////////////////////////////////////// +// 6. 模式匹配 +///////////////////////////////////////////////// -// while 循环 -var i = 0 -while (i < 10) { println("i " + i); i+=1 } - -while (i < 10) { println("i " + i); i+=1 } // 发生了什么?为什么? - -i // 展示 i 的值。注意到 while 是一个传统意义上的循环 - // 它顺序地执行并且改变循环变量的值。while 非常快,比 Java // 循环快, - // 但是在其上使用选择器和包含更容易理解和并行。 - -// do while 循环 -do { - println("x is still less then 10"); - x += 1 -} while (x < 10) +// 模式匹配是一个强大和常用的 Scala 特性。这是用模式匹配一个 case 类的例子。 +// 留意:不像其他语言, Scala 的 case 不需要 break, 其他语言中 switch 语句的 +// fall-through 现象不会发生。 -// 在 Scala中,尾递归是一种惯用的执行循环的方式。 -// 递归函数需要显示的返回类型,编译器不能推断出类型。 -// 这里它是 Unit。 -def showNumbersInRange(a:Int, b:Int):Unit = { - print(a) - if (a < b) - showNumbersInRange(a + 1, b) +def matchPerson(person: Person): String = person match { + // Then you specify the patterns: + case Person("George", number) => "We found George! His number is " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number } +val email = "(.*)@(.*)".r // 定义下一个例子会用到的正则 +// 模式匹配看起来和 C语言家族的 switch 语句相似,但更为强大。 +// Scala 中您可以很多东西: +def matchEverything(obj: Any): String = obj match { + // 匹配值: + case "Hello world" => "Got the string Hello world" -// 条件语句 - -val x = 10 - -if (x == 1) println("yeah") -if (x == 10) println("yeah") -if (x == 11) println("yeah") -if (x == 11) println ("yeah") else println("nay") + // 匹配类型: + case x: Double => "Got a Double: " + x -println(if (x == 10) "yeah" else "nope") -val text = if (x == 10) "yeah" else "nope" + // 匹配时指定条件 + case x: Int if x > 10000 => "Got a pretty big number!" -var i = 0 -while (i < 10) { println("i " + i); i+=1 } + // 像之前一样匹配 case 类: + case Person(name, number) => s"Got contact info for $name!" + // 匹配正则表达式: + case email(name, domain) => s"Got email address $name@$domain" + // 匹配元组: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" -// 面向对象特性 + // 匹配数据结构: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" -// 类名是 Dog -class Dog { - //bark 方法,返回字符串 - def bark: String = { - // the body of the method - "Woof, woof!" - } + // 模式可以嵌套 + case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" } -// 类可以包含几乎其它的构造,包括其它的类, -// 函数,方法,对象,case 类,特性等等。 - - +// 事实上,你可以对任何有 "unapply" 方法的对象进行模式匹配。 +// 这个特性如此强大以致于 Scala 允许定义一个函数作为模式匹配: +val patternFunc: Person => String = { + case Person("George", number) => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} -// Case 类 -case class Person(name:String, phoneNumber:String) +///////////////////////////////////////////////// +// 7. 函数式编程 +///////////////////////////////////////////////// -Person("George", "1234") == Person("Kate", "1236") +// Scala 允许方法和函数作为其他方法和函数的参数和返回值。 +val add10: Int => Int = _ + 10 // 一个接受一个 Int 类型参数并返回一个 Int 类型值的函数 +List(1, 2, 3) map add10 // List(11, 12, 13) - add10 被应用到每一个元素 +// 匿名函数可以被使用来代替有命名的函数: +List(1, 2, 3) map (x => x + 10) +// 下划线标志,如果匿名函数只有一个参数可以被使用来表示该参数变量 +List(1, 2, 3) map (_ + 10) -// 模式匹配 +// 如果您所应用的匿名块和匿名函数都接受一个参数,那么你甚至可以省略下划线 +List("Dom", "Bob", "Natalia") foreach println -val me = Person("George", "1234") -me match { case Person(name, number) => { - "We matched someone : " + name + ", phone : " + number }} +// 组合子 -me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } +// 译注: val sq: Int => Int = x => x * x +s.map(sq) -me match { case Person("George", number) => "Match"; case _ => "Hm..." } +val sSquared = s. map(sq) -me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } +sSquared.filter(_ < 10) -me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } +sSquared.reduce (_+_) -val kate = Person("Kate", "1234") +// filter 函数接受一个 predicate (函数从 A -> Boolean)并选择 +// 所有满足 predicate 的元素 +List(1, 2, 3) filter (_ > 2) // List(3) +case class Person(name:String, age:Int) +List( + Person(name = "Dom", age = 23), + Person(name = "Bob", age = 30) +).filter(_.age > 25) // List(Person("Bob", 30)) -kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } +// Scala 的 foreach 方法定义在特定集合中,接受一个类型并返回 Unit (void 方法) +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println +// For 推导式 -// 正则表达式 +for { n <- s } yield sq(n) -val email = "(.*)@(.*)".r // 在字符串上调用 r 会使它变成一个正则表达式 +val nSquared2 = for { n <- s } yield sq(n) -val email(user, domain) = "henry@zkpr.com" +for { n <- nSquared2 if n < 10 } yield n -"mrbean@pyahoo.com" match { - case email(name, domain) => "I know your name, " + name -} +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared +/* 注意,这些不是 for 循环,for 循环的语义是‘重复’,然而 for 推导式定义 + 两个数据集合的关系。 */ -// 字符串 +///////////////////////////////////////////////// +// 8. 隐式转换 +///////////////////////////////////////////////// -"Scala 字符串被双引号包围" // -'a' // Scala 字符 -'单引号的字符串不存在' // 错误 -"字符串拥有通常的 Java 方法定义在其上".length -"字符串也有额外的 Scala 方法".reverse +/* 警告 警告: 隐式转换是 Scala 中一套强大的特性,因此容易被滥用。 + * Scala 初学者在理解它们的工作原理和最佳实践之前,应抵制使用它的诱惑。 + * 我们加入这一章节仅因为它们在 Scala 的库中太过常见,导致没有用隐式转换的库 + * 就不可能做有意义的事情。这章节主要让你理解和使用隐式转换,而不是自己声明。 + */ -// 参见: scala.collection.immutable.StringOps +// 任何值(val, 函数,对象等)可以被声明为隐式的,你可以猜到的,通过加上 "implicit" +// 关键字。请注意这些例子中,我们用到第5部分的 Dog 类。 +implicit val myImplicitInt = 100 +implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) -println("ABCDEF".length) -println("ABCDEF".substring(2, 6)) -println("ABCDEF".replace("C", "3")) +// implicit 关键字本身不改变值的行为,所以上面的值可以照常使用。 +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" -val n = 45 -println(s"We have $n apples") +// 区别在于,当另一段代码“需要”隐式值时,这些值现在有资格作为隐式值。 +// 一种情况是隐式函数参数。 +def sendGreetings(toWhom: String)(implicit howMany: Int) = + s"Hello $toWhom, $howMany blessings to you and yours!" -val a = Array(11, 9, 6) -println(s"My second daughter is ${a(2-1)} years old") +// 如果提供值给 “howMany”,函数正常运行 +sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" -// 一些字符需要被转义,举例来说,字符串中的双引号: -val a = "They stood outside the \"Rose and Crown\"" +// 如果省略隐式参数,会传一个和参数类型相同的隐式值, +// 在这个例子中, 是 “myImplicitInt": +sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" -// 三个双引号使得字符串可以跨行并且可以包含引号(无需转义) +// 隐式的函数参数使我们可以模拟其他函数式语言的 type 类(type classes)。 +// 它经常被用到所以有特定的简写。这两行代码是一样的: +def foo[T](implicit c: C[T]) = ... +def foo[T : C] = ... -val html = """
-

Press belo', Joe

- | -
""" +// 编译器寻找隐式值另一种情况是你调用方法时 +// obj.method(...) +// 但 "obj" 没有一个名为 "method" 的方法。这样的话,如果存在一个将类型 A +// 转变为 B 的隐式转换,A 是 obj 的类型,B有一个叫 "method" 的方法,这样 +// 转换就会被应用。所以作用域里有上面的 myImplicitFunction, 我们可以这样做: +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" +// 这里字符串先被上面的函数转换为 Dog 对象,然后调用合适的方法。 +// 这是相当强大的特性,但再次提醒,请勿轻率使用。 +// 事实上,当你定义上面的隐式函数时,编译器会作出警告,除非你真的了解 +// 你正在做什么否则不要使用。 -// 应用结果和组织 +///////////////////////////////////////////////// +// 9. 杂项 +///////////////////////////////////////////////// -// import +// 导入类 import scala.collection.immutable.List -// Import 所有的子包 +// 导入所有子包 import scala.collection.immutable._ -// 在一条语句中 Import 多个类 +// 一条语句导入多个类 import scala.collection.immutable.{List, Map} -// 使用 '=>' 来重命名一个 import +// 使用 ‘=>’ 对导入进行重命名 import scala.collection.immutable.{ List => ImmutableList } -// import 除了一些类的其它所有的类。下面的例子除去了 Map 类和 Set 类: +// 导入所有类,排除其中一些。下面的语句排除了 Map 和 Set: import scala.collection.immutable.{Map => _, Set => _, _} -// 在 scala 源文件中,你的程序入口点使用一个拥有单一方法 main 的对象来定义: - +// 在 Scala 文件用 object 和单一的 main 方法定义程序入口: object Application { def main(args: Array[String]): Unit = { // stuff goes here. } } -// 文件可以包含多个类和对象。由 scalac 来编译 +// 文件可以包含多个 class 和 object,用 scalac 编译源文件 -// 输入和输出 +// 输入输出 -// 一行一行读取文件 +// 按行读文件 import scala.io.Source -for(line <- Source.fromPath("myfile.txt").getLines()) +for(line <- Source.fromFile("myfile.txt").getLines()) println(line) -// 使用 Java 的 PrintWriter 来写文件 - +// 用 Java 的 PrintWriter 写文件 +val writer = new PrintWriter("myfile.txt") +writer.write("Writing line for line" + util.Properties.lineSeparator) +writer.write("Another line here" + util.Properties.lineSeparator) +writer.close() ``` -- cgit v1.2.3 From 8f0027683d316d0b614be8841a76453fb4cfb347 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Wed, 15 Apr 2015 18:09:34 +0800 Subject: Some bug fixes. --- zh-cn/c++-cn.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index eed20721..46a34141 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -535,7 +535,7 @@ failure: } // 如果用异常捕获机制来指示错误的话, -// 代码会变得清晰一些,但是仍然有优化的餘地。 +// 代码会变得清晰一些,但是仍然有优化的余地。 void doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 @@ -548,7 +548,7 @@ void doSomethingWithAFile(const char* filename) } catch (...) { fclose(fh); // 保证出错的时候文件被正确关闭 - throw; // Then re-throw the exception. + throw; // 之后,重新抛出这个异常 } fclose(fh); // 关闭文件 @@ -573,7 +573,7 @@ void doSomethingWithAFile(const std::string& filename) // 1. 无论发生了什么情况,资源(此例当中是文件句柄)都会被正确关闭。 // 只要你正确使用了析构器,就_不会_因为忘记关闭句柄,造成资源的泄漏。 // 2. 可以注意到,通过这种方式写出来的代码十分简洁。 -// 析构器会在后臺关闭文件句柄,不再需要你来操心这些琐事。 +// 析构器会在后台关闭文件句柄,不再需要你来操心这些琐事。 // 3. 这种方式的代码具有异常安全性。 // 无论在函数中的何处拋出异常,都不会阻碍对文件资源的释放。 -- cgit v1.2.3 From 60b56e777efa1b5c24cf5104556a2eb7aa6fbed2 Mon Sep 17 00:00:00 2001 From: yejinchang Date: Wed, 15 Apr 2015 18:12:21 +0800 Subject: fix minor mistake --- zh-cn/scala-cn.html.markdown | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 5d5d93c7..f292271e 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -191,7 +191,7 @@ addOne(5) // => 6 weirdSum(2, 4) // => 16 -// return 关键字是存在的,但它从最里面包裹了 return 的 def 函数中返回。 +// return 关键字是存在的,但它只从最里面包裹了 return 的 def 函数中返回。 // 警告: 在 Scala 中使用 return 容易出错,应该避免使用。 // 在匿名函数中没有效果,例如: def foo(x: Int): Int = { @@ -304,13 +304,11 @@ s(1) (a, 2, "three") // 为什么有这个? - val divideInts = (x:Int, y:Int) => (x / y, x % y) divideInts(10,3) // 函数 divideInts 返回您结果和余数 // 要读取元组的元素,使用 _._n,n是从1开始的元素索引 - val d = divideInts(10,3) d._1 @@ -360,7 +358,7 @@ println(mydog.bark) // => "Woof, woof!" // "object" 关键字创造一种类型和该类型的单例。 // Scala 的 class 常常也含有一个 “伴生对象”,class 中包含每个实例的行为,所有实例 -// 共用的行为则放入 object 中。两者的区别和其他语言中方法和静态方法类似。 +// 共用的行为则放入 object 中。两者的区别和其他语言中类方法和静态方法类似。 // 请注意 object 和 class 可以同名。 object Dog { def allKnownBreeds = List("pitbull", "shepherd", "retriever") @@ -374,14 +372,14 @@ object Dog { // 数据。它们通常只有几个方法,且方法几乎没有副作用。 case class Person(name: String, phoneNumber: String) -// 创造新实例,注意 case 类不需要 "new" 关键字 +// 创造新实例,注意 case 类不需要使用 "new" 关键字 val george = Person("George", "1234") val kate = Person("Kate", "4567") // 使用 case 类,您可以轻松得到一些功能,像 getters: george.phoneNumber // => "1234" -// 每个字段的相等性(无需覆盖 .equals) +// 每个字段的相等性比较(无需覆盖 .equals) Person("George", "1234") == Person("Kate", "1236") // => false // 简单的拷贝方式 @@ -412,7 +410,7 @@ def matchPerson(person: Person): String = person match { val email = "(.*)@(.*)".r // 定义下一个例子会用到的正则 // 模式匹配看起来和 C语言家族的 switch 语句相似,但更为强大。 -// Scala 中您可以很多东西: +// Scala 中您可以匹配很多东西: def matchEverything(obj: Any): String = obj match { // 匹配值: case "Hello world" => "Got the string Hello world" -- cgit v1.2.3 From 6e9ccfaea3bf2963dc624cd7a6cc198cd1147aa9 Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 15 Apr 2015 14:33:52 +0200 Subject: fix #1032 and a few more fixes/moving arounds --- perl6.html.markdown | 60 ++++++++++++++++------------------------------------- 1 file changed, 18 insertions(+), 42 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 8404f9f8..b2d7d48c 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -307,37 +307,9 @@ if long-computation() -> $result { say "The result is $result"; } -# Now that you've seen how to traverse a list, you need to be aware of something: -# List context (@) flattens. If you traverse nested lists, you'll actually be traversing a -# shallow list. -for 1, 2, (3, (4, ((5)))) { - say "Got $_."; -} #=> Got 1. Got 2. Got 3. Got 4. Got 5. - -# ... However: (forcing item context with `$`) -for 1, 2, $(3, 4) { - say "Got $_."; -} #=> Got 1. Got 2. Got 3 4. - -# Note that the last one actually joined 3 and 4. -# While `$(...)` will apply item to context to just about anything, you can also create -# an array using `[]`: -for [1, 2, 3, 4] { - say "Got $_."; -} #=> Got 1 2 3 4. - -# You need to be aware of when flattening happens exactly. -# The general guideline is that argument lists flatten, but not method calls. -# Also note that `.list` and array assignment flatten (`@ary = ...`) flatten. -((1,2), 3, (4,5)).map({...}); # iterates over three elements (method call) -map {...}, ((1,2),3,(4,5)); # iterates over five elements (argument list is flattened) - -(@a, @b, @c).pick(1); # picks one of three arrays (method call) -pick 1, @a, @b, @c; # flattens argument list and pick one element - ### Operators -## Since Perl languages are very much operator-based languages +## Since Perl languages are very much operator-based languages, ## Perl 6 operators are actually just funny-looking subroutines, in syntactic ## categories, like infix:<+> (addition) or prefix: (bool not). @@ -396,17 +368,21 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return # "1 2 3 4 5 6 7 8 9 10" (and not run out of memory !) # Note : when reading an infinite list, Perl 6 will "reify" the elements # it needs, then keep them in memory. They won't be calculated more than once. - -# Warning, though: if you try this example in the REPL and just put `1..*`, -# Perl 6 will be forced to try and evaluate the whole array (to print it), -# so you'll end with an infinite loop. - -# You can use that in most places you'd expect, even assigning to an array -my @numbers = ^20; -@numbers[5..*] = 3, 9 ... * > 90; # The right hand side could be infinite as well. - # (but not both, as this would be an infinite loop) -say @numbers; #=> 3 9 15 21 27 [...] 81 87 - +# It also will never calculate more elements that are needed. + +# An array subscript can also be a closure. +# It'll be called with the length as the argument +say join(' ', @array[15..*]); #=> 15 16 17 18 19 +# which is equivalent to: +say join(' ', @array[-> $n { 15..$n }]); + +# You can use that in most places you'd expect, even assigning to an array +my @numbers = ^20; +my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99 +@numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite, + # only the 15 needed values will be calculated. +say @numbers; #=> 0 1 2 3 4 3 9 15 21 [...] 81 87 + # (only 20 values) ## * And, Or 3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`. @@ -418,7 +394,7 @@ $a && $b && $c; # Returns the first argument that evaluates to False, $a || $b; # And because you're going to want them, -# you also have composed assignment operators: +# you also have compound assignment operators: $a *= 2; # multiply and assignment $b %%= 5; # divisible by and assignment @array .= sort; # calls the `sort` method and assigns the result back @@ -428,7 +404,7 @@ $b %%= 5; # divisible by and assignment # a few more key concepts that make them better than in any other language :-). ## Unpacking ! -# It's the ability to "extract" arrays and keys. +# It's the ability to "extract" arrays and keys (AKA "destructuring"). # It'll work in `my`s and in parameter lists. my ($a, $b) = 1, 2; say $a; #=> 1 -- cgit v1.2.3 From 4adbf231c805afdf68fed3a5e2aba9c90fd4c0c1 Mon Sep 17 00:00:00 2001 From: yejinchang Date: Thu, 16 Apr 2015 17:53:40 +0800 Subject: make corrections --- scala.html.markdown | 3 ++- zh-cn/scala-cn.html.markdown | 39 ++++++++++++++++++++------------------- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index ed1ddabb..e6638121 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -186,7 +186,7 @@ val sq: Int => Int = x => x * x // Anonymous functions can be called as usual: sq(10) // => 100 -// If your anonymous function has one or two arguments, and each argument is +// If each argument in your anonymous function is // used only once, Scala gives you an even shorter way to define them. These // anonymous functions turn out to be extremely common, as will be obvious in // the data structure section. @@ -465,6 +465,7 @@ val patternFunc: Person => String = { // Scala allows methods and functions to return, or take as parameters, other // functions or methods. +val add10: Int => Int = _ + 10 // A function taking an Int and returning an Int List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element // Anonymous functions can be used instead of named functions: diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index f292271e..343982ff 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -8,10 +8,11 @@ contributors: translators: - ["Peiyong Lin", ""] - ["Jinchang Ye", "http://github.com/alwayswithme"] + - ["Guodong Qu", "https://github.com/jasonqu"] lang: zh-cn --- -Scala - 一门可拓展性的语言 +Scala - 一门可拓展的语言 ```scala @@ -103,7 +104,7 @@ true == false // false 'a' // Scala 的字符 // '不存在单引号字符串' <= 这会导致错误 -// 字符串定义了常见的 Java 方法 +// String 有常见的 Java 字符串方法 "hello world".length "hello world".substring(2, 6) "hello world".replace("C", "3") @@ -174,14 +175,14 @@ addWithDefault(1) // => 6 // 匿名函数是这样的: (x:Int) => x * x -// 和 def 不同,如果语义清晰,匿名函数的输入类型也可以省略。 +// 和 def 不同,如果语义清晰,匿名函数的参数类型也可以省略。 // 类型 "Int => Int" 意味着这个函数接收一个 Int 并返回一个 Int。 val sq: Int => Int = x => x * x // 匿名函数的调用也是类似的: sq(10) // => 100 -// 如果您的匿名函数有一到两个参数,每一个参数仅使用一次, +// 如果您的匿名函数中每个参数仅使用一次, // Scala 提供一个更简洁的方式来定义他们。这样的匿名函数极为常见, // 在数据结构部分会明显可见。 val addOne: Int => Int = _ + 1 @@ -221,7 +222,7 @@ val r = 1 to 5 r.foreach( println ) r foreach println -// 留意: Scala 对点和括号的要求比较宽松,对这些规则加以区分。 +// 附注: Scala 对点和括号的要求想当宽松,注意其规则是不同的。 // 这有助于写出读起来像英语的 DSL(领域特定语言) 和 API(应用编程接口)。 (5 to 1 by -1) foreach ( println ) @@ -306,7 +307,7 @@ s(1) // 为什么有这个? val divideInts = (x:Int, y:Int) => (x / y, x % y) -divideInts(10,3) // 函数 divideInts 返回您结果和余数 +divideInts(10,3) // 函数 divideInts 同时返回结果和余数 // 要读取元组的元素,使用 _._n,n是从1开始的元素索引 val d = divideInts(10,3) @@ -322,9 +323,9 @@ d._2 /* 旁白: 教程中到现在为止我们所做的一切只是简单的表达式(值,函数等)。 - 这些表达示可以输入到命令行解释器中作为快速测试,但它们无法单一的存在于 Scala - 文件。举个例子,您不能在 Scala 文件上简单的写上 "val x = 5"。而 Scala 允许存 - 在的顶级结构是: + 这些表达式可以输入到命令行解释器中作为快速测试,但它们不能独立存在于 Scala + 文件。举个例子,您不能在 Scala 文件上简单的写上 "val x = 5"。相反 Scala 文件 + 允许的顶级结构是: - objects - classes @@ -346,7 +347,7 @@ class Dog(br: String) { private def sleep(hours: Int) = println(s"I'm sleeping for $hours hours") - // 抽象方法是没有方法体的方法。如果取消下面那行注释,Dog 类需要被声明为 abstract + // 抽象方法是没有方法体的方法。如果取消下面那行注释,Dog 类必须被声明为 abstract // abstract class Dog(...) { ... } // def chaseAfter(what: String): String } @@ -397,7 +398,7 @@ val otherGeorge = george.copy(phoneNumber = "9876") ///////////////////////////////////////////////// // 模式匹配是一个强大和常用的 Scala 特性。这是用模式匹配一个 case 类的例子。 -// 留意:不像其他语言, Scala 的 case 不需要 break, 其他语言中 switch 语句的 +// 附注:不像其他语言, Scala 的 case 不需要 break, 其他语言中 switch 语句的 // fall-through 现象不会发生。 def matchPerson(person: Person): String = person match { @@ -457,7 +458,7 @@ List(1, 2, 3) map add10 // List(11, 12, 13) - add10 被应用到每一个元素 // 匿名函数可以被使用来代替有命名的函数: List(1, 2, 3) map (x => x + 10) -// 下划线标志,如果匿名函数只有一个参数可以被使用来表示该参数变量 +// 如果匿名函数只有一个参数可以用下划线作为变量 List(1, 2, 3) map (_ + 10) // 如果您所应用的匿名块和匿名函数都接受一个参数,那么你甚至可以省略下划线 @@ -475,7 +476,7 @@ sSquared.filter(_ < 10) sSquared.reduce (_+_) -// filter 函数接受一个 predicate (函数从 A -> Boolean)并选择 +// filter 函数接受一个 predicate (函数根据条件 A 返回 Boolean)并选择 // 所有满足 predicate 的元素 List(1, 2, 3) filter (_ > 2) // List(3) case class Person(name:String, age:Int) @@ -514,8 +515,8 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared * 就不可能做有意义的事情。这章节主要让你理解和使用隐式转换,而不是自己声明。 */ -// 任何值(val, 函数,对象等)可以被声明为隐式的,你可以猜到的,通过加上 "implicit" -// 关键字。请注意这些例子中,我们用到第5部分的 Dog 类。 +// 可以通过 "implicit" 声明任何值(val, 函数,对象等)为隐式值, +// 请注意这些例子中,我们用到第5部分的 Dog 类。 implicit val myImplicitInt = 100 implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) @@ -542,13 +543,13 @@ def foo[T : C] = ... // 编译器寻找隐式值另一种情况是你调用方法时 // obj.method(...) -// 但 "obj" 没有一个名为 "method" 的方法。这样的话,如果存在一个将类型 A -// 转变为 B 的隐式转换,A 是 obj 的类型,B有一个叫 "method" 的方法,这样 +// 但 "obj" 没有一个名为 "method" 的方法。这样的话,如果有一个参数类型为 A +// 返回值类型为 B 的隐式转换,obj 的类型是 A,B 有一个方法叫 "method" ,这样 // 转换就会被应用。所以作用域里有上面的 myImplicitFunction, 我们可以这样做: "Retriever".breed // => "Golden Retriever" "Sheperd".bark // => "Woof, woof!" -// 这里字符串先被上面的函数转换为 Dog 对象,然后调用合适的方法。 +// 这里字符串先被上面的函数转换为 Dog 对象,然后调用相应的方法。 // 这是相当强大的特性,但再次提醒,请勿轻率使用。 // 事实上,当你定义上面的隐式函数时,编译器会作出警告,除非你真的了解 // 你正在做什么否则不要使用。 @@ -585,7 +586,7 @@ object Application { -// 输入输出 +// 输入和输出 // 按行读文件 import scala.io.Source -- cgit v1.2.3 From c8c6924dccf3184b0c2c60226291de3cae4c1380 Mon Sep 17 00:00:00 2001 From: alwayswithme Date: Fri, 17 Apr 2015 14:55:01 +0800 Subject: resolve translation errors --- zh-cn/scala-cn.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 343982ff..508dd58e 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -97,7 +97,7 @@ true == false // false 这意味着计算 1 + 7 的结果是一个 Int 类型的对象,其值为 8 注意 "res29" 是一个连续生成的变量名,用以存储您输入的表达式结果, - 您看到的输入可能不一样。 + 您看到的输出可能不一样。 */ "Scala strings are surrounded by double quotes" @@ -486,7 +486,9 @@ List( ).filter(_.age > 25) // List(Person("Bob", 30)) -// Scala 的 foreach 方法定义在特定集合中,接受一个类型并返回 Unit (void 方法) +// Scala 的 foreach 方法定义在某些集合中,接受一个函数并返回 Unit (void 方法) +// 另请参见: +// http://www.scala-lang.org/api/current/index.html#scala.collection.IterableLike@foreach(f:A=>Unit):Unit val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println -- cgit v1.2.3 From c5212932b9e7fb2d42eb74049877488678b85967 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Fri, 17 Apr 2015 22:19:13 +0800 Subject: More bug fixes. --- zh-cn/c++-cn.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index 46a34141..e5c5d5df 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -282,7 +282,7 @@ public: void bark() const { std::cout << name << " barks!\n" } // 除了构造器以外,C++还提供了析构器。 - // 当一个对象被删除或者脱离其定义域时时,它的析构函数会被调用。 + // 当一个对象被删除或者脱离其定义域时,它的析构函数会被调用。 // 这使得RAII这样的强大范式(参见下文)成为可能。 // 为了衍生出子类来,基类的析构函数必须定义为虚函数。 virtual ~Dog(); @@ -353,7 +353,7 @@ class OwnedDog : public Dog { // 重写OwnedDogs类的print方法。 // 如果你不熟悉子类多态的话,可以参考这个页面中的概述: - // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // http://zh.wikipedia.org/wiki/%E5%AD%90%E7%B1%BB%E5%9E%8B // override关键字是可选的,它确保你所重写的是基类中的方法。 void print() const override; -- cgit v1.2.3 From 7bab2c5e8d0301ca3480cbac92ecee99233f6677 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Fri, 17 Apr 2015 22:51:02 +0800 Subject: Remove duplicate code. --- zh-cn/c++-cn.html.markdown | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index e5c5d5df..e1551e2b 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -289,8 +289,6 @@ public: }; // 在类的定义之后,要加一个分号 -}; // 记住,在类的定义之后,要加一个分号! - // 类的成员函数通常在.cpp文件中实现。 void Dog::Dog() { @@ -309,22 +307,6 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时出现 -void Dog::print() const -{ - std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; -} - -void Dog::~Dog() -{ - cout << "Goodbye " << name << "\n"; -} - -void Dog::setWeight(int dogsWeight) -{ - weight = dogsWeight; -} - // 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复 void Dog::print() const { -- cgit v1.2.3