diff options
-rw-r--r-- | bash.html.markdown | 64 | ||||
-rw-r--r-- | brainfuck.html.markdown | 14 | ||||
-rw-r--r-- | csharp.html.markdown | 81 | ||||
-rw-r--r-- | es-es/perl-es.html.markdown | 160 | ||||
-rw-r--r-- | haskell.html.markdown | 2 | ||||
-rw-r--r-- | javascript.html.markdown | 5 | ||||
-rw-r--r-- | ko-kr/brainfuck-kr.html.markdown | 83 | ||||
-rw-r--r-- | matlab.html.markdown | 140 | ||||
-rw-r--r-- | php.html.markdown | 2 | ||||
-rw-r--r-- | pogo.html.markdown | 202 | ||||
-rw-r--r-- | python.html.markdown | 44 | ||||
-rw-r--r-- | tr-tr/brainfuck-tr.html.markdown | 87 | ||||
-rw-r--r-- | tr-tr/objective-c-tr.html.markdown | 320 | ||||
-rw-r--r-- | tr-tr/php-tr.html.markdown | 7 |
14 files changed, 1132 insertions, 79 deletions
diff --git a/bash.html.markdown b/bash.html.markdown index 708131bd..4d80545e 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -4,6 +4,7 @@ tool: bash contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] filename: LearnBash.sh --- @@ -35,8 +36,22 @@ VARIABLE = "Some string" # Using the variable: echo $VARIABLE echo "$VARIABLE" +echo '$VARIABLE' # When you use the variable itself — assign it, export it, or else — you write # its name without $. If you want to use variable's value, you should use $. +# Note that ' (single quote) won't expand the variables! + +# String substitution in variables +echo ${VARIABLE/Some/A} +# This will substitute the first occurance of "Some" with "A" + +# Bultin variables: +# There are some useful builtin variables, like +echo "Last program return value: $?" +echo "Script's PID: $$" +echo "Number of arguments: $#" +echo "Scripts arguments: $@" +echo "Scripts arguments separeted in different variables: $1 $2..." # Reading a value from input: echo "What's your name?" @@ -44,13 +59,18 @@ read NAME # Note that we didn't need to declare new variable echo Hello, $NAME! # We have the usual if structure: -if true +# use 'man test' for more info about conditionals +if [ $NAME -ne $USER ] then - echo "This is expected" + echo "Your name is you username" else - echo "And this is not" + echo "Your name isn't you username" fi +# There is also conditional execution +echo "Always executed" || echo "Only executed if first command fail" +echo "Always executed" && echo "Only executed if first command does NOT fail" + # Expressions are denoted with the following format: echo $(( 10 + 5 )) @@ -67,6 +87,13 @@ ls -l # Lists every file and directory on a separate line # txt files in the current directory: ls -l | grep "\.txt" +# You can also redirect a command output, input and error output. +python2 hello.py < "input.in" +python2 hello.py > "output.out" +python2 hello.py 2> "error.err" +# The output error will overwrite the file if it exists, if you want to +# concatenate them, use ">>" instead. + # Commands can be substitued within other commands using $( ): # The following command displays the number of files and directories in the # current directory. @@ -80,11 +107,36 @@ case "$VARIABLE" in *) echo "It is not null.";; esac -#For loops iterate for as many arguments given: -#The contents of var $VARIABLE is printed three times. -for VARIABLE in x y z +# For loops iterate for as many arguments given: +# The contents of var $VARIABLE is printed three times. +# Note that ` ` is equivalent to $( ) and that seq returns a sequence of size 3. +for VARIABLE in `seq 3` do echo "$VARIABLE" done +# You can also define functions +# Definition: +foo () +{ + echo "Arguments work just like script arguments: $@" + echo "And: $1 $2..." + echo "This is a function" + return 0 +} + +# Calling your function +foo "My name is" $NAME + +# There are a lot of useful commands you should learn: +tail -n 10 file.txt +# prints last 10 lines of file.txt +head -n 10 file.txt +# prints first 10 lines of file.txt +sort file.txt +# sort file.txt's lines +uniq -d file.txt +# report or omit repeated lines, with -d it reports them +cut -d ',' -f 1 file.txt +# prints only the first column before the ',' character ``` diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown index 9282381f..27ac6921 100644 --- a/brainfuck.html.markdown +++ b/brainfuck.html.markdown @@ -53,25 +53,27 @@ until cell #1 is 0, and cell #2 holds cell #1's old value. Because we're on cell #1 at the end of the loop, move to cell #2, and then print out the value in ASCII. -Also keep in mind that the spaces are purely for readibility purposes. You +Also keep in mind that the spaces are purely for readability purposes. You could just as easily write it as: ,[>+<-]>. Try and figure out what this program does: -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> This program takes two numbers for input, and multiplies them. The gist is it first reads in two inputs. Then it starts the outer loop, conditioned on cell #1. Then it moves to cell #2, and starts the inner -loop conditioned on cell #2, incrementing cell #3. However, there comes a -problem: at the end of the inner loop, cell #2 is zero. To solve this problem, +loop conditioned on cell #2, incrementing cell #3. However, there comes a +problem: At the end of the inner loop, cell #2 is zero. In that case, +inner loop won't work anymore since next time. To solve this problem, we also increment cell #4, and then recopy cell #4 into cell #2. +Then cell #3 is the result. ``` -And that's brainfuck. Not that hard, eh? For fun, you can write your own -brainfuck programs, or you can write a brainfuck interpreter in another +And that's brainfuck. Not that hard, eh? For fun, you can write your own +brainfuck programs, or you can write a brainfuck interpreter in another language. The interpreter is fairly simple to implement, but if you're a masochist, try writing a brainfuck interpreter… in brainfuck. diff --git a/csharp.html.markdown b/csharp.html.markdown index d3adbd01..1471b833 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -3,6 +3,7 @@ language: c# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] + - ["Melvyn Laïly", "http://x2a.yt"] filename: LearnCSharp.cs --- @@ -95,17 +96,25 @@ namespace Learning // Double - Double-precision 64-bit IEEE 754 Floating Point // Precision: 15-16 digits double fooDouble = 123.4; + + // Decimal - a 128-bits data type, with more precision than other floating-point types, + // suited for financial and monetary calculations + decimal fooDecimal = 150.3m; - // Bool - true & false + // Boolean - true & false bool fooBoolean = true; bool barBoolean = false; // Char - A single 16-bit Unicode character char fooChar = 'A'; - // Strings + // Strings -- unlike the previous base types which are all value types, + // a string is a reference type. That is, you can set it to null string fooString = "My string is here!"; Console.WriteLine(fooString); + // You can access each character of the string with an indexer: + char charFromString = fooString[1]; // 'y' + // Strings are immutable: you can't do fooString[1] = 'X'; // formatting string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); @@ -138,14 +147,21 @@ namespace Learning const int HOURS_I_WORK_PER_WEEK = 9001; // Nullable types - // any type can be made nullable by suffixing a ? + // any value type (i.e. not a class) can be made nullable by suffixing a ? // <type>? <var name> = <value> int? nullable = null; Console.WriteLine("Nullable variable: " + nullable); - // In order to use nullable's value, you have to use Value property or to explicitly cast it - string? nullableString = "not null"; - Console.WriteLine("Nullable value is: " + nullableString.Value + " or: " + (string) nullableString ); + // In order to use nullable's value, you have to use Value property + // or to explicitly cast it + DateTime? nullableDate = null; + // The previous line would not have compiled without the '?' + // because DateTime is a value type + // <type>? is equivalent to writing Nullable<type> + Nullable<DateTime> otherNullableDate = nullableDate; + + nullableDate = DateTime.Now; + Console.WriteLine("Nullable value is: " + nullableDate.Value + " or: " + (DateTime) nullableDate ); // ?? is syntactic sugar for specifying default value // in case variable is null @@ -153,6 +169,8 @@ namespace Learning Console.WriteLine("Not nullable variable: " + notNullable); // Var - compiler will choose the most appropriate type based on value + // Please note that this does not remove type safety. + // In this case, the type of fooImplicit is known to be a bool at compile time var fooImplicit = true; /////////////////////////////////////////////////// @@ -201,7 +219,7 @@ namespace Learning // Others data structures to check out: // // Stack/Queue - // Dictionary + // Dictionary (an implementation of a hash map) // Read-only Collections // Tuple (.Net 4+) @@ -235,7 +253,6 @@ namespace Learning ~ Unary bitwise complement << Signed left shift >> Signed right shift - >>> Unsigned right shift & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR @@ -308,6 +325,18 @@ namespace Learning //Iterated 10 times, fooFor 0->9 } Console.WriteLine("fooFor Value: " + fooFor); + + // For Each Loop + // foreach loop structure => foreach(<iteratorType> <iteratorName> in <enumerable>) + // The foreach loop loops over any object implementing IEnumerable or IEnumerable<T> + // All the collection types (Array, List, Dictionary...) in the .Net framework + // implement one or both of these interfaces. + // (The ToCharArray() could be removed, because a string also implements IEnumerable) + foreach (char character in "Hello World".ToCharArray()) + { + //Console.WriteLine(character); + //Iterated over all the characters in the string + } // Switch Case // A switch works with the byte, short, char, and int data types. @@ -327,6 +356,14 @@ namespace Learning case 3: monthString = "March"; break; + // You can assign more than one case to an action + // But you can't add an action without a break before another case + // (if you want to do this, you would have to explicitly add a goto case x + case 6: + case 7: + case 8: + monthString = "Summer time!!"; + break; default: monthString = "Some other month"; break; @@ -335,7 +372,7 @@ namespace Learning /////////////////////////////////////// - // Converting Data Types And Typcasting + // Converting Data Types And Typecasting /////////////////////////////////////// // Converting data @@ -389,7 +426,7 @@ namespace Learning // Class Declaration Syntax: - // <public/private/protected> class <class name>{ + // <public/private/protected/internal> class <class name>{ // //data fields, constructors, functions all inside. // //functions are called as methods in Java. // } @@ -404,17 +441,20 @@ namespace Learning string name; // Everything is private by default: Only accessible from within this class // Enum is a value type that consists of a set of named constants + // It is really just mapping a name to a value (an int, unless specified otherwise). + // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. + // An enum can't contain the same value twice. public enum Brand { AIST, BMC, - Electra, + Electra=42, //you can explicitly set a value to a name Gitane } // We defined this type inside a Bicycle class, so it is a nested type // Code outside of this class should reference this type as Bicycle.Brand - public Brand brand; // After declaing an enum type, we can declare the field of this type + public Brand brand; // After declaring an enum type, we can declare the field of this type // Static members belong to the type itself rather then specific object. static public int bicyclesCreated = 0; @@ -459,7 +499,7 @@ namespace Learning // <public/private/protected> <return type> <function name>(<args>) // classes can implement getters and setters for their fields - // or they can implement properties + // or they can implement properties (this is the preferred way in C#) // Method declaration syntax: // <scope> <return type> <method name>(<args>) @@ -474,13 +514,14 @@ namespace Learning cadence = newValue; } - // virtual keyword indicates this method can be overridden + // virtual keyword indicates this method can be overridden in a derived class public virtual void SetGear(int newValue) { gear = newValue; } - // Method parameters can have defaut values. In this case, methods can be called with these parameters omitted + // Method parameters can have default values. + // In this case, methods can be called with these parameters omitted public void SpeedUp(int increment = 1) { _speed += increment; @@ -500,6 +541,12 @@ namespace Learning get { return _hasTassles; } set { _hasTassles = value; } } + + // You can also define an automatic property in one line + // this syntax will create a backing field automatically. + // You can set an access modifier on either the getter or the setter (or both) + // to restrict its access: + public bool IsBroken { get; private set; } // Properties can be auto-implemented public int FrameSize @@ -525,7 +572,7 @@ namespace Learning // Methods can also be static. It can be useful for helper methods public static bool DidWeCreateEnoughBycles() { - // Within a static method, we only can reference static class memebers + // Within a static method, we only can reference static class members return bicyclesCreated > 9000; } // If your class only needs static members, consider marking the class itself as static. @@ -564,7 +611,7 @@ namespace Learning interface IBreakable { - bool Broken { get; } // interfaces can contain properties as well as methods, fields & events + bool Broken { get; } // interfaces can contain properties as well as methods & events } // Class can inherit only one other class, but can implement any amount of interfaces diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown new file mode 100644 index 00000000..4f0c26c1 --- /dev/null +++ b/es-es/perl-es.html.markdown @@ -0,0 +1,160 @@ +--- +name: perl +category: language +language: perl +filename: learnperl-es.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] +translators: + - ["Francisco Gomez", "http://github.com/frncscgmz"] +lang: es-es +--- + +Perl 5 es un lenguaje de programación altamente capaz, rico en características con mas de 25 años de desarrollo. + +Perl 5 corre en mas de 100 plataformas desde portales hasta mainframes y es adecuado para realizar prototipos rápidos hasta desarrollar proyectos a gran escala. + +```perl +# Comentarios de una sola linea con un carácter hash. + +#### Tipos de variables en Perl + +# Las variables comienzan con el símbolo $. +# Un nombre de variable valido empieza con una letra o un guión bajo, +# seguido por cualquier numero de letras, números o guiones bajos. + +### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes. + +## Escalares +# Un escalar representa un solo valor: +my $animal = "camello"; +my $respuesta = 42; + +# Los valores escalares pueden ser cadenas de caracteres, números enteros o +# de punto flotante, Perl automáticamente los convertirá como sea requerido. + +## Arreglos +# Un arreglo representa una lista de valores: +my @animales = {"camello","llama","buho"}; +my @numeros = {23,42,69}; +my @mixto = {"camello",42,1.23}; + + + +## Hashes +# Un hash representa un conjunto de pares llave/valor: + +my %color_fruta = {"manzana","rojo","banana","amarillo"}; + +# Puedes usar un espacio en blanco y el operador "=>" para asignarlos mas +# fácilmente. + +my %color_fruta = ( + manzana => "rojo", + banana => "amarillo", + ); +# Los escalares, arreglos y hashes están mas documentados en perldata. (perldoc perldata). + +# Los tipos de datos mas complejos pueden ser construidos utilizando +# referencias, las cuales te permiten construir listas y hashes dentro +# de listas y hashes. + +#### Estructuras condicionales y de ciclos + +# Perl tiene la mayoría de las estructuras condicionales y de ciclos mas comunes. + +if ( $var ) { + ... +} elsif ( $var eq 'bar' ) { + ... +} else { + ... +} + +unless ( condicion ) { + ... + } +# Esto es proporcionado como una version mas fácil de leer que "if (!condición)" + +# La post condición al modo Perl +print "Yow!" if $zippy; +print "No tenemos bananas" unless $bananas; + +# while + while ( condicion ) { + ... + } + + +# for y foreach +for ($i = 0; $i <= $max; $i++) { + ... + } + +foreach (@array) { + print "Este elemento es $_\n"; + } + + +#### Expresiones regulares + +# El soporte de expresiones regulares en Perl es muy amplio y profundo, y es +# sujeto a una extensa documentación en perlrequick, perlretut, entre otros. +# Sin embargo, resumiendo: + +# Pareo simple +if (/foo/) { ... } # verdadero si $_ contiene "foo" +if ($a =~ /foo/) { ... } # verdadero si $a contiene "foo" + +# Substitución simple +$a =~ s/foo/bar/; # remplaza foo con bar en $a +$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de foo con bar en $a + + +#### Archivos e I/O + +# Puedes abrir un archivo para obtener datos o escribirlos utilizando la +# función "open()". + +open(my $entrada, "<" "entrada.txt") or die "No es posible abrir entrada.txt: $!"; +open(my $salida, ">", "salida.txt") or die "No es posible abrir salida.txt: $!"; +open(my $log, ">>", "mi.log") or die "No es posible abrir mi.log: $!"; + +# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>" +# operador. En contexto escalar leer una sola linea desde el gestor de +# archivo, y en contexto de lista leer el archivo completo en donde, asigna +# cada linea a un elemento de la lista. + +my $linea = <$entrada>; +my @lineas = <$entrada>; + +#### Escribiendo subrutinas + +# Escribir subrutinas es fácil: + +sub logger { + my $mensajelog = shift; + open my $archivolog, ">>", "mi.log" or die "No es posible abrir mi.log: $!"; + print $archivolog $mensajelog; +} + +# Ahora podemos utilizar la subrutina al igual que cualquier otra función +# incorporada: + +logger("Tenemos una subrutina logger!"); + + +``` + +#### Utilizando módulos Perl + +Los módulos en Perl proveen una gama de funciones que te pueden ayudar a evitar reinventar la rueda, estas pueden ser descargadas desde CPAN( http://www.cpan.org/ ). Algunos de los módulos mas populares ya están incluidos con la misma distribución de Perl. + +perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos CPAN para usar. + +#### Material de Lectura + + - [perl-tutorial](http://perl-tutorial.org/) + - [Aprende en www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - y perl incorporado: `perldoc perlintro` diff --git a/haskell.html.markdown b/haskell.html.markdown index e3ec3f38..6b3c6e17 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -329,7 +329,7 @@ main' = interact countLines sayHello :: IO () sayHello = do putStrLn "What is your name?" - name <- getLine -- this gets a line and gives it the name "input" + name <- getLine -- this gets a line and gives it the name "name" putStrLn $ "Hello, " ++ name -- Exercise: write your own version of `interact` that only reads diff --git a/javascript.html.markdown b/javascript.html.markdown index 2f742574..b15eae7c 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -358,12 +358,15 @@ myObj.meaningOfLife; // = 43 // the constructor function itself; instead, it's the prototype that new objects // are given when they're created with that constructor and the new keyword. myConstructor.prototype = { + myNumber: 5, getMyNumber: function(){ - return this.myNumber + return this.myNumber; } }; var myNewObj2 = new myConstructor(); myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 // Built-in types like strings and numbers also have constructors that create // equivalent wrapper objects. diff --git a/ko-kr/brainfuck-kr.html.markdown b/ko-kr/brainfuck-kr.html.markdown new file mode 100644 index 00000000..661fcfea --- /dev/null +++ b/ko-kr/brainfuck-kr.html.markdown @@ -0,0 +1,83 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["JongChan Choi", "http://0xABCDEF.com/"] +lang: ko-kr +--- + +Brainfuck(f는 대문자로 적지 않습니다)은 +여덟가지 명령어만으로 튜링-완전한 최소주의 프로그래밍 언어입니다. + +``` +"><+-.,[]" 이외의 문자들은 무시됩니다. (쌍따옴표는 제외) + +브레인퍽은 30,000 칸 짜리의 0으로 초기화된 배열과, +현재 칸을 가르키는 포인터로 표현됩니다. + +여덟가지의 명령어는 다음과 같습니다: ++ : 포인터가 가르키는 현재 칸의 값을 1 증가시킵니다. +- : 포인터가 가르키는 현재 칸의 값을 1 감소시킵니다. +> : 포인터가 다음 칸(오른쪽 칸)을 가르키도록 이동시킵니다. +< : 포인터가 이전 칸(왼쪽 칸)을 가르키도록 이동시킵니다. +. : 현재 칸의 값을 ASCII 문자로 출력합니다. (즉, 65 = 'A') +, : 하나의 문자를 입력받고 그 값을 현재 칸에 대입합니다. +[ : 현재 칸의 값이 0이면 짝이 맞는 ] 명령으로 넘어갑니다. + 0이 아니면 다음 명령어로 넘어갑니다. +] : 현재 칸의 값이 0이면 다음 명령어로 넘어갑니다. + 0이 아니면 짝이 맞는 [ 명령으로 다시 돌아갑니다. + +[이랑 ]은 while 루프를 만들어냅니다. 무조건, 짝이 맞아야 합니다. + +몇가지 간단한 브레인퍽 프로그램을 보겠습니다. + +++++++ [ > ++++++++++ < - ] > +++++ . + +이 프로그램은 문자 'A'를 출력합니다. 처음에는, 반복할 횟수를 정하기 위한 값을 +만들기 위해 첫번째 칸의 값을 6으로 증가시킵니다. 그리고 루프로 들어가서([) +두번째 칸으로 넘어갑니다. 루프 안에서는 두번째 칸의 값을 10 증가시키고, +다시 첫번째 칸으로 넘어가서 값을 1 감소시킵니다. 이 루프는 여섯번 돕니다. +(첫번째 칸의 값을 6번 감소시켜서 0이 될 때 까지는 ] 명령을 만날 때마다 +루프의 시작 지점으로 돌아갑니다) + +이 시점에서, 두번째 칸의 값은 60이고, 포인터는 값이 0인 첫번째 칸에 위치합니다. +여기서 두번째 칸으로 넘어간 다음 값을 5 증가시키면 두번째 칸의 값이 65가 되고, +65는 문자 'A'에 대응하는 아스키 코드이기 때문에, 두번째 칸의 값을 출력하면 +터미널에 'A'가 출력됩니다. + +, [ > + < - ] > . + +이 프로그램은 사용자로부터 문자 하나를 입력받아 첫번째 칸에 집어넣습니다. +그리고 루프에 들어가서, 두번째 칸으로 넘어가 값을 한 번 증가시킨 다음, +다시 첫번째 칸으로 넘어가서 값을 한 번 감소시킵니다. +이는 첫번째 칸의 값이 0이 될 때까지 지속되며, +두번째 칸은 첫번째 칸이 갖고있던 값을 가지게 됩니다. +루프가 종료되면 포인터는 첫번째 칸을 가르키기 때문에 두번째 칸으로 넘어가고, +해당 아스키 코드에 대응하는 문자를 출력합니다. + +또한 공백문자는 순전히 가독성을 위해서 작성되었다는 것을 기억하세요. +다음과 같이 작성해도 똑같이 돌아갑니다: + +,[>+<-]>. + +한 번 돌려보고 아래의 프로그램이 실제로 무슨 일을 하는지 맞춰보세요: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +이 프로그램은 두 개의 숫자를 입력받은 뒤, 그 둘을 곱합니다. + +위 코드는 일단 두 번의 입력을 받고, 첫번째 칸의 값만큼 바깥 루프를 돕니다. +그리고 루프 안에서 다시 두번째 칸의 값만큼 안쪽의 루프를 돕니다. +그리고 그 루프에서는 세번째 칸의 값을 증가시키는데, 문제가 하나 있습니다: +내부 루프가 한 번 끝나게 되면 두번째 칸의 값은 0이 됩니다. +그럼 다시 바깥 루프를 돌 때에 안쪽의 루프를 돌지 않게 되는데, 이를 해결하려면 +네번째 칸의 값도 같이 증가시킨 다음, 그 값을 두번째 칸으로 옮기면 됩니다. +그러면 세번째 칸에 곱셈의 결과가 남습니다. +``` + +여기까지 브레인퍽이었습니다. 참 쉽죠? +재미삼아 브레인퍽 프로그램이나 다른 언어로 브레인퍽 인터프리터를 작성해보세요. +인터프리터 구현은 간단한 편인데, +사서 고생하는 것을 즐기는 편이라면 한 번 작성해보세요… 브레인퍽으로. diff --git a/matlab.html.markdown b/matlab.html.markdown index e72a95ea..15ff2303 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -20,18 +20,25 @@ something like this %} +% commands can span multiple lines, using '...': + a = 1 + 2 + ... + + 4 + +% commands can be passed to the operating system +!ping google.com + who % Displays all variables in memory whos % Displays all variables in memory, with their types clear % Erases all your variables from memory -clear('A') % Erases a aprticualr variable +clear('A') % Erases a particular variable openvar('A') % Open variable in variable editor clc % Erases the writing on your Command Window diary % Toggle writing Command Window text to file ctrl-c % Abort current computation -edit('myfunction.m') % Open function in editor -type('myfunction.m') % Print the source of function to Command Window +edit('myfunction.m') % Open function/script in editor +type('myfunction.m') % Print the source of function/script to Command Window profile viewer % Open profiler @@ -43,6 +50,7 @@ lookfor command % Searches for a given command % Output formatting format short % 4 decimals in a floating number format long % 15 decimals +format bank % only two digits after decimal point - for financial calculations fprintf % Variables & Expressions @@ -54,6 +62,17 @@ myVariable = 4; % Semi colon suppresses output to the Command Window a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 +% Calling functions can be done in either of two ways: +% Standard function syntax: +load('myFile.mat', 'y') +% Command syntax: +load myFile.mat y % no parentheses, and spaces instead of commas +% Note the lack of quote marks in command form: inputs are always passed as +% literal text - cannot pass variable values. Also, can't receive output: +[V,D] = eig(A) % this has no equivalent in command form + + + % Logicals 1 > 5 % ans = 0 10 >= 10 % ans = 1 @@ -63,7 +82,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891 3 > 1 || 4 > 1 % OR -> ans = 1 ~1 % NOT -> ans = 0 -% Logicals can be applied to matricies: +% Logicals can be applied to matrices: A > 5 % for each element, if condition is true, that element is 1 in returned matrix A[ A > 5 ] @@ -169,9 +188,18 @@ transpose(A) % Transpose the matrix, without taking complex conjugate % Element by Element Arithmetic vs. Matrix Arithmetic +% On their own, the arithmetic operators act on whole matrices. When preceded +% by a period, they act on each element instead. For example: A * B % Matrix multiplication A .* B % Multiple each element in A by its corresponding element in B +% There are several pairs of functions, where one acts on each element, and +% the other (whose name ends in m) acts on the whole matrix. +exp(A) % exponentiate each element +expm(A) % calculate the matrix exponential +sqrt(A) % take the square root of each element +sqrtm(A) % find the matrix whose square is A + % Plotting x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 @@ -181,9 +209,24 @@ xlabel('x axis') ylabel('y axis') title('Plot of y = sin(x)') axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 -plot(x,y1,'-',x,y2,'--',x,y3,':'') % For multiple functions on one plot -grid on % Show grid; turn off with 'grid off' +plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot +legend('Line 1 label', 'Line 2 label') % Label curves with a legend + +% Alternative method to plot multiple functions in one plot. +% while 'hold' is on, commands add to existing graph rather than replacing it +plot(x, y) +hold on +plot(x, z) +hold off + +loglog(x, y) % A log-log plot +semilogx(x, y) % A plot with logarithmic x-axis +semilogy(x, y) % A plot with logarithmic y-axis + +fplot (@(x) x^2, [2,5]) % plot the function x^2 from x=2 to x=5 + +grid on % Show grid; turn off with 'grid off' axis square % Makes the current axes region square axis equal % Set aspect ratio so data units are the same in every direction @@ -197,11 +240,19 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value contour(A) % Contour plot of matrix mesh(A) % Plot as a mesh surface -h = figure %C reate new figure object, with handle f -figure(h) %M akes the figure corresponding to handle h the current figure +h = figure % Create new figure object, with handle f +figure(h) % Makes the figure corresponding to handle h the current figure +close(h) % close figure with handle h +close all % close all open figure windows +close % close current figure window -% Properties can be set and changed through a figure handle -h = plot(x, y); +shg % bring an existing graphics window forward, or create new one if needed +clf clear % clear current figure window, and reset most figure properties + +% Properties can be set and changed through a figure handle. +% You can save a handle to a figure when you create it. +% The function gcf returns a handle to the current figure +h = plot(x, y); % you can save a handle to a figure when you create it set(h, 'Color', 'r') % 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black set(h, 'LineStyle', '--') @@ -209,22 +260,38 @@ set(h, 'LineStyle', '--') get(h, 'LineStyle') +% The function gca returns a handle to the axes for the current figure +set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis + +% To create a figure that contains several axes in tiled positions, use subplot +subplot(2,3,1); % select the first position in a 2-by-3 grid of subplots +plot(x1); title('First Plot') % plot something in this position +subplot(2,3,2); % select second position in the grid +plot(x2); title('Second Plot') % plot something there + + +% To use functions or scripts, they must be on your path or current directory +path % display current path +addpath /path/to/dir % add to path +rmpath /path/to/dir % remove from path +cd /path/to/move/into % change directory + + % Variables can be saved to .mat files save('myFileName.mat') % Save the variables in your Workspace load('myFileName.mat') % Load saved variables into Workspace - % M-file Scripts % A script file is an external file that contains a sequence of statements. % They let you avoid repeatedly typing the same code in the Command Window % Have .m extensions - % M-file Functions % Like scripts, and have the same .m extension % But can accept input arguments and return an output -% Also, they have their own workspace (ie. different variable scope) -% double_input.m - .m file name must be same as function name in file +% Also, they have their own workspace (ie. different variable scope). +% Function name should match file name (so save this example as double_input.m). +% 'help double_input.m' returns the comments under line beginning function function output = double_input(x) %double_input(x) returns twice the value of x output = 2*x; @@ -234,14 +301,26 @@ double_input(6) % ans = 12 % You can also have subfunctions and nested functions. % Subfunctions are in the same file as the primary function, and can only be -% called from within that function. Nested functions are defined within another +% called by functions in the file. Nested functions are defined within another % functions, and have access to both its workspace and their own workspace. +% If you want to create a function without creating a new file you can use an +% anonymous function. Useful when quickly defining a function to pass to +% another function (eg. plot with fplot, evaluate an indefinite integral +% with quad, find roots with fzero, or find minimum with fminsearch). +% Example that returns the square of it's input, assigned to to the handle sqr: +sqr = @(x) x.^2; +sqr(10) % ans = 100 +doc function_handle % find out more % User input a = input('Enter the value: ') -% Reading in data +% Stops execution of file and gives control to the keyboard: user can examine +% or change variables. Type 'return' to continue execution, or 'dbquit' to exit +keyboard + +% Reading in data (also xlsread/importdata/imread for excel/CSV/image files) fopen(filename) % Output @@ -249,10 +328,10 @@ disp(a) % Print out the value of variable a disp('Hello World') % Print out a string fprintf % Print to Command Window with more control -% Conditional statements -if a > 15 +% Conditional statements (the parentheses are optional, but good style) +if (a > 15) disp('Greater than 15') -elseif a == 23 +elseif (a == 23) disp('a is 23') else disp('neither condition met') @@ -316,14 +395,20 @@ NaN inf % Solving matrix equations (if no solution, returns a least squares solution) -x=A\b % Solves Ax=b -x=B/a % Solves xa=B +% The \ and / operators are equivalent to the functions mldivide and mrdivide +x=A\b % Solves Ax=b. Faster and more numerically accurate than using inv(A)*b. +x=b/A % Solves xA=b + +inv(A) % calculate the inverse matrix +pinv(A) % calculate the pseudo-inverse % Common matrix functions zeros(m,n) % m x n matrix of 0's ones(m,n) % m x n matrix of 1's -diag(A) % Extracts the diagonal elements of a matrix -eye(m,n) % Indentity matrix +diag(A) % Extracts the diagonal elements of a matrix A +diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere +eye(m,n) % Identity matrix +linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2 inv(A) % Inverse of matrix A det(A) % Determinant of A eig(A) % Eigenvalues and eigenvectors of A @@ -331,7 +416,7 @@ trace(A) % Trace of matrix - equivalent to sum(diag(A)) isempty(A) % Tests if array is empty all(A) % Tests if all elements are nonzero or true any(A) % Tests if any elements are nonzero or true -isequal(A, B) %Tests equality of two arrays +isequal(A, B) % Tests equality of two arrays numel(A) % Number of elements in matrix triu(x) % Returns the upper triangular part of x tril(x) % Returns the lower triangular part of x @@ -340,13 +425,18 @@ dot(A,B) % Returns scalar product of two vectors (must have the same length) transpose(A) % Returns the transpose of A flipl(A) % Flip matrix left to right +% Matrix Factorisations +[L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix +[P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues +[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order + % Common vector functions max % largest component min % smallest component length % length of a vector sort % sort in ascending order sum % sum of elements -prod % product of elements +prod % product of elements mode % modal value median % median value mean % mean value diff --git a/php.html.markdown b/php.html.markdown index 1952d833..226eefff 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -72,7 +72,7 @@ $quotient = 2 / 1; // 2 $number = 0; $number += 1; // Increment $number by 1 echo $number++; // Prints 1 (increments after evaluation) -echo ++$number; // Prints 3 (increments before evalutation) +echo ++$number; // Prints 3 (increments before evaluation) $number /= $float; // Divide and assign the quotient to $number // Strings should be enclosed in single quotes; diff --git a/pogo.html.markdown b/pogo.html.markdown new file mode 100644 index 00000000..60a83edd --- /dev/null +++ b/pogo.html.markdown @@ -0,0 +1,202 @@ +--- +language: pogoscript +contributors: + - ["Tim Macfarlane", "http://github.com/refractalize"] +filename: learnPogo.pogo +--- + +Pogoscript is a little language that emphasises readability, DSLs and provides excellent asynchronous primitives for writing connected JavaScript applications for the browser or server. + +``` javascript +// defining a variable +water temperature = 24 + +// re-assigning a variable after its definition +water temperature := 26 + +// functions allow their parameters to be placed anywhere +temperature at (a) altitude = 32 - a / 100 + +// longer functions are just indented +temperature at (a) altitude := + if (a < 0) + water temperature + else + 32 - a / 100 + +// calling a function +current temperature = temperature at 3200 altitude + +// this function constructs a new object with methods +position (x, y) = { + x = x + y = y + + distance from position (p) = + dx = self.x - p.x + dy = self.y - p.y + Math.sqrt (dx * dx + dy * dy) +} + +// `self` is similar to `this` in JavaScript with the +// exception that `self` isn't redefined in each new +// function definition +// `self` just does what you expect + +// calling methods +position (7, 2).distance from position (position (5, 1)) + +// as in JavaScript, objects are hashes too +position.'x' == position.x == position.('x') + +// arrays +positions = [ + position (1, 1) + position (1, 2) + position (1, 3) +] + +// indexing an array +positions.0.y + +n = 2 +positions.(n).y + +// strings +poem = 'Tail turned to red sunset on a juniper crown a lone magpie cawks. + Mad at Oryoki in the shrine-room -- Thistles blossomed late afternoon. + Put on my shirt and took it off in the sun walking the path to lunch. + A dandelion seed floats above the marsh grass with the mosquitos. + At 4 A.M. the two middleaged men sleeping together holding hands. + In the half-light of dawn a few birds warble under the Pleiades. + Sky reddens behind fir trees, larks twitter, sparrows cheep cheep cheep + cheep cheep.' + +// that's Allen Ginsburg + +// interpolation +outlook = 'amazing!' +console.log "the weather tomorrow is going to be #(outlook)" + +// regular expressions +r/(\d+)m/i +r/(\d+) degrees/mg + +// operators +true @and true +false @or true +@not false +2 < 4 +2 >= 2 +2 > 1 + +// plus all the javascript ones + +// to define your own +(p1) plus (p2) = + position (p1.x + p2.x, p1.y + p2.y) + +// `plus` can be called as an operator +position (1, 1) @plus position (0, 2) +// or as a function +(position (1, 1)) plus (position (0, 2)) + +// explicit return +(x) times (y) = return (x * y) + +// new +now = @new Date () + +// functions can take named optional arguments +spark (position, color: 'black', velocity: {x = 0, y = 0}) = { + color = color + position = position + velocity = velocity +} + +red = spark (position 1 1, color: 'red') +fast black = spark (position 1 1, velocity: {x = 10, y = 0}) + +// functions can unsplat arguments too +log (messages, ...) = + console.log (messages, ...) + +// blocks are functions passed to other functions. +// This block takes two parameters, `spark` and `c`, +// the body of the block is the indented code after the +// function call + +render each @(spark) into canvas context @(c) + ctx.begin path () + ctx.stroke style = spark.color + ctx.arc ( + spark.position.x + canvas.width / 2 + spark.position.y + 3 + 0 + Math.PI * 2 + ) + ctx.stroke () + +// asynchronous calls + +// JavaScript both in the browser and on the server (with Node.js) +// makes heavy use of asynchronous IO with callbacks. Async IO is +// amazing for performance and making concurrency simple but it +// quickly gets complicated. +// Pogoscript has a few things to make async IO much much easier + +// Node.js includes the `fs` module for accessing the file system. +// Let's list the contents of a directory + +fs = require 'fs' +directory listing = fs.readdir! '.' + +// `fs.readdir()` is an asynchronous function, so we can call it +// using the `!` operator. The `!` operator allows you to call +// async functions with the same syntax and largely the same +// semantics as normal synchronous functions. Pogoscript rewrites +// it so that all subsequent code is placed in the callback function +// to `fs.readdir()`. + +// to catch asynchronous errors while calling asynchronous functions + +try + another directory listing = fs.readdir! 'a-missing-dir' +catch (ex) + console.log (ex) + +// in fact, if you don't use `try catch`, it will raise the error up the +// stack to the outer-most `try catch` or to the event loop, as you'd expect +// with non-async exceptions + +// all the other control structures work with asynchronous calls too +// here's `if else` +config = + if (fs.stat! 'config.json'.is file ()) + JSON.parse (fs.read file! 'config.json' 'utf-8') + else + { + color: 'red' + } + +// to run two asynchronous calls concurrently, use the `?` operator. +// The `?` operator returns a *future* which can be executed to +// wait for and obtain the result, again using the `!` operator + +// we don't wait for either of these calls to finish +a = fs.stat? 'a.txt' +b = fs.stat? 'b.txt' + +// now we wait for the calls to finish and print the results +console.log "size of a.txt is #(a!.size)" +console.log "size of b.txt is #(b!.size)" + +// futures in Pogoscript are analogous to Promises +``` + +That's it. + +Download [Node.js](http://nodejs.org/) and `npm install pogo`. + +There is plenty of documentation on [http://pogoscript.org/](http://pogoscript.org/), inlcuding a [cheat sheet](http://pogoscript.org/cheatsheet.html), a [guide](http://pogoscript.org/guide/), and how [Pogoscript translates to Javascript](http://featurist.github.io/pogo-examples/). Get in touch on the [google group](http://groups.google.com/group/pogoscript) if you have questions! diff --git a/python.html.markdown b/python.html.markdown index bad9a360..08e68407 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -112,8 +112,10 @@ None is None #=> True ## 2. Variables and Collections #################################################### -# Printing is pretty easy -print "I'm Python. Nice to meet you!" +# Python has a print function, available in versions 2.7 and 3... +print("I'm Python. Nice to meet you!") +# and an older print statement, in all 2.x versions but removed from 3. +print "I'm also Python!" # No need to declare variables before assigning to them. @@ -224,7 +226,7 @@ filled_dict.get("four") #=> None filled_dict.get("one", 4) #=> 1 filled_dict.get("four", 4) #=> 4 -# "setdefault()" method is a safe way to add new key-value pair into dictionary +# "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 @@ -235,7 +237,7 @@ empty_set = set() some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4]) # Since Python 2.7, {} can be used to declare a set -filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} # Add more items to a set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} @@ -265,11 +267,11 @@ 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." + print("some_var is totally bigger than 10.") elif some_var < 10: # This elif clause is optional. - print "some_var is smaller than 10." + print("some_var is smaller than 10.") else: # This is optional too. - print "some_var is indeed 10." + print("some_var is indeed 10.") """ @@ -281,10 +283,10 @@ prints: """ for animal in ["dog", "cat", "mouse"]: # You can use % to interpolate formatted strings - print "%s is a mammal" % animal - + print("%s is a mammal" % animal) + """ -"range(number)" returns a list of numbers +"range(number)" returns a list of numbers from zero to the given number prints: 0 @@ -293,7 +295,7 @@ prints: 3 """ for i in range(4): - print i + print(i) """ While loops go until a condition is no longer met. @@ -305,7 +307,7 @@ prints: """ x = 0 while x < 4: - print x + print(x) x += 1 # Shorthand for x = x + 1 # Handle exceptions with a try/except block @@ -324,7 +326,7 @@ except IndexError as e: # Use "def" to create new functions def add(x, y): - print "x is %s and y is %s" % (x, y) + print("x is %s and y is %s" % (x, y)) return x + y # Return values with a return statement # Calling functions with parameters @@ -351,8 +353,8 @@ 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 + print(args) + print(kwargs) """ all_the_args(1, 2, a=3, b=4) prints: (1, 2) @@ -420,10 +422,10 @@ class Human(object): # Instantiate a class i = Human(name="Ian") -print i.say("hi") # prints out "Ian: hi" +print(i.say("hi")) # prints out "Ian: hi" j = Human("Joel") -print j.say("hello") #prints out "Joel: hello" +print(j.say("hello")) #prints out "Joel: hello" # Call our class method i.get_species() #=> "H. sapiens" @@ -443,12 +445,12 @@ Human.grunt() #=> "*grunt*" # You can import modules import math -print math.sqrt(16) #=> 4 +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 +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 @@ -459,7 +461,7 @@ 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 +# 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 diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/brainfuck-tr.html.markdown new file mode 100644 index 00000000..baca4217 --- /dev/null +++ b/tr-tr/brainfuck-tr.html.markdown @@ -0,0 +1,87 @@ +--- +language: brainfuck +filename: brainfuck-tr +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io"] +translators: + - ["Haydar KULEKCI", "http://scanf.info/"] +lang: tr-tr +--- + +Brainfuck (normalde brainfuck olarak bütün harfleri küçük olarak yazılır.) +son derece minimal bir programlama dilidir. (Sadece 8 komut) ve tamamen +Turing'dir. + +``` +"><+-.,[]" (tırnak işaretleri hariç) karakterleri dışındaki her karakter +gözardı edilir. + +Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir +dizidir. İşaretçi ilk hücreyi işaret eder. + +Sekik komut vardır: ++ : Geçerli hücrenin değerini bir artırır. +- : Geçerli hücrenin değerini bir azaltır. +> : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye). +< : Veri işaretçisini bir önceki hücreye hareket ettirir(soldaki hücreye). +. : Geçerli hücrenin ASCII değerini yazdırır (örn: 65 = 'A'). +, : Bir girdilik karakteri aktif hücre için okur. +[ : Eğer geçerli hücredeki değer sıfır ise, ]ifadesine atlar. + Diğer durumlarda bir sonraki yönergeye geçer. +] : Eğer geçerli hücredeki değer sıfır ise, bir sonraki yönergeye geçer. + Diğer durumlarda, [ ifadesine karşılık gelen yönergelere döner. + +[ ve ] bir while döngüsü oluşturur. Açıkça, dengeli olmalıdırlar. + +Basit bir brainfuck programına göz atalım. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Bu program 'A' karaterini ekrana basar. İlk olarak, #1'inci hücre 6'ya artırılır. +#1'inci hücre döngü için kullanılacaktır. Sonra, ([) döngüsüne girilir ve +#2'inci hücreye hareket edilir. #2'inci hücre 10 kez artırılır, #1'inci hücreye +geri dönülür. #1 hücresini bir azaltır. Bu döngü 6 kez gerçekleşir. (Bu 6 kez +azaltmak demektir, #1 hücresi 0 değerini alır ve bu noktada ] ifadesini atlar). + +Bu noktada, biz #1 hücresindeyiz, değeri şu anda 0 ve #2 hücresinin değeri +60'tır. Biz #2 hücresine hareket diyoruz ve bu hücreyi 5 defa artırıyoruz. +#2'nin şu anki değeri 65 olur. Sonra #2 hücresinin ASCII karşılığını +yazdırıyoruz. 65 değerinin ASCII karşılığı 'A'dır. Ekrana 'A' yazılacaktır. + + +, [ > + < - ] > . + +Bu program kullanıcıdan bir girdi okur, ve karakteri bir diğer hücreye yazdırır, +ve daha sonra aynı karakteri ekrana yazdırır. + +, ifadesi kullanıcıdan karakteri #1 hücresine okur. Sonra bir döngü +başlar. #2 hücresine hareket edilir, #2 hücresinin değeri bir artırılır, #1 +hücresine geri dönülür, ve #1 hücresinin değer bir azaltılır. Bu #1 hücresinin +değeri 0 olana kadar devam eder ve #2 hücresi #1'in eski değerini tutar. Çünkü +biz #1 hücresindeki verileri döngü süresince #2 hücresine taşıyoruz, ve sonunda +#2 hücresinin ASCII değerini yazdırıyoruz. + +Boşluk karakteri sadece okunabilirliği artırmak içindir. Aşağıdaki gibi de +yazabilirsiniz. + +,[>+<-]>. + + +Bu uygulamanın ne yaptığına bakalım: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Bu program 2 sayı alır, ve birbiri ile çarpar. + +Özetle, ilk olarak iki girdi alır. Sonra, #1 hücresinde şarta bağlı harici bir +döngü başlar. Sonra #2 ye hareket edilir, ve içerde #2 hücresine bağlı bir döngü +daha başlar ve #3 hücresinin değerini artırır. Ama, Bir problem vardır: iç +döngünün sonunda #2'inci hücrenin değeri 0 olacaktır. Bunu çözmek için #4 +hücresinin de değerini yükseltiyoruz, ve sonra #4 hücresinin değerini #2'ye +kopyalıyoruz. +``` + +İşte brainfuck. Zor değil değil mi? Eğlenmek için kendi programınızı +yazabilirsiniz, veya farklı bir dilde brainfuck yorumlayıcısı yazabilirsiniz. +Yorumlayıcı oldukça basittir, ama mazoşist iseniz, brainfuck içerisinde bir +brainfuck yorumlayıcısı yazmayı deneyebilirsiniz. diff --git a/tr-tr/objective-c-tr.html.markdown b/tr-tr/objective-c-tr.html.markdown new file mode 100644 index 00000000..854d70f6 --- /dev/null +++ b/tr-tr/objective-c-tr.html.markdown @@ -0,0 +1,320 @@ +--- +language: Objective-C +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] +filename: LearnObjectiveC-tr.m +translators: + - ["Haydar KULEKCI", "http://scanf.info/"] +lang: tr-tr +--- + +Objective-C Apple tarafından, OSX ve iOS işletim sistemleri ve onların +kendi çatıları olan Cocoa ve Cocoa Touch için kullanılan bir programlama dilidir. +Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C +programlama diline Smalltalk stilinde mesajlaşma ekler. + +```cpp +// Tek satır yorum // işaretleri ile başlar + +/* +Çoklu satır yorum bu şekilde görünür. +*/ + +// #import ile Foundation başlıklarını projeye import edebiliriz. +#import <Foundation/Foundation.h> +#import "MyClass.h" + +// Progarmınızı girişi bir main fonksiyonudur ve bir integer değer döner. +int main (int argc, const char * argv[]) +{ + // Programdaki bellek kullanımını kontrol etmek için autorelease bir + // oluşturuyoruz. Autorelease bellekte kullanılmayan değerlerin kendi + // kendini silmesi demektir. + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + // NSLog konsola bir satırlık bilgi yazdırmak için kullanılır. + NSLog(@"Hello World!"); // "Hello World!" değeri yazdırılır. + + /////////////////////////////////////// + // Tipler & Değişkenler + /////////////////////////////////////// + + // Basit Tanımlamalar + int myPrimitive1 = 1; + long myPrimitive2 = 234554664565; + + // Nesne Tanımlamaları + // strongly-typed nesne tanımlaması için karakter değişken isminin önüne + // * karakteri konulur. + MyClass *myObject1 = nil; // Strong typing + id myObject2 = nil; // Weak typing + // %@ bir nesnedir. + // 'description' objelerin değerlerinin gösterilmesi için bir düzendir. + NSLog(@"%@ and %@", myObject1, [myObject2 description]); + // "(null) and (null)" yazdırılacaktır. + + // Karakter Dizisi (String) + NSString *worldString = @"World"; + NSLog(@"Hello %@!", worldString); // "Hello World!" yazdırılacaktır. + + // Karakterler + NSNumber *theLetterZNumber = @'Z'; + char theLetterZ = [theLetterZNumber charValue]; + NSLog(@"%c", theLetterZ); + + // Tamsayılar + NSNumber *fortyTwoNumber = @42; + int fortyTwo = [fortyTwoNumber intValue]; + NSLog(@"%i", fortyTwo); + + NSNumber *fortyTwoUnsignedNumber = @42U; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; + NSLog(@"%u", fortyTwoUnsigned); + + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; + NSLog(@"%hi", fortyTwoShort); + + NSNumber *fortyTwoLongNumber = @42L; + long fortyTwoLong = [fortyTwoLongNumber longValue]; + NSLog(@"%li", fortyTwoLong); + + // Kayan Noktalı Sayılar (Floats) + NSNumber *piFloatNumber = @3.141592654F; + float piFloat = [piFloatNumber floatValue]; + NSLog(@"%f", piFloat); + + NSNumber *piDoubleNumber = @3.1415926535; + piDouble = [piDoubleNumber doubleValue]; + NSLog(@"%f", piDouble); + + // BOOL Değerler + NSNumber *yesNumber = @YES; + NSNumber *noNumber = @NO; + + // Dizi objeleri + NSArray *anArray = @[@1, @2, @3, @4]; + NSNumber *thirdNumber = anArray[2]; + NSLog(@"Third number = %@", thirdNumber); // "Third number = 3" yazdırılır + + // Dictionary objeleri + NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSObject *valueObject = aDictionary[@"A Key"]; + NSLog(@"Object = %@", valueObject); // "Object = (null)" yazıdılır + + /////////////////////////////////////// + // Operatörler + /////////////////////////////////////// + + // Operatörler C dilindeki gibi çalışır. + // Örneğin: + 2 + 5; // => 7 + 4.2f + 5.1f; // => 9.3f + 3 == 2; // => 0 (NO) + 3 != 2; // => 1 (YES) + 1 && 1; // => 1 (Logical and) + 0 || 1; // => 1 (Logical or) + ~0x0F; // => 0xF0 (bitwise negation) + 0x0F & 0xF0; // => 0x00 (bitwise AND) + 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) + + /////////////////////////////////////// + // Kontrol Yapıları + /////////////////////////////////////// + + // If-Else ifadesi + if (NO) + { + NSLog(@"I am never run"); + } else if (0) + { + NSLog(@"I am also never run"); + } else + { + NSLog(@"I print"); + } + + // Switch ifadesi + switch (2) + { + case 0: + { + NSLog(@"I am never run"); + } break; + case 1: + { + NSLog(@"I am also never run"); + } break; + default: + { + NSLog(@"I print"); + } break; + } + + // While döngü ifadesi + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++, ii değişkenini kullanıldıktan + //sonra yerinde artırır. + } // => "0," + // "1," + // "2," + // "3," yazdırılır + + // For döngü ifadesi + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", jj++); + } // => "0," + // "1," + // "2," + // "3," yazdırılır + + // Foreach ifadesi + NSArray *values = @[@0, @1, @2, @3]; + for (NSNumber *value in values) + { + NSLog(@"%@,", value); + } // => "0," + // "1," + // "2," + // "3," yazdırılır + + // Try-Catch-Finally ifadesi + @try + { + // İfadelerinizi buraya yazın + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"Sistemde Dosya Bulunamadı" userInfo:nil]; + } @catch (NSException * e) + { + NSLog(@"Exception: %@", e); + } @finally + { + NSLog(@"Finally"); + } // => "Exception: Sistemde Dosya Bulunamadı" + // "Finally" + // yazdırılacaktır + + /////////////////////////////////////// + // Objeler + /////////////////////////////////////// + + // Bellekten bir alan ayırmak ve objeyi burada oluşturmak bir obje örneği + // oluşturalım. Bir obje allocate ve init aşamalarını bitirmeden tam olarak + // işlevsel değildir. + MyClass *myObject = [[MyClass alloc] init]; + + // Objective-C nesne yönelimli programlama modelinin temelinde objelere + // mesaj gönderme vardır. + // Objective-C'de bir method çağırılmaz, ona bir mesaj gönderilir. + [myObject instanceMethodWithParameter:@"Steve Jobs"]; + + // Programda kullanılan bellek temizlenir + [pool drain]; + + // Program Sonu + return 0; +} + +/////////////////////////////////////// +// Sınıflar ve Fonksiyonlar +/////////////////////////////////////// + +// Sınıfınızı (MyClass.h) header dosyasında tanımlayın: + +// Sınıf tanımlama yapısı: +// @interface ClassName : ParentClassName <ImplementedProtocols> +// { +// Üye değişken (member variable) tanımlaması; +// } +// -/+ (type) Method tanımlaması; +// @end +@interface MyClass : NSObject <MyCustomProtocol> +{ + int count; + id data; + NSString *name; +} +// getter ve setter için otomatik oluşturulmuş gösterim. +@property int count; +@property (copy) NSString *name; // Copy the object during assignment. +@property (readonly) id data; // Declare only a getter method. + +// Metodlar ++/- (return type)methodSignature:(Parameter Type *)parameterName; + +// "+" class metodları içindir ++ (NSString *)classMethod; + +// "-" instance metodu içindir +- (NSString *)instanceMethodWithParmeter:(NSString *)string; +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; + +@end + +// Metodların implementasyonlarını (MyClass.m) dosyasında yapıyoruz: + +@implementation UserObject + +// Obje bellekten silineceği (release) zaman çağırılır +- (void)dealloc +{ +} + +// Constructor'lar sınıf oluşturmanın bir yoludur +// Bu varsayılan bir constructor'dur ve bir obje oluşturulurken çağrılır. +- (id)init +{ + if ((self = [super init])) + { + self.count = 1; + } + return self; +} + ++ (NSString *)classMethod +{ + return [[self alloc] init]; +} + +- (NSString *)instanceMethodWithParmeter:(NSString *)string +{ + return @"New string"; +} + +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number +{ + return @42; +} + +// MyProtocol içerisinde metod tanımlamaları +- (void)myProtocolMethod +{ + // ifadeler +} + +@end + +/* + * Bir `protocol` herhangi bir sınıf tarafından implement edilen metodları tanımlar + * `Protocol`ler sınıfların kendileri değildir. Onlar basitçe diğer objelerin + * implementasyon için sorumlu oldukları bir arayüz (interface) tanımlarlar. + */ +@protocol MyProtocol + - (void)myProtocolMethod; +@end + + + +``` +## Daha Fazla Okuma + +[Vikipedi Objective-C](http://tr.wikipedia.org/wiki/Objective-C) + +[Objective-C Öğrenme](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) + +[Lise Öğrencileri için iOS: Başlangıç](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) diff --git a/tr-tr/php-tr.html.markdown b/tr-tr/php-tr.html.markdown index c5576fd7..3db437cf 100644 --- a/tr-tr/php-tr.html.markdown +++ b/tr-tr/php-tr.html.markdown @@ -146,6 +146,11 @@ echo $associative['One']; // 1 yazdıracaktır. $array = ['One', 'Two', 'Three']; echo $array[0]; // => "One" +// Dizinin sonuna bir eleman ekleme +$array[] = 'Four'; + +// Diziden eleman silme +unset($array[3]); /******************************** * Çıktı @@ -692,7 +697,7 @@ $cls = new SomeOtherNamespace\MyClass(); Referans ve topluluk yazıları için [official PHP documentation](http://www.php.net/manual/) adresini ziyaret edin. -Gncel en yi örnekler için [PHP Usulüne Uygun](http://kulekci.net/php-the-right-way/) adresini ziyaret edin. +Güncel en yi örnekler için [PHP Usulüne Uygun](http://kulekci.net/php-the-right-way/) adresini ziyaret edin. Eğer bir paket yöneticisi olan dil kullandıysanız, [Composer](http://getcomposer.org/)'a bir göz atın. |