From 4c1a57714b6ee0db2ed93dd04811333e2c4de326 Mon Sep 17 00:00:00 2001 From: eugene Date: Wed, 3 Jul 2013 11:57:52 -0400 Subject: added Objective-C --- objvectiv-C.html.markdown | 67 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 objvectiv-C.html.markdown diff --git a/objvectiv-C.html.markdown b/objvectiv-C.html.markdown new file mode 100644 index 00000000..02975eb6 --- /dev/null +++ b/objvectiv-C.html.markdown @@ -0,0 +1,67 @@ +--- +language: Objectiv-C +author: Eugene Yagrushkin +author_url: www.about.me/yagrushkin +filename: learnc.Objectiv-C +--- + +Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch. +It's is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. + +```Objective-C +// Single-line comments start with // + +/* +Multi-line comments look like this. +*/ + +// Import headers with #import +#import +#import "SomeAppDelegate.h" + +// Declare your class in a header(.h) file: + +@interface UserObject : NSObject{ +// instance variables +} + +// Class method + + (NSString*) ClassMethod; + +// Instance method + - (NSString*) instanceMethodWithParmeter:(NSString*)string; + +@end + +// Add class methods in an implementation (.m) file: + +@implementation UserObject + ++ (NSString*) ClassMethod{ + return @"SomeString"; +} + +- (NSString*) instanceMethodWithParmeter:(NSString*)string; +{ + return [NSString stringWithString:string]; +} + +@end + +// Create an object instance by allocating memory and initializing it. An object is not fully functional until both steps have been completed. +UserObject *someObject = [[UserObject alloc] init]; + +// The Objective-C model of object-oriented programming is based on message passing to object instances. +// In Objective-C one does not simply call a method; one sends a message. + +[someObject instanceMethodWithParmeter@"Steve Jobs"]; + + +``` +## Further Reading + +[Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) + +[Objectively Speaking: A Crash Course in Objective-C](http://www.raywenderlich.com/12444/objectively-speaking-a-crash-course-in-objective-c) + +[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From a46ae22bf785bf74334a309c9b2f0a64f5a05659 Mon Sep 17 00:00:00 2001 From: paierlep Date: Wed, 3 Jul 2013 19:50:20 +0200 Subject: Update php.html.markdown a few sentences to constants --- php.html.markdown | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index f0c5c918..c6811282 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -99,6 +99,21 @@ END; echo 'This string ' . 'is concatenated'; +/******************************** + * Constants + */ + +// A constant is defined by using define() +// and can never be changed during runtime! + +// a valid constant name starts with a letter or underscore, +// followed by any number of letters, numbers, or underscores. +define("FOO", "something"); + +// access to a constant is possible by direct using the choosen name +echo 'This outputs '.FOO; + + /******************************** * Arrays */ -- cgit v1.2.3 From 040896b050e92a44c7c58be51ff4c9b8b7bb523d Mon Sep 17 00:00:00 2001 From: paierlep Date: Wed, 3 Jul 2013 19:55:03 +0200 Subject: Update php.html.markdown ?> instead of ? > --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index c6811282..73445839 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -8,7 +8,7 @@ filename: learnphp.php This document describes PHP 5+. ```php - tags + tags // If your php file only contains PHP code, it is best practise // to omit the php closing tag. -- cgit v1.2.3 From 4f06e456a973a99e15a232cee60a53c9f0bd8ace Mon Sep 17 00:00:00 2001 From: Dominic Bou-Samra Date: Sun, 30 Jun 2013 17:52:21 +1000 Subject: Started on Scala --- scala.html.markdown | 178 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 scala.html.markdown diff --git a/scala.html.markdown b/scala.html.markdown new file mode 100644 index 00000000..e8cde611 --- /dev/null +++ b/scala.html.markdown @@ -0,0 +1,178 @@ +--- +language: scala +author: Dominic Bou-Samra +author_url: http://dbousamra.github.com +filename: learnscala.scala +--- + +Scala is a + +```scala + +/////////////////////////////////////// +// Basic syntax +/////////////////////////////////////// + +// Single line comments start with two forward slashes +/* +Multi line comments look like this. +*/ + +// Import packages +import scala.collection.immutable.List +// Import all "sub packages" +import scala.collection.immutable._ +// Import multiple classes in one statement +import scala.collection.immutable.{List, Map} +// Rename an import using '=>' +import scala.collection.immutable{ List => ImmutableList } +// Import all classes, except some. The following excludes Map and Set: +import scala.collection.immutable.{Map => _, Set => _, _} + +// Your programs entry point is defined in an scala file using an object, with a single method, main: +object Application { + def main(args: Array[String]): Unit = { + // stuff goes here. + } +} + +// Printing, and forcing a new line on the next print +println("Hello world!") +// Printing, without forcing a new line on next print +print("Hello world") + +// Declaring values is done using either var or val +// val declarations are immutable, whereas var's are mutable. Immutablility is a good thing. +val x = 10 // x is now 10 +x = 20 // error: reassignment to val +var x = 10 +x = 20 // x is now 20 + +/////////////////////////////////////// +// Types +/////////////////////////////////////// + +// Almost all types are objects. + +// You have numbers +3 //3 + +// Math is as per usual +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 + +// Boolean values +true +false + +// Boolean operations +!true // false +!false // true +true == false // false +10 > 5 // true + +// Strings and characters +"Scala strings are surrounded by double quotes" // +'a' // A Scala Char +'Single quote strings don't exist' // Error +"Strings have the usual Java methods defined on them".length +"They also have some extra Scala methods.".reverse // See scala.collection.immutable.StringOps + +/////////////////////////////////////// +// Basic control constructs +/////////////////////////////////////// + +// if statements (else statements are optional) +if (10 > 5) println("10 is greater than 5") +// an else +if (x > 5) println("x is greater than 5") +else println("No it's not.") + +// Iteration + +// A while loop +while (x < 10) { + println("x is still less then 10") + x += 1 +} + +// A do while loop +do { + println("x is still less then 10"); + x += 1 +} while (x < 10) + +// A for loop +for (x <- 0 until 10) { + println(x) +} + +// Any object implementing the map/filter/flatMap methods allows the use of a for loop: +val aListOfNumbers: List[Int] = List(1, 2, 3) +for (x <- aListOfNumbers) { + println(x) +} + +// Pattern matching (see respective section) +x match { + case 5 => println("x is 5") + case 10 => println("x is 10") + case _ => println("default case") +} + +/////////////////////////////////////// +// Functions, methods and classes +/////////////////////////////////////// + +// Scala has classes + +// classname is Dog +class Dog { + //A method called bark, returning a String + def bark: String = { + // the body of the method + "Woof, woof!" + } +} + +// They can contain nearly any other construct, including other classes, functions, methods, objects, case classes, traits etc. + +/////////////////////////////////////// +// Higher-order functions +/////////////////////////////////////// + +// 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: +List(1, 2, 3) map (x => x + 10) + +// And the underscore symbol, can be used if there is just one argument to the anonymous function. It gets bound as the variable +List(1, 2, 3) map (_ + 10) + +TODO // If the anonymous block AND the function you are applying both take one argument, you can even omit the underscore +List("Dom", "Bob", "Natalia") foreach println + + +// Scala collections have rich higher-order functions defined on them. Some examples: + +// The map function takes a function/method, and applies it to each element in the structure +List(1, 2, 3) map (number => number.toString) + +// The filter function takes a predicate (a function from A -> Boolean) and selects all elements which satisfy the predicate +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)) + + +// Scala a foreach method defined on certain collections that takes a type returning Unit (a void method) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + + -- cgit v1.2.3 From 5207af80f59cc4cbbccb47f4b05860c487891427 Mon Sep 17 00:00:00 2001 From: Brian Martin Date: Fri, 5 Jul 2013 00:28:20 +0100 Subject: Create Visual Basic Contributing Visual Basic. --- Visual Basic | 248 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 248 insertions(+) create mode 100644 Visual Basic diff --git a/Visual Basic b/Visual Basic new file mode 100644 index 00000000..73430633 --- /dev/null +++ b/Visual Basic @@ -0,0 +1,248 @@ +--- +language: Visual Basic Console Application +contributors: + - ["Brian Martin", "http://brianmartin.biz"] +filename: learnvisualbasic.vb + +Module Module1 + + Sub Main() + 'A Quick Overview of Visual Basic Console Applications before we dive in to the deep end. + 'Apostrophe starts comments. + 'To Navigate this tutorial within the Visual Basic Complier, I've put together a navigation system. + 'This navigation system is explained however as we go deeper into this tutorial, you'll understand what it all means. + Console.Title = ("Learn X in Y Minutes") + Console.WriteLine("NAVIGATION") 'Display + Console.WriteLine("") + Console.ForegroundColor = ConsoleColor.Green + Console.WriteLine("1. Hello World Output") + Console.WriteLine("2. Hello World Input") + Console.WriteLine("3. Calculating Whole Numbers") + Console.WriteLine("4. Calculating Decimal Numbers") + Console.WriteLine("5. Working Calculator") + Console.WriteLine("6. Using Do While Loops") + Console.WriteLine("7. Using For While Loops") + Console.WriteLine("8. Conditional Statements") + Console.WriteLine("9. Select A Drink") + Console.WriteLine("50. About") + Console.WriteLine("Please Choose A Number From The Above List") + Dim selection As String = Console.ReadLine + Select Case selection + Case "1" 'HelloWorld Output + Console.Clear() 'Clears the application and opens the private sub + HelloWorldOutput() 'Name Private Sub, Opens Private Sub + Case "2" 'Hello Input + Console.Clear() + HelloWorldInput() + Case "3" 'Calculating Whole Numbers + Console.Clear() + CalculatingWholeNumbers() + Case "4" 'Calculting Decimal Numbers + Console.Clear() + CalculatingDecimalNumbers() + Case "5" 'Working Calcculator + Console.Clear() + WorkingCalculator() + Case "6" 'Using Do While Loops + Console.Clear() + UsingDoWhileLoops() + Case "7" 'Using For While Loops + Console.Clear() + UsingForLoops() + Case "8" 'Conditional Statements + Console.Clear() + ConditionalStatement() + Case "9" 'If/Else Statement + Console.Clear() + IfElseStatement() 'Select a drink + Case "50" 'About msg box + Console.Clear() + Console.Title = ("Learn X in Y Minutes :: About") + MsgBox("Learn X in Y Minutes is a creation of Adam Bard (@adambard) This particular program tutorial is by Brian Martin (@BrianMartinn") + Console.Clear() + Main() + Console.ReadLine() + + End Select + End Sub + + 'One - I'm using numbers to help with the above navigation when I come back later to build it. + Private Sub HelloWorldOutput() 'We use private subs to seperate different sections of the program. + Console.Title = "Hello World Ouput | Learn X in Y Minutes" 'Title of Console Application + 'Use Console.Write("") or Console.WriteLine("") to print outputs. + 'Followed by Console.Read() alternatively Console.Readline() + 'Console.ReadLine() prints the output to the console. + Console.WriteLine("Hello World") + Console.ReadLine() + End Sub + 'Two + Private Sub HelloWorldInput() 'We use private subs to seperate different sections of the program. + Console.Title = "Hello World YourName | Learn X in Y Minutes" 'Title of Console Application + 'Variables + 'Data entered by a user needs to be stored. + 'Variables also start with a Dim and end with an As VariableType. + Dim username As String 'In this tutorial, we want to know what your name, and make the program respond to what is said. + 'We use string as string is a text based variable. + Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. + username = Console.ReadLine() 'Stores the users name. + Console.WriteLine("Hello " + username) 'Output is Hello 'Their name' + Console.ReadLine() 'Outsputs the above. + 'The above will ask you a question followed by printing your answer. + 'Other variables include Integer and we use Integer for whole numbers. + End Sub + 'Three + Private Sub CalculatingWholeNumbers() 'We use private subs to seperate different sections of the program. + Console.Title = "Calculating Whole Numbers | Learn X in Y Minutes" 'Title of Console Application + Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104 ect + Dim a As Integer = Console.ReadLine() + Console.Write("Second number: ") 'Enter second whole number. + Dim b As Integer = Console.ReadLine() + Dim c As Integer = a + b + Console.WriteLine(c) + Console.ReadLine() + 'The above is a simple calculator + End Sub + 'Four + Private Sub CalculatingDecimalNumbers() + Console.Title = "Calculating with Double | Learn X in Y Minutes" 'Title of Console Application + 'Of course we would like to be able to add up decimals. + 'Therefore we could change the above from Integer to Double. + Console.Write("First number: ") 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect + Dim a As Double = Console.ReadLine + Console.Write("Second number: ") 'Enter second whole number. + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Console.WriteLine(c) + Console.ReadLine() + 'Therefore the above program can add up 1.1 - 2.2 + End Sub + 'Five + Private Sub WorkingCalculator() + Console.Title = "The Working Calculator| Learn X in Y Minutes" 'Title of Console Application + 'However if you'd like the calculator to subtract, divide, multiple and add up. + 'Copy and paste the above again. + Console.Write("First number: ") 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect + Dim a As Double = Console.ReadLine + Console.Write("Second number: ") 'Enter second whole number. + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + 'By adding the below lines we are able to calculate the subtract, multply as well as divide the a and b values + Console.Write(a.ToString() + " + " + b.ToString()) + Console.WriteLine(" = " + c.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. + Console.ReadLine() + + End Sub + 'Six + Private Sub UsingDoWhileLoops() + 'Just as the previous private sub + 'This Time We Ask If The User Wishes To Continue (Yes or No?) + 'We're using Do While Loop as we're unsure if the user wants to use the program more than once. + Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes" + Dim answer As String 'We use the variable "String" as the answer is text + Do 'We start the program with + Console.Write("First number: ") + Dim a As Double = Console.ReadLine + Console.Write("Second number: ") + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + Console.Write(a.ToString() + " + " + b.ToString()) + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.ReadLine() + 'Ask the question, does the user wish to continue? Unfortunately it is case sensitive. + Console.Write("Would you like to continue? (yes / no)") + answer = Console.ReadLine 'The program grabs the variable and prints and starts again. + Loop While answer = "yes" 'The command for the variable to work would be in this case "yes" + + End Sub + 'Seven + Private Sub UsingForLoops() + 'Sometimes the program only needs to run once. + 'In this program we'll be counting down from 10. + + Console.Title = "Using For Loops | Learn X in Y Minutes" + For i As Integer = 10 To 0 Step -1 'Declare Vairable and what number it should count down in Step -1, Step -2, Step -3 ect. + Console.WriteLine(i.ToString) 'Print the value of the counter variable + Next i 'Calculate new value + Console.WriteLine("Start") 'Lets start the program baby!! + Console.ReadLine() 'POW!! - Perhaps I got a little excited then :) + End Sub + 'Eight + Private Sub ConditionalStatement() + Console.Title = "Conditional Statements | Learn X in Y Minutes" + Dim userName As String = Console.ReadLine + Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. + userName = Console.ReadLine() 'Stores the users name. + If userName = "Adam" Then 'Hey, if Adam uses this program, kudos where kudos is due, right? + Console.WriteLine("Hello Adam") + Console.WriteLine("Thanks for creating the useful tutorial site www.learnxinyminutes.com!") + Console.ReadLine() + Else + Console.WriteLine("Hello " + userName) 'prints the username of the user + Console.WriteLine("Hope all is well have you checked out www.learnxinyminutes.com") 'Prints a message to the user + Console.ReadLine() 'Ends and prints the above statement. + End If + End Sub + 'Nine + Private Sub IfElseStatement() + Console.Title = "If / Else Statement | Learn X in Y Minutes" + 'Sometimes its important to consider more than two alternatives. Sometimes there are a good few others. + 'When this is the case, more than one if statement would be required. + 'An if statement is great for vending machines. Where the user enters a code. + 'A1, A2, A3, ect to select an item. + 'All choices can be combined into a single if statement. + + Dim selection As String = Console.ReadLine 'Value for selection + Console.WriteLine("A1. for 7Up") + Console.WriteLine("A2. for Fanta") + Console.WriteLine("A3. for Dr. Pepper") + Console.WriteLine("A4. for Diet Coke") + Console.ReadLine() + If selection = "A1" Then + Console.WriteLine("7up") + Console.ReadLine() + ElseIf selection = "A2" Then + Console.WriteLine("fanta") + Console.ReadLine() + ElseIf selection = "A3" Then + Console.WriteLine("dr. pepper") + Console.ReadLine() + ElseIf selection = "A4" Then + Console.WriteLine("diet coke") + Console.ReadLine() + Else + Console.WriteLine("Please select a product") + Console.ReadLine() + End If + + End Sub + +End Module + + +``` +## References + +I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily. + +I created a more indepth Visual Basic tutorial for those who would like to learn more. + +The entire syntax is valid. Copy the and paste in to the Visual Basic complier and run (F5) the program. -- cgit v1.2.3 From 3f814e58e9ab19348a985cf02e1fbdac407f3a6d Mon Sep 17 00:00:00 2001 From: Eugene Yagrushkin Date: Wed, 10 Jul 2013 14:20:46 -0400 Subject: Update objvectiv-C.html.markdown --- objvectiv-C.html.markdown | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/objvectiv-C.html.markdown b/objvectiv-C.html.markdown index 02975eb6..787a9219 100644 --- a/objvectiv-C.html.markdown +++ b/objvectiv-C.html.markdown @@ -15,10 +15,32 @@ It's is a general-purpose, object-oriented programming language that adds Smallt Multi-line comments look like this. */ +##Basic types +// all the primitive variable types are the same as in C +// char, int, long, double, float + + +// Simple, common classes +// number +NSNumber *firstNumber = @1; +NSNumber *secondNumber = @23.0; +NSNumber *boolNumber = @YES; + +// string +NSString *aString = @"some string"; + +// array +NSArray *array = @[ @1, @2]; + +// dictionary +NSDictionay *dictionary = @{ @"aKey" : @"aValue", @"aKey2" : @"aValue2" }; + // Import headers with #import #import #import "SomeAppDelegate.h" +##Coding classes + // Declare your class in a header(.h) file: @interface UserObject : NSObject{ @@ -43,19 +65,29 @@ Multi-line comments look like this. - (NSString*) instanceMethodWithParmeter:(NSString*)string; { - return [NSString stringWithString:string]; + return @"New string"; } +- (NSString*) otherMethodWithString:(NSString*)string; +{ + return [NSString stringWithString:string]; +} @end // Create an object instance by allocating memory and initializing it. An object is not fully functional until both steps have been completed. UserObject *someObject = [[UserObject alloc] init]; +##Calling Methods + // The Objective-C model of object-oriented programming is based on message passing to object instances. // In Objective-C one does not simply call a method; one sends a message. -[someObject instanceMethodWithParmeter@"Steve Jobs"]; +[someObject instanceMethodWithParmeter:@"Steve Jobs"]; + +##Nested Messages +// nested messages look like this: +[someObject instanceMethodWithParmeter:[someObject otherMethodWithString:@"Jony Ive"]]; ``` ## Further Reading -- cgit v1.2.3 From 2e7c3ba085da91a198f7b339d57bdf1fd8c8b49c Mon Sep 17 00:00:00 2001 From: George Petrov Date: Sun, 28 Jul 2013 20:52:32 +0100 Subject: Starting a Scala one --- scala.html.markdown | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 scala.html.markdown diff --git a/scala.html.markdown b/scala.html.markdown new file mode 100644 index 00000000..f087881a --- /dev/null +++ b/scala.html.markdown @@ -0,0 +1,53 @@ +/* + Set yourself up: + + 1) Download Scala - http://www.scala-lang.org/downloads + 2) unzip/untar in your favourite location and put the bin subdir on the path + 3) Start a scala REPL by typing scala. You should see the prompt: + + scala> + + This is the so called REPL. You can run commands in the REPL. Let do just that: +*/ + +println(10) // prints the integer 10 + +println("Boo!") // printlns the string Boo! + + +// Evaluating a command gives you the type and value of the result + +1 + 7 + +/* The above line results in: + + scala> 1 + 7 + res29: Int = 8 + + This means the result of evaluating 1 + 7 is an object of type Int with a value of 8 + + 1+7 will give you the same result +*/ + + +// Everything is an object, including a function type these in the repl: + +7 // results in res30: Int = 7 (res30 is just a generated var name for the result) + +// The next line gives you a function that takes an Int and returns it squared +(x:Int) => x * x + +// You can assign this function to an identifier, like this: +val sq = (x:Int) => x * x + +/* The above says this + + sq: Int => Int = + + Which means that this time we gave an explicit name to the value - sq is a function that take an Int and returns Int. + + sq can be executed as follows: +*/ + +sq(10) // Gives you this: res33: Int = 100. The result is the Int with a value 100 + -- cgit v1.2.3 From 7673ae8a6dc79fdc8f555d8e0c64834af17403d1 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 09:29:14 +0100 Subject: Added arrays and maps --- scala.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/scala.html.markdown b/scala.html.markdown index f087881a..82bf9db2 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -51,3 +51,16 @@ val sq = (x:Int) => x * x sq(10) // Gives you this: res33: Int = 100. The result is the Int with a value 100 + + +// Data structures + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Throws an exception + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Throws an exception \ No newline at end of file -- cgit v1.2.3 From 8c89f3f6083c93fa7ca04148a0e7aa07ff0d4545 Mon Sep 17 00:00:00 2001 From: Luke Holder Date: Mon, 29 Jul 2013 16:30:51 +0800 Subject: Explained syntactic sugar is really just method calls. Objects in ruby receive a message via the . (dot) notation. The arithmetic operators are just syntactic sugar of the . message notation. --- ruby.html.markdown | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 38d060a3..7729e0ff 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -312,4 +312,22 @@ dwight.name #=> "Dwight K. Schrute" # Call the class method Human.say("Hi") #=> "Hi" + + +=begin +Arithmetic is just syntactic sugar +for calling a method on an object: +=end +1.+ 1 #=> 2 +1.+(1) #=> 2 + +8.- 1 #=> 7 +8.-(1) #=> 7 + +10.* 2 #=> 20 +10.*(2) #=> 20 + +35./ 5 #=> 7 +35./(5) #=> 7 + ``` -- cgit v1.2.3 From 04e50a75fa253f71cf5de0f45d423f06dd9933d2 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 13:53:55 +0100 Subject: Added for comprehensions and conditionals --- scala.html.markdown | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 82bf9db2..783c7ae6 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -63,4 +63,50 @@ a(21) // Throws an exception val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") m("fork") m("spoon") -m("bottle") // Throws an exception \ No newline at end of file +m("bottle") // Throws an exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + + +// Tuples + + +// Combinators + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + + +// For comprehensions + +for { n <- s } yield sq(n) + +val nSquared2 = for { n <- s } yield sq(n) + +for { n <- nSquared2 if n < 10 } yield n + +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + + + +// Conditionals + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") + + +// Object oriented features + -- cgit v1.2.3 From 3cc4c64fb75581a21a2d8d4c2a28f3e83b5cf2f7 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 13:57:44 +0100 Subject: Added header --- scala.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/scala.html.markdown b/scala.html.markdown index 783c7ae6..173d271d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,3 +1,9 @@ +--- +language: scala +author: George Petrov +author_url: http://www.georgepetrov.com +--- + /* Set yourself up: @@ -106,6 +112,11 @@ 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("nope") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + // Object oriented features -- cgit v1.2.3 From d346342ad608849bdd1bcae7973bbff571225ba1 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 14:09:11 +0100 Subject: Added some pattern matching --- scala.html.markdown | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/scala.html.markdown b/scala.html.markdown index 173d271d..d6524a8f 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -121,3 +121,25 @@ val text = if (x == 10) "yeah" else "nope" // Object oriented features +class Person + + + +// Case classes + +case class Person(name:String, phoneNumber:String) + +Person("George", "1234") == Person("Kate", "1236") + + + +// Pattern matching + + +// Regular expressions + + +// Strings + + +// Input and output \ No newline at end of file -- cgit v1.2.3 From 33f3d4d6953cce6c45f2a7f4e8afc12571193c73 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 15:14:37 +0100 Subject: Fixing formatting --- scala.html.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index d6524a8f..3aedc88a 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,9 +1,16 @@ --- language: scala +filename: learn.scala author: George Petrov -author_url: http://www.georgepetrov.com +author_url: http://www.github.com/petrovg --- +Scala - the scalable language + +```c + + + /* Set yourself up: -- cgit v1.2.3 From 99b16c2672a2fc0b1dbb063c0b6e066158922099 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 15:18:24 +0100 Subject: Now really adding some pattern matching --- scala.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/scala.html.markdown b/scala.html.markdown index d6524a8f..d0187667 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -135,10 +135,29 @@ Person("George", "1234") == Person("Kate", "1236") // Pattern matching +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..." } + +me match { case Person("George", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + +val kate = Person("Kate", "1234") + +kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + + // Regular expressions + + // Strings -- cgit v1.2.3 From 3f2922d87a1c947eb6e20551846fd1b307984680 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 16:03:49 +0100 Subject: Adding some strings and docs links --- scala.html.markdown | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 8c000177..a1396b4d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -85,6 +85,10 @@ val s = Set(1, 3, 7) s(0) s(1) +/* Look up the documentation of map here - http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * and make sure you can read it + */ + // Tuples @@ -128,9 +132,6 @@ val text = if (x == 10) "yeah" else "nope" // Object oriented features -class Person - - // Case classes @@ -162,10 +163,32 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions - +// TODO // Strings +println("ABCDEF".length) +println("ABCDEF".substring(2, 6)) +println("ABCDEF".replace("C", "3")) + +val n = 45 +println(s"We have $n apples") + +val a = Array(11, 9, 6) +println(s"My second daughter is ${a(2-1)} years old") + +// Input and output + + +``` + +## Further resources + +[Scala for the impatient](http://horstmann.com/scala/) + +[Twitter Scala school(http://twitter.github.io/scala_school/) + +[The scala documentation] -// Input and output \ No newline at end of file +Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) \ No newline at end of file -- cgit v1.2.3 From a6ec23d414ba495b26a4028f9a6795d18a02cdac Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 18:33:03 +0100 Subject: Added loops, iterators and regex --- scala.html.markdown | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index a1396b4d..8bcbc27f 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -93,6 +93,7 @@ s(1) // Tuples + // Combinators s.map(sq) @@ -114,6 +115,37 @@ for { n <- nSquared2 if n < 10 } yield n for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared +/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas a for-comprehension + defines a relationship between two sets of data. Research this further */ + + + +// Loops and iteration + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// NB: Scala is quite lenien when it comes to dots and brackets - study the rules separately. This +// helps write DSLs and APIs that read like English + +(5 to 1 by -1) foreach ( println ) + +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why? + +i // Show the value of i. Note that while is a loop in the classical sense - it executes + // sequentially while changing the loop variable. while is very fast, faster that Java + // loops, but using the combinators and comprehensions above is easier to understand + // and parallelize + +// Tail recursion is an idiomatic way of doing things in Scala. Recursive functions need an +// explicit return type, the compile can't infer it. Here it's Unit. +def showNumbersInRange(a:Int, b:Int):Unit = { print(a); if (a < b) showNumbersInRange(a+1, b) } + // Conditionals @@ -128,11 +160,13 @@ if (x == 11) println ("yeah") else println("nope") println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" - +var i = 0 +while (i < 10) { println("i " + i); i+=1 } // Object oriented features + // Case classes case class Person(name:String, phoneNumber:String) @@ -141,6 +175,7 @@ Person("George", "1234") == Person("Kate", "1236") + // Pattern matching val me = Person("George", "1234") @@ -163,7 +198,14 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions -// TODO +val email = "(.*)@(.*)".r // The suffix .r invokes method r on String, which makes it a Regex + +val email(user, domain) = "henry@zkpr.com" + +"mrbean@pyahoo.com" match { + case email(name, domain) => "I know your name, " + name +} + // Strings @@ -178,6 +220,16 @@ println(s"We have $n apples") val a = Array(11, 9, 6) println(s"My second daughter is ${a(2-1)} years old") +// Some characters need to be 'escaped', e.g. a double quote inside a string: +val a = "They stood outside the \"Rose and Crown\"" + +// Triple double-quotes allow for strings to span multiple rows and contain funny characters +val html = """
+

Press belo', Joe

+ | +
""" + + // Input and output -- cgit v1.2.3 From 8235ddc50fce389356bc9ebb9e1b7249fa8bd5e7 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 22:19:15 +0100 Subject: Fixing a typo --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 8bcbc27f..57706c1f 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -20,7 +20,7 @@ Scala - the scalable language scala> - This is the so called REPL. You can run commands in the REPL. Let do just that: + This is the so called REPL. You can run commands in the REPL. Let's do just that: */ println(10) // prints the integer 10 -- cgit v1.2.3 From 82a5e4c8f0b3d79a2797fa0b5cdaf962bd7b3bf4 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 23:59:12 +0100 Subject: Fixed header --- scala.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 57706c1f..e7a432f6 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,8 +1,7 @@ --- -language: scala +language: Scala filename: learn.scala -author: George Petrov -author_url: http://www.github.com/petrovg +contributors:["George Petrov", "http://github.com/petrovg"] --- Scala - the scalable language @@ -43,7 +42,7 @@ println("Boo!") // printlns the string Boo! */ -// Everything is an object, including a function type these in the repl: +// Everything is an object, including a function. Type these in the REPL: 7 // results in res30: Int = 7 (res30 is just a generated var name for the result) -- cgit v1.2.3 From 11edf04311e33fad32c0bc943980482433b63460 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 23:59:58 +0100 Subject: Tweaking the header --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index e7a432f6..49c7bb14 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,7 +1,7 @@ --- language: Scala filename: learn.scala -contributors:["George Petrov", "http://github.com/petrovg"] +contributors: ["George Petrov", "http://github.com/petrovg"] --- Scala - the scalable language -- cgit v1.2.3 From 49ee527a79adbe3fde50b71effb4a9340b7ab7dc Mon Sep 17 00:00:00 2001 From: George Petrov Date: Tue, 30 Jul 2013 00:03:28 +0100 Subject: Header messages --- scala.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 49c7bb14..b22ba15b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,7 +1,8 @@ --- language: Scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] filename: learn.scala -contributors: ["George Petrov", "http://github.com/petrovg"] --- Scala - the scalable language -- cgit v1.2.3 From 99e1c31b19547fbe117a77047bb23eff0edafaea Mon Sep 17 00:00:00 2001 From: Luke Holder Date: Tue, 30 Jul 2013 15:26:51 +0800 Subject: Updated location, and reduced examples also added array [] access example. --- ruby.html.markdown | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 7729e0ff..9a59be90 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -4,6 +4,7 @@ filename: learnruby.rb contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] --- ```ruby @@ -30,6 +31,11 @@ You shouldn't either 10 * 2 #=> 20 35 / 5 #=> 7 +## Arithmetic is just syntactic sugar +## for calling a method on an object +1.+(3) #=> 4 +10.* 5 #=> 50 + # Special values are objects nil # Nothing to see here true # truth @@ -121,6 +127,12 @@ array = [1, "hello", false] #=> => [1, "hello", false] array[0] #=> 1 array[12] #=> nil +# Like arithmetic, [var] access +# is just syntactic sugar +# for calling a method [] on an object +array.[] 0 #=> 1 +array.[] 12 #=> nil + # From the end array[-1] #=> 5 @@ -313,21 +325,4 @@ dwight.name #=> "Dwight K. Schrute" # Call the class method Human.say("Hi") #=> "Hi" - -=begin -Arithmetic is just syntactic sugar -for calling a method on an object: -=end -1.+ 1 #=> 2 -1.+(1) #=> 2 - -8.- 1 #=> 7 -8.-(1) #=> 7 - -10.* 2 #=> 20 -10.*(2) #=> 20 - -35./ 5 #=> 7 -35./(5) #=> 7 - ``` -- cgit v1.2.3 From df90e4957246c422c00b07f788d825d327304d11 Mon Sep 17 00:00:00 2001 From: Luke Holder Date: Tue, 30 Jul 2013 15:28:40 +0800 Subject: Fixed comment style --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 9a59be90..a3bcbbd5 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -31,8 +31,8 @@ You shouldn't either 10 * 2 #=> 20 35 / 5 #=> 7 -## Arithmetic is just syntactic sugar -## for calling a method on an object +# Arithmetic is just syntactic sugar +# for calling a method on an object 1.+(3) #=> 4 10.* 5 #=> 50 -- cgit v1.2.3 From 9aec48beaef4f97a7fdb61478e20303c42e2d0f4 Mon Sep 17 00:00:00 2001 From: Tenor Biel Date: Wed, 31 Jul 2013 02:46:16 -0500 Subject: Added Whip LISP dialect --- whip.html.markdown | 237 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 237 insertions(+) create mode 100644 whip.html.markdown diff --git a/whip.html.markdown b/whip.html.markdown new file mode 100644 index 00000000..3fe9b2f4 --- /dev/null +++ b/whip.html.markdown @@ -0,0 +1,237 @@ +--- +language: whip +contributors: + - ["Tenor Biel", "http://github.com/L8D"] +author: Tenor Biel +author_url: http://github.com/L8D +filename: whip.lisp +--- + +Whip is a LISP-dialect made for scripting and simplified concepts. +It has also borrowed a lot of functions and syntax from Haskell(a non-related language). + +These docs were written by the creator of the language himself. So is this line. + +``` lisp +; Comments are like LISP. Semi-solons... + +; Majority of first-level statements are inside "forms" +; which are just things inside parens separated by whitespace +not_in_form +(in_form) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 1. Numbers, Strings, and Operators + +; Whip has one number type (which is a 64-bit IEEE 754 double, from JavaScript). +3 ; => 3 +1.5 ; => 1.5 + +; Functions are called if they are the first element in a form +(called_function args) + +; Majority of operations are done with functions +; All the basic arihmetic is pretty straight forward +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 +; even modulo +(% 9 4) ; => 1 +; JavaScript-style uneven division. +(/ 5 2) ; => 2.5 + +; Nesting forms works as you expect. +(* 2 (+ 1 3)) ; => 8 + +; There's a boolean type. +true +false + +; String are created with ". +"Hello, world" + +; Single chars are created with '. +'a' + +; Negation uses the 'not' function. +(not true) ; => false +(not false) ; => true + +; But the majority of non-haskell functions have shortcuts +; not's shortcut is a '!'. +(! (! true)) ; => true + +; Equality is `equal` or `=`. +(= 1 1) ; => true +(equal 2 1) ; => false + +; For example, inequality would be combinding the not and equal functions. +(! (= 2 1)) ; => true + +; More comparisons +(< 1 10) ; => true +(> 1 10) ; => false +; and their word counterpart. +(lesser 1 10) ; => true +(greater 1 10) ; => false + +; Strings can be concatenated with +. +(+ "Hello " "world!") ; => "Hello world!" + +; You can use JavaScript's comparative abilities. +(< 'a' 'b') ; => true +; ...and type coercion +(= '5' 5) + +; The `at` or @ function will access characters in strings, starting at 0. +(at 0 'a') ; => 'a' +(@ 3 "foobar") ; => 'b' + +; There is also the `null` and `undefined` variables. +null ; used to indicate a deliberate non-value +undefined ; user to indicate a value that hasn't been set + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 2. Vairbles, Lists, and Dicts + +; Variables are declared with the `def` or `let` functions. +; Variab;es that haven't been set will be `undefined`. +(def some_var 5) +; `def` will keep the variable in the global context. +; `let` will only have the variable inside it's context, and has a wierder syntax. +(let ((a_var 5)) (+ a_var 5)) ; => 10 +(+ a_var 5) ; = undefined + 5 => undefined + +; Lists are arrays of values of any type. +; They basically are just forms without functions at the beginning. +(1 2 3) ; => [1, 2, 3] (JavaScript syntax) + +; Dictionaries are Whip's equivalent to JavaScript 'objects' or Python 'dictionaries' +; or Ruby 'hashes': an unordered collection of key-value pairs. +{"key1":"value1" "key2":2 3:3} + +; Keys are just values, either identifier, number, or string. +(def my_dict {my_key:"my_value" "my other key":4}) +; But in Whip, dictionaries get parsed like: value, colon, value; with whitespace between each. +; So that means +{"key": "value" +"another key" +: 1234 +} +; is evaluated to the same as +{"key":"value" "another key":1234} + +; Dictionary definitions can be accessed used the `at` function, like strings and lists. +(@ "my other key" my_dict) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 3. Logic and Control sequences + +; The `if` function is pretty simple, though different than most imperitave langs. +(if true "returned if first arg is true" "returned if first arg is false") +; => "returned if first arg is true" + +; And for the sake of ternary operator legacy +; `?` is if's unused shortcut. +(? false true false) ; => false + +; `both` is a logical 'and' statement, and `either` is a logical 'or'. +(both true true) ; => true +(both true false) ; => false +(either true false) ; => true +(either false false) ; => false +; And their shortcuts are +; & => both +; ^ => either +(& true true) ; => true +(^ false true) ; => true + +;;;;;;;;; +; Lambdas + +; Lambdas in Whip are declared with the `lambda` or `->` function. +; And functions are really just lambdas with names. +(def my_function (-> (x y) (+ (x y) 10))) +; | | | | +; | | | returned value(with scope containing argument vars) +; | | arguments +; | lambda declaration function +; | +; name of the to-be-decalred lambda + +(my_function 10 10) ; = (+ (+ 10 10) 10) => 30 + +; Obiously, all lambdas by definition are anonymous and +; technically always used anonymouesly. Redundancy. +((lambda (x) x) 10) ; => 10 + +;;;;;;;;;;;;;;;; +; Comprehensions + +; `range` or `..` generates a list of numbers for +; each number between it's two args. +(range 1 5) ; => (1 2 3 4 5) +(.. 0 2) ; => (0 1 2) + +; `map` applies it's first arg(which should be a lambda/function) +; to each item in the following arg(which should be a list) +(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) + +; Reduce +(reduce + (.. 1 5)) +; equivalent to +((+ (+ (+ 1 2) 3) 4) 5) + +; Note: map and reduce don't have shortcuts + +; `slice` or `\` is just like JavaScript's .slice() +; But do note, it takes the list as the first argument, not the last. +(slice (.. 1 5) 2) ; => (3 4 5) +(\ (.. 0 100) -5) ; => (96 97 98 99 100) + +; `append` or `<<` is self expanatory +(append 4 (1 2 3)) ; => (1 2 3 4) +(<< "bar" ("foo")) ; => ("foo" "bar") + +; Length is self explanatory. +(length (1 2 3)) ; => 3 +(_ "foobar") ; => 6 + +;;;;;;;;;;;;;;; +; Haskell fluff + +; First item in list +(head (1 2 3)) ; => 1 +; List from second to last elements in list +(tail (1 2 3)) ; => (2 3) +; Last item in list +(last (1 2 3)) ; => 3 +; Reverse of `tail` +(init (1 2 3)) ; => (1 2) +; List from first to specified elements in list +(take 1 (1 2 3 4)) ; (1 2) +; Reverse of `take` +(drop 1 (1 2 3 4)) ; (3 4) +; Lowest value in list +(min (1 2 3 4)) ; 1 +; Highest value in list +(max (1 2 3 4)) ; 4 +; If value is in list or object +(elem 1 (1 2 3)) ; true +(elem "foo" {"foo":"bar"}) ; true +(elem "bar" {"foo":"bar"}) ; false +; Reverse list order +(reverse (1 2 3 4)) ; => (4 3 2 1) +; If value is even or odd +(even 1) ; => false +(odd 1) ; => true +; Split string into list of strings by whitespace +(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese") +; Join list of strings together. +(unwords ("foo" "bar")) ; => "foobar" +(pred 21) ; => 20 +(succ 20) ; => 21 +``` + +For more info, check out the [repo](http://github.com/L8D/whip) -- cgit v1.2.3 From 38bd9a18fda39e70060cd64a49a0095ba4901e26 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Wed, 31 Jul 2013 20:52:59 +0100 Subject: Added tuples --- scala.html.markdown | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/scala.html.markdown b/scala.html.markdown index b22ba15b..8bcb5975 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -92,6 +92,26 @@ s(1) // Tuples +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(a, 2, "three") + +// Why have this? +val divideInts = (x:Int, y:Int) => (x / y, x % y) + +divideInts(10,3) // The function divideInts gives you the result and the remainder + +// To access the elements of a tuple, use _._n where n is the 1-based index of the element +val d = divideInts(10,3) + +d._1 + +d._2 + // Combinators -- cgit v1.2.3 From e22b3e57a8c0b65dc8e43c3c185e3f7ca3a98b4a Mon Sep 17 00:00:00 2001 From: L8D Date: Wed, 31 Jul 2013 19:13:11 -0500 Subject: Started on the addition of coffeescript --- coffeescript.html.markdown | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 coffeescript.html.markdown diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown new file mode 100644 index 00000000..429f10b5 --- /dev/null +++ b/coffeescript.html.markdown @@ -0,0 +1,55 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] +filename: coffeescript.coffee +--- + +``` coffeescript +# CoffeeScript is a hipster language. +# It goes with the trends of many modern languages. +# So comments are like Ruby and Python, they use hashes. + +### +Block comments are like these, and they translate directly to '/ *'s and '* /'s +for the resulting JavaScript code. + +You should understand most of JavaScript semantices +before continuing. +### + +# Assignment: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Conditions: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Functions: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +# Ranges: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objects: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +#} + +# Splats: +race = (winner, runners...) -> + print winner, runners + +# Existence: +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# Array comprehensions: +cubes = (math.cube num for num in list) #=> ... +``` -- cgit v1.2.3 From 4ecd73fc9cd766557e10fc2fa0c3351c373ff1a0 Mon Sep 17 00:00:00 2001 From: Adam Date: Thu, 1 Aug 2013 11:24:23 -0700 Subject: An assortment --- c.html.markdown | 2 + visualbasic.html.markdown | 281 +++++++++++++++++++++++++++++++++++++++++ whip.html.markdown | 13 +- zh-cn/c-cn.html.markdown | 5 +- zh-cn/elisp-cn.html.markdown | 10 +- zh-cn/java-cn.html.markdown | 9 +- zh-cn/javascript.html.markdown | 11 +- zh-cn/php-cn.html.markdown | 3 +- 8 files changed, 314 insertions(+), 20 deletions(-) create mode 100644 visualbasic.html.markdown diff --git a/c.html.markdown b/c.html.markdown index 132f75dc..b5286f70 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -1,4 +1,6 @@ --- +name: c +category: language language: c filename: learnc.c contributors: diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown new file mode 100644 index 00000000..fbfa500d --- /dev/null +++ b/visualbasic.html.markdown @@ -0,0 +1,281 @@ +--- +language: Visual Basic +contributors: + - ["Brian Martin", "http://brianmartin.biz"] +filename: learnvisualbasic.vb +--- + +```vb +Module Module1 + + Sub Main() + ' A Quick Overview of Visual Basic Console Applications before we dive + ' in to the deep end. + ' Apostrophe starts comments. + ' To Navigate this tutorial within the Visual Basic Complier, I've put + ' together a navigation system. + ' This navigation system is explained however as we go deeper into this + ' tutorial, you'll understand what it all means. + Console.Title = ("Learn X in Y Minutes") + Console.WriteLine("NAVIGATION") 'Display + Console.WriteLine("") + Console.ForegroundColor = ConsoleColor.Green + Console.WriteLine("1. Hello World Output") + Console.WriteLine("2. Hello World Input") + Console.WriteLine("3. Calculating Whole Numbers") + Console.WriteLine("4. Calculating Decimal Numbers") + Console.WriteLine("5. Working Calculator") + Console.WriteLine("6. Using Do While Loops") + Console.WriteLine("7. Using For While Loops") + Console.WriteLine("8. Conditional Statements") + Console.WriteLine("9. Select A Drink") + Console.WriteLine("50. About") + Console.WriteLine("Please Choose A Number From The Above List") + Dim selection As String = Console.ReadLine + Select Case selection + Case "1" 'HelloWorld Output + Console.Clear() 'Clears the application and opens the private sub + HelloWorldOutput() 'Name Private Sub, Opens Private Sub + Case "2" 'Hello Input + Console.Clear() + HelloWorldInput() + Case "3" 'Calculating Whole Numbers + Console.Clear() + CalculatingWholeNumbers() + Case "4" 'Calculting Decimal Numbers + Console.Clear() + CalculatingDecimalNumbers() + Case "5" 'Working Calcculator + Console.Clear() + WorkingCalculator() + Case "6" 'Using Do While Loops + Console.Clear() + UsingDoWhileLoops() + Case "7" 'Using For While Loops + Console.Clear() + UsingForLoops() + Case "8" 'Conditional Statements + Console.Clear() + ConditionalStatement() + Case "9" 'If/Else Statement + Console.Clear() + IfElseStatement() 'Select a drink + Case "50" 'About msg box + Console.Clear() + Console.Title = ("Learn X in Y Minutes :: About") + MsgBox("This tutorial is by Brian Martin (@BrianMartinn") + Console.Clear() + Main() + Console.ReadLine() + + End Select + End Sub + + 'One - I'm using numbers to help with the above navigation when I come back + 'later to build it. + + 'We use private subs to seperate different sections of the program. + Private Sub HelloWorldOutput() + 'Title of Console Application + Console.Title = "Hello World Ouput | Learn X in Y Minutes" + 'Use Console.Write("") or Console.WriteLine("") to print outputs. + 'Followed by Console.Read() alternatively Console.Readline() + 'Console.ReadLine() prints the output to the console. + Console.WriteLine("Hello World") + Console.ReadLine() + End Sub + + 'Two + Private Sub HelloWorldInput() + Console.Title = "Hello World YourName | Learn X in Y Minutes" + ' Variables + ' Data entered by a user needs to be stored. + ' Variables also start with a Dim and end with an As VariableType. + + ' In this tutorial, we want to know what your name, and make the program + ' respond to what is said. + Dim username As String + 'We use string as string is a text based variable. + Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. + username = Console.ReadLine() 'Stores the users name. + Console.WriteLine("Hello " + username) 'Output is Hello 'Their name' + Console.ReadLine() 'Outsputs the above. + 'The above will ask you a question followed by printing your answer. + 'Other variables include Integer and we use Integer for whole numbers. + End Sub + + 'Three + Private Sub CalculatingWholeNumbers() + Console.Title = "Calculating Whole Numbers | Learn X in Y Minutes" + Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104 ect + Dim a As Integer = Console.ReadLine() + Console.Write("Second number: ") 'Enter second whole number. + Dim b As Integer = Console.ReadLine() + Dim c As Integer = a + b + Console.WriteLine(c) + Console.ReadLine() + 'The above is a simple calculator + End Sub + + 'Four + Private Sub CalculatingDecimalNumbers() + Console.Title = "Calculating with Double | Learn X in Y Minutes" + 'Of course we would like to be able to add up decimals. + 'Therefore we could change the above from Integer to Double. + + 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect + Console.Write("First number: ") + Dim a As Double = Console.ReadLine + Console.Write("Second number: ") 'Enter second whole number. + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Console.WriteLine(c) + Console.ReadLine() + 'Therefore the above program can add up 1.1 - 2.2 + End Sub + + 'Five + Private Sub WorkingCalculator() + Console.Title = "The Working Calculator| Learn X in Y Minutes" + 'However if you'd like the calculator to subtract, divide, multiple and + 'add up. + 'Copy and paste the above again. + Console.Write("First number: ") + Dim a As Double = Console.ReadLine + Console.Write("Second number: ") 'Enter second whole number. + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + 'By adding the below lines we are able to calculate the subtract, + 'multply as well as divide the a and b values + Console.Write(a.ToString() + " + " + b.ToString()) + 'We want to pad the answers to the left by 3 spaces. + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.ReadLine() + + End Sub + + 'Six + Private Sub UsingDoWhileLoops() + 'Just as the previous private sub + 'This Time We Ask If The User Wishes To Continue (Yes or No?) + 'We're using Do While Loop as we're unsure if the user wants to use the + 'program more than once. + Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes" + Dim answer As String 'We use the variable "String" as the answer is text + Do 'We start the program with + Console.Write("First number: ") + Dim a As Double = Console.ReadLine + Console.Write("Second number: ") + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + Console.Write(a.ToString() + " + " + b.ToString()) + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.ReadLine() + 'Ask the question, does the user wish to continue? Unfortunately it + 'is case sensitive. + Console.Write("Would you like to continue? (yes / no)") + 'The program grabs the variable and prints and starts again. + answer = Console.ReadLine + 'The command for the variable to work would be in this case "yes" + Loop While answer = "yes" + + End Sub + + 'Seven + Private Sub UsingForLoops() + 'Sometimes the program only needs to run once. + 'In this program we'll be counting down from 10. + + Console.Title = "Using For Loops | Learn X in Y Minutes" + 'Declare Variable and what number it should count down in Step -1, + 'Step -2, Step -3 ect. + For i As Integer = 10 To 0 Step -1 + Console.WriteLine(i.ToString) 'Print the value of the counter + Next i 'Calculate new value + Console.WriteLine("Start") 'Lets start the program baby!! + Console.ReadLine() 'POW!! - Perhaps I got a little excited then :) + End Sub + + 'Eight + Private Sub ConditionalStatement() + Console.Title = "Conditional Statements | Learn X in Y Minutes" + Dim userName As String = Console.ReadLine + Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. + userName = Console.ReadLine() 'Stores the users name. + If userName = "Adam" Then + Console.WriteLine("Hello Adam") + Console.WriteLine("Thanks for creating this useful site") + Console.ReadLine() + Else + Console.WriteLine("Hello " + userName) + Console.WriteLine("Have you checked out www.learnxinyminutes.com") + Console.ReadLine() 'Ends and prints the above statement. + End If + End Sub + + 'Nine + Private Sub IfElseStatement() + Console.Title = "If / Else Statement | Learn X in Y Minutes" + 'Sometimes its important to consider more than two alternatives. + 'Sometimes there are a good few others. + 'When this is the case, more than one if statement would be required. + 'An if statement is great for vending machines. Where the user enters a code. + 'A1, A2, A3, ect to select an item. + 'All choices can be combined into a single if statement. + + Dim selection As String = Console.ReadLine 'Value for selection + Console.WriteLine("A1. for 7Up") + Console.WriteLine("A2. for Fanta") + Console.WriteLine("A3. for Dr. Pepper") + Console.WriteLine("A4. for Diet Coke") + Console.ReadLine() + If selection = "A1" Then + Console.WriteLine("7up") + Console.ReadLine() + ElseIf selection = "A2" Then + Console.WriteLine("fanta") + Console.ReadLine() + ElseIf selection = "A3" Then + Console.WriteLine("dr. pepper") + Console.ReadLine() + ElseIf selection = "A4" Then + Console.WriteLine("diet coke") + Console.ReadLine() + Else + Console.WriteLine("Please select a product") + Console.ReadLine() + End If + + End Sub + +End Module + +``` + +## References + +I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily. + +I created a more indepth Visual Basic tutorial for those who would like to learn more. + +The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program. diff --git a/whip.html.markdown b/whip.html.markdown index 3fe9b2f4..b8852ecb 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -12,8 +12,8 @@ It has also borrowed a lot of functions and syntax from Haskell(a non-related la These docs were written by the creator of the language himself. So is this line. -``` lisp -; Comments are like LISP. Semi-solons... +```scheme +; Comments are like LISP. Semi-colons... ; Majority of first-level statements are inside "forms" ; which are just things inside parens separated by whitespace @@ -107,14 +107,14 @@ undefined ; user to indicate a value that hasn't been set ; They basically are just forms without functions at the beginning. (1 2 3) ; => [1, 2, 3] (JavaScript syntax) -; Dictionaries are Whip's equivalent to JavaScript 'objects' or Python 'dictionaries' +; Dictionaries are Whip's equivalent to JavaScript 'objects' or Python 'dicts' ; or Ruby 'hashes': an unordered collection of key-value pairs. {"key1":"value1" "key2":2 3:3} ; Keys are just values, either identifier, number, or string. (def my_dict {my_key:"my_value" "my other key":4}) -; But in Whip, dictionaries get parsed like: value, colon, value; with whitespace between each. -; So that means +; But in Whip, dictionaries get parsed like: value, colon, value; +; with whitespace between each. So that means {"key": "value" "another key" : 1234 @@ -122,7 +122,8 @@ undefined ; user to indicate a value that hasn't been set ; is evaluated to the same as {"key":"value" "another key":1234} -; Dictionary definitions can be accessed used the `at` function, like strings and lists. +; Dictionary definitions can be accessed used the `at` function +; (like strings and lists.) (@ "my other key" my_dict) ; => 4 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown index ed55203c..f8a8e0bd 100755 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -2,9 +2,10 @@ language: c filename: learnc.c contributors: - - ["Adam Bard", "http://adambard.com/"] + - ["Adam Bard", "http://adambard.com/"] translators: - - ["Chenbo Li", "http://binarythink.net/"] + - ["Chenbo Li", "http://binarythink.net/"] +lang: zh-cn --- C语言在今天仍然是高性能计算的主要选择。 diff --git a/zh-cn/elisp-cn.html.markdown b/zh-cn/elisp-cn.html.markdown index d9a8ce35..c3a2f927 100755 --- a/zh-cn/elisp-cn.html.markdown +++ b/zh-cn/elisp-cn.html.markdown @@ -3,12 +3,15 @@ language: elisp contributors: - ["Bastien Guerry", "http://bzg.fr"] translators: - - ["Chenbo Li", "http://binarythink.net"] + - ["Chenbo Li", "http://binarythink.net"] filename: learn-emacs-lisp.el +lang: zh-cn --- ```scheme -;; 15分钟学会Emacs Lisp (v0.2a) (作者:bzg,https://github.com/bzg 译者:lichenbo,http://douban.com/people/lichenbo) +;; 15分钟学会Emacs Lisp (v0.2a) +;;(作者:bzg,https://github.com/bzg +;; 译者:lichenbo,http://douban.com/people/lichenbo) ;; ;; 请先阅读Peter Norvig的一篇好文: ;; http://norvig.com/21-days.html @@ -301,7 +304,8 @@ filename: learn-emacs-lisp.el (list 'face 'bold))) (other-window 1)) -;; 这个函数使用了 `re-search-forward': 和查找一个字符串不同,你用这个命令可以查找一个模式,即正则表达式 +;; 这个函数使用了 `re-search-forward': +;; 和查找一个字符串不同,你用这个命令可以查找一个模式,即正则表达式 ;; 正则表达式 "Bonjour \\(.+\\)!" 的意思是: ;; 字符串 "Bonjour ", 之后跟着 diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index 4db4e91e..b9ccf61a 100755 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -1,12 +1,13 @@ --- - +name: java +category: language language: java +lang: zh-cn +filename: LearnJava.java contributors: - ["Jake Prather", "http://github.com/JakeHP"] translators: - - ["Chenbo Li", "http://binarythink.net"] -filename: LearnJava.java - + - ["Chenbo Li", "http://binarythink.net"] --- Java是一个通用的程序语言, 包含并发, 基于类的面向对象等特性 diff --git a/zh-cn/javascript.html.markdown b/zh-cn/javascript.html.markdown index dd04c8a5..3b5cfa94 100755 --- a/zh-cn/javascript.html.markdown +++ b/zh-cn/javascript.html.markdown @@ -1,9 +1,12 @@ --- language: javascript -author: Adam Brenecki -author_url: http://adam.brenecki.id.au -translator: Chenbo Li -translator_url: http://binarythink.net +category: language +name: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] +translators: + - ["Chenbo Li", "http://binarythink.net"] +lang: zh-cn --- Javascript于1995年由网景公司的Brendan Eich发明。 diff --git a/zh-cn/php-cn.html.markdown b/zh-cn/php-cn.html.markdown index e3dfe419..3b242ce1 100755 --- a/zh-cn/php-cn.html.markdown +++ b/zh-cn/php-cn.html.markdown @@ -4,8 +4,9 @@ contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] translators: - - ["Chenbo Li", "http://binarythink.net"] + - ["Chenbo Li", "http://binarythink.net"] filename: learnphp.php +lang: zh-cn --- 这份教程所使用的版本是 PHP 5+. -- cgit v1.2.3 From 1a52aefcba5c31bb05b58290380509d6da81045c Mon Sep 17 00:00:00 2001 From: Chenbo Li Date: Fri, 2 Aug 2013 23:40:47 +0800 Subject: add git-cn and rename javascript --- zh-cn/git-cn.html.markdown | 375 ++++++++++++++++++++++++++++++++++ zh-cn/javascript-cn.html.markdown | 415 ++++++++++++++++++++++++++++++++++++++ zh-cn/javascript.html.markdown | 415 -------------------------------------- 3 files changed, 790 insertions(+), 415 deletions(-) create mode 100755 zh-cn/git-cn.html.markdown create mode 100755 zh-cn/javascript-cn.html.markdown delete mode 100755 zh-cn/javascript.html.markdown diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown new file mode 100755 index 00000000..7aab8986 --- /dev/null +++ b/zh-cn/git-cn.html.markdown @@ -0,0 +1,375 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: + - ["Chenbo Li", "http://binarythink.net"] +filename: LearnGit.txt +lang: zh-cn +--- + +Git是一个分布式版本控制及源代码管理工具 + +Git可以为你的项目保存若干快照,以此来对整个项目进行版本管理 + +## 版本 + +### 什么是版本控制 + +版本控制系统就是根据时间来记录一个或多个文件的更改情况的系统。 + +### 集中式版本控制 VS 分布式版本控制 + +* 集中式版本控制的主要功能为同步,跟踪以及备份文件 +* 分布式版本控制则更注重共享更改。每一次更改都有唯一的标识 +* 分布式系统没有预定的结构。你也可以用git很轻松的实现SVN风格的集中式系统控制 + +[更多信息](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### 为什么要使用Git + +* 可以离线工作 +* 和他人协同工作变得简单 +* 分支很轻松 +* 合并很容易 +* Git系统速度快,也很灵活 + +## Git 架构 + + +### 版本库 + +一系列文件,目录,历史记录,提交记录和头指针。 +可以把它视作每个源代码文件都带有历史记录属性数据结构 + +一个Git版本库包括一个 .git 目录和其工作目录 + +### .git 目录(版本库的一部分) + +.git 目录包含所有的配置、日志、分支信息、头指针等 +[详细列表](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### 工作目录 (版本库的一部分) + +版本库中的目录和文件,可以看做就是你工作时的目录 + +### 索引(.git 目录) + +索引就是git中的 staging 区. 可以算作是把你的工作目录与Git版本库分割开的一层 +这使得开发者能够更灵活的决定要将要在版本库中添加什么内容 + +### 提交 + +一个 git 提交就是一组更改或者对工作目录操作的快照 +比如你添加了5个文件,删除了2个文件,那么这些变化就会被写入一个提交比如你添加了5个文件,删除了2个文件,那么这些变化就会被写入一个提交中 +而这个提交之后也可以被决定是否推送到另一个版本库中 + +### 分支 + +分支其实就是一个指向你最后一次的提交的指针 +当你提交时,这个指针就会自动指向最新的提交 + +### 头指针 与 头(.git 文件夹的作用) + +头指针是一个指向当前分支的指针,一个版本库只有一个当前活动的头指针 +而头则可以指向版本库中任意一个提交,每个版本库也可以有多个头 + +### 其他形象化解释 + +* [给计算机科学家的解释](http://eagain.net/articles/git-for-computer-scientists/) +* [给设计师的解释](http://hoth.entp.com/output/git_for_designers.html) + + +## 命令 + + +### 初始化 + +创建一个新的git版本库。这个版本库的配置、存储等信息会被保存到.git文件夹中 + +```bash +$ git init +``` + +### 配置 + +更改设置。可以是版本库的设置,也可以是系统的或全局的 + + +```bash +# 输出、设置基本的全局变量 +$ git config --global user.email +$ git config --global user.name + +$ git config --global user.email "MyEmail@Zoho.com" +$ git config --global user.name "My Name" +``` + +[关于git的更多设置](http://git-scm.com/docs/git-config) + +### 帮助 + +git内置了对命令非常详细的解释,可以供我们快速查阅 + +```bash +# 查找可用命令 +$ git help + +# 查找所有可用命令 +$ git help -a + +# 在文档当中查找特定的命令 +$ git help <命令> +$ git help add +$ git help commit +$ git help init +``` + +### 状态 + +显示索引文件(也就是当前工作空间)和当前的头指针指向的提交的不同 + + +```bash +# 显示分支,为跟踪文件,更改和其他不同 +$ git status + +# 查看其他的git status的用法 +$ git help status +``` + +### 添加 + +添加文件到当前工作空间中。如果你不使用 `git add` 将文件添加进去, +那么这些文件也不会添加到之后的提交之中 + +```bash +# 添加一个文件 +$ git add HelloWorld.java + +# 添加一个子目录中的文件 +$ git add /path/to/file/HelloWorld.c + +# 支持正则表达式 +$ git add ./*.java +``` + +### 分支 + +管理分支,可以通过下列命令对分支进行增删改查 + +```bash +# 查看所有的分支和远程分支 +$ git branch -a + +# 创建一个新的分支 +$ git branch myNewBranch + +# 删除一个分支 +$ git branch -d myBranch + +# 重命名分支 +# git branch -m <旧名称> <新名称> +$ git branch -m myBranchName myNewBranchName + +# 编辑分支的介绍 +$ git branch myBranchName --edit-description +``` + +### 检出 + +将当前工作空间更新到索引所标识的或者某一特定的工作空间 + +```bash +# 检出一个版本库,默认将更新到master分支 +$ git checkout +# 检出到一个特定的分支 +$ git checkout branchName +# 新建一个分支,并且切换过去,相当于"git branch <名字>; git checkout <名字>" +$ git checkout -b newBranch +``` + +### clone + +这个命令就是将一个版本库拷贝到另一个目录中,同时也将 +分支都拷贝到新的版本库中。这样就可以在新的版本库中提交到远程分支 + +```bash +# clone learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +``` + +### commit + +将当前索引的更改保存为一个新的提交,这个提交包括用户做出的更改与信息 + +```bash +# 提交时附带提交信息 +$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" +``` + +### diff + +显示当前工作空间和提交的不同 + +```bash +# 显示工作目录和索引的不同 +$ git diff + +# 显示索引和最近一次提交的不同 +$ git diff --cached + +# 显示宫缩目录和最近一次提交的不同 +$ git diff HEAD +``` + +### grep + +可以在版本库中快速查找 + +可选配置: + +```bash +# 感谢Travis Jeffery提供的以下用法: +# 在搜索结果中显示行号 +$ git config --global grep.lineNumber true + +# 是搜索结果可读性更好 +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# 在所有的java中查找variableName +$ git grep 'variableName' -- '*.java' + +# 搜索包含 "arrayListName" 和, "add" 或 "remove" 的所有行 +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +更多的例子可以查看: +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +显示这个版本库的所有提交 + +```bash +# 显示所有提交 +$ git log + +# 显示某几条提交信息 +$ git log -n 10 + +# 仅显示合并提交 +$ git log --merges +``` + +### merge + +合并就是将外部的提交合并到自己的分支中 + +```bash +# 将其他分支合并到当前分支 +$ git merge branchName + +# 在合并时创建一个新的合并后的提交 +$ git merge --no-ff branchName +``` + +### mv + +重命名或移动一个文件 + +```bash +# 重命名 +$ git mv HelloWorld.c HelloNewWorld.c + +# 移动 +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# 强制重命名或移动 +# 这个文件已经存在,将要覆盖掉 +$ git mv -f myFile existingFile +``` + +### pull + +从远端版本库合并到当前分支 + +```bash +# 从远端origin的master分支更新版本库 +# git pull <远端> <分支> +$ git pull origin master +``` + +### push + +把远端的版本库更新 + +```bash +# 把本地的分支更新到远端origin的master分支上 +# git push <远端> <分支> +# git push 相当于 git push origin master +$ git push origin master +``` + +### rebase (谨慎使用) + +将一个分支上所有的提交历史都应用到另一个分支上 +*不要在一个已经公开的远端分支上使用rebase*. + +```bash +# 将experimentBranch应用到master上面 +# git rebase +$ git rebase master experimentBranch +``` + +[更多阅读](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (谨慎使用) + +将当前的头指针复位到一个特定的状态。这样可以使你撤销merge、pull、commits、add等 +这是个很强大的命令,但是在使用时一定要清楚其所产生的后果 + +```bash +# 使 staging 区域恢复到上次提交时的状态,不改变现在的工作目录 +$ git reset + +# 使 staging 区域恢复到上次提交时的状态,覆盖现在的工作目录 +$ git reset --hard + +# 将当前分支恢复到某次提交,不改变现在的工作目录 +# 在工作目录中所有的改变仍然存在 +$ git reset 31f2bb1 + +# 将当前分支恢复到某次提交,覆盖现在的工作目录 +# 并且删除所有未提交的改变和指定提交之后的所有提交 +$ git reset --hard 31f2bb1 +``` + +### rm + +和add相反,从工作空间中去掉某个文件爱你 + +```bash +# 移除 HelloWorld.c +$ git rm HelloWorld.c + +# 移除子目录中的文件 +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## 更多阅读 + +* [tryGit - 学习Git的有趣方式](http://try.github.io/levels/1/challenges/1) + +* [git-scm - 视频教程](http://git-scm.com/videos) + +* [git-scm - 文档](http://git-scm.com/docs) + +* [Atlassian Git - 教程与工作流程](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown new file mode 100755 index 00000000..dd04c8a5 --- /dev/null +++ b/zh-cn/javascript-cn.html.markdown @@ -0,0 +1,415 @@ +--- +language: javascript +author: Adam Brenecki +author_url: http://adam.brenecki.id.au +translator: Chenbo Li +translator_url: http://binarythink.net +--- + +Javascript于1995年由网景公司的Brendan Eich发明。 +最初发明的目的是作为一个简单的网站脚本语言,来作为 +复杂网站应用java的补充。但由于javascript和网站结合度很高 +所以javascript逐渐变得比java在前端更为流行了。 + +JavaScript 不仅仅只可以用于浏览器, 也可用于 Node.js 等后台环境。 + +很欢迎来自您的反馈,您可以通过下列方式联系到我: +[@adambrenecki](https://twitter.com/adambrenecki), 或者 +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// 注释方式和C很像,这是单行注释 +/* 这是多行 + 注释 */ + +// 语句可以以分号结束 +doStuff(); + +// ... 但是分号也可以省略,每当遇到一个新行时,分号会自动插入 +doStuff() + +// 我们在这里会去掉分号,但是否添加最后的分号取决于你个人的习惯 +// 及你所在团队的编程风格 + +/////////////////////////////////// +// 1. 数字、字符串与操作符 + +// Javascript 只有一种数字类型 (即 64位 IEEE 754 双精度浮点). +3 // = 3 +1.5 // = 1.5 + +// 所有基本的算数运算 +1 + 1 // = 2 +8 - 1 // = 7 +10 * 2 // = 20 +35 / 5 // = 7 + +// 包括无法整除的除法 +5 / 2 // = 2.5 + +// 位运算也和其他语言一样。当你对浮点数进行位运算时, +// 浮点数会转换为至多 32 位的无符号整数 +1 << 2 // = 4 + +// 括号可以决定优先级 +(1 + 3) * 2 // = 8 + +// 有三种非数字的数字类型 +Infinity // 1/0 的结果 +-Infinity // -1/0 的结果 +NaN // 0/0 的结果 + +// 也有布尔值 +true +false + +// 可以通过单引号或双引号来构造字符串 +'abc' +"Hello, world" + +// 用!来取非 +!true // = false +!false // = true + +// 相等 == +1 == 1 // = true +2 == 1 // = false + +// 不等 != +1 != 1 // = false +2 != 1 // = true + +// 更多的比较操作符 +1 < 10 // = true +1 > 10 // = false +2 <= 2 // = true +2 >= 2 // = true + +// 字符串用+连接 +"Hello " + "world!" // = "Hello world!" + +// 字符串也可以用 < 、> 来比较 +"a" < "b" // = true + +// 比较时会进行类型转换... +"5" == 5 // = true + +// ...除非你是用 === +"5" === 5 // = false + +// 你可以用charAt来得到字符串中的字符 +"This is a string".charAt(0) + +// 还有两个特殊的值:null和undefined +null // 用来表示刻意设置成的空值 +undefined // 用来表示还没有设置的值 + +// null, undefined, NaN, 0 和 "" 都是假的(false),其他的都视作逻辑真 +// 注意 0 是逻辑假而 "0"是逻辑真, 尽管 0 == "0". + +/////////////////////////////////// +// 2. 变量、数组和对象 + +// 变量需要用 var 这个关键字声明. Javascript是动态类型语言 +// 所以你在声明时无需指定类型。 赋值需要用 = +var someVar = 5 + +// 如果你在声明时没有加var关键字,你也不会得到错误 +someOtherVar = 10 + +// ...但是此时这个变量就会拥有全局的作用域,而非当前作用域 + +// 没有被赋值的变量都会返回undefined这个值 +var someThirdVar // = undefined + +// 对变量进行数学运算有一些简写法 +someVar += 5 // 等价于 someVar = someVar + 5; someVar 现在是 10 +someVar *= 10 // 现在 someVar 是 100 + +// 自增和自减也有简写 +someVar++ // someVar 是 101 +someVar-- // 回到 100 + +// 数组是任意类型组成的有序列表 +var myArray = ["Hello", 45, true] + +// 数组的元素可以用方括号下标来访问 +// 数组的索引从0开始 +myArray[1] // = 45 + +// javascript中的对象相当于其他语言中的字典或映射:是键-值的集合 +{key1: "Hello", key2: "World"} + +// 键是字符串,但是引号也并非是必须的,如果键本身是合法的js标识符 +// 而值则可以是任意类型的值 +var myObj = {myKey: "myValue", "my other key": 4} + +// 对象的访问可以通过下标 +myObj["my other key"] // = 4 + +// ... 或者也可以用 . ,如果属性是合法的标识符 +myObj.myKey // = "myValue" + +// 对象是可变的,键和值也可以被更改或增加 +myObj.myThirdKey = true + +// 如果你想要访问一个还没有被定义的属性,那么会返回undefined +myObj.myFourthKey // = undefined + +/////////////////////////////////// +// 3. 逻辑与控制结构 + +// if语句和其他语言中一样 +var count = 1 +if (count == 3){ + // count 是 3 时执行 +} else if (count == 4) { + // count 是 4 时执行 +} else { + // 其他情况下执行 +} + +// while循环 +while (true) { + // 无限循环 +} + +// Do-while 和 While 循环很像 ,但前者会至少执行一次 +var input +do { + input = getInput() +} while (!isValid(input)) + +// for循环和C、Java中的一样 +// 初始化; 继续执行的条件; 遍历后执行. +for (var i = 0; i < 5; i++){ + // 遍历5次 +} + +// && 是逻辑与, || 是逻辑或 +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear" +} +if (colour == "red" || colour == "blue"){ + // colour是red或者blue时执行 +} + +// && 和 || 是“短路”语句,在初始化值时会变得有用 +var name = otherName || "default" + +/////////////////////////////////// +// 4. 函数、作用域、闭包 + +// JavaScript 函数由function关键字定义 +function myFunction(thing){ + return thing.toUpperCase() +} +myFunction("foo") // = "FOO" + +// 函数也可以是匿名的: +function(thing){ + return thing.toLowerCase() +} +// (我们无法调用此函数,因为我们不知道这个函数的名字) + +// javascript中的函数也是对象,所以函数也能够赋给一个变量,并且被传递 +// 比如一个事件处理函数: +function myFunction(){ + // this code will be called in 5 seconds' time +} +setTimeout(myFunction, 5000) + +// 你甚至可以直接把一个函数写到另一个函数的参数中 + +setTimeout(function myFunction(){ + // 5秒之后会执行这里的代码 +}, 5000) + +// JavaScript 仅有函数作用于,而其他的语句则没有作用域 +if (true){ + var i = 5 +} +i // = 5 - 并非我们在其他语言中所得到的undefined + +// 这就导致了人们经常用一种叫做“即使执行匿名函数”的模式 +// 这样可以避免一些临时变量扩散到外边去 +function(){ + var temporary = 5 + // 我们可以访问一个全局对象来访问全局作用域 + // 在浏览器中是 'window' 这个对象。 + // 在Node.js中这个对象的名字可能会不同。 + window.permanent = 10 + // 或者,我们也可以把var去掉就行了 + permanent2 = 15 +}() +temporary // 抛出引用异常 +permanent // = 10 +permanent2 // = 15 + +// javascript最强大的功能之一就是闭包 +// 如果一个函数在另一个函数中定义,那么这个函数就拥有外部函数的所有访问权 +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!" + function inner(){ + alert(prompt) + } + setTimeout(inner, 5000) + // setTimeout 是异步的,所以这个函数会马上终止不会等待。 + // 然而,在5秒结束后,inner函数仍然会弹出prompt信息。 +} +sayHelloInFiveSeconds("Adam") // 会在5秒后弹出 "Hello, Adam!" + +/////////////////////////////////// +// 5. 对象、构造函数与原型 + +// 对象包含方法 +var myObj = { + myFunc: function(){ + return "Hello world!" + } +} +myObj.myFunc() // = "Hello world!" + +// 当对象中的函数被调用时,这个函数就可以通过this关键字访问这个对象 +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString + } +} +myObj.myFunc() // = "Hello world!" + +// 但这个函数访问的其实是其运行时环境,而非定义时环境 +// 所以如果函数所在的环境不在当前对象的环境中运行时,就运行不成功了 +var myFunc = myObj.myFunc +myFunc() // = undefined + +// 相应的,一个函数也可以被指定为一个对象的方法,并且用过this可以访问 +// 这个对象的成员,即使在定义时并没有绑定任何值 +var myOtherFunc = function(){ + return this.myString.toUpperCase() +} +myObj.myOtherFunc = myOtherFunc +myObj.myOtherFunc() // = "HELLO WORLD!" + +// 当你通过new关键字调用一个函数时,就会生成一个对象 +// 而对象的成员需要通过this来定义。 +// 这样的函数就叫做构造函数 + +var MyConstructor = function(){ + this.myNumber = 5 +} +myNewObj = new MyConstructor() // = {myNumber: 5} +myNewObj.myNumber // = 5 + +// 每一个js对象都有一个原型,当你要访问一个没有定义过的成员时, +// 解释器就回去找这个对象的原型 + +// 有一些JS实现会让你通过一个对象的__proto__方法访问这个原型。 +// 这虽然对理解这个对象很有用,但是这并不是标准的一部分 +// 我们之后会通过标准方式来访问原型。 +var myObj = { + myString: "Hello world!", +} +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +} +myObj.__proto__ = myPrototype +myObj.meaningOfLife // = 42 + +// This works for functions, too. +myObj.myFunc() // = "hello world!" + +// 当然,如果你要访问的成员在原型当中也没有定义的话,解释器就会去找原型的原型。 +myPrototype.__proto__ = { + myBoolean: true +} +myObj.myBoolean // = true + +// 这其中并没有对象的拷贝。每个对象的原型实际上是持有原型对象的引用 +// 这说明当我们改变对象的原型时,会影响到其他以这个原型为原型的对象 +myPrototype.meaningOfLife = 43 +myObj.meaningOfLife // = 43 + +// 我们知道 __proto__ 并非标准规定,实际上也没有办法更改已经指定好的原型。 +// 但是,我们有两种方式可以为新的对象指定原型。 + +// 第一种方式是 Object.create,这个方法是在最近才被添加到Js中的 +// 也因此并不是所有的JS实现都有这个放啊 +var myObj = Object.create(myPrototype) +myObj.meaningOfLife // = 43 + +// 第二种方式可以在任意版本中使用,不过需要通过构造函数。 +// 构造函数有一个属性prototype。但是这 *不是* 构造函数本身的函数 +// 而是通过构造函数和new关键字生成新对象时自动生成的。 +myConstructor.prototype = { + getMyNumber: function(){ + return this.myNumber + } +} +var myNewObj2 = new myConstructor() +myNewObj2.getMyNumber() // = 5 + +// 字符串和数字等内置类型也有通过构造函数来创建的包装类型 +var myNumber = 12 +var myNumberObj = new Number(12) +myNumber == myNumberObj // = true + +// 但是它们并非严格等价 +typeof(myNumber) // = 'number' +typeof(myNumberObj) // = 'object' +myNumber === myNumberObj // = false +if (0){ + // 这段代码不会执行,因为0代表假 +} +if (Number(0)){ + // 这段代码会执行,因为Number(0)代表真 +} + +// 但是,包装类型和内置类型共享一个原型 +// 这样你就可以给内置类型也增加一些功能 +String.prototype.firstCharacter = function(){ + return this.charAt(0) +} +"abc".firstCharacter() // = "a" + +// 这个技巧可以用来用老版本的javascript子集来是实现新版本js的功能 +// 这样就可以在老的浏览器中使用新功能了。 + +// 比如,我们知道Object.create并没有在所有的版本中都实现 +// 但是我们仍然可以通过这个技巧来使用 +if (Object.create === undefined){ // 如果存在则不覆盖 + Object.create = function(proto){ + // 用正确的原型来创建一个临时构造函数 + var Constructor = function(){} + Constructor.prototype = proto + // 之后用它来创建一个新的对象 + return new Constructor() + } +} +``` + +## 更多阅读 + +[Mozilla 开发者 +网络](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 提供了很好的 +Javascript文档,并且由于是wiki,所以你也可以自行编辑来分享你的知识。 +wiki, so as you learn more you can help others out by sharing your own +knowledge. + +MDN的 [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +覆盖了这里提到的绝大多数话题,大多数只是Javascript这个语言本身。 +如果你想了解Javascript是如何在网页中被应用的,那么可以查看 +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) 是一个深入 +讲解所有Javascript反直觉部分的一本书 + +除了这篇文章的直接贡献者之外,这篇文章也参考了这个网站上 +Louie Dinh 的 Python 教程,以及 Mozilla开发者网络上的[JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) diff --git a/zh-cn/javascript.html.markdown b/zh-cn/javascript.html.markdown deleted file mode 100755 index dd04c8a5..00000000 --- a/zh-cn/javascript.html.markdown +++ /dev/null @@ -1,415 +0,0 @@ ---- -language: javascript -author: Adam Brenecki -author_url: http://adam.brenecki.id.au -translator: Chenbo Li -translator_url: http://binarythink.net ---- - -Javascript于1995年由网景公司的Brendan Eich发明。 -最初发明的目的是作为一个简单的网站脚本语言,来作为 -复杂网站应用java的补充。但由于javascript和网站结合度很高 -所以javascript逐渐变得比java在前端更为流行了。 - -JavaScript 不仅仅只可以用于浏览器, 也可用于 Node.js 等后台环境。 - -很欢迎来自您的反馈,您可以通过下列方式联系到我: -[@adambrenecki](https://twitter.com/adambrenecki), 或者 -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). - -```js -// 注释方式和C很像,这是单行注释 -/* 这是多行 - 注释 */ - -// 语句可以以分号结束 -doStuff(); - -// ... 但是分号也可以省略,每当遇到一个新行时,分号会自动插入 -doStuff() - -// 我们在这里会去掉分号,但是否添加最后的分号取决于你个人的习惯 -// 及你所在团队的编程风格 - -/////////////////////////////////// -// 1. 数字、字符串与操作符 - -// Javascript 只有一种数字类型 (即 64位 IEEE 754 双精度浮点). -3 // = 3 -1.5 // = 1.5 - -// 所有基本的算数运算 -1 + 1 // = 2 -8 - 1 // = 7 -10 * 2 // = 20 -35 / 5 // = 7 - -// 包括无法整除的除法 -5 / 2 // = 2.5 - -// 位运算也和其他语言一样。当你对浮点数进行位运算时, -// 浮点数会转换为至多 32 位的无符号整数 -1 << 2 // = 4 - -// 括号可以决定优先级 -(1 + 3) * 2 // = 8 - -// 有三种非数字的数字类型 -Infinity // 1/0 的结果 --Infinity // -1/0 的结果 -NaN // 0/0 的结果 - -// 也有布尔值 -true -false - -// 可以通过单引号或双引号来构造字符串 -'abc' -"Hello, world" - -// 用!来取非 -!true // = false -!false // = true - -// 相等 == -1 == 1 // = true -2 == 1 // = false - -// 不等 != -1 != 1 // = false -2 != 1 // = true - -// 更多的比较操作符 -1 < 10 // = true -1 > 10 // = false -2 <= 2 // = true -2 >= 2 // = true - -// 字符串用+连接 -"Hello " + "world!" // = "Hello world!" - -// 字符串也可以用 < 、> 来比较 -"a" < "b" // = true - -// 比较时会进行类型转换... -"5" == 5 // = true - -// ...除非你是用 === -"5" === 5 // = false - -// 你可以用charAt来得到字符串中的字符 -"This is a string".charAt(0) - -// 还有两个特殊的值:null和undefined -null // 用来表示刻意设置成的空值 -undefined // 用来表示还没有设置的值 - -// null, undefined, NaN, 0 和 "" 都是假的(false),其他的都视作逻辑真 -// 注意 0 是逻辑假而 "0"是逻辑真, 尽管 0 == "0". - -/////////////////////////////////// -// 2. 变量、数组和对象 - -// 变量需要用 var 这个关键字声明. Javascript是动态类型语言 -// 所以你在声明时无需指定类型。 赋值需要用 = -var someVar = 5 - -// 如果你在声明时没有加var关键字,你也不会得到错误 -someOtherVar = 10 - -// ...但是此时这个变量就会拥有全局的作用域,而非当前作用域 - -// 没有被赋值的变量都会返回undefined这个值 -var someThirdVar // = undefined - -// 对变量进行数学运算有一些简写法 -someVar += 5 // 等价于 someVar = someVar + 5; someVar 现在是 10 -someVar *= 10 // 现在 someVar 是 100 - -// 自增和自减也有简写 -someVar++ // someVar 是 101 -someVar-- // 回到 100 - -// 数组是任意类型组成的有序列表 -var myArray = ["Hello", 45, true] - -// 数组的元素可以用方括号下标来访问 -// 数组的索引从0开始 -myArray[1] // = 45 - -// javascript中的对象相当于其他语言中的字典或映射:是键-值的集合 -{key1: "Hello", key2: "World"} - -// 键是字符串,但是引号也并非是必须的,如果键本身是合法的js标识符 -// 而值则可以是任意类型的值 -var myObj = {myKey: "myValue", "my other key": 4} - -// 对象的访问可以通过下标 -myObj["my other key"] // = 4 - -// ... 或者也可以用 . ,如果属性是合法的标识符 -myObj.myKey // = "myValue" - -// 对象是可变的,键和值也可以被更改或增加 -myObj.myThirdKey = true - -// 如果你想要访问一个还没有被定义的属性,那么会返回undefined -myObj.myFourthKey // = undefined - -/////////////////////////////////// -// 3. 逻辑与控制结构 - -// if语句和其他语言中一样 -var count = 1 -if (count == 3){ - // count 是 3 时执行 -} else if (count == 4) { - // count 是 4 时执行 -} else { - // 其他情况下执行 -} - -// while循环 -while (true) { - // 无限循环 -} - -// Do-while 和 While 循环很像 ,但前者会至少执行一次 -var input -do { - input = getInput() -} while (!isValid(input)) - -// for循环和C、Java中的一样 -// 初始化; 继续执行的条件; 遍历后执行. -for (var i = 0; i < 5; i++){ - // 遍历5次 -} - -// && 是逻辑与, || 是逻辑或 -if (house.size == "big" && house.colour == "blue"){ - house.contains = "bear" -} -if (colour == "red" || colour == "blue"){ - // colour是red或者blue时执行 -} - -// && 和 || 是“短路”语句,在初始化值时会变得有用 -var name = otherName || "default" - -/////////////////////////////////// -// 4. 函数、作用域、闭包 - -// JavaScript 函数由function关键字定义 -function myFunction(thing){ - return thing.toUpperCase() -} -myFunction("foo") // = "FOO" - -// 函数也可以是匿名的: -function(thing){ - return thing.toLowerCase() -} -// (我们无法调用此函数,因为我们不知道这个函数的名字) - -// javascript中的函数也是对象,所以函数也能够赋给一个变量,并且被传递 -// 比如一个事件处理函数: -function myFunction(){ - // this code will be called in 5 seconds' time -} -setTimeout(myFunction, 5000) - -// 你甚至可以直接把一个函数写到另一个函数的参数中 - -setTimeout(function myFunction(){ - // 5秒之后会执行这里的代码 -}, 5000) - -// JavaScript 仅有函数作用于,而其他的语句则没有作用域 -if (true){ - var i = 5 -} -i // = 5 - 并非我们在其他语言中所得到的undefined - -// 这就导致了人们经常用一种叫做“即使执行匿名函数”的模式 -// 这样可以避免一些临时变量扩散到外边去 -function(){ - var temporary = 5 - // 我们可以访问一个全局对象来访问全局作用域 - // 在浏览器中是 'window' 这个对象。 - // 在Node.js中这个对象的名字可能会不同。 - window.permanent = 10 - // 或者,我们也可以把var去掉就行了 - permanent2 = 15 -}() -temporary // 抛出引用异常 -permanent // = 10 -permanent2 // = 15 - -// javascript最强大的功能之一就是闭包 -// 如果一个函数在另一个函数中定义,那么这个函数就拥有外部函数的所有访问权 -function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!" - function inner(){ - alert(prompt) - } - setTimeout(inner, 5000) - // setTimeout 是异步的,所以这个函数会马上终止不会等待。 - // 然而,在5秒结束后,inner函数仍然会弹出prompt信息。 -} -sayHelloInFiveSeconds("Adam") // 会在5秒后弹出 "Hello, Adam!" - -/////////////////////////////////// -// 5. 对象、构造函数与原型 - -// 对象包含方法 -var myObj = { - myFunc: function(){ - return "Hello world!" - } -} -myObj.myFunc() // = "Hello world!" - -// 当对象中的函数被调用时,这个函数就可以通过this关键字访问这个对象 -myObj = { - myString: "Hello world!", - myFunc: function(){ - return this.myString - } -} -myObj.myFunc() // = "Hello world!" - -// 但这个函数访问的其实是其运行时环境,而非定义时环境 -// 所以如果函数所在的环境不在当前对象的环境中运行时,就运行不成功了 -var myFunc = myObj.myFunc -myFunc() // = undefined - -// 相应的,一个函数也可以被指定为一个对象的方法,并且用过this可以访问 -// 这个对象的成员,即使在定义时并没有绑定任何值 -var myOtherFunc = function(){ - return this.myString.toUpperCase() -} -myObj.myOtherFunc = myOtherFunc -myObj.myOtherFunc() // = "HELLO WORLD!" - -// 当你通过new关键字调用一个函数时,就会生成一个对象 -// 而对象的成员需要通过this来定义。 -// 这样的函数就叫做构造函数 - -var MyConstructor = function(){ - this.myNumber = 5 -} -myNewObj = new MyConstructor() // = {myNumber: 5} -myNewObj.myNumber // = 5 - -// 每一个js对象都有一个原型,当你要访问一个没有定义过的成员时, -// 解释器就回去找这个对象的原型 - -// 有一些JS实现会让你通过一个对象的__proto__方法访问这个原型。 -// 这虽然对理解这个对象很有用,但是这并不是标准的一部分 -// 我们之后会通过标准方式来访问原型。 -var myObj = { - myString: "Hello world!", -} -var myPrototype = { - meaningOfLife: 42, - myFunc: function(){ - return this.myString.toLowerCase() - } -} -myObj.__proto__ = myPrototype -myObj.meaningOfLife // = 42 - -// This works for functions, too. -myObj.myFunc() // = "hello world!" - -// 当然,如果你要访问的成员在原型当中也没有定义的话,解释器就会去找原型的原型。 -myPrototype.__proto__ = { - myBoolean: true -} -myObj.myBoolean // = true - -// 这其中并没有对象的拷贝。每个对象的原型实际上是持有原型对象的引用 -// 这说明当我们改变对象的原型时,会影响到其他以这个原型为原型的对象 -myPrototype.meaningOfLife = 43 -myObj.meaningOfLife // = 43 - -// 我们知道 __proto__ 并非标准规定,实际上也没有办法更改已经指定好的原型。 -// 但是,我们有两种方式可以为新的对象指定原型。 - -// 第一种方式是 Object.create,这个方法是在最近才被添加到Js中的 -// 也因此并不是所有的JS实现都有这个放啊 -var myObj = Object.create(myPrototype) -myObj.meaningOfLife // = 43 - -// 第二种方式可以在任意版本中使用,不过需要通过构造函数。 -// 构造函数有一个属性prototype。但是这 *不是* 构造函数本身的函数 -// 而是通过构造函数和new关键字生成新对象时自动生成的。 -myConstructor.prototype = { - getMyNumber: function(){ - return this.myNumber - } -} -var myNewObj2 = new myConstructor() -myNewObj2.getMyNumber() // = 5 - -// 字符串和数字等内置类型也有通过构造函数来创建的包装类型 -var myNumber = 12 -var myNumberObj = new Number(12) -myNumber == myNumberObj // = true - -// 但是它们并非严格等价 -typeof(myNumber) // = 'number' -typeof(myNumberObj) // = 'object' -myNumber === myNumberObj // = false -if (0){ - // 这段代码不会执行,因为0代表假 -} -if (Number(0)){ - // 这段代码会执行,因为Number(0)代表真 -} - -// 但是,包装类型和内置类型共享一个原型 -// 这样你就可以给内置类型也增加一些功能 -String.prototype.firstCharacter = function(){ - return this.charAt(0) -} -"abc".firstCharacter() // = "a" - -// 这个技巧可以用来用老版本的javascript子集来是实现新版本js的功能 -// 这样就可以在老的浏览器中使用新功能了。 - -// 比如,我们知道Object.create并没有在所有的版本中都实现 -// 但是我们仍然可以通过这个技巧来使用 -if (Object.create === undefined){ // 如果存在则不覆盖 - Object.create = function(proto){ - // 用正确的原型来创建一个临时构造函数 - var Constructor = function(){} - Constructor.prototype = proto - // 之后用它来创建一个新的对象 - return new Constructor() - } -} -``` - -## 更多阅读 - -[Mozilla 开发者 -网络](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 提供了很好的 -Javascript文档,并且由于是wiki,所以你也可以自行编辑来分享你的知识。 -wiki, so as you learn more you can help others out by sharing your own -knowledge. - -MDN的 [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -覆盖了这里提到的绝大多数话题,大多数只是Javascript这个语言本身。 -如果你想了解Javascript是如何在网页中被应用的,那么可以查看 -[Document Object -Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) - -[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) 是一个深入 -讲解所有Javascript反直觉部分的一本书 - -除了这篇文章的直接贡献者之外,这篇文章也参考了这个网站上 -Louie Dinh 的 Python 教程,以及 Mozilla开发者网络上的[JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -- cgit v1.2.3 From 226533c33179a91763e517f8b78209e471a79414 Mon Sep 17 00:00:00 2001 From: Chenbo Li Date: Sat, 3 Aug 2013 00:34:12 +0800 Subject: rename js --- zh-cn/javascript-cn.html.markdown | 418 ++++++++++++++++++++++++++++++++++++++ zh-cn/javascript.html.markdown | 418 -------------------------------------- 2 files changed, 418 insertions(+), 418 deletions(-) create mode 100755 zh-cn/javascript-cn.html.markdown delete mode 100755 zh-cn/javascript.html.markdown diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown new file mode 100755 index 00000000..3b5cfa94 --- /dev/null +++ b/zh-cn/javascript-cn.html.markdown @@ -0,0 +1,418 @@ +--- +language: javascript +category: language +name: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] +translators: + - ["Chenbo Li", "http://binarythink.net"] +lang: zh-cn +--- + +Javascript于1995年由网景公司的Brendan Eich发明。 +最初发明的目的是作为一个简单的网站脚本语言,来作为 +复杂网站应用java的补充。但由于javascript和网站结合度很高 +所以javascript逐渐变得比java在前端更为流行了。 + +JavaScript 不仅仅只可以用于浏览器, 也可用于 Node.js 等后台环境。 + +很欢迎来自您的反馈,您可以通过下列方式联系到我: +[@adambrenecki](https://twitter.com/adambrenecki), 或者 +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// 注释方式和C很像,这是单行注释 +/* 这是多行 + 注释 */ + +// 语句可以以分号结束 +doStuff(); + +// ... 但是分号也可以省略,每当遇到一个新行时,分号会自动插入 +doStuff() + +// 我们在这里会去掉分号,但是否添加最后的分号取决于你个人的习惯 +// 及你所在团队的编程风格 + +/////////////////////////////////// +// 1. 数字、字符串与操作符 + +// Javascript 只有一种数字类型 (即 64位 IEEE 754 双精度浮点). +3 // = 3 +1.5 // = 1.5 + +// 所有基本的算数运算 +1 + 1 // = 2 +8 - 1 // = 7 +10 * 2 // = 20 +35 / 5 // = 7 + +// 包括无法整除的除法 +5 / 2 // = 2.5 + +// 位运算也和其他语言一样。当你对浮点数进行位运算时, +// 浮点数会转换为至多 32 位的无符号整数 +1 << 2 // = 4 + +// 括号可以决定优先级 +(1 + 3) * 2 // = 8 + +// 有三种非数字的数字类型 +Infinity // 1/0 的结果 +-Infinity // -1/0 的结果 +NaN // 0/0 的结果 + +// 也有布尔值 +true +false + +// 可以通过单引号或双引号来构造字符串 +'abc' +"Hello, world" + +// 用!来取非 +!true // = false +!false // = true + +// 相等 == +1 == 1 // = true +2 == 1 // = false + +// 不等 != +1 != 1 // = false +2 != 1 // = true + +// 更多的比较操作符 +1 < 10 // = true +1 > 10 // = false +2 <= 2 // = true +2 >= 2 // = true + +// 字符串用+连接 +"Hello " + "world!" // = "Hello world!" + +// 字符串也可以用 < 、> 来比较 +"a" < "b" // = true + +// 比较时会进行类型转换... +"5" == 5 // = true + +// ...除非你是用 === +"5" === 5 // = false + +// 你可以用charAt来得到字符串中的字符 +"This is a string".charAt(0) + +// 还有两个特殊的值:null和undefined +null // 用来表示刻意设置成的空值 +undefined // 用来表示还没有设置的值 + +// null, undefined, NaN, 0 和 "" 都是假的(false),其他的都视作逻辑真 +// 注意 0 是逻辑假而 "0"是逻辑真, 尽管 0 == "0". + +/////////////////////////////////// +// 2. 变量、数组和对象 + +// 变量需要用 var 这个关键字声明. Javascript是动态类型语言 +// 所以你在声明时无需指定类型。 赋值需要用 = +var someVar = 5 + +// 如果你在声明时没有加var关键字,你也不会得到错误 +someOtherVar = 10 + +// ...但是此时这个变量就会拥有全局的作用域,而非当前作用域 + +// 没有被赋值的变量都会返回undefined这个值 +var someThirdVar // = undefined + +// 对变量进行数学运算有一些简写法 +someVar += 5 // 等价于 someVar = someVar + 5; someVar 现在是 10 +someVar *= 10 // 现在 someVar 是 100 + +// 自增和自减也有简写 +someVar++ // someVar 是 101 +someVar-- // 回到 100 + +// 数组是任意类型组成的有序列表 +var myArray = ["Hello", 45, true] + +// 数组的元素可以用方括号下标来访问 +// 数组的索引从0开始 +myArray[1] // = 45 + +// javascript中的对象相当于其他语言中的字典或映射:是键-值的集合 +{key1: "Hello", key2: "World"} + +// 键是字符串,但是引号也并非是必须的,如果键本身是合法的js标识符 +// 而值则可以是任意类型的值 +var myObj = {myKey: "myValue", "my other key": 4} + +// 对象的访问可以通过下标 +myObj["my other key"] // = 4 + +// ... 或者也可以用 . ,如果属性是合法的标识符 +myObj.myKey // = "myValue" + +// 对象是可变的,键和值也可以被更改或增加 +myObj.myThirdKey = true + +// 如果你想要访问一个还没有被定义的属性,那么会返回undefined +myObj.myFourthKey // = undefined + +/////////////////////////////////// +// 3. 逻辑与控制结构 + +// if语句和其他语言中一样 +var count = 1 +if (count == 3){ + // count 是 3 时执行 +} else if (count == 4) { + // count 是 4 时执行 +} else { + // 其他情况下执行 +} + +// while循环 +while (true) { + // 无限循环 +} + +// Do-while 和 While 循环很像 ,但前者会至少执行一次 +var input +do { + input = getInput() +} while (!isValid(input)) + +// for循环和C、Java中的一样 +// 初始化; 继续执行的条件; 遍历后执行. +for (var i = 0; i < 5; i++){ + // 遍历5次 +} + +// && 是逻辑与, || 是逻辑或 +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear" +} +if (colour == "red" || colour == "blue"){ + // colour是red或者blue时执行 +} + +// && 和 || 是“短路”语句,在初始化值时会变得有用 +var name = otherName || "default" + +/////////////////////////////////// +// 4. 函数、作用域、闭包 + +// JavaScript 函数由function关键字定义 +function myFunction(thing){ + return thing.toUpperCase() +} +myFunction("foo") // = "FOO" + +// 函数也可以是匿名的: +function(thing){ + return thing.toLowerCase() +} +// (我们无法调用此函数,因为我们不知道这个函数的名字) + +// javascript中的函数也是对象,所以函数也能够赋给一个变量,并且被传递 +// 比如一个事件处理函数: +function myFunction(){ + // this code will be called in 5 seconds' time +} +setTimeout(myFunction, 5000) + +// 你甚至可以直接把一个函数写到另一个函数的参数中 + +setTimeout(function myFunction(){ + // 5秒之后会执行这里的代码 +}, 5000) + +// JavaScript 仅有函数作用于,而其他的语句则没有作用域 +if (true){ + var i = 5 +} +i // = 5 - 并非我们在其他语言中所得到的undefined + +// 这就导致了人们经常用一种叫做“即使执行匿名函数”的模式 +// 这样可以避免一些临时变量扩散到外边去 +function(){ + var temporary = 5 + // 我们可以访问一个全局对象来访问全局作用域 + // 在浏览器中是 'window' 这个对象。 + // 在Node.js中这个对象的名字可能会不同。 + window.permanent = 10 + // 或者,我们也可以把var去掉就行了 + permanent2 = 15 +}() +temporary // 抛出引用异常 +permanent // = 10 +permanent2 // = 15 + +// javascript最强大的功能之一就是闭包 +// 如果一个函数在另一个函数中定义,那么这个函数就拥有外部函数的所有访问权 +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!" + function inner(){ + alert(prompt) + } + setTimeout(inner, 5000) + // setTimeout 是异步的,所以这个函数会马上终止不会等待。 + // 然而,在5秒结束后,inner函数仍然会弹出prompt信息。 +} +sayHelloInFiveSeconds("Adam") // 会在5秒后弹出 "Hello, Adam!" + +/////////////////////////////////// +// 5. 对象、构造函数与原型 + +// 对象包含方法 +var myObj = { + myFunc: function(){ + return "Hello world!" + } +} +myObj.myFunc() // = "Hello world!" + +// 当对象中的函数被调用时,这个函数就可以通过this关键字访问这个对象 +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString + } +} +myObj.myFunc() // = "Hello world!" + +// 但这个函数访问的其实是其运行时环境,而非定义时环境 +// 所以如果函数所在的环境不在当前对象的环境中运行时,就运行不成功了 +var myFunc = myObj.myFunc +myFunc() // = undefined + +// 相应的,一个函数也可以被指定为一个对象的方法,并且用过this可以访问 +// 这个对象的成员,即使在定义时并没有绑定任何值 +var myOtherFunc = function(){ + return this.myString.toUpperCase() +} +myObj.myOtherFunc = myOtherFunc +myObj.myOtherFunc() // = "HELLO WORLD!" + +// 当你通过new关键字调用一个函数时,就会生成一个对象 +// 而对象的成员需要通过this来定义。 +// 这样的函数就叫做构造函数 + +var MyConstructor = function(){ + this.myNumber = 5 +} +myNewObj = new MyConstructor() // = {myNumber: 5} +myNewObj.myNumber // = 5 + +// 每一个js对象都有一个原型,当你要访问一个没有定义过的成员时, +// 解释器就回去找这个对象的原型 + +// 有一些JS实现会让你通过一个对象的__proto__方法访问这个原型。 +// 这虽然对理解这个对象很有用,但是这并不是标准的一部分 +// 我们之后会通过标准方式来访问原型。 +var myObj = { + myString: "Hello world!", +} +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +} +myObj.__proto__ = myPrototype +myObj.meaningOfLife // = 42 + +// This works for functions, too. +myObj.myFunc() // = "hello world!" + +// 当然,如果你要访问的成员在原型当中也没有定义的话,解释器就会去找原型的原型。 +myPrototype.__proto__ = { + myBoolean: true +} +myObj.myBoolean // = true + +// 这其中并没有对象的拷贝。每个对象的原型实际上是持有原型对象的引用 +// 这说明当我们改变对象的原型时,会影响到其他以这个原型为原型的对象 +myPrototype.meaningOfLife = 43 +myObj.meaningOfLife // = 43 + +// 我们知道 __proto__ 并非标准规定,实际上也没有办法更改已经指定好的原型。 +// 但是,我们有两种方式可以为新的对象指定原型。 + +// 第一种方式是 Object.create,这个方法是在最近才被添加到Js中的 +// 也因此并不是所有的JS实现都有这个放啊 +var myObj = Object.create(myPrototype) +myObj.meaningOfLife // = 43 + +// 第二种方式可以在任意版本中使用,不过需要通过构造函数。 +// 构造函数有一个属性prototype。但是这 *不是* 构造函数本身的函数 +// 而是通过构造函数和new关键字生成新对象时自动生成的。 +myConstructor.prototype = { + getMyNumber: function(){ + return this.myNumber + } +} +var myNewObj2 = new myConstructor() +myNewObj2.getMyNumber() // = 5 + +// 字符串和数字等内置类型也有通过构造函数来创建的包装类型 +var myNumber = 12 +var myNumberObj = new Number(12) +myNumber == myNumberObj // = true + +// 但是它们并非严格等价 +typeof(myNumber) // = 'number' +typeof(myNumberObj) // = 'object' +myNumber === myNumberObj // = false +if (0){ + // 这段代码不会执行,因为0代表假 +} +if (Number(0)){ + // 这段代码会执行,因为Number(0)代表真 +} + +// 但是,包装类型和内置类型共享一个原型 +// 这样你就可以给内置类型也增加一些功能 +String.prototype.firstCharacter = function(){ + return this.charAt(0) +} +"abc".firstCharacter() // = "a" + +// 这个技巧可以用来用老版本的javascript子集来是实现新版本js的功能 +// 这样就可以在老的浏览器中使用新功能了。 + +// 比如,我们知道Object.create并没有在所有的版本中都实现 +// 但是我们仍然可以通过这个技巧来使用 +if (Object.create === undefined){ // 如果存在则不覆盖 + Object.create = function(proto){ + // 用正确的原型来创建一个临时构造函数 + var Constructor = function(){} + Constructor.prototype = proto + // 之后用它来创建一个新的对象 + return new Constructor() + } +} +``` + +## 更多阅读 + +[Mozilla 开发者 +网络](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 提供了很好的 +Javascript文档,并且由于是wiki,所以你也可以自行编辑来分享你的知识。 +wiki, so as you learn more you can help others out by sharing your own +knowledge. + +MDN的 [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +覆盖了这里提到的绝大多数话题,大多数只是Javascript这个语言本身。 +如果你想了解Javascript是如何在网页中被应用的,那么可以查看 +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) 是一个深入 +讲解所有Javascript反直觉部分的一本书 + +除了这篇文章的直接贡献者之外,这篇文章也参考了这个网站上 +Louie Dinh 的 Python 教程,以及 Mozilla开发者网络上的[JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) diff --git a/zh-cn/javascript.html.markdown b/zh-cn/javascript.html.markdown deleted file mode 100755 index 3b5cfa94..00000000 --- a/zh-cn/javascript.html.markdown +++ /dev/null @@ -1,418 +0,0 @@ ---- -language: javascript -category: language -name: javascript -contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] -translators: - - ["Chenbo Li", "http://binarythink.net"] -lang: zh-cn ---- - -Javascript于1995年由网景公司的Brendan Eich发明。 -最初发明的目的是作为一个简单的网站脚本语言,来作为 -复杂网站应用java的补充。但由于javascript和网站结合度很高 -所以javascript逐渐变得比java在前端更为流行了。 - -JavaScript 不仅仅只可以用于浏览器, 也可用于 Node.js 等后台环境。 - -很欢迎来自您的反馈,您可以通过下列方式联系到我: -[@adambrenecki](https://twitter.com/adambrenecki), 或者 -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). - -```js -// 注释方式和C很像,这是单行注释 -/* 这是多行 - 注释 */ - -// 语句可以以分号结束 -doStuff(); - -// ... 但是分号也可以省略,每当遇到一个新行时,分号会自动插入 -doStuff() - -// 我们在这里会去掉分号,但是否添加最后的分号取决于你个人的习惯 -// 及你所在团队的编程风格 - -/////////////////////////////////// -// 1. 数字、字符串与操作符 - -// Javascript 只有一种数字类型 (即 64位 IEEE 754 双精度浮点). -3 // = 3 -1.5 // = 1.5 - -// 所有基本的算数运算 -1 + 1 // = 2 -8 - 1 // = 7 -10 * 2 // = 20 -35 / 5 // = 7 - -// 包括无法整除的除法 -5 / 2 // = 2.5 - -// 位运算也和其他语言一样。当你对浮点数进行位运算时, -// 浮点数会转换为至多 32 位的无符号整数 -1 << 2 // = 4 - -// 括号可以决定优先级 -(1 + 3) * 2 // = 8 - -// 有三种非数字的数字类型 -Infinity // 1/0 的结果 --Infinity // -1/0 的结果 -NaN // 0/0 的结果 - -// 也有布尔值 -true -false - -// 可以通过单引号或双引号来构造字符串 -'abc' -"Hello, world" - -// 用!来取非 -!true // = false -!false // = true - -// 相等 == -1 == 1 // = true -2 == 1 // = false - -// 不等 != -1 != 1 // = false -2 != 1 // = true - -// 更多的比较操作符 -1 < 10 // = true -1 > 10 // = false -2 <= 2 // = true -2 >= 2 // = true - -// 字符串用+连接 -"Hello " + "world!" // = "Hello world!" - -// 字符串也可以用 < 、> 来比较 -"a" < "b" // = true - -// 比较时会进行类型转换... -"5" == 5 // = true - -// ...除非你是用 === -"5" === 5 // = false - -// 你可以用charAt来得到字符串中的字符 -"This is a string".charAt(0) - -// 还有两个特殊的值:null和undefined -null // 用来表示刻意设置成的空值 -undefined // 用来表示还没有设置的值 - -// null, undefined, NaN, 0 和 "" 都是假的(false),其他的都视作逻辑真 -// 注意 0 是逻辑假而 "0"是逻辑真, 尽管 0 == "0". - -/////////////////////////////////// -// 2. 变量、数组和对象 - -// 变量需要用 var 这个关键字声明. Javascript是动态类型语言 -// 所以你在声明时无需指定类型。 赋值需要用 = -var someVar = 5 - -// 如果你在声明时没有加var关键字,你也不会得到错误 -someOtherVar = 10 - -// ...但是此时这个变量就会拥有全局的作用域,而非当前作用域 - -// 没有被赋值的变量都会返回undefined这个值 -var someThirdVar // = undefined - -// 对变量进行数学运算有一些简写法 -someVar += 5 // 等价于 someVar = someVar + 5; someVar 现在是 10 -someVar *= 10 // 现在 someVar 是 100 - -// 自增和自减也有简写 -someVar++ // someVar 是 101 -someVar-- // 回到 100 - -// 数组是任意类型组成的有序列表 -var myArray = ["Hello", 45, true] - -// 数组的元素可以用方括号下标来访问 -// 数组的索引从0开始 -myArray[1] // = 45 - -// javascript中的对象相当于其他语言中的字典或映射:是键-值的集合 -{key1: "Hello", key2: "World"} - -// 键是字符串,但是引号也并非是必须的,如果键本身是合法的js标识符 -// 而值则可以是任意类型的值 -var myObj = {myKey: "myValue", "my other key": 4} - -// 对象的访问可以通过下标 -myObj["my other key"] // = 4 - -// ... 或者也可以用 . ,如果属性是合法的标识符 -myObj.myKey // = "myValue" - -// 对象是可变的,键和值也可以被更改或增加 -myObj.myThirdKey = true - -// 如果你想要访问一个还没有被定义的属性,那么会返回undefined -myObj.myFourthKey // = undefined - -/////////////////////////////////// -// 3. 逻辑与控制结构 - -// if语句和其他语言中一样 -var count = 1 -if (count == 3){ - // count 是 3 时执行 -} else if (count == 4) { - // count 是 4 时执行 -} else { - // 其他情况下执行 -} - -// while循环 -while (true) { - // 无限循环 -} - -// Do-while 和 While 循环很像 ,但前者会至少执行一次 -var input -do { - input = getInput() -} while (!isValid(input)) - -// for循环和C、Java中的一样 -// 初始化; 继续执行的条件; 遍历后执行. -for (var i = 0; i < 5; i++){ - // 遍历5次 -} - -// && 是逻辑与, || 是逻辑或 -if (house.size == "big" && house.colour == "blue"){ - house.contains = "bear" -} -if (colour == "red" || colour == "blue"){ - // colour是red或者blue时执行 -} - -// && 和 || 是“短路”语句,在初始化值时会变得有用 -var name = otherName || "default" - -/////////////////////////////////// -// 4. 函数、作用域、闭包 - -// JavaScript 函数由function关键字定义 -function myFunction(thing){ - return thing.toUpperCase() -} -myFunction("foo") // = "FOO" - -// 函数也可以是匿名的: -function(thing){ - return thing.toLowerCase() -} -// (我们无法调用此函数,因为我们不知道这个函数的名字) - -// javascript中的函数也是对象,所以函数也能够赋给一个变量,并且被传递 -// 比如一个事件处理函数: -function myFunction(){ - // this code will be called in 5 seconds' time -} -setTimeout(myFunction, 5000) - -// 你甚至可以直接把一个函数写到另一个函数的参数中 - -setTimeout(function myFunction(){ - // 5秒之后会执行这里的代码 -}, 5000) - -// JavaScript 仅有函数作用于,而其他的语句则没有作用域 -if (true){ - var i = 5 -} -i // = 5 - 并非我们在其他语言中所得到的undefined - -// 这就导致了人们经常用一种叫做“即使执行匿名函数”的模式 -// 这样可以避免一些临时变量扩散到外边去 -function(){ - var temporary = 5 - // 我们可以访问一个全局对象来访问全局作用域 - // 在浏览器中是 'window' 这个对象。 - // 在Node.js中这个对象的名字可能会不同。 - window.permanent = 10 - // 或者,我们也可以把var去掉就行了 - permanent2 = 15 -}() -temporary // 抛出引用异常 -permanent // = 10 -permanent2 // = 15 - -// javascript最强大的功能之一就是闭包 -// 如果一个函数在另一个函数中定义,那么这个函数就拥有外部函数的所有访问权 -function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!" - function inner(){ - alert(prompt) - } - setTimeout(inner, 5000) - // setTimeout 是异步的,所以这个函数会马上终止不会等待。 - // 然而,在5秒结束后,inner函数仍然会弹出prompt信息。 -} -sayHelloInFiveSeconds("Adam") // 会在5秒后弹出 "Hello, Adam!" - -/////////////////////////////////// -// 5. 对象、构造函数与原型 - -// 对象包含方法 -var myObj = { - myFunc: function(){ - return "Hello world!" - } -} -myObj.myFunc() // = "Hello world!" - -// 当对象中的函数被调用时,这个函数就可以通过this关键字访问这个对象 -myObj = { - myString: "Hello world!", - myFunc: function(){ - return this.myString - } -} -myObj.myFunc() // = "Hello world!" - -// 但这个函数访问的其实是其运行时环境,而非定义时环境 -// 所以如果函数所在的环境不在当前对象的环境中运行时,就运行不成功了 -var myFunc = myObj.myFunc -myFunc() // = undefined - -// 相应的,一个函数也可以被指定为一个对象的方法,并且用过this可以访问 -// 这个对象的成员,即使在定义时并没有绑定任何值 -var myOtherFunc = function(){ - return this.myString.toUpperCase() -} -myObj.myOtherFunc = myOtherFunc -myObj.myOtherFunc() // = "HELLO WORLD!" - -// 当你通过new关键字调用一个函数时,就会生成一个对象 -// 而对象的成员需要通过this来定义。 -// 这样的函数就叫做构造函数 - -var MyConstructor = function(){ - this.myNumber = 5 -} -myNewObj = new MyConstructor() // = {myNumber: 5} -myNewObj.myNumber // = 5 - -// 每一个js对象都有一个原型,当你要访问一个没有定义过的成员时, -// 解释器就回去找这个对象的原型 - -// 有一些JS实现会让你通过一个对象的__proto__方法访问这个原型。 -// 这虽然对理解这个对象很有用,但是这并不是标准的一部分 -// 我们之后会通过标准方式来访问原型。 -var myObj = { - myString: "Hello world!", -} -var myPrototype = { - meaningOfLife: 42, - myFunc: function(){ - return this.myString.toLowerCase() - } -} -myObj.__proto__ = myPrototype -myObj.meaningOfLife // = 42 - -// This works for functions, too. -myObj.myFunc() // = "hello world!" - -// 当然,如果你要访问的成员在原型当中也没有定义的话,解释器就会去找原型的原型。 -myPrototype.__proto__ = { - myBoolean: true -} -myObj.myBoolean // = true - -// 这其中并没有对象的拷贝。每个对象的原型实际上是持有原型对象的引用 -// 这说明当我们改变对象的原型时,会影响到其他以这个原型为原型的对象 -myPrototype.meaningOfLife = 43 -myObj.meaningOfLife // = 43 - -// 我们知道 __proto__ 并非标准规定,实际上也没有办法更改已经指定好的原型。 -// 但是,我们有两种方式可以为新的对象指定原型。 - -// 第一种方式是 Object.create,这个方法是在最近才被添加到Js中的 -// 也因此并不是所有的JS实现都有这个放啊 -var myObj = Object.create(myPrototype) -myObj.meaningOfLife // = 43 - -// 第二种方式可以在任意版本中使用,不过需要通过构造函数。 -// 构造函数有一个属性prototype。但是这 *不是* 构造函数本身的函数 -// 而是通过构造函数和new关键字生成新对象时自动生成的。 -myConstructor.prototype = { - getMyNumber: function(){ - return this.myNumber - } -} -var myNewObj2 = new myConstructor() -myNewObj2.getMyNumber() // = 5 - -// 字符串和数字等内置类型也有通过构造函数来创建的包装类型 -var myNumber = 12 -var myNumberObj = new Number(12) -myNumber == myNumberObj // = true - -// 但是它们并非严格等价 -typeof(myNumber) // = 'number' -typeof(myNumberObj) // = 'object' -myNumber === myNumberObj // = false -if (0){ - // 这段代码不会执行,因为0代表假 -} -if (Number(0)){ - // 这段代码会执行,因为Number(0)代表真 -} - -// 但是,包装类型和内置类型共享一个原型 -// 这样你就可以给内置类型也增加一些功能 -String.prototype.firstCharacter = function(){ - return this.charAt(0) -} -"abc".firstCharacter() // = "a" - -// 这个技巧可以用来用老版本的javascript子集来是实现新版本js的功能 -// 这样就可以在老的浏览器中使用新功能了。 - -// 比如,我们知道Object.create并没有在所有的版本中都实现 -// 但是我们仍然可以通过这个技巧来使用 -if (Object.create === undefined){ // 如果存在则不覆盖 - Object.create = function(proto){ - // 用正确的原型来创建一个临时构造函数 - var Constructor = function(){} - Constructor.prototype = proto - // 之后用它来创建一个新的对象 - return new Constructor() - } -} -``` - -## 更多阅读 - -[Mozilla 开发者 -网络](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 提供了很好的 -Javascript文档,并且由于是wiki,所以你也可以自行编辑来分享你的知识。 -wiki, so as you learn more you can help others out by sharing your own -knowledge. - -MDN的 [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -覆盖了这里提到的绝大多数话题,大多数只是Javascript这个语言本身。 -如果你想了解Javascript是如何在网页中被应用的,那么可以查看 -[Document Object -Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) - -[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) 是一个深入 -讲解所有Javascript反直觉部分的一本书 - -除了这篇文章的直接贡献者之外,这篇文章也参考了这个网站上 -Louie Dinh 的 Python 教程,以及 Mozilla开发者网络上的[JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -- cgit v1.2.3 From 906c7164d0975d14da0391ff47b5c384f0dd1c47 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 2 Aug 2013 09:39:30 -0700 Subject: Updated scala for line lengths --- scala.html.markdown | 86 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 53 insertions(+), 33 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 8e00f135..687914ef 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -8,9 +8,7 @@ filename: learn.scala Scala - the scalable language -```c - - +```scala /* Set yourself up: @@ -21,7 +19,8 @@ Scala - the scalable language scala> - This is the so called REPL. You can run commands in the REPL. Let's do just that: + This is the so called REPL. You can run commands in the REPL. Let's do just + that: */ println(10) // prints the integer 10 @@ -37,7 +36,8 @@ println("Hello world!") print("Hello world") // Declaring values is done using either var or val -// val declarations are immutable, whereas var's are mutable. Immutablility is a good thing. +// val declarations are immutable, whereas var's are mutable. Immutablility is +// a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val var x = 10 @@ -74,7 +74,8 @@ true == false // false scala> 1 + 7 res29: Int = 8 - This means the result of evaluating 1 + 7 is an object of type Int with a value of 8 + This means the result of evaluating 1 + 7 is an object of type Int with a + value of 8 1+7 will give you the same result */ @@ -94,14 +95,16 @@ val sq = (x:Int) => x * x sq: Int => Int = - Which means that this time we gave an explicit name to the value - sq is a function that take an Int and returns Int. + Which means that this time we gave an explicit name to the value - sq is a + function that take an Int and returns Int. sq can be executed as follows: */ -sq(10) // Gives you this: res33: Int = 100. The result is the Int with a value 100 +sq(10) // Gives you this: res33: Int = 100. -// Scala allows methods and functions to return, or take as parameters, other functions or methods. +// 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 @@ -109,10 +112,12 @@ 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: List(1, 2, 3) map (x => x + 10) -// And the underscore symbol, can be used if there is just one argument to the anonymous function. It gets bound as the variable +// And the underscore symbol, can be used if there is just one argument to the +// anonymous function. It gets bound as the variable List(1, 2, 3) map (_ + 10) -TODO // If the anonymous block AND the function you are applying both take one argument, you can even omit the underscore +// If the anonymous block AND the function you are applying both take one +// argument, you can even omit the underscore List("Dom", "Bob", "Natalia") foreach println @@ -136,7 +141,8 @@ val s = Set(1, 3, 7) s(0) s(1) -/* Look up the documentation of map here - http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map +/* Look up the documentation of map here - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map * and make sure you can read it */ @@ -156,7 +162,8 @@ val divideInts = (x:Int, y:Int) => (x / y, x % y) divideInts(10,3) // The function divideInts gives you the result and the remainder -// To access the elements of a tuple, use _._n where n is the 1-based index of the element +// To access the elements of a tuple, use _._n where n is the 1-based index of +// the element val d = divideInts(10,3) d._1 @@ -175,7 +182,8 @@ sSquared.filter(_ < 10) sSquared.reduce (_+_) -// The filter function takes a predicate (a function from A -> Boolean) and selects all elements which satisfy the predicate +// The filter function takes a predicate (a function from A -> Boolean) and +// selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) List( Person(name = "Dom", age = 23), @@ -183,7 +191,8 @@ List( ).filter(_.age > 25) // List(Person("Bob", 30)) -// Scala a foreach method defined on certain collections that takes a type returning Unit (a void method) +// Scala a foreach method defined on certain collections that takes a type +// returning Unit (a void method) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println @@ -200,8 +209,8 @@ for { n <- nSquared2 if n < 10 } yield n for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared -/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas a for-comprehension - defines a relationship between two sets of data. Research this further */ +/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas + a for-comprehension defines a relationship between two sets of data. */ @@ -212,8 +221,8 @@ val r = 1 to 5 r.foreach( println ) r foreach println -// NB: Scala is quite lenien when it comes to dots and brackets - study the rules separately. This -// helps write DSLs and APIs that read like English +// NB: Scala is quite lenient when it comes to dots and brackets - study the +// rules separately. This helps write DSLs and APIs that read like English (5 to 1 by -1) foreach ( println ) @@ -223,20 +232,25 @@ while (i < 10) { println("i " + i); i+=1 } while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why? -i // Show the value of i. Note that while is a loop in the classical sense - it executes - // sequentially while changing the loop variable. while is very fast, faster that Java - // loops, but using the combinators and comprehensions above is easier to understand - // and parallelize +i // Show the value of i. Note that while is a loop in the classical sense - + // it executes sequentially while changing the loop variable. while is very + // fast, faster that Java // loops, but using the combinators and + // comprehensions above is easier to understand and parallelize // A do while loop -do { +do { println("x is still less then 10"); x += 1 } while (x < 10) -// Tail recursion is an idiomatic way of doing recurring things in Scala. Recursive functions need an -// explicit return type, the compiler can't infer it. Here it's Unit. -def showNumbersInRange(a:Int, b:Int):Unit = { print(a); if (a < b) showNumbersInRange(a+1, b) } +// Tail recursion is an idiomatic way of doing recurring things in Scala. +// Recursive functions need an explicit return type, the compiler can't infer it. +// Here it's Unit. +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} @@ -268,7 +282,8 @@ class Dog { } } -// Classes can contain nearly any other construct, including other classes, functions, methods, objects, case classes, traits etc. +// Classes can contain nearly any other construct, including other classes, +// functions, methods, objects, case classes, traits etc. @@ -285,7 +300,8 @@ Person("George", "1234") == Person("Kate", "1236") val me = Person("George", "1234") -me match { case Person(name, number) => "We matched someone : " + name + ", phone : " + number } +me match { case Person(name, number) => { + "We matched someone : " + name + ", phone : " + number }} me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } @@ -303,7 +319,7 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions -val email = "(.*)@(.*)".r // The suffix .r invokes method r on String, which makes it a Regex +val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex val email(user, domain) = "henry@zkpr.com" @@ -319,7 +335,9 @@ val email(user, domain) = "henry@zkpr.com" 'a' // A Scala Char 'Single quote strings don't exist' // Error "Strings have the usual Java methods defined on them".length -"They also have some extra Scala methods.".reverse // See scala.collection.immutable.StringOps +"They also have some extra Scala methods.".reverse + +// Seealso: scala.collection.immutable.StringOps println("ABCDEF".length) println("ABCDEF".substring(2, 6)) @@ -334,7 +352,8 @@ println(s"My second daughter is ${a(2-1)} years old") // Some characters need to be 'escaped', e.g. a double quote inside a string: val a = "They stood outside the \"Rose and Crown\"" -// Triple double-quotes allow for strings to span multiple rows and contain funny characters +// Triple double-quotes let strings span multiple rows and contain quotes + val html = """

Press belo', Joe

| @@ -359,7 +378,8 @@ import scala.collection.immutable{ List => ImmutableList } // Import all classes, except some. The following excludes Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} -// Your programs entry point is defined in an scala file using an object, with a single method, main: +// Your programs entry point is defined in an scala file using an object, with a +// single method, main: object Application { def main(args: Array[String]): Unit = { // stuff goes here. -- cgit v1.2.3 From 18a5e58b16e6e0b172c010fd3bba07e81701222a Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 2 Aug 2013 09:40:22 -0700 Subject: Fixed php and removed old VB file --- Visual Basic | 248 ------------------------------------------------------ php.html.markdown | 5 +- 2 files changed, 3 insertions(+), 250 deletions(-) delete mode 100644 Visual Basic diff --git a/Visual Basic b/Visual Basic deleted file mode 100644 index 73430633..00000000 --- a/Visual Basic +++ /dev/null @@ -1,248 +0,0 @@ ---- -language: Visual Basic Console Application -contributors: - - ["Brian Martin", "http://brianmartin.biz"] -filename: learnvisualbasic.vb - -Module Module1 - - Sub Main() - 'A Quick Overview of Visual Basic Console Applications before we dive in to the deep end. - 'Apostrophe starts comments. - 'To Navigate this tutorial within the Visual Basic Complier, I've put together a navigation system. - 'This navigation system is explained however as we go deeper into this tutorial, you'll understand what it all means. - Console.Title = ("Learn X in Y Minutes") - Console.WriteLine("NAVIGATION") 'Display - Console.WriteLine("") - Console.ForegroundColor = ConsoleColor.Green - Console.WriteLine("1. Hello World Output") - Console.WriteLine("2. Hello World Input") - Console.WriteLine("3. Calculating Whole Numbers") - Console.WriteLine("4. Calculating Decimal Numbers") - Console.WriteLine("5. Working Calculator") - Console.WriteLine("6. Using Do While Loops") - Console.WriteLine("7. Using For While Loops") - Console.WriteLine("8. Conditional Statements") - Console.WriteLine("9. Select A Drink") - Console.WriteLine("50. About") - Console.WriteLine("Please Choose A Number From The Above List") - Dim selection As String = Console.ReadLine - Select Case selection - Case "1" 'HelloWorld Output - Console.Clear() 'Clears the application and opens the private sub - HelloWorldOutput() 'Name Private Sub, Opens Private Sub - Case "2" 'Hello Input - Console.Clear() - HelloWorldInput() - Case "3" 'Calculating Whole Numbers - Console.Clear() - CalculatingWholeNumbers() - Case "4" 'Calculting Decimal Numbers - Console.Clear() - CalculatingDecimalNumbers() - Case "5" 'Working Calcculator - Console.Clear() - WorkingCalculator() - Case "6" 'Using Do While Loops - Console.Clear() - UsingDoWhileLoops() - Case "7" 'Using For While Loops - Console.Clear() - UsingForLoops() - Case "8" 'Conditional Statements - Console.Clear() - ConditionalStatement() - Case "9" 'If/Else Statement - Console.Clear() - IfElseStatement() 'Select a drink - Case "50" 'About msg box - Console.Clear() - Console.Title = ("Learn X in Y Minutes :: About") - MsgBox("Learn X in Y Minutes is a creation of Adam Bard (@adambard) This particular program tutorial is by Brian Martin (@BrianMartinn") - Console.Clear() - Main() - Console.ReadLine() - - End Select - End Sub - - 'One - I'm using numbers to help with the above navigation when I come back later to build it. - Private Sub HelloWorldOutput() 'We use private subs to seperate different sections of the program. - Console.Title = "Hello World Ouput | Learn X in Y Minutes" 'Title of Console Application - 'Use Console.Write("") or Console.WriteLine("") to print outputs. - 'Followed by Console.Read() alternatively Console.Readline() - 'Console.ReadLine() prints the output to the console. - Console.WriteLine("Hello World") - Console.ReadLine() - End Sub - 'Two - Private Sub HelloWorldInput() 'We use private subs to seperate different sections of the program. - Console.Title = "Hello World YourName | Learn X in Y Minutes" 'Title of Console Application - 'Variables - 'Data entered by a user needs to be stored. - 'Variables also start with a Dim and end with an As VariableType. - Dim username As String 'In this tutorial, we want to know what your name, and make the program respond to what is said. - 'We use string as string is a text based variable. - Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. - username = Console.ReadLine() 'Stores the users name. - Console.WriteLine("Hello " + username) 'Output is Hello 'Their name' - Console.ReadLine() 'Outsputs the above. - 'The above will ask you a question followed by printing your answer. - 'Other variables include Integer and we use Integer for whole numbers. - End Sub - 'Three - Private Sub CalculatingWholeNumbers() 'We use private subs to seperate different sections of the program. - Console.Title = "Calculating Whole Numbers | Learn X in Y Minutes" 'Title of Console Application - Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104 ect - Dim a As Integer = Console.ReadLine() - Console.Write("Second number: ") 'Enter second whole number. - Dim b As Integer = Console.ReadLine() - Dim c As Integer = a + b - Console.WriteLine(c) - Console.ReadLine() - 'The above is a simple calculator - End Sub - 'Four - Private Sub CalculatingDecimalNumbers() - Console.Title = "Calculating with Double | Learn X in Y Minutes" 'Title of Console Application - 'Of course we would like to be able to add up decimals. - 'Therefore we could change the above from Integer to Double. - Console.Write("First number: ") 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect - Dim a As Double = Console.ReadLine - Console.Write("Second number: ") 'Enter second whole number. - Dim b As Double = Console.ReadLine - Dim c As Double = a + b - Console.WriteLine(c) - Console.ReadLine() - 'Therefore the above program can add up 1.1 - 2.2 - End Sub - 'Five - Private Sub WorkingCalculator() - Console.Title = "The Working Calculator| Learn X in Y Minutes" 'Title of Console Application - 'However if you'd like the calculator to subtract, divide, multiple and add up. - 'Copy and paste the above again. - Console.Write("First number: ") 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect - Dim a As Double = Console.ReadLine - Console.Write("Second number: ") 'Enter second whole number. - Dim b As Integer = Console.ReadLine - Dim c As Integer = a + b - Dim d As Integer = a * b - Dim e As Integer = a - b - Dim f As Integer = a / b - 'By adding the below lines we are able to calculate the subtract, multply as well as divide the a and b values - Console.Write(a.ToString() + " + " + b.ToString()) - Console.WriteLine(" = " + c.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. - Console.Write(a.ToString() + " * " + b.ToString()) - Console.WriteLine(" = " + d.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. - Console.Write(a.ToString() + " - " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. - Console.Write(a.ToString() + " / " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. - Console.ReadLine() - - End Sub - 'Six - Private Sub UsingDoWhileLoops() - 'Just as the previous private sub - 'This Time We Ask If The User Wishes To Continue (Yes or No?) - 'We're using Do While Loop as we're unsure if the user wants to use the program more than once. - Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes" - Dim answer As String 'We use the variable "String" as the answer is text - Do 'We start the program with - Console.Write("First number: ") - Dim a As Double = Console.ReadLine - Console.Write("Second number: ") - Dim b As Integer = Console.ReadLine - Dim c As Integer = a + b - Dim d As Integer = a * b - Dim e As Integer = a - b - Dim f As Integer = a / b - - Console.Write(a.ToString() + " + " + b.ToString()) - Console.WriteLine(" = " + c.ToString.PadLeft(3)) - Console.Write(a.ToString() + " * " + b.ToString()) - Console.WriteLine(" = " + d.ToString.PadLeft(3)) - Console.Write(a.ToString() + " - " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) - Console.Write(a.ToString() + " / " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) - Console.ReadLine() - 'Ask the question, does the user wish to continue? Unfortunately it is case sensitive. - Console.Write("Would you like to continue? (yes / no)") - answer = Console.ReadLine 'The program grabs the variable and prints and starts again. - Loop While answer = "yes" 'The command for the variable to work would be in this case "yes" - - End Sub - 'Seven - Private Sub UsingForLoops() - 'Sometimes the program only needs to run once. - 'In this program we'll be counting down from 10. - - Console.Title = "Using For Loops | Learn X in Y Minutes" - For i As Integer = 10 To 0 Step -1 'Declare Vairable and what number it should count down in Step -1, Step -2, Step -3 ect. - Console.WriteLine(i.ToString) 'Print the value of the counter variable - Next i 'Calculate new value - Console.WriteLine("Start") 'Lets start the program baby!! - Console.ReadLine() 'POW!! - Perhaps I got a little excited then :) - End Sub - 'Eight - Private Sub ConditionalStatement() - Console.Title = "Conditional Statements | Learn X in Y Minutes" - Dim userName As String = Console.ReadLine - Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. - userName = Console.ReadLine() 'Stores the users name. - If userName = "Adam" Then 'Hey, if Adam uses this program, kudos where kudos is due, right? - Console.WriteLine("Hello Adam") - Console.WriteLine("Thanks for creating the useful tutorial site www.learnxinyminutes.com!") - Console.ReadLine() - Else - Console.WriteLine("Hello " + userName) 'prints the username of the user - Console.WriteLine("Hope all is well have you checked out www.learnxinyminutes.com") 'Prints a message to the user - Console.ReadLine() 'Ends and prints the above statement. - End If - End Sub - 'Nine - Private Sub IfElseStatement() - Console.Title = "If / Else Statement | Learn X in Y Minutes" - 'Sometimes its important to consider more than two alternatives. Sometimes there are a good few others. - 'When this is the case, more than one if statement would be required. - 'An if statement is great for vending machines. Where the user enters a code. - 'A1, A2, A3, ect to select an item. - 'All choices can be combined into a single if statement. - - Dim selection As String = Console.ReadLine 'Value for selection - Console.WriteLine("A1. for 7Up") - Console.WriteLine("A2. for Fanta") - Console.WriteLine("A3. for Dr. Pepper") - Console.WriteLine("A4. for Diet Coke") - Console.ReadLine() - If selection = "A1" Then - Console.WriteLine("7up") - Console.ReadLine() - ElseIf selection = "A2" Then - Console.WriteLine("fanta") - Console.ReadLine() - ElseIf selection = "A3" Then - Console.WriteLine("dr. pepper") - Console.ReadLine() - ElseIf selection = "A4" Then - Console.WriteLine("diet coke") - Console.ReadLine() - Else - Console.WriteLine("Please select a product") - Console.ReadLine() - End If - - End Sub - -End Module - - -``` -## References - -I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily. - -I created a more indepth Visual Basic tutorial for those who would like to learn more. - -The entire syntax is valid. Copy the and paste in to the Visual Basic complier and run (F5) the program. diff --git a/php.html.markdown b/php.html.markdown index 5f5a4b54..ce228870 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -9,7 +9,7 @@ filename: learnphp.php This document describes PHP 5+. ```php - tags +Hello World Again! +?> +Hello World Again! Date: Fri, 2 Aug 2013 09:43:54 -0700 Subject: corrected scala --- scala.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 687914ef..a5920aa8 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,8 +1,9 @@ --- language: Scala +filename: learnscala.scala contributors: - ["George Petrov", "http://github.com/petrovg"] - - ["Dominic Bou-Samra, "http://dbousamra.github.com"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] filename: learn.scala --- -- cgit v1.2.3 From 22f1469dd8092ff46a73e27b56363f7c922ac875 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 2 Aug 2013 09:47:13 -0700 Subject: Used c syntax highlighting for scala for now --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index a5920aa8..fef09404 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -9,7 +9,7 @@ filename: learn.scala Scala - the scalable language -```scala +```cpp /* Set yourself up: -- cgit v1.2.3 From a6fc64199c581cc1ab18f90f06d2036ee27737ce Mon Sep 17 00:00:00 2001 From: Chenbo Li Date: Sat, 3 Aug 2013 12:30:25 +0800 Subject: fix a typo --- git.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index 00f38d60..375a6c57 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -126,7 +126,7 @@ $ git help $ git help -a # Command specific help - user manual -# git help +$ git help $ git help add $ git help commit $ git help init -- cgit v1.2.3 From 981fe303f323c91bad1ac23bdd4c49575414c8ec Mon Sep 17 00:00:00 2001 From: Chenbo Li Date: Sat, 3 Aug 2013 14:53:27 +0800 Subject: fix a typo --- git.html.markdown | 2 +- zh-cn/git-cn.html.markdown | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/git.html.markdown b/git.html.markdown index 375a6c57..00f38d60 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -126,7 +126,7 @@ $ git help $ git help -a # Command specific help - user manual -$ git help +# git help $ git help add $ git help commit $ git help init diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown index 7aab8986..8c24f0b8 100755 --- a/zh-cn/git-cn.html.markdown +++ b/zh-cn/git-cn.html.markdown @@ -120,7 +120,7 @@ $ git help $ git help -a # 在文档当中查找特定的命令 -$ git help <命令> +# git help <命令> $ git help add $ git help commit $ git help init -- cgit v1.2.3 From cfff5122a3e6b85c34bb66e7efe8ba3b96562253 Mon Sep 17 00:00:00 2001 From: lpy Date: Sat, 3 Aug 2013 15:16:28 +0800 Subject: Add Haskell zh-cn translation --- zh-cn/haskell-cn.html.markdown | 407 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 407 insertions(+) create mode 100755 zh-cn/haskell-cn.html.markdown diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown new file mode 100755 index 00000000..cb0de467 --- /dev/null +++ b/zh-cn/haskell-cn.html.markdown @@ -0,0 +1,407 @@ +--- +language: haskell +filename: learn-haskell.hs +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["Peiyong Lin", ""] +lang: zh-cn +--- + +Haskell 被设计成一种实用的纯函数式编程语言。它因为 monads 及其类型系统而出名,但是我回归到它本身因为。Haskell 使得编程对于我而言是一种真正的快乐。 + +```haskell +-- 单行注释以两个破折号开头 +{- 多行注释像这样 + 被一个闭合的块包围 +-} + +---------------------------------------------------- +-- 1. 简单的数据类型和操作符 +---------------------------------------------------- + +-- 你有数字 +3 -- 3 +-- 数学计算就像你所期待的那样 +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- 默认除法不是整除 +35 / 4 -- 8.75 + +-- 整除 +35 `div` 4 -- 8 + +-- 布尔值也简单 +True +False + +-- 布尔操作 +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- 在上述的例子中,`not` 是一个接受一个值的函数。 +-- Haskell 不需要括号来调用函数。。。所有的参数 +-- 都只是在函数名之后列出来。因此,通常的函数调用模式是: +-- func arg1 arg2 arg3... +-- 查看关于函数的章节以获得如何写你自己的函数的相关信息。 + +-- 字符串和字符 +"This is a string." +'a' -- 字符 +'对于字符串你不能使用单引号。' -- 错误! + +-- 连结字符串 +"Hello " ++ "world!" -- "Hello world!" + +-- 一个字符串是一系列字符 +"This is a string" !! 0 -- 'T' + + +---------------------------------------------------- +-- 列表和元组 +---------------------------------------------------- + +-- 一个列表中的每一个元素都必须是相同的类型 +-- 下面两个列表一样 +[1, 2, 3, 4, 5] +[1..5] + +-- 在 Haskell 你可以拥有含有无限元素的列表 +[1..] -- 一个含有所有自然数的列表 + +-- 因为 Haskell 有“懒惰计算”,所以无限元素的列表可以正常运作。这意味着 +-- Haskell 可以只在它需要的时候计算。所以你可以请求 +-- 列表中的第1000个元素,Haskell 会返回给你 + +[1..] !! 999 -- 1000 + +-- 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) + +-- 获取元组中的元素 +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. 函数 +---------------------------------------------------- +-- 一个接受两个变量的简单函数 +add a b = a + b + +-- 注意,如果你使用 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 + +-- 守卫:一个简单的方法在函数里做分支 +fib x + | x < 2 = x + | otherwise = fib (x - 1) + fib (x - 2) + +-- 模式匹配是类型的。这里有三种不同的 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` 是列表剩余的部分。我们可以写 +-- 自己的 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 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. 更多的函数 +---------------------------------------------------- + +-- 柯里化(currying):如果你不传递函数中所有的参数, +-- 它就变成“柯里化的”。这意味着,它返回一个接受剩余参数的函数。 + +add a b = a + b +foo = add 10 -- foo 现在是一个接受一个数并对其加 10 的函数 +foo 5 -- 15 + +-- 另外一种方式去做同样的事 +foo = (+10) +foo 5 -- 15 + +-- 函数组合 +-- (.) 函数把其它函数链接到一起 +-- 举个列子,这里 foo 是一个接受一个值的函数。它对接受的值加 10, +-- 并对结果乘以 5,之后返回最后的值。 +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +-- 修复优先级 +-- Haskell 有另外一个函数称为 `$`。它改变优先级 +-- 使得其左侧的每一个操作先计算然后应用到 +-- 右侧的每一个操作。你可以使用 `.` 和 `$` 来除去很多 +-- 括号: + +-- before +(even (fib 7)) -- true + +-- after +even . fib $ 7 -- true + +---------------------------------------------------- +-- 5. 类型签名 +---------------------------------------------------- + +-- Haskell 有一个非常强壮的类型系统,一切都有一个类型签名。 + +-- 一些基本的类型: +5 :: Integer +"hello" :: String +True :: Bool + +-- 函数也有类型。 +-- `not` 接受一个布尔型返回一个布尔型: +-- not :: Bool -> Bool + +-- 这是接受两个参数的函数: +-- add :: Integer -> Integer -> Integer + +-- 当你定义一个值,在其上写明它的类型是一个好实践: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. 控制流和 If 语句 +---------------------------------------------------- + +-- if 语句 +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- if 语句也可以有多行,缩进是很重要的 +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- case 语句:这里是你可以怎样去解析命令行参数 +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- Haskell 没有循环因为它使用递归取代之。 +-- map 应用一个函数到一个数组中的每一个元素 + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- 你可以使用 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 是右手边的- +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- 这和下面是一样的 +(2 * 3 + (2 * 2 + (2 * 1 + 4))) + +---------------------------------------------------- +-- 7. 数据类型 +---------------------------------------------------- + +-- 这里展示在 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 的所有 +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- 虽然在没有解释 monads 的情况下 IO不能被完全地解释, +-- 着手解释到位并不难。 + +-- 当一个 Haskell 程序被执行,函数 `main` 就被调用。 +-- 它必须返回一个类型 `IO ()` 的值。举个列子: + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- putStrLn has type String -> IO () + +-- 如果你能实现你的程序依照函数从 String 到 String,那样编写 IO 是最简单的。 +-- 函数 +-- interact :: (String -> String) -> IO () +-- 输入一些文本,在其上运行一个函数,并打印出输出 + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- 你可以考虑一个 `IO()` 类型的值,当做一系列计算机所完成的动作的代表, +-- 就像一个以命令式语言编写的计算机程序。我们可以使用 `do` 符号来把动作链接到一起。 +-- 举个列子: + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + name <- getLine -- this gets a line and gives it the name "input" + putStrLn $ "Hello, " ++ name + +-- 练习:编写只读取一行输入的 `interact` + +-- 然而,`sayHello` 中的代码将不会被执行。唯一被执行的动作是 `main` 的值。 +-- 为了运行 `sayHello`,注释上面 `main` 的定义,并代替它: +-- main = sayHello + +-- 让我们来更好地理解刚才所使用的函数 `getLine` 是怎样工作的。它的类型是: +-- getLine :: 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 + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- 我们可以使用这个动作就像我们使用 `getLine`: + +main'' = do + putStrLn "I will echo two lines!" + result <- action + putStrLn result + putStrLn "This was all, folks!" + +-- `IO` 类型是一个 "monad" 的例子。Haskell 使用一个 monad 来做 IO的方式允许它是一门纯函数式语言。 +-- 任何与外界交互的函数(也就是 IO) 都在它的类型签名处做一个 `IO` 标志 +-- 着让我们推出 什么样的函数是“纯洁的”(不与外界交互,不修改状态) 和 什么样的函数不是 “纯洁的” + +-- 这是一个强有力的特征,因为并发地运行纯函数是简单的;因此,Haskell 中并发是非常简单的。 + + +---------------------------------------------------- +-- 9. The Haskell REPL +---------------------------------------------------- + +-- 键入 `ghci` 开始 repl。 +-- 现在你可以键入 Haskell 代码。 +-- 任何新值都需要通过 `let` 来创建: + +let foo = 5 + +-- 你可以查看任何值的类型,通过命令 `:t`: + +>:t foo +foo :: Integer + +-- 你也可以运行任何 `IO ()`类型的动作 + +> sayHello +What is your name? +Friend! +Hello, Friend! + +``` + +还有很多关于 Haskell,包括类型类和 monads。这些是使得编码 Haskell 是如此有趣的主意。我用一个最后的 Haskell 例子来结束:一个 Haskell 的快排实现: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +安装 Haskell 是简单的。你可以从[这里](http://www.haskell.org/platform/)获得它。 + +你可以从优秀的 +[Learn you a Haskell](http://learnyouahaskell.com/) 或者 +[Real World Haskell](http://book.realworldhaskell.org/) +找到优雅不少的入门介绍。 \ No newline at end of file -- cgit v1.2.3 From 521940d7080fba907fafc1bb01f96e1de2e79de5 Mon Sep 17 00:00:00 2001 From: Chenbo Li Date: Sat, 3 Aug 2013 22:36:38 +0800 Subject: add python-cn --- zh-cn/python-cn.html.markdown | 475 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 475 insertions(+) create mode 100755 zh-cn/python-cn.html.markdown diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown new file mode 100755 index 00000000..259e4ed8 --- /dev/null +++ b/zh-cn/python-cn.html.markdown @@ -0,0 +1,475 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Chenbo Li", "http://binarythink.net"] +filename: learnpython.py +lang: zh-cn +--- + +Python 由 Guido Van Rossum 在90年代初创建。 它现在是最流行的语言之一 +我喜爱python是因为它有极为清晰的语法,甚至可以说,它就是可以执行的伪代码 + +很欢迎来自您的反馈,你可以在[@louiedinh](http://twitter.com/louiedinh) 和 louiedinh [at] [google's email service] 这里找到我 + +注意: 这篇文章针对的版本是Python 2.7,但大多也可使用于其他Python 2的版本 +如果是Python 3,请在网络上寻找其他教程 + +```python +# 单行注释 +""" 多行字符串可以用 + 三个引号包裹,不过这也可以被当做 + 多行注释 +""" + +#################################################### +## 1. 原始数据类型和操作符 +#################################################### + +# 数字类型 +3 #=> 3 + +# 简单的算数 +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# 整数的除法会自动取整 +5 / 2 #=> 2 + +# 要做精确的除法,我们需要引入浮点数 +2.0 # 浮点数 +11.0 / 4.0 #=> 2.75 好多了 + +# 括号具有最高优先级 +(1 + 3) * 2 #=> 8 + +# 布尔值也是原始数据类型 +True +False + +# 用not来取非 +not True #=> False +not False #=> True + +# 相等 +1 == 1 #=> True +2 == 1 #=> False + +# 不等 +1 != 1 #=> False +2 != 1 #=> True + +# 更多的比较操作符 +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# 比较运算可以连起来写! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# 字符串通过"或'括起来 +"This is a string." +'This is also a string.' + +# 字符串通过加号拼接 +"Hello " + "world!" #=> "Hello world!" + +# 字符串可以被视为字符的列表 +"This is a string"[0] #=> 'T' + +# % 可以用来格式化字符串 +"%s can be %s" % ("strings", "interpolated") + +# 也可以用format方法来格式化字符串 +# 推荐使用这个方法 +"{0} can be {1}".format("strings", "formatted") +# 也可以用变量名代替数字 +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# None 是对象 +None #=> None + +# 不要用相等 `==` 符号来和None进行比较 +# 要用 `is` +"etc" is None #=> False +None is None #=> True + +# 'is' 可以用来比较对象的相等性 +# 这个操作符在比较原始数据时没多少用,但是比较对象时必不可少 + +# None, 0, 和空字符串都被算作False +# 其他的均为True +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. 变量和集合 +#################################################### + +# 很方便的输出 +print "I'm Python. Nice to meet you!" + + +# 给变量赋值前不需要事先生命 +some_var = 5 # 规范用小写字母和下划线来做为变量名 +some_var #=> 5 + +# 访问之前为赋值的变量会抛出异常 +# 查看控制流程一节来了解异常处理 +some_other_var # 抛出命名异常 + +# if语句可以作为表达式来使用 +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# 列表用来保存序列 +li = [] +# 可以直接初始化列表 +other_li = [4, 5, 6] + +# 在列表末尾添加元素 +li.append(1) #li 现在是 [1] +li.append(2) #li 现在是 [1, 2] +li.append(4) #li 现在是 [1, 2, 4] +li.append(3) #li 现在是 [1, 2, 4, 3] +# 移除列表末尾元素 +li.pop() #=> 3 and li is now [1, 2, 4] +# 放回来 +li.append(3) # li is now [1, 2, 4, 3] again. + +# 像其他语言访问数组一样访问列表 +li[0] #=> 1 +# 访问最后一个元素 +li[-1] #=> 3 + +# 越界会抛出异常 +li[4] # 抛出越界异常 + +# 切片语法需要用到列表的索引访问 +# 可以看做数学之中左闭右开区间 +li[1:3] #=> [2, 4] +# 省略开头的元素 +li[2:] #=> [4, 3] +# 省略末尾的元素 +li[:3] #=> [1, 2, 4] + +# 删除特定元素 +del li[2] # li 现在是 [1, 2, 3] + +# 合并列表 +li + other_li #=> [1, 2, 3, 4, 5, 6] - 不改变这两个列表 + +# 通过拼接合并列表 +li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6] + +# 用in来返回元素是否在列表中 +1 in li #=> True + +# 返回列表长度 +len(li) #=> 6 + + +# 元组类似于列表,但是他是不可改变的 +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # 类型错误 + +# 对于大多数的列表操作,也适用于元组 +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# 你可以将元组解包赋给多个变量 +a, b, c = (1, 2, 3) # a是1,b是2,c是3 +# 如果不加括号,那么会自动视为元组 +d, e, f = 4, 5, 6 +# 现在我们可以看看交换两个数字是多么容易的事 +e, d = d, e # d是5,e是4 + + +# 字典用来储存映射关系 +empty_dict = {} +# 字典初始化 +filled_dict = {"one": 1, "two": 2, "three": 3} + +# 字典也用中括号访问元素 +filled_dict["one"] #=> 1 + +# 把所有的键保存在列表中 +filled_dict.keys() #=> ["three", "two", "one"] +# 键的顺序并不是唯一的,得到的不一定是这个顺序 + +# 把所有的值保存在列表中 +filled_dict.values() #=> [3, 2, 1] +# 和键的顺序相同 + +# 判断一个键是否存在 +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# 查询一个不存在的键会抛出键异常 +filled_dict["four"] # 键异常 + +# 用get方法来避免键异常 +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# get方法支持在不存在的时候返回一个默认值 +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Setdefault是一个更安全的添加字典元素的方法 +filled_dict.setdefault("five", 5) #filled_dict["five"] 的值为 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] 的值仍然是 5 + + +# 集合储存无顺序的元素 +empty_set = set() +# 出事话一个集合 +some_set = set([1,2,2,3,4]) # filled_set 现在是 set([1, 2, 3, 4]) + +# Python 2.7 之后,大括号可以用来表示集合 +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# 为集合添加元素 +filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5} + +# 用&来实现集合的交 +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# 用|来实现集合的并 +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# 用-来实现集合的差 +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# 用in来判断元素是否存在于集合中 +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. 控制流程 +#################################################### + +# 新建一个变量 +some_var = 5 + +# 这是个if语句,在python中缩进是很重要的。 +# 会输出 "some var is smaller than 10" +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # 这个 elif 语句是不必须的 + print "some_var is smaller than 10." +else: # 也不是必须的 + print "some_var is indeed 10." + + +""" +用for循环遍历列表 +输出: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # 你可以用 % 来格式化字符串 + print "%s is a mammal" % animal + +""" +`range(number)` 返回从0到给定数字的列表 +输出: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While循环 +输出: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Shorthand for x = x + 1 + +# 用 try/except块来处理异常 + +# Python 2.6 及以上适用: +try: + # 用raise来抛出异常 + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass就是什么都不做,不过通常这里会做一些恢复工作 + + +#################################################### +## 4. 函数 +#################################################### + +# 用def来新建函数 +def add(x, y): + print "x is %s and y is %s" % (x, y) + return x + y # Return values with a return statement + +# 调用带参数的函数 +add(5, 6) #=> 输出 "x is 5 and y is 6" 返回 11 + +# 通过关键字赋值来调用函数 +add(y=6, x=5) # 顺序是无所谓的 + +# 我们也可以定义接受多个变量的函数,这些变量是按照顺序排列的 +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# 我们也可以定义接受多个变量的函数,这些变量是按照关键字排列的 +def keyword_args(**kwargs): + return kwargs + +# 实际效果: +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# 你也可以同时将一个函数定义成两种形式 +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} +""" + +# 当调用函数的时候,我们也可以和之前所做的相反,把元组和字典展开为参数 +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) + +# Python 有一等函数: +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# 匿名函数 +(lambda x: x > 2)(3) #=> True + +# 内置高阶函数 +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# 可以用列表方法来对高阶函数进行更巧妙的引用 +[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. 类 +#################################################### + +# 我们新建的类是从object类中继承的 +class Human(object): + + # 类属性,由所有类的对象共享 + species = "H. sapiens" + + # 基本构造函数 + def __init__(self, name): + # 将参数赋给对象成员属性 + self.name = name + + # 成员方法,参数要有self + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # 类方法由所有类的对象共享 + # 这类方法在调用时,会把类本身传给第一个参数 + @classmethod + def get_species(cls): + return cls.species + + # 静态方法是不需要类和对象的引用就可以调用的方法 + @staticmethod + def grunt(): + return "*grunt*" + + +# 实例化一个类 +i = Human(name="Ian") +print i.say("hi") # 输出 "Ian: hi" + +j = Human("Joel") +print j.say("hello") # 输出 "Joel: hello" + +# 访问类的方法 +i.get_species() #=> "H. sapiens" + +# 改变共享属性 +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# 访问静态变量 +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. 模块 +#################################################### + +# 我们可以导入其他模块 +import math +print math.sqrt(16) #=> 4 + +# 我们也可以从一个模块中特定的函数 +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# 从模块中导入所有的函数 +# 警告:不推荐使用 +from math import * + +# 简写模块名 +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Python的模块其实只是普通的python文件 +# 你也可以创建自己的模块,并且导入它们 +# 模块的名字就和文件的名字相同 + +# 以可以通过下面的信息找找要成为模块需要什么属性或方法 +import math +dir(math) + + +``` + +## 更多阅读 + +希望学到更多?试试下面的链接: + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) -- cgit v1.2.3 From df6ff15f9f0b70e8c1307a14c5ceaa44ee76ea08 Mon Sep 17 00:00:00 2001 From: FlaskBreaker Date: Mon, 5 Aug 2013 12:51:58 +0200 Subject: Added c-es --- es-es/c-es.html.markdown | 417 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 417 insertions(+) create mode 100644 es-es/c-es.html.markdown diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown new file mode 100644 index 00000000..72902dd2 --- /dev/null +++ b/es-es/c-es.html.markdown @@ -0,0 +1,417 @@ +--- +language: c +filename: learnc.c +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Francisco Garca", "http://flaskbreaker.tumblr.com/"] +lang: es-es +--- + +Ah!, C. Aun hoy en da sigue siendo el lenguaje por excelencia de la +computacin moderna de alto rendimiento. + +C es el lenguaje de ms bajo nivel que la mayora de los programadores +llegarn a usar, pero lo compensa de sobra con pura velocidad. Solo +ten en cuenta el manejo manual de memoria y te llevar tan lejos como +necesites. + +```c +// Los comentarios de una sola lnea comienzan con // + +/* +Los comentarios multilnea tienen este aspecto. +*/ + +// Importa cabeceras con #include +#include +#include +#include + +// Declara por adelantado las armaduras de las funciones en un archivo .h, +// o al principio de tu archivo .c . +void function_1(); +void function_2(); + +// El punto de entrada de tu programa es una funcin llamada main con +// retorno de tipo entero (integer). +int main() { + +// Muestra la salida usando printf, para el "formato print" +// %d es un entero, \n es una nueva lnea +printf("%d\n", 0); // => Muestra 0 +// Todas las sentencias deben terminar con un punto y coma. + +/////////////////////////////////////// +// Tipos +/////////////////////////////////////// + +// Tienes que declarar una variable antes de usarla. La declaracin de una +// variable necesites que especifiques su tipo; el tipo de una variable +// determina su tamao en bytes. + +// 'ints' (enteros) son normalmente de 4 bytes +int x_int = 0; + +// 'shorts' son normalmente de 2 bytes +short x_short = 0; + +// 'chars' son fijo de 1 byte +char x_char = 0; +char y_char = 'y'; // Los caracteres literales se entrecomillan con '' + +// 'longs' son a menudo de 4 a 8 bytes; 'long longs' son fijo de por lo +// menos 64 bits +long x_long = 0; +long long x_long_long = 0; + +// 'floats' son normalmente nmeros de coma flotante de 32 bits +float x_float = 0.0; + +// 'doubles' son normalmente nmeros de coma flotante de 64 bits +double x_double = 0.0; + +// Todos los tipos enteros pueden ser 'unsigned'. Esto significa que no +// pueden ser negativos, pero el valor mximo de una variable 'unsigned' +// es mayor que el de una no 'unsigned' del mismo tamao. +unsigned char ux_char; +unsigned short ux_short; +unsigned int ux_int; +unsigned long long ux_long_long; + +// Todos menos 'char', que es siempre de 1 byte, varan el tamao +// dependiendo de tu mquina. sizeof(T) te dice el tamao de una variable +// de tipo T en bytes por lo que podemos expresar el tamao de estos tipos +// portatilmente. +// Por ejemplo, +printf("%lu\n", sizeof(int)); // => 4 (en mquinas con 'words' de 4 bytes) + +// Los arrays deben ser inicializados con un tamao concreto. +char my_char_array[20]; // Este array ocupa 1 * 20 = 20 bytes +int my_int_array[20]; // Este array ocupa 4 * 20 = 80 bytes + // (suponiendo que tenemos 'words' de 4-byte) + + +// Puedes inicializar un array a 0 as: +char my_array[20] = {0}; + +// Indexar un array es como en otros lenguajes -o, ms bien, otros +// lenguajes son como C- +my_array[0]; // => 0 + +// Los arrays varan; son slo memoria! +my_array[1] = 2; +printf("%d\n", my_array[1]); // => 2 + +// Las cadenas (strings) son slo arrays de 'chars' (caracteres) +// terminados en un byte NUL (0x00), representado en las cadenas como el carcter especial '\0'. +// (No tenemos porqu aadir el byte nulo en cadenas literales; el +// compilador lo aade al final por nosotros.) +char a_string[20] = "Esto es una cadena"; +printf("%s\n", a_string); // %s se sutituye por una cadena. + +/* +Te habrs dado cuenta de que a_string es solo de 18 caracteres. +El 'char' #19 es el byte nulo. +El 'char' #20 es de valor indefinido. +*/ + +printf("%d\n", a_string[18]); // => 0 + +/////////////////////////////////////// +// Operadores +/////////////////////////////////////// + +int i1 = 1, i2 = 2; // Forma corta de declaracin mltiple +float f1 = 1.0, f2 = 2.0; + +// La aritmtica es sencilla +i1 + i2; // => 3 +i2 - i1; // => 1 +i2 * i1; // => 2 +i1 / i2; // => 0 (0.5, pero es truncado tras el 0) + +f1 / f2; // => 0.5, ms o menos psilon +// Mdulo est tambin +11 % 3; // => 2 + +// Los operadores de comparacin te resultaran familiares, pero no hay +// booleanos en C. Usamos enteros (ints) en su lugar. 0 es falso, +// cualquier otra cosa es verdadero. (Los operadores de comparacin +// siempre devuelven 0 o 1) +3 == 2; // => 0 (Falso) +3 != 2; // => 1 (Verdadero) +3 > 2; // => 1 +3 < 2; // => 0 +2 <= 2; // => 1 +2 >= 2; // => 1 + +// La lgica funiona en enteros +!3; // => 0 (not lgico) +!0; // => 1 +1 && 1; // => 1 (and lgico) +0 && 1; // => 0 +0 || 1; // => 1 (or lgico) +0 || 0; // => 0 + +// Operadores de bits! +~0x0F; // => 0xF0 (Negacin) +0x0F & 0xF0; // => 0x00 (AND) +0x0F | 0xF0; // => 0xFF (OR) +0x04 ^ 0x0F; // => 0x0B (XOR) +0x01 << 1; // => 0x02 (desplazar hacia la izquierda (por 1)) +0x02 >> 1; // => 0x01 (desplazar hacia la derecha (por 1)) + +/////////////////////////////////////// +// Estructuras de Control +/////////////////////////////////////// + +if (0) { + printf("Yo nunca ocurro\n"); +} else if (0) { + printf("Yo tampoco ocurro nunca\n"); +} else { + printf("Yo me muestro\n"); +} + +// Mientras el bucle exista +int ii = 0; +while (ii < 10) { + printf("%d, ", ii++); // ii++ incrementa ii en uno, despus de usar su valor. +} // => muestra "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + +printf("\n"); + +int kk = 0; +do { + printf("%d, ", kk); +} while (++kk < 10); // ++kk incrementa kk en uno, antes de usar su valor. +// => muestra "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + +printf("\n"); + +// Bucles 'for' tambin +int jj; +for (jj=0; jj < 10; jj++) { + printf("%d, ", jj); +} // => muestra "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + +printf("\n"); + +/////////////////////////////////////// +// Cambios de Tipo +/////////////////////////////////////// + +// Cada valor en C tiene un tipo, pero tu puedes ingresar un valor en +// otro tipo si quieres. + +int x_hex = 0x01; // Puedes asignar hexadecimales a variables + +// El cambio de tipos intentar mantener sus valores numricos +printf("%d\n", x_hex); // => Muestra 1 +printf("%d\n", (short) x_hex); // => Muestra 1 +printf("%d\n", (char) x_hex); // => Muestra 1 + +// Los tipos se desbordan sin aviso +printf("%d\n", (char) 257); // => 1 (El valor mximo de un 'char' es 255) + +// Los tipos enteros puden cambiarse a tipos de coma flotante, y viceversa +printf("%f\n", (float)100); // %f se sustituye por un 'float' +printf("%lf\n", (double)100); // %lf se sustituye por un 'double' +printf("%d\n", (char)100.0); + +/////////////////////////////////////// +// Punteros +/////////////////////////////////////// + +// Un puntero es una variable declarada para almacenar una direccin de +// memoria. Su declaracin adems nos dir el tipo de dato al que apunta. +// Puedes obtener la direccin de memoria de tus variables, y despus +// enlazarlas con ellos. + +int x = 0; +printf("%p\n", &x); // Usa & para obtener la direccin de una variable. +// (%p se sustituye por un puntero) +// => Muestra alguna direccin de memoria; + +// Los tipos de puntero terminan con * en su declaracin +int* px; // px es un puntero a un 'int' +px = &x; // Almacena la direccin de x en px +printf("%p\n", px); // => Muestra alguna direccin de memoria + +// Para obtener el valor de la direccin a la que apunta un puntero, pon +// * delante para desreferenciarle. +printf("%d\n", *px); // => Muestra 0, el valor de x y de la direccin a la + // que apunta px + +// Tambin puedes cambiar el valor al que est apuntando el puntero. +// Tenemos que meter la desreferencia entre parntesis porque ++ tiene +// prioridad frente a *. +(*px)++; // Incrementa el valor al que apunta px en 1 +printf("%d\n", *px); // => Muestra 1 +printf("%d\n", x); // => Muestra 1 + +int x_array[20]; // Los arrays son una buena manera de distribuir bloques +int xx; // continuos de memoria. +for (xx=0; xx<20; xx++) { + x_array[xx] = 20 - xx; +} // Inicializa x_array a 20, 19, 18,... 2, 1 + +// Declara un puntero de tipo 'int' y lo inicializa para apuntar a x_array +int* x_ptr = x_array; +// x_ptr ahira apunta al primer elemento del 'array' (el entero 20). +// Esto funciona porque las 'arrays' actualmente son solo punteros a su +// primer elemento. + +// Los 'arrays' son punteros a su primer elemento. +printf("%d\n", *(x_ptr)); // => Muestra 20 +printf("%d\n", x_array[0]); // => Muestra 20 + +// Los punteros aumentan y disminuyen en funcin de su tipo. +printf("%d\n", *(x_ptr + 1)); // => Muestra 19 +printf("%d\n", x_array[1]); // => Muestra 19 + +// Puedes tambin asigner dinamicamente bloques contiguos de memoria con +// la funcin malloc de la librera estndard, que toma un entero como +// argumento representando el nmero de bytes a asignar de la pila. +int* my_ptr = (int*) malloc(sizeof(int) * 20); +for (xx=0; xx<20; xx++) { + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx funcionara tambin aqu +} // Inicializa la memoria a 20, 19, 18, 17... 2, 1 (como 'ints') + +// Desreferenciando la memoria que no has asignado te dar resultados +// impredecibles +printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? + +// Cuando hallas acabado con el bloque de memora malloc, necesitas +// liberarlo o sino nadie ms podr usarlo hasta que tu programa se cierre +free(my_ptr); + +// Las cadenas pueden ser 'arrays' de chars, pero normalmente se +// representan con punteros 'char': +char* my_str = "This is my very own string"; + +printf("%c\n", *my_str); // => 'T' + +function_1(); +} // fin de la funcin main + +/////////////////////////////////////// +// Funciones +/////////////////////////////////////// + +// Sintexis de la declaracin de funciones: +// () + +int add_two_ints(int x1, int x2){ + return x1 + x2; // Usa 'return' para dar una salida +} + +/* +Las funciones son de paso por valor, pero puedes hacer tus propias +referencias con punteros de manera que las funciones puedan cambiar sus +valores. + +Ejemplo: invertidor de cadenas in-situ +*/ + +// Una funcin 'void' no retorna valor +void str_reverse(char* str_in){ + char tmp; + int ii=0, len = strlen(str_in); // Strlen es parte de la librera + for(ii=0; ii ".abeurp anu se otsE" +*/ + +/////////////////////////////////////// +// Definicin de tipos y estructuras +/////////////////////////////////////// + +// Los 'Typedefs' pueden ser utilizados para crear alias de tipos. +typedef int my_type; +my_type my_type_var = 0; + +// Las estructuras son slo grupos de datos. +struct rectangle { + int width; + int height; +}; + + +void function_1(){ + + struct rectangle my_rec; + + // Utiliza los miembros de una estructura con . + my_rec.width = 10; + my_rec.height = 20; + + // Puedes declarar punteros a estructuras + struct rectangle* my_rec_ptr = &my_rec; + + // Usa la desreferencia para modificar sus miembros... + (*my_rec_ptr).width = 30; + + // ... o usa la abreviatura -> + my_rec_ptr->height = 10; // Lo mismo que (*my_rec_ptr).height = 10; +} + +// Puedes aplicar un 'typedef' a una estructura por convenienca. +typedef struct rectangle rect; + +int area(rect r){ + return r.width * r.height; +} + +/////////////////////////////////////// +// Punteros a Funciones +/////////////////////////////////////// +/* +En tiempo de ejecucin, las funciones se localizan en unas direcciones de +memoria concretas. Los punteros a funciones son como cualquier otro +puntero (almacenan una direccin de memoria), pero pueden ser usados para +utilizar funciones directamente, o para pasar 'handlers' (o funciones +'callback') por todos lados. +Sin embargo, la sintaxis de definicin parecera confusa al principio. + +Ejemplo: usar str_reverse desde un puntero +*/ +void str_reverse_through_pointer(char * str_in) { + // Define un puntero a una funcin, llamado f. + void (*f)(char *); // La armadura debe coincidir exactamente con al funcin objetivo. + f = &str_reverse; // Assigna la direccin de la funcin (determinado en tiempo de ejecuin) + (*f)(str_in); // Llamando la funcin desde el puntero + // f(str_in); // Esta es una alternativa para llamarla pero con una sintaxis igual de vlida. +} + +/* +Tanto tiempo como las armaduras de las funciones coincidan, podrs asignar +cualquier funcin al mismo puntero. +Los punteros a funciones son normalmente envueltos en 'typedef' para +simplificar su legibilidad, como sigue: +*/ + +typedef void (*my_fnp_type)(char *); + +// Es usado para declarar la variable puntero actual: +// ... +// my_fnp_type f; + +``` + +## Otras lecturas + +Lo mejor que puedes en contrar es una copia de [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) + +Otro buen recurso es [Learn C the hard way](http://c.learncodethehardway.org/book/) + +Aparte de eso, Google es tu amigo. -- cgit v1.2.3 From ea3d1b6415c4ded7ad4651f70cecf5bf87ce6ae3 Mon Sep 17 00:00:00 2001 From: Linxiangyu Date: Mon, 5 Aug 2013 19:04:42 +0800 Subject: Add ruby-cn --- zh-cn/ruby-cn.html.markdown | 329 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 329 insertions(+) create mode 100644 zh-cn/ruby-cn.html.markdown diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown new file mode 100644 index 00000000..f66d1a03 --- /dev/null +++ b/zh-cn/ruby-cn.html.markdown @@ -0,0 +1,329 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] +translators: + - ["Lin Xiangyu", "https://github.com/oa414"] +--- + +```ruby +# 这是单行注释 + +=begin +这是多行注释 +没人用这个 +你也不该用 +=end + +# 首先,也是最重要的,所有东西都是对象 + +# 数字是对象 + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# 一些基本的算术符号 +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# 算术符号只是语法糖而已 +# 实际上是调用对象的方法 +1.+(3) #=> 4 +10.* 5 #=> 50 + +# 特殊的只也是对象 +nil # 空 +true # 真 +false # 假 + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# 相等运算符 +1 == 1 #=> true +2 == 1 #=> false + +# 不等运算符 +1 != 1 #=> false +2 != 1 #=> true +!true #=> false +!false #=> true + +# 除了false自己,nil是唯一的值为false的对象 + +!nil #=> true +!false #=> true +!0 #=> false + +# 更多比较 +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# 字符串是对象 + +'I am a string'.class #=> String +"I am a string too".class #=> String + +placeholder = "use string interpolation" +"I can #{placeholder} when using double quoted strings" +#=> "I can use string interpolation when using double quoted strings" + + +# 输出值 +puts "I'm printing!" + +# 变量 +x = 25 #=> 25 +x #=> 25 + +# 注意赋值语句返回了赋的值 +# 这意味着你可以用多重赋值语句 + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# 按照惯例,用snake_case 作为变量名 +snake_case = true + +# 使用具有描述性的运算符 +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# 符号(Symbols,也是对象) +# 符号是不可变的,内部用整数类型表示的可重用的值。通常用它代替字符串来有效地表达有意义的值 + + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# 数组 + +# 这是一个数组 +[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# 数组可以包含不同类型的元素 + +array = [1, "hello", false] #=> => [1, "hello", false] + +# 数组可以被索引 +# 从前面开始 +array[0] #=> 1 +array[12] #=> nil + +# 像运算符一样,[var]形式的访问 +# 也就是一个语法糖 +# 实际上是调用对象的[] 方法 +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# 从尾部开始 +array[-1] #=> 5 + +# 同时指定开始的位置和结束的位置 +array[2, 4] #=> [3, 4, 5] + +# 或者指定一个范围 +array[1..3] #=> [2, 3, 4] + +# 像这样往数组增加一个元素 +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# 哈希表是Ruby的键值对的基本数据结构 +# 哈希表由大括号定义 +hash = {'color' => 'green', 'number' => 5} + +hash.keys #=> ['color', 'number'] + +# 哈希表可以通过键快速地查询 +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# 查询一个不存在地键将会返回nil +hash['nothing here'] #=> nil + +# 用 #each 方法来枚举哈希表: +hash.each do |k, v| + puts "#{k} is #{v}" +end + +# 从Ruby 1.9开始, 用符号作为键的时候有特别的记号表示: + +new_hash = { defcon: 3, action: true} + +new_hash.keys #=> [:defcon, :action] + +# 小贴士:数组和哈希表都是可枚举的 +# 它们可以共享一些有用的方法,比如each, map, count, 和more + +# 控制流 + +if true + "if statement" +elsif false + "else if, optional" +else + "else, also optional" +end + +for counter in 1..5 + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# 然而 +# 没人用for循环 +# 用`each`来代替,就像这样 + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +grade = 'B' + +case grade +when 'A' + puts "Way to go kiddo" +when 'B' + puts "Better luck next time" +when 'C' + puts "You can do better" +when 'D' + puts "Scraping through" +when 'F' + puts "You failed!" +else + puts "Alternative grading system, eh?" +end + +# 函数 + +def double(x) + x * 2 +end + +# 函数 (以及所有的方法块) 隐式地返回了最后语句的值 +double(2) #=> 4 + +# 当不存在歧义的时候括号是可有可无的 +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x,y) + x + y +end + +# 方法的参数通过逗号分隔 +sum 3, 4 #=> 7 + +sum sum(3,4), 5 #=> 12 + +# yield +# 所有的方法都有一个隐式的块参数 +# 可以用yield参数调用 + +def surround + puts "{" + yield + puts "}" +end + +surround { puts 'hello world' } + +# { +# hello world +# } + + +# 用class关键字定义一个类 +class Human + + # 一个类变量,它被这个类地所有实例变量共享 + @@species = "H. sapiens" + + # 构造函数 + def initialize(name, age=0) + # 将参数name的值赋给实例变量@name + @name = name + # 如果没有给出age, 那么会采用参数列表中地默认地值 + @age = age + end + + # 基本的 setter 方法 + def name=(name) + @name = name + end + + # 基本地 getter 方法 + def name + @name + end + + # 一个类方法以self.开头 + # 它可以被类调用,但不能被类的实例调用 + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end + +end + + +# 类的例子 +jim = Human.new("Jim Halpert") + +dwight = Human.new("Dwight K. Schrute") + +# 让我们来调用一些方法 +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# 调用对象的方法 +Human.say("Hi") #=> "Hi" + +``` -- cgit v1.2.3 From f5023cc9b35be5d1986a76ce1d6f44979a766afb Mon Sep 17 00:00:00 2001 From: greybird Date: Mon, 5 Aug 2013 17:22:53 +0400 Subject: fix immediately-executing function --- javascript.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 9cc7617d..cc279b9a 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -241,7 +241,7 @@ i // = 5 - not undefined as you'd expect in a block-scoped language // This has led to a common pattern of "immediately-executing anonymous // functions", which prevent temporary variables from leaking into the global // scope. -function(){ +(function(){ var temporary = 5 // We can access the global scope by assiging to the 'global object', which // in a web browser is always 'window'. The global object may have a @@ -249,7 +249,7 @@ function(){ window.permanent = 10 // Or, as previously mentioned, we can just leave the var keyword off. permanent2 = 15 -}() +})() temporary // raises ReferenceError permanent // = 10 permanent2 // = 15 -- cgit v1.2.3 From 2dac6eb4f98db6a930e0101eb3529ffc7290496a Mon Sep 17 00:00:00 2001 From: Guillermo Vaya Date: Fri, 2 Aug 2013 14:24:27 +0200 Subject: emacs lisp translated --- es-es/elisp-es.html.markdown | 377 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 377 insertions(+) create mode 100644 es-es/elisp-es.html.markdown diff --git a/es-es/elisp-es.html.markdown b/es-es/elisp-es.html.markdown new file mode 100644 index 00000000..8c220109 --- /dev/null +++ b/es-es/elisp-es.html.markdown @@ -0,0 +1,377 @@ +--- +language: elisp +contributors: + - ["Bastien Guerry", "http://bzg.fr"] +translators: + - ["Guillermo Vayá", "http://willyfrog.es"] +lang: es-es +filename: learn-emacs-lisp.el +--- + +```scheme +;; Introduccion a Emacs Lisp en 15 minutos (v0.2d) +;; +;; Autor: Bastien / @bzg2 / http://bzg.fr +;; Traducción: Guillermo Vayá +;; +;; Antes de nada, lee este texto de Peter Norvig: +;; http://norvig.com/21-days.html +;; +;; Ahora instala GNU Emacs 24.3: +;; +;; Debian: apt-get install emacs +;; (o sigue las instrucciones de tu distribución preferida) +;; OSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg +;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip +;; +;; Puedes encontrar información general sobre Emacs en: +;; http://www.gnu.org/software/emacs/#Obtaining + +;; Aviso importante: +;; +;; Seguir este tutorial no provocará daños en tu ordenador a menos que +;; te enfades tanto que que acabes tirándolo al suelo. En tal caso +;; declino cualquier responsabilidad. ¡A divertirse! + + +;; "N. del. T.": Algunos términos comunes de la informática se han dejado +;; sin traducir ya que es mucho más probable que el lector los conozca en +;; su forma en inglés, siendo la versión en español de muy raro uso. +;; Además "sexps" se ha decidido traducir por sexpresión. +;; Por último, añadir que no se han traducido los ejemplos de código ya que no +;; es necesario entender qué dice el string para comprender el funcionamiento +;; y podría llevar a error. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Inicia Emacs. +;; +;; Pulsa la tecla `q' para pasar el mensaje de bienvenida. +;; +;; Mira a la línea gris en la parte inferior de la ventana: +;; +;; "*scratch*" es el nombre del espacio editable donde estás. +;; A este espacio editable se le llama "buffer". +;; +;; Scratch es el buffer por defecto cuando abres Emacs. +;; En Emacs nunca editas ficheros, sino que editas buffers que +;; posteriormente pueden grabarse a un fichero. +;; can save to a file. +;; +;; "Lisp interaction" indica el conjunto de ordenes disponibles. +;; +;; Emacs dispone de un set de comandos disponibles en cualquier buffer +;; ("built-ins") y aparte varios conjuntos de ordenes disponibles +;; según el modo específico que esté activo. En nuestro caso +;; estamos usando `lisp-interaction-mode', el cual incluye las +;; ordenes necesarias para evaluar y navegar código Elisp. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Un punto y coma comienza un comentario. Pueden ponerse en cualquier +;; posicion de la linea. +;; +;; Los programas en Elisp se componen de expresiones simbólicas +;; tambien llamadas "sexps": +(+ 2 2) + +;; Esta expresión simbólica se lee tal que "Suma 2 y 2" + +;; Las sexpresiones se rodean por paréntesis, y pueden anidarse: +(+ 2 (+ 1 1)) + +;; Una expresion simbólica está formada bien por átomos o bien por otras +;; expresiones simbólicas. En el ejemplo de arriba, 1 y 2 son átomos, +;; mientras que (+ 2 (+ 1 1)) y (+ 1 1) son expresiones simbólicas. + +;; Gracias a `lisp-interaction-mode' puedes evaluar las sexpresiones. +;; Coloca el cursor justo despues del paréntesis de cierre y +;; mantén pulsada la tecla Control y la j (para abreviar usaremos "C-j"). + +(+ 3 (+ 1 2)) +;; ^ pon aquí el cursor +;; `C-j' => 6 + +;; `C-j' añade el resultado de la evaluación al buffer. + +;; `C-xC-e' muestra el mismo resultado pero en la linea inferior +;; la cual se llama "minibuffer". Este será el metodo que usaremos +;; normalmente para no llenar el buffer con texto inútil. + +;; `setq' guarda un valor en una variable: +(setq my-name "Bastien") +;; `C-xC-e' => "Bastien" (aparece en el mini-buffer) + +;; `insert' añade "Hello!" en el punto donde esté tu cursor: +(insert "Hello!") +;; `C-xC-e' => "Hello!" + +;; Aunque hemos usado `insert' con solo un parámetro "Hello!", se +;; pueden pasar más. Por ejemplo, en esta otra sexpresión usamos dos: + +(insert "Hello" " world!") +;; `C-xC-e' => "Hello world!" + +;; Se pueden usar variables en lugar de strings: +(insert "Hello, I am " my-name) +;; `C-xC-e' => "Hello, I am Bastien" + +;; Puedes combinar sexpresiones en funciones: +(defun hello () (insert "Hello, I am " my-name)) +;; `C-xC-e' => hello + +;; Evaluemos la funcion: +(hello) +;; `C-xC-e' => Hello, I am Bastien + +;; Los parentesis vacios en la definicion de una funcion indican +;; que no acepta parámetros. En cualquier caso, usar `my-name' siempre +;; es aburrido, asi que vamos a hacer que la función accepte un parámetro +;; (en este caso el parametro se llama "name"): +(defun hello (name) (insert "Hello " name)) +;; `C-xC-e' => hello + +;; Ahora vamos a llamar a la funcion con el string "you" como valor para +;; el único parámetro que posee. +(hello "you") +;; `C-xC-e' => "Hello you" + +;; ¡Genial! + +;; Descansa un poco y respira. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Ahora cambiaremos al nuevo buffer, llamado "*test*", en una nueva ventana. + +(switch-to-buffer-other-window "*test*") +;; `C-xC-e' +;; => [La pantalla ahora tiene dos ventanas y el cursor está en el buffer *test*] + +;; Mueve el ratón sobre la ventana superior y pulsa el boton izdo. para volver. +;; Otra forma es usando `C-xo' (pulsa simultaneamente control y x y luego la o) +;; para ir a la otra ventana. + +;; Se pueden combinar varias sexpresiones mediante `progn': +(progn + (switch-to-buffer-other-window "*test*") + (hello "you")) +;; `C-xC-e' +;; => [De las dos ventanas de la pantalla, el cursor está en la marcada como *test*] + +;; A partir de ahora, si no te importa, dejaremos de decir que pulses `C-xC-e': +;; tendrás que hacerlo para ejecutar cada sexpresión que siga. + +;; También tendrás que volver al buffer *scratch* bien con el ratón o con `C-xo'. + +;; En ocasiones será util limpiar el buffer: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "there")) + +;; O volver a la ventana anterior: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "you") + (other-window 1)) + +;; Puedes enlazar un valor a una variable local con `let': +(let ((local-name "you")) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello local-name) + (other-window 1)) + +;; En este caso, no hace falta añadir `progn' ya que `let' permite combinar +;; varias sexpresiones. + +;; Vamos a darle formato a un string: +(format "Hello %s!\n" "visitor") + +;; Cada %s indica la posicion donde irá un string, el cual será reemplazado +;; por "visitor". "\n" es el caracter de nueva línea. + +;; Mejoremos nuestra funcion usando `format': +(defun hello (name) + (insert (format "Hello %s!\n" name))) + +(hello "you") + +;; Creemos una nueva funcion que utililce `let': +(defun greeting (name) + (let ((your-name "Bastien")) + (insert (format "Hello %s!\n\nI am %s." + name ; the argument of the function + your-name ; the let-bound variable "Bastien" + )))) + +;; Y ahora la evaluamos: +(greeting "you") + +;; Algunas funciones son interactivas: +(read-from-minibuffer "Enter your name: ") + +;; Al evaluar esta función, ésta devuelve lo que hayas introducido. + +;; Ahora hagamos nuestra función `greeting' preguntar por tu nombre: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (insert (format "Hello!\n\nI am %s and you are %s." + from-name ; the argument of the function + your-name ; the let-bound var, entered at prompt + )))) + +(greeting "Bastien") + +;; Y ahora la completamos mostrando el resultado en la otra ventana: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (insert (format "Hello %s!\n\nI am %s." your-name from-name)) + (other-window 1))) + +;; Probémosla: +(greeting "Bastien") + +;; Descansa un poco y respira. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Creemos una lista de nombres: +(setq list-of-names '("Sarah" "Chloe" "Mathilde")) + +;; Para coger el primer elemento de la lista usaremos `car': +(car list-of-names) + +;; Para coger todos menos el primer elemento de la lista +;; usaremos `cdr': +(cdr list-of-names) + +;; Para añadir un elemento al comienzo de la lista utilizamos `push': +(push "Stephanie" list-of-names) + +;; OJO: `car' y `cdr' no modifican la lista, mientras que `push' sí. +;; ¡Es una diferencia importante! Algunas funciones no tienen efectos +;; colaterales (como `car') mientras que otras sí (como `push'). +;; "N. del T.": estos efectos colaterales se les llama `side-effects' en +;; las distintas variantes de lisp. + +;; Llamemos a `hello' con cada elemento de `list-of-names': +(mapcar 'hello list-of-names) + +;; Retocamos `greeting' para que salude a todos los que estén en `list-of-names': +(defun greeting () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (mapcar 'hello list-of-names) + (other-window 1)) + +(greeting) + +;; ¿Te acuerdas de la función `hello' definida un poco más arriba? +;; Recibía un parámetro: `name'. Así que `mapcar' llama a `hello' con cada +;; elemento de `list-of-names' como parámetro de `hello'. + +;; Ahora ordenaremos un poco lo que tenemos en el buffer: + +(defun replace-hello-by-bonjour () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (search-forward "Hello") + (replace-match "Bonjour")) + (other-window 1)) + +;; (goto-char (point-min)) mueve el cursor al principio del buffer. +;; (search-forward "Hello") busca un string "Hello". +;; (while x y) evalua la/s sexpresion/es y mientras que x devuelva +;; alguna cosa. +;; En el momento que x devuelva `nil' (es decir nada), sale del +;; bucle `while'. + +(replace-hello-by-bonjour) + +;; Observamos que todas las veces que teníamos la palabra "Hello" en el buffer *test* +;; han sido reemplazadas por "Bonjour". + +;; Y además, hemos obtenido un error: "Search failed: Hello". +;; +;; Para evitar este error, hay que decirle a `search-forward' si debería dejar de +;; buscar en el buffer en algún momento y si debería fallar sin quejarse cuando +;; no encuentra nada. + +;; (search-forward "Hello" nil t) justo hace eso: + +;; El argumento `nil' significa que la busqueda no está ligada a ninguna posición. +;; Y el argumento `t' le pide que no diga nada si no encuentra el string. + +;; Usaremos esta sexpresión en la función siguiente, la cual ya +;; no muestra ningún error: + +(defun hello-to-bonjour () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + ;; Say hello to names in `list-of-names' + (mapcar 'hello list-of-names) + (goto-char (point-min)) + ;; Replace "Hello" by "Bonjour" + (while (search-forward "Hello" nil t) + (replace-match "Bonjour")) + (other-window 1)) + +(hello-to-bonjour) + +;; Añadamos algo de color a los nombres: + +(defun boldify-names () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (re-search-forward "Bonjour \\(.+\\)!" nil t) + (add-text-properties (match-beginning 1) + (match-end 1) + (list 'face 'bold))) + (other-window 1)) + +;; Esta función nos presenta `re-search-forward': en vez de +;; buscar el string "Bonjour" exacto, se busca por un patrón +;; usando una "expresión regular" (lo cual se muestra abreviado +;; en el prefijo "re-" del inglés "Regular Expression"). + +;; La expresión regular a utilizar es "Bonjour \\(.+\\)!" y se traduce como: +;; el string "Bonjour ", seguido de +;; un grupo de | representado por \\( ... \\) +;; cualquier caracter | representado por . +;; al menos una vez | representado por + +;; y el string "!". + +;; ¿Preparado? ¡Probemoslo! + +(boldify-names) + +;; `add-text-properties' añade propiedades al texto, como una fuente. + +;; ¡Hale! ¡Ya lo tenemos! ¡Feliz hacking! + +;; Si quieres saber más sobre una función o una variable: +;; +;; C-h v la-variable RET +;; C-h f la-funcion RET +;; +;; Si quieres leer el manual de Emacs Lisp desde dentro de Emacs: +;; +;; C-h i m elisp RET +;; +;; Para leer una introducción en linea de Emacs Lisp: +;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html + +;; Me gustaría agradecer a las siguientes personas su feedback y sugerencias: +;; - Wes Hardaker +;; - notbob +;; - Kevin Montuori +;; - Arne Babenhauserheide +;; - Alan Schmitt +;; - LinXitoW +;; - Aaron Meurer +``` -- cgit v1.2.3 From c10f6a688865b667aa2936d7bd748122560f5c91 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 5 Aug 2013 08:33:24 -0700 Subject: Changed c-es to utf8 --- es-es/c-es.html.markdown | 168 +++++++++++++++++++++++------------------------ 1 file changed, 84 insertions(+), 84 deletions(-) diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown index 72902dd2..2e7cf8be 100644 --- a/es-es/c-es.html.markdown +++ b/es-es/c-es.html.markdown @@ -4,23 +4,23 @@ filename: learnc.c contributors: - ["Adam Bard", "http://adambard.com/"] translators: - - ["Francisco Garca", "http://flaskbreaker.tumblr.com/"] + - ["Francisco García", "http://flaskbreaker.tumblr.com/"] lang: es-es --- -Ah!, C. Aun hoy en da sigue siendo el lenguaje por excelencia de la -computacin moderna de alto rendimiento. +¡Ah!, C. Aun hoy en día sigue siendo el lenguaje por excelencia de la +computación moderna de alto rendimiento. -C es el lenguaje de ms bajo nivel que la mayora de los programadores -llegarn a usar, pero lo compensa de sobra con pura velocidad. Solo -ten en cuenta el manejo manual de memoria y te llevar tan lejos como +C es el lenguaje de más bajo nivel que la mayoría de los programadores +llegarán a usar, pero lo compensa de sobra con pura velocidad. Solo +ten en cuenta el manejo manual de memoria y te llevará tan lejos como necesites. ```c -// Los comentarios de una sola lnea comienzan con // +// Los comentarios de una sola línea comienzan con // /* -Los comentarios multilnea tienen este aspecto. +Los comentarios multilínea tienen este aspecto. */ // Importa cabeceras con #include @@ -33,12 +33,12 @@ Los comentarios multil void function_1(); void function_2(); -// El punto de entrada de tu programa es una funcin llamada main con +// El punto de entrada de tu programa es una función llamada main con // retorno de tipo entero (integer). int main() { // Muestra la salida usando printf, para el "formato print" -// %d es un entero, \n es una nueva lnea +// %d es un entero, \n es una nueva línea printf("%d\n", 0); // => Muestra 0 // Todas las sentencias deben terminar con un punto y coma. @@ -46,9 +46,9 @@ printf("%d\n", 0); // => Muestra 0 // Tipos /////////////////////////////////////// -// Tienes que declarar una variable antes de usarla. La declaracin de una +// Tienes que declarar una variable antes de usarla. La declaración de una // variable necesites que especifiques su tipo; el tipo de una variable -// determina su tamao en bytes. +// determina su tamaño en bytes. // 'ints' (enteros) son normalmente de 4 bytes int x_int = 0; @@ -65,53 +65,53 @@ char y_char = 'y'; // Los caracteres literales se entrecomillan con '' long x_long = 0; long long x_long_long = 0; -// 'floats' son normalmente nmeros de coma flotante de 32 bits +// 'floats' son normalmente números de coma flotante de 32 bits float x_float = 0.0; -// 'doubles' son normalmente nmeros de coma flotante de 64 bits +// 'doubles' son normalmente números de coma flotante de 64 bits double x_double = 0.0; // Todos los tipos enteros pueden ser 'unsigned'. Esto significa que no -// pueden ser negativos, pero el valor mximo de una variable 'unsigned' -// es mayor que el de una no 'unsigned' del mismo tamao. +// pueden ser negativos, pero el valor máximo de una variable 'unsigned' +// es mayor que el de una no 'unsigned' del mismo tamaño. unsigned char ux_char; unsigned short ux_short; unsigned int ux_int; unsigned long long ux_long_long; -// Todos menos 'char', que es siempre de 1 byte, varan el tamao -// dependiendo de tu mquina. sizeof(T) te dice el tamao de una variable -// de tipo T en bytes por lo que podemos expresar el tamao de estos tipos +// Todos menos 'char', que es siempre de 1 byte, varían el tamaño +// dependiendo de tu máquina. sizeof(T) te dice el tamaño de una variable +// de tipo T en bytes por lo que podemos expresar el tamaño de estos tipos // portatilmente. // Por ejemplo, -printf("%lu\n", sizeof(int)); // => 4 (en mquinas con 'words' de 4 bytes) +printf("%lu\n", sizeof(int)); // => 4 (en máquinas con 'words' de 4 bytes) -// Los arrays deben ser inicializados con un tamao concreto. +// Los arrays deben ser inicializados con un tamaño concreto. char my_char_array[20]; // Este array ocupa 1 * 20 = 20 bytes int my_int_array[20]; // Este array ocupa 4 * 20 = 80 bytes // (suponiendo que tenemos 'words' de 4-byte) -// Puedes inicializar un array a 0 as: +// Puedes inicializar un array a 0 así: char my_array[20] = {0}; -// Indexar un array es como en otros lenguajes -o, ms bien, otros +// Indexar un array es como en otros lenguajes -o, más bien, otros // lenguajes son como C- my_array[0]; // => 0 -// Los arrays varan; son slo memoria! +// Los arrays varían; ¡son sólo memoria! my_array[1] = 2; printf("%d\n", my_array[1]); // => 2 -// Las cadenas (strings) son slo arrays de 'chars' (caracteres) -// terminados en un byte NUL (0x00), representado en las cadenas como el carcter especial '\0'. -// (No tenemos porqu aadir el byte nulo en cadenas literales; el -// compilador lo aade al final por nosotros.) +// Las cadenas (strings) son sólo arrays de 'chars' (caracteres) +// terminados en un byte NUL (0x00), representado en las cadenas como el carácter especial '\0'. +// (No tenemos porqué añadir el byte nulo en cadenas literales; el +// compilador lo añade al final por nosotros.) char a_string[20] = "Esto es una cadena"; printf("%s\n", a_string); // %s se sutituye por una cadena. /* -Te habrs dado cuenta de que a_string es solo de 18 caracteres. +Te habrás dado cuenta de que a_string es solo de 18 caracteres. El 'char' #19 es el byte nulo. El 'char' #20 es de valor indefinido. */ @@ -122,22 +122,22 @@ printf("%d\n", a_string[18]); // => 0 // Operadores /////////////////////////////////////// -int i1 = 1, i2 = 2; // Forma corta de declaracin mltiple +int i1 = 1, i2 = 2; // Forma corta de declaración múltiple float f1 = 1.0, f2 = 2.0; -// La aritmtica es sencilla +// La aritmética es sencilla i1 + i2; // => 3 i2 - i1; // => 1 i2 * i1; // => 2 i1 / i2; // => 0 (0.5, pero es truncado tras el 0) -f1 / f2; // => 0.5, ms o menos psilon -// Mdulo est tambin +f1 / f2; // => 0.5, más o menos épsilon +// Módulo está también 11 % 3; // => 2 -// Los operadores de comparacin te resultaran familiares, pero no hay +// Los operadores de comparación te resultaran familiares, pero no hay // booleanos en C. Usamos enteros (ints) en su lugar. 0 es falso, -// cualquier otra cosa es verdadero. (Los operadores de comparacin +// cualquier otra cosa es verdadero. (Los operadores de comparación // siempre devuelven 0 o 1) 3 == 2; // => 0 (Falso) 3 != 2; // => 1 (Verdadero) @@ -146,16 +146,16 @@ f1 / f2; // => 0.5, m 2 <= 2; // => 1 2 >= 2; // => 1 -// La lgica funiona en enteros -!3; // => 0 (not lgico) +// La lógica funiona en enteros +!3; // => 0 (not lógico) !0; // => 1 -1 && 1; // => 1 (and lgico) +1 && 1; // => 1 (and lógico) 0 && 1; // => 0 -0 || 1; // => 1 (or lgico) +0 || 1; // => 1 (or lógico) 0 || 0; // => 0 -// Operadores de bits! -~0x0F; // => 0xF0 (Negacin) +// ¡Operadores de bits! +~0x0F; // => 0xF0 (Negación) 0x0F & 0xF0; // => 0x00 (AND) 0x0F | 0xF0; // => 0xFF (OR) 0x04 ^ 0x0F; // => 0x0B (XOR) @@ -177,7 +177,7 @@ if (0) { // Mientras el bucle exista int ii = 0; while (ii < 10) { - printf("%d, ", ii++); // ii++ incrementa ii en uno, despus de usar su valor. + printf("%d, ", ii++); // ii++ incrementa ii en uno, después de usar su valor. } // => muestra "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); @@ -190,7 +190,7 @@ do { printf("\n"); -// Bucles 'for' tambin +// Bucles 'for' también int jj; for (jj=0; jj < 10; jj++) { printf("%d, ", jj); @@ -207,13 +207,13 @@ printf("\n"); int x_hex = 0x01; // Puedes asignar hexadecimales a variables -// El cambio de tipos intentar mantener sus valores numricos +// El cambio de tipos intentará mantener sus valores numéricos printf("%d\n", x_hex); // => Muestra 1 printf("%d\n", (short) x_hex); // => Muestra 1 printf("%d\n", (char) x_hex); // => Muestra 1 // Los tipos se desbordan sin aviso -printf("%d\n", (char) 257); // => 1 (El valor mximo de un 'char' es 255) +printf("%d\n", (char) 257); // => 1 (El valor máximo de un 'char' es 255) // Los tipos enteros puden cambiarse a tipos de coma flotante, y viceversa printf("%f\n", (float)100); // %f se sustituye por un 'float' @@ -224,28 +224,28 @@ printf("%d\n", (char)100.0); // Punteros /////////////////////////////////////// -// Un puntero es una variable declarada para almacenar una direccin de -// memoria. Su declaracin adems nos dir el tipo de dato al que apunta. -// Puedes obtener la direccin de memoria de tus variables, y despus +// Un puntero es una variable declarada para almacenar una dirección de +// memoria. Su declaración además nos dirá el tipo de dato al que apunta. +// Puedes obtener la dirección de memoria de tus variables, y después // enlazarlas con ellos. int x = 0; -printf("%p\n", &x); // Usa & para obtener la direccin de una variable. +printf("%p\n", &x); // Usa & para obtener la dirección de una variable. // (%p se sustituye por un puntero) -// => Muestra alguna direccin de memoria; +// => Muestra alguna dirección de memoria; -// Los tipos de puntero terminan con * en su declaracin +// Los tipos de puntero terminan con * en su declaración int* px; // px es un puntero a un 'int' -px = &x; // Almacena la direccin de x en px -printf("%p\n", px); // => Muestra alguna direccin de memoria +px = &x; // Almacena la dirección de x en px +printf("%p\n", px); // => Muestra alguna dirección de memoria -// Para obtener el valor de la direccin a la que apunta un puntero, pon +// Para obtener el valor de la dirección a la que apunta un puntero, pon // * delante para desreferenciarle. -printf("%d\n", *px); // => Muestra 0, el valor de x y de la direccin a la +printf("%d\n", *px); // => Muestra 0, el valor de x y de la dirección a la // que apunta px -// Tambin puedes cambiar el valor al que est apuntando el puntero. -// Tenemos que meter la desreferencia entre parntesis porque ++ tiene +// También puedes cambiar el valor al que está apuntando el puntero. +// Tenemos que meter la desreferencia entre paréntesis porque ++ tiene // prioridad frente a *. (*px)++; // Incrementa el valor al que apunta px en 1 printf("%d\n", *px); // => Muestra 1 @@ -267,24 +267,24 @@ int* x_ptr = x_array; printf("%d\n", *(x_ptr)); // => Muestra 20 printf("%d\n", x_array[0]); // => Muestra 20 -// Los punteros aumentan y disminuyen en funcin de su tipo. +// Los punteros aumentan y disminuyen en función de su tipo. printf("%d\n", *(x_ptr + 1)); // => Muestra 19 printf("%d\n", x_array[1]); // => Muestra 19 -// Puedes tambin asigner dinamicamente bloques contiguos de memoria con -// la funcin malloc de la librera estndard, que toma un entero como -// argumento representando el nmero de bytes a asignar de la pila. +// Puedes también asigner dinamicamente bloques contiguos de memoria con +// la función malloc de la librería estándard, que toma un entero como +// argumento representando el número de bytes a asignar de la pila. int* my_ptr = (int*) malloc(sizeof(int) * 20); for (xx=0; xx<20; xx++) { - *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx funcionara tambin aqu + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx funcionaría también aquí } // Inicializa la memoria a 20, 19, 18, 17... 2, 1 (como 'ints') -// Desreferenciando la memoria que no has asignado te dar resultados +// Desreferenciando la memoria que no has asignado te dará resultados // impredecibles printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? -// Cuando hallas acabado con el bloque de memora malloc, necesitas -// liberarlo o sino nadie ms podr usarlo hasta que tu programa se cierre +// Cuando hallas acabado con el bloque de memoría malloc, necesitas +// liberarlo o sino nadie más podrá usarlo hasta que tu programa se cierre free(my_ptr); // Las cadenas pueden ser 'arrays' de chars, pero normalmente se @@ -294,13 +294,13 @@ char* my_str = "This is my very own string"; printf("%c\n", *my_str); // => 'T' function_1(); -} // fin de la funcin main +} // fin de la función main /////////////////////////////////////// // Funciones /////////////////////////////////////// -// Sintexis de la declaracin de funciones: +// Sintexis de la declaración de funciones: // () int add_two_ints(int x1, int x2){ @@ -315,13 +315,13 @@ valores. Ejemplo: invertidor de cadenas in-situ */ -// Una funcin 'void' no retorna valor +// Una función 'void' no retorna valor void str_reverse(char* str_in){ char tmp; - int ii=0, len = strlen(str_in); // Strlen es parte de la librera - for(ii=0; ii ".abeurp anu se otsE" */ /////////////////////////////////////// -// Definicin de tipos y estructuras +// Definición de tipos y estructuras /////////////////////////////////////// // Los 'Typedefs' pueden ser utilizados para crear alias de tipos. typedef int my_type; my_type my_type_var = 0; -// Las estructuras son slo grupos de datos. +// Las estructuras son sólo grupos de datos. struct rectangle { int width; int height; @@ -365,7 +365,7 @@ void function_1(){ my_rec_ptr->height = 10; // Lo mismo que (*my_rec_ptr).height = 10; } -// Puedes aplicar un 'typedef' a una estructura por convenienca. +// Puedes aplicar un 'typedef' a una estructura por conveniencía. typedef struct rectangle rect; int area(rect r){ @@ -376,26 +376,26 @@ int area(rect r){ // Punteros a Funciones /////////////////////////////////////// /* -En tiempo de ejecucin, las funciones se localizan en unas direcciones de +En tiempo de ejecución, las funciones se localizan en unas direcciones de memoria concretas. Los punteros a funciones son como cualquier otro -puntero (almacenan una direccin de memoria), pero pueden ser usados para +puntero (almacenan una dirección de memoria), pero pueden ser usados para utilizar funciones directamente, o para pasar 'handlers' (o funciones 'callback') por todos lados. -Sin embargo, la sintaxis de definicin parecera confusa al principio. +Sin embargo, la sintaxis de definición parecera confusa al principio. Ejemplo: usar str_reverse desde un puntero */ void str_reverse_through_pointer(char * str_in) { - // Define un puntero a una funcin, llamado f. - void (*f)(char *); // La armadura debe coincidir exactamente con al funcin objetivo. - f = &str_reverse; // Assigna la direccin de la funcin (determinado en tiempo de ejecuin) - (*f)(str_in); // Llamando la funcin desde el puntero - // f(str_in); // Esta es una alternativa para llamarla pero con una sintaxis igual de vlida. + // Define un puntero a una función, llamado f. + void (*f)(char *); // La armadura debe coincidir exactamente con al función objetivo. + f = &str_reverse; // Assigna la dirección de la función (determinado en tiempo de ejecuión) + (*f)(str_in); // Llamando la función desde el puntero + // f(str_in); // Esta es una alternativa para llamarla pero con una sintaxis igual de válida. } /* -Tanto tiempo como las armaduras de las funciones coincidan, podrs asignar -cualquier funcin al mismo puntero. +Tanto tiempo como las armaduras de las funciones coincidan, podrás asignar +cualquier función al mismo puntero. Los punteros a funciones son normalmente envueltos en 'typedef' para simplificar su legibilidad, como sigue: */ -- cgit v1.2.3 From 54f682e5d2932121139350381cc23526b4c8002e Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 5 Aug 2013 08:38:09 -0700 Subject: Line lenght edits for c-es --- es-es/c-es.html.markdown | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown index 2e7cf8be..0624f4be 100644 --- a/es-es/c-es.html.markdown +++ b/es-es/c-es.html.markdown @@ -104,9 +104,10 @@ my_array[1] = 2; printf("%d\n", my_array[1]); // => 2 // Las cadenas (strings) son sólo arrays de 'chars' (caracteres) -// terminados en un byte NUL (0x00), representado en las cadenas como el carácter especial '\0'. +// terminados en un byte NUL (0x00), representado en las cadenas como el +// carácter especial '\0'. // (No tenemos porqué añadir el byte nulo en cadenas literales; el -// compilador lo añade al final por nosotros.) +// compilador lo añade al final por nosotros.) char a_string[20] = "Esto es una cadena"; printf("%s\n", a_string); // %s se sutituye por una cadena. @@ -387,10 +388,17 @@ Ejemplo: usar str_reverse desde un puntero */ void str_reverse_through_pointer(char * str_in) { // Define un puntero a una función, llamado f. - void (*f)(char *); // La armadura debe coincidir exactamente con al función objetivo. - f = &str_reverse; // Assigna la dirección de la función (determinado en tiempo de ejecuión) - (*f)(str_in); // Llamando la función desde el puntero - // f(str_in); // Esta es una alternativa para llamarla pero con una sintaxis igual de válida. + void (*f)(char *); + // La armadura debe coincidir exactamente con al función objetivo. + + // Assigna la dirección de la función (determinado en tiempo de ejecuión) + f = &str_reverse; + + // Llamando la función desde el puntero + (*f)(str_in); + + // Esta es una alternativa para llamarla pero con una sintaxis igual de válida. + // f(str_in); } /* -- cgit v1.2.3 From e037df9c91b303ce21847dd5e8fa3bf8b9376aed Mon Sep 17 00:00:00 2001 From: Trent Ogren Date: Mon, 5 Aug 2013 13:06:21 -0500 Subject: C: Signed/unsigned clarification --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index b5286f70..d243b19d 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -70,7 +70,7 @@ double x_double = 0.0; // Integral types may be unsigned. This means they can't be negative, but // the maximum value of an unsigned variable is greater than the maximum -// value of the same size. +// signed value of the same size. unsigned char ux_char; unsigned short ux_short; unsigned int ux_int; -- cgit v1.2.3 From 56f6ad5a0327aeb98b352fe861cf93d258251102 Mon Sep 17 00:00:00 2001 From: Trent Ogren Date: Mon, 5 Aug 2013 13:06:21 -0500 Subject: C: Signed/unsigned clarification --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index b5286f70..d243b19d 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -70,7 +70,7 @@ double x_double = 0.0; // Integral types may be unsigned. This means they can't be negative, but // the maximum value of an unsigned variable is greater than the maximum -// value of the same size. +// signed value of the same size. unsigned char ux_char; unsigned short ux_short; unsigned int ux_int; -- cgit v1.2.3 From d2f0d8222e9e5c4c17f6ccde096df3c4d02d43af Mon Sep 17 00:00:00 2001 From: ldinh Date: Mon, 5 Aug 2013 17:42:38 -0700 Subject: Fix typo --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index e7ee6fbd..1a54e633 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -232,7 +232,7 @@ filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 # Sets store ... well sets empty_set = set() # Initialize a set with a bunch of values -some_set = set([1,2,2,3,4]) # filled_set is now set([1, 2, 3, 4]) +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} -- cgit v1.2.3 From 5617b2804895e096801c2c9bb5f1386d18095276 Mon Sep 17 00:00:00 2001 From: Louie Dinh Date: Mon, 5 Aug 2013 17:54:50 -0700 Subject: Expand on References. Add Books. --- python.html.markdown | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 1a54e633..298b7bb7 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -470,12 +470,19 @@ dir(math) ``` -## Further Reading +## Ready For More? -Still up for more? Try: +### Free Online * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) * [The Official Docs](http://docs.python.org/2.6/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) + +### 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 dae7c446926b338a05c8dfcfc68e64acf5b80128 Mon Sep 17 00:00:00 2001 From: Guillermo Vaya Date: Tue, 6 Aug 2013 10:01:42 +0200 Subject: added contact info and norvig's text translated link --- es-es/elisp-es.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/es-es/elisp-es.html.markdown b/es-es/elisp-es.html.markdown index 8c220109..431ea794 100644 --- a/es-es/elisp-es.html.markdown +++ b/es-es/elisp-es.html.markdown @@ -12,10 +12,11 @@ filename: learn-emacs-lisp.el ;; Introduccion a Emacs Lisp en 15 minutos (v0.2d) ;; ;; Autor: Bastien / @bzg2 / http://bzg.fr -;; Traducción: Guillermo Vayá +;; Traducción: Guillermo Vayá / @Driadan / http://willyfrog.es ;; ;; Antes de nada, lee este texto de Peter Norvig: -;; http://norvig.com/21-days.html +;; Traducido: http://loro.sourceforge.net/notes/21-dias.html +;; Original: http://norvig.com/21-days.html ;; ;; Ahora instala GNU Emacs 24.3: ;; -- cgit v1.2.3 From 80c71ef1c849d4294e13c3dbfce6fad66a79e99a Mon Sep 17 00:00:00 2001 From: greybird Date: Wed, 7 Aug 2013 11:20:20 +0400 Subject: Ruby. Difference between class instance variables and class variables --- ruby.html.markdown | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index a3bcbbd5..99817982 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -325,4 +325,50 @@ dwight.name #=> "Dwight K. Schrute" # Call the class method Human.say("Hi") #=> "Hi" +# Class also is object in ruby. So class can have instance variables. +# Class variable is shared among the class and all of its descendants. + +# base class +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# derived class +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# Class instance variable is not shared by the class's descendants. + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +Human.bar # 0 +Doctor.bar # nil + ``` -- cgit v1.2.3 From 0dff3a936cc7ca9e5a9574a889fcf1d4180efcab Mon Sep 17 00:00:00 2001 From: cssmagic Date: Wed, 7 Aug 2013 22:48:11 +0800 Subject: Fix tiny typos. --- python.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 298b7bb7..a32db51a 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -67,7 +67,7 @@ not False #=> True 2 <= 2 #=> True 2 >= 2 #=> True -# Comparisons can be chained ! +# Comparisons can be chained! 1 < 2 < 3 #=> True 2 < 3 < 2 #=> False @@ -214,7 +214,7 @@ filled_dict.values() #=> [3, 2, 1] "one" in filled_dict #=> True 1 in filled_dict #=> False - # Looking up a non-existing key is a KeyError +# Looking up a non-existing key is a KeyError filled_dict["four"] # KeyError # Use get method to avoid the KeyError @@ -263,7 +263,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6} some_var = 5 # Here is an if statement. Indentation is significant in python! -# prints "some var is smaller than 10" +# 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. @@ -394,7 +394,7 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] # We subclass from object to get a class. class Human(object): - # A class attribute. It is shared by all instances of this class + # A class attribute. It is shared by all instances of this class species = "H. sapiens" # Basic initializer -- cgit v1.2.3 From bd2a852ae827a979f2170f90d6bd7bca4ef7c084 Mon Sep 17 00:00:00 2001 From: Eran Medan Date: Wed, 7 Aug 2013 17:31:49 -0400 Subject: fixed some broken / missing markdown links and added a resource --- scala.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index fef09404..b1b3ecbf 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -408,9 +408,11 @@ for(line <- Source.fromPath("myfile.txt").getLines()) [Scala for the impatient](http://horstmann.com/scala/) -[Twitter Scala school(http://twitter.github.io/scala_school/) +[Twitter Scala school](http://twitter.github.io/scala_school/) -[The scala documentation] +[The scala documentation](http://docs.scala-lang.org/) + +[Try Scala in your browser](http://scalatutorials.com/tour/) Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From 6db6606d2e5e7a22e30dd004bf67dc399f5627fc Mon Sep 17 00:00:00 2001 From: Camilo Garrido Date: Wed, 7 Aug 2013 22:54:20 -0400 Subject: Add python-es file --- es-es/python-es.html.markdown | 490 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 490 insertions(+) create mode 100644 es-es/python-es.html.markdown diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown new file mode 100644 index 00000000..1ec8d7e4 --- /dev/null +++ b/es-es/python-es.html.markdown @@ -0,0 +1,490 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Camilo Garrido", "http://www.twitter.com/hirohope"] +lang: es-es +filename: learnpython.py +--- + +Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno +de los lenguajes más populares en existencia. Me enamoré de Python por su claridad sintáctica. +Es básicamente pseudocódigo ejecutable. + +¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google] + +Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser aplicable a Python 2.x. ¡Pronto un recorrido por Python 3! + +```python +# Comentarios de una línea comienzan con una almohadilla (o signo gato) +""" Strings multilinea pueden escribirse + usando tres "'s, y comunmente son usados + como comentarios. +""" + +#################################################### +## 1. Tipos de datos primitivos y operadores. +#################################################### + +# Tienes números +3 #=> 3 + +# Matemática es lo que esperarías +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# La división es un poco complicada. Es división entera y toma la parte entera +# de los resultados automáticamente. +5 / 2 #=> 2 + +# Para arreglar la división necesitamos aprender sobre 'floats' +# (números de coma flotante). +2.0 # Esto es un 'float' +11.0 / 4.0 #=> 2.75 ahhh...mucho mejor + +# Refuerza la precedencia con paréntesis +(1 + 3) * 2 #=> 8 + +# Valores 'boolean' (booleanos) son primitivos +True +False + +# Niega con 'not' +not True #=> False +not False #=> True + +# Igualdad es == +1 == 1 #=> True +2 == 1 #=> False + +# Desigualdad es != +1 != 1 #=> False +2 != 1 #=> True + +# Más comparaciones +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# ¡Las comparaciones pueden ser concatenadas! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings se crean con " o ' +"Esto es un string." +'Esto también es un string' + +# ¡Strings también pueden ser sumados! +"Hola " + "mundo!" #=> "Hola mundo!" + +# Un string puede ser tratado como una lista de caracteres +"Esto es un string"[0] #=> 'E' + +# % pueden ser usados para formatear strings, como esto: +"%s pueden ser %s" % ("strings", "interpolados") + +# Una forma más reciente de formatear strings es el método 'format'. +# Este método es la forma preferida +"{0} pueden ser {1}".format("strings", "formateados") +# Puedes usar palabras claves si no quieres contar. +"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") + +# None es un objeto +None #=> None + +# No uses el símbolo de igualdad `==` para comparar objetos con None +# Usa `is` en lugar de +"etc" is None #=> False +None is None #=> True + +# El operador 'is' prueba la identidad del objeto. Esto no es +# muy útil cuando se trata de datos primitivos, pero es +# muy útil cuando se trata de objetos. + +# None, 0, y strings/listas vacíos(as) todas se evalúan como False. +# Todos los otros valores son True +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Variables y Colecciones +#################################################### + +# Imprimir es muy fácil +print "Soy Python. ¡Encantado de conocerte!" + + +# No hay necesidad de declarar las variables antes de asignarlas. +una_variable = 5 # La convención es usar guiones_bajos_con_minúsculas +una_variable #=> 5 + +# Acceder a variables no asignadas previamente es una excepción. +# Ve Control de Flujo para aprender más sobre el manejo de excepciones. +otra_variable # Levanta un error de nombre + +# 'if' puede ser usado como una expresión +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listas sobre secuencias +lista = [] +# Puedes empezar con una lista prellenada +otra_lista = [4, 5, 6] + +# Añadir cosas al final de una lista con 'append' +lista.append(1) #lista ahora es [1] +lista.append(2) #lista ahora es [1, 2] +lista.append(4) #lista ahora es [1, 2, 4] +lista.append(3) #lista ahora es [1, 2, 4, 3] +# Remueve del final de la lista con 'pop' +lista.pop() #=> 3 y lista ahora es [1, 2, 4] +# Pongámoslo de vuelta +lista.append(3) # Nuevamente lista ahora es [1, 2, 4, 3]. + +# Accede a una lista como lo harías con cualquier arreglo +lista[0] #=> 1 +# Mira el último elemento +lista[-1] #=> 3 + +# Mirar fuera de los límites es un error 'IndexError' +lista[4] # Levanta la excepción IndexError + +# Puedes mirar por rango con la sintáxis de trozo. +# (Es un rango cerrado/abierto para ustedes los matemáticos.) +lista[1:3] #=> [2, 4] +# Omite el inicio +lista[2:] #=> [4, 3] +# Omite el final +lista[:3] #=> [1, 2, 4] + +# Remueve elementos arbitrarios de una lista con 'del' +del lista[2] # lista ahora es [1, 2, 3] + +# Puedes sumar listas +lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan + +# Concatenar listas con 'extend' +lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] + +# Chequea la existencia en una lista con +1 in lista #=> True + +# Examina el largo de una lista con 'len' +len(lista) #=> 6 + + +# Tuplas son como listas pero son inmutables. +tupla = (1, 2, 3) +tupla[0] #=> 1 +tupla[0] = 3 # Levanta un error TypeError + +# También puedes hacer todas esas cosas que haces con listas +len(tupla) #=> 3 +tupla + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tupla[:2] #=> (1, 2) +2 in tupla #=> True + +# Puedes desempacar tuplas (o listas) en variables +a, b, c = (1, 2, 3) # a ahora es 1, b ahora es 2 y c ahora es 3 +# Tuplas son creadas por defecto si omites los paréntesis +d, e, f = 4, 5, 6 +# Ahora mira que fácil es intercambiar dos valores +e, d = d, e # d ahora es 5 y e ahora es 4 + + +# Diccionarios almacenan mapeos +dicc_vacio = {} +# Aquí está un diccionario prellenado +dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} + +# Busca valores con [] +dicc_lleno["uno"] #=> 1 + +# Obtén todas las llaves como una lista +dicc_lleno.keys() #=> ["tres", "dos", "uno"] +# Nota - El orden de las llaves del diccionario no está garantizada. +# Tus resultados podrían no ser los mismos del ejemplo. + +# Obtén todos los valores como una lista +dicc_lleno.values() #=> [3, 2, 1] +# Nota - Lo mismo que con las llaves, no se garantiza el orden. + +# Chequea la existencia de una llave en el diccionario con 'in' +"uno" in dicc_lleno #=> True +1 in dicc_lleno #=> False + +# Buscar una llave inexistente deriva en KeyError +dicc_lleno["cuatro"] # KeyError + +# Usa el método 'get' para evitar la excepción KeyError +dicc_lleno.get("uno") #=> 1 +dicc_lleno.get("cuatro") #=> None +# El método 'get' soporta un argumento por defecto cuando el valor no existe. +dicc_lleno.get("uno", 4) #=> 1 +dicc_lleno.get("cuatro", 4) #=> 4 + +# El método 'setdefault' es una manera segura de añadir nuevos pares +# llave-valor en un diccionario +dicc_lleno.setdefault("cinco", 5) #dicc_lleno["cinco"] es puesto con valor 5 +dicc_lleno.setdefault("cinco", 6) #dicc_lleno["cinco"] todavía es 5 + + +# Sets (conjuntos) almacenan ... bueno, conjuntos +conjunto_vacio = set() +# Inicializar un conjunto con montón de valores +un_conjunto = set([1,2,2,3,4]) # un_conjunto ahora es set([1, 2, 3, 4]) + +# Desde Python 2.7, {} puede ser usado para declarar un conjunto +conjunto_lleno = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Añade más valores a un conjunto +conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5} + +# Haz intersección de conjuntos con & +otro_conjunto = {3, 4, 5, 6} +conjunto_lleno & otro_conjunto #=> {3, 4, 5} + +# Haz unión de conjuntos con | +conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} + +# Haz diferencia de conjuntos con - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# CHequea la existencia en un conjunto con 'in' +2 in conjunto_lleno #=> True +10 in conjunto_lleno #=> False + + +#################################################### +## 3. Control de Flujo +#################################################### + +# Hagamos sólo una variable +una_variable = 5 + +# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! +# imprime "una_variable es menor que 10" +if una_variable > 10: + print "una_variable es completamente mas grande que 10." +elif una_variable < 10: # Este condición 'elif' es opcional. + print "una_variable es mas chica que 10." +else: # Esto también es opcional. + print "una_variable es de hecho 10." + + +""" +For itera sobre listas +imprime: + perro es un mamifero + gato es un mamifero + raton es un mamifero +""" +for animal in ["perro", "gato", "raton"]: + # Puedes usar % para interpolar strings formateados + print "%s es un mamifero" % animal + +""" +`range(número)` retorna una lista de números +desde cero hasta el número dado +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While itera hasta que una condición no se cumple. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # versión corta de x = x + 1 + +# Maneja excepciones con un bloque try/except + +# Funciona desde Python 2.6 en adelante: +try: + # Usa raise para levantar un error + raise IndexError("Este es un error de indice") +except IndexError as e: + pass # Pass no hace nada. Usualmente harias alguna recuperacion aqui. + + +#################################################### +## 4. Funciones +#################################################### + +# Usa 'def' para crear nuevas funciones +def add(x, y): + print "x es %s y y es %s" % (x, y) + return x + y # Retorna valores con una la declaración return + +# Llamando funciones con parámetros +add(5, 6) #=> imprime "x es 5 y y es 6" y retorna 11 + +# Otra forma de llamar funciones es con argumentos de palabras claves +add(y=6, x=5) # Argumentos de palabra clave pueden ir en cualquier orden. + +# Puedes definir funciones que tomen un número variable de argumentos +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Puedes definir funciones que toman un número variable de argumentos +# de palabras claves +def keyword_args(**kwargs): + return kwargs + +# Llamémosla para ver que sucede +keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"} + +# Puedes hacer ambas a la vez si quieres +def todos_los_argumentos(*args, **kwargs): + print args + print kwargs +""" +todos_los_argumentos(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# ¡Cuando llames funciones, puedes hacer lo opuesto a varargs/kwargs! +# Usa * para expandir tuplas y usa ** para expandir argumentos de palabras claves. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +todos_los_argumentos(*args) # es equivalente a foo(1, 2, 3, 4) +todos_los_argumentos(**kwargs) # es equivalente a foo(a=3, b=4) +todos_los_argumentos(*args, **kwargs) # es equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Python tiene funciones de primera clase +def crear_suma(x): + def suma(y): + return x + y + return suma + +sumar_10 = crear_suma(10) +sumar_10(3) #=> 13 + +# También hay funciones anónimas +(lambda x: x > 2)(3) #=> True + +# Hay funciones integradas de orden superior +map(sumar_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Podemos usar listas por comprensión para mapeos y filtros agradables +[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. Clases +#################################################### + +# Heredamos de object para obtener una clase. +class Humano(object): + + # Un atributo de clase es compartido por todas las instancias de esta clase + especie = "H. sapiens" + + # Constructor basico + def __init__(self, nombre): + # Asigna el argumento al atributo nombre de la instancia + self.nombre = nombre + + # Un metodo de instancia. Todos los metodos toman self como primer argumento + def decir(self, msg): + return "%s: %s" % (self.nombre, msg) + + # Un metodo de clase es compartido a través de todas las instancias + # Son llamados con la clase como primer argumento + @classmethod + def get_especie(cls): + return cls.especie + + # Un metodo estatico es llamado sin la clase o instancia como referencia + @staticmethod + def roncar(): + return "*roncar*" + + +# Instancia una clase +i = Humano(nombre="Ian") +print i.decir("hi") # imprime "Ian: hi" + +j = Humano("Joel") +print j.decir("hello") #imprime "Joel: hello" + +# Llama nuestro método de clase +i.get_especie() #=> "H. sapiens" + +# Cambia los atributos compartidos +Humano.especie = "H. neanderthalensis" +i.get_especie() #=> "H. neanderthalensis" +j.get_especie() #=> "H. neanderthalensis" + +# Llama al método estático +Humano.roncar() #=> "*roncar*" + + +#################################################### +## 6. Módulos +#################################################### + +# Puedes importar módulos +import math +print math.sqrt(16) #=> 4 + +# Puedes obtener funciones específicas desde un módulo +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Puedes importar todas las funciones de un módulo +# Precaución: Esto no es recomendable +from math import * + +# Puedes acortar los nombres de los módulos +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Los módulos de Python son sólo archivos ordinarios de Python. +# Puedes escribir tus propios módulos e importarlos. El nombre del módulo +# es el mismo del nombre del archivo. + +# Puedes encontrar que funciones y atributos definen un módulo. +import math +dir(math) + + +``` + +## ¿Listo para más? + +### Gratis y en línea + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Encuadernados + +* [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 10ffa5a7815ae40803ad409dd25170883291e498 Mon Sep 17 00:00:00 2001 From: michaelstewart Date: Thu, 8 Aug 2013 18:49:45 +1000 Subject: Added an apostrophe to Its --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index a32db51a..f0b74d08 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -6,7 +6,7 @@ filename: learnpython.py --- Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular -languages in existence. I fell in love with Python for its syntactic clarity. Its basically +languages in existence. I fell in love with Python for its syntactic clarity. It's basically executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] -- cgit v1.2.3 From 97a99b0ad55894631bcca03e086a2f23033c7c4b Mon Sep 17 00:00:00 2001 From: m5o Date: Thu, 8 Aug 2013 12:17:10 +0200 Subject: fix indentation by 2 spaces --- ruby.html.markdown | 60 +++++++++++++++++++++++++++--------------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 99817982..861a94ad 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -275,36 +275,36 @@ surround { puts 'hello world' } # Define a class with the class keyword class Human - # A class variable. It is shared by all instances of this class. - @@species = "H. sapiens" - - # Basic initializer - def initialize(name, age=0) - # Assign the argument to the "name" instance variable for the instance - @name = name - # If no age given, we will fall back to the default in the arguments list. - @age = age - end - - # Basic setter method - def name=(name) - @name = name - end - - # Basic getter method - def name - @name - end - - # A class method uses self to distinguish from instance methods. - # It can only be called on the class, not an instance. - def self.say(msg) - puts "#{msg}" - end - - def species - @@species - end + # A class variable. It is shared by all instances of this class. + @@species = "H. sapiens" + + # Basic initializer + def initialize(name, age=0) + # Assign the argument to the "name" instance variable for the instance + @name = name + # If no age given, we will fall back to the default in the arguments list. + @age = age + end + + # Basic setter method + def name=(name) + @name = name + end + + # Basic getter method + def name + @name + end + + # A class method uses self to distinguish from instance methods. + # It can only be called on the class, not an instance. + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end end -- cgit v1.2.3 From 191552ad49210a98e4b9e6620abf092755bf3d18 Mon Sep 17 00:00:00 2001 From: Camilo Garrido Date: Thu, 8 Aug 2013 12:25:00 -0400 Subject: Java file translated to spanish --- es-es/java-es.html.markdown | 410 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 410 insertions(+) create mode 100644 es-es/java-es.html.markdown diff --git a/es-es/java-es.html.markdown b/es-es/java-es.html.markdown new file mode 100644 index 00000000..90a43935 --- /dev/null +++ b/es-es/java-es.html.markdown @@ -0,0 +1,410 @@ +--- +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: + - ["Camilo Garrido", "http://www.twitter.com/hirohope"] +lang: es-es +filename: LearnJava.java +--- + +Java es un lenguage de programación de propósito general, concurrente, basado en clases y +orientado a objetos. +[Lee más aquí.](http://docs.oracle.com/javase/tutorial/java/index.html) + +```java +// Comentarios de una sóla línea comienzan con // +/* +Comentarios multilínea lucen así +*/ +/** +Comentarios JavaDoc lucen así. Suelen describir la clase o varios atributos +de una clase. +*/ + +// Importa la clase ArrayList dentro del paquete java.util +import java.util.ArrayList; +// Importa todas las clases dentro del paquete java.security +import java.security.*; + +// Cada archivo .java contiene una clase pública, con el mismo nombre del archivo. +public class AprendeJava { + + // Un programa debe tener un método 'main' como punto de entrada + public static void main (String[] args) { + + // Usa System.out.println para imprimir líneas + System.out.println("¡Hola mundo!"); + System.out.println( + "Entero (int): " + 10 + + " Doble (double): " + 3.14 + + " Booleano (boolean): " + true); + + // Para imprimir sin el salto de línea, usa System.out.print + System.out.print("Hola "); + System.out.print("Mundo"); + + + /////////////////////////////////////// + // Tipos & Variables + /////////////////////////////////////// + + // Declara una variable usando [ + // Byte - Entero complemento a dos con signo de 8-bit + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - Entero complemento a dos con signo de 16-bit + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - Entero complemento a dos con signo de 32-bit + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - Entero complemento a dos con signo de 64-bit + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L es usado para denotar que el valor de esta variable es del tipo Long; + // cualquier cosa sin ella es tratado como un entero por defecto. + + // Nota: Java no tiene tipos sin signo + + // Float - Número de coma flotante IEEE 754 de precisión simple de 32-bit + float fooFloat = 234.5f; + // f es usado para denotar qeu el valor de esta variable es del tipo float; + // de otra manera es tratado como un double. + + // Double - Número de coma flotante IEEE 754 de precisión doble de 64-bit + double fooDouble = 123.4; + + // Boolean - true & false + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - Un simple carácter unicode de 16-bit + char fooChar = 'A'; + + // Usa 'final' para hacer inmutable las variables + final int HORAS_QUE_TRABAJO_POR_SEMANA = 9001; + + // Strings + String fooString = "¡Mi String está aquí!"; + + // \n es un carácter escapado que inicia una nueva línea + String barString = "¿Imprimiendo en una nueva linea?\n¡Ningun problema!"; + // \t es un carácter escapado que añade un carácter tab + String bazString = "¿Quieres añadir un 'tab'?\t¡Ningun problema!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Arreglos + //El tamaño del arreglo debe decidirse en la declaración + //El formato para la declaración de un arreglo es la siguiente: + // [] = new []; + int [] arreglo_de_enteros = new int[10]; + String [] arreglo_de_strings = new String[1]; + boolean [] arreglo_de_booleanos = new boolean[100]; + + // Otra forma de declarar & inicializar un arreglo + int [] y = {9000, 1000, 1337}; + + // Indexación de un arreglo - Accediendo un elemento + System.out.println("arreglo_de_enteros @ 0: " + arreglo_de_enteros[0]); + + // Arreglos comienzan su indexación en cero y son mutables + arreglo_de_enteros[1] = 1; + System.out.println("arreglo_de_enteros @ 1: " + arreglo_de_enteros[1]); // => 1 + + // Otros para echar un vistazo + // ArrayLists - Son como arreglos excepto que ofrecen más funcionalidades + // y el tamaño es mutable + // LinkedLists + // Maps + // HashMaps + + /////////////////////////////////////// + // Operadores + /////////////////////////////////////// + System.out.println("\n->Operadores"); + + int i1 = 1, i2 = 2; // Abreviación para múltiples declaraciones + + // La aritmética es directa + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncado) + + // Módulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Operadores de comparación + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // ¡Operaciones a nivel de bits! + /* + ~ Complemento unario bit a bit + << Deplazamiento hacia la izquierda con signo + >> Deplazamiento hacia la derecha con signo + >>> Deplazamiento hacia la derecha sin signo + & AND lógico + ^ OR lógico exclusivo + | OR lógico inclusivo + */ + + // Incrementos + int i = 0; + System.out.println("\n->Incrementos y reducciones"); + System.out.println(i++); //i = 1. Post-incremento + System.out.println(++i); //i = 2. Pre-incremento + System.out.println(i--); //i = 1. Post-reducción + System.out.println(--i); //i = 0. Pre-reducción + + /////////////////////////////////////// + // Estructuras de Control + /////////////////////////////////////// + System.out.println("\n->Estructuras de Control"); + + // Condiciones 'if' son como en c + int j = 10; + if (j == 10){ + System.out.println("Me imprimieron"); + } else if (j > 10) { + System.out.println("A mi no"); + } else { + System.out.println("A mi tampoco"); + } + + // Ciclos 'while' + int fooWhile = 0; + while(fooWhile < 100) + { + //System.out.println(fooWhile); + //Incrementar el contador + //Iteró 99 veces, fooWhile 0->99 + fooWhile++; + } + System.out.println("Valor fooWhile: " + fooWhile); + + // Ciclos 'do while' + int fooDoWhile = 0; + do + { + //System.out.println(fooDoWhile); + //Incrementar el contador + //Iteró 99 veces, fooDoWhile 0->99 + fooDoWhile++; + }while(fooDoWhile < 100); + System.out.println("Valor fooDoWhile: " + fooDoWhile); + + // Ciclos 'for' + int fooFor; + //Estructura del ciclo 'for' => for(; ; ) + for(fooFor=0; fooFor<10; fooFor++){ + //System.out.println(fooFor); + //Iteró 10 veces, fooFor 0->9 + } + System.out.println("Valor fooFor: " + fooFor); + + // Switch Case + // Un 'switch' funciona con un tipo de dato byte, short, char e int + // También funciona con tipos enumerados (discutido en tipos Enum), + // la clase String y unas pocas clases especiales que envuelven + // tipos primitivos: Character, Byte, Short e Integer. + int mes = 3; + String mesString; + switch (mes){ + case 1: + mesString = "Enero"; + break; + case 2: + mesString = "Febrero"; + break; + case 3: + mesString = "Marzo"; + break; + default: + mesString = "Algun otro mes"; + break; + } + System.out.println("Resultado switch Case: " + mesString); + + + /////////////////////////////////////// + // Convirtiendo Tipos de Datos y Conversión de Tipos + /////////////////////////////////////// + + // Convirtiendo datos + + // Convertir String a Integer + Integer.parseInt("123");//retorna una versión entera de "123" + + // Convertir Integer a String + Integer.toString(123);//retorna una versión string de 123 + + // Para otras conversiones fíjate en las siguientes clases + // Double + // Long + // String + + // Conversión de tipos + // También puedes convertir objetos java, hay muchos detalles + // con unos pocos conceptos intermedios + // No dudes en verlos acá + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Clases y Funciones + /////////////////////////////////////// + + System.out.println("\n->Clases & Funciones"); + + // (A continuación la definición de una clase Bicicleta) + + // Usa 'new' para instanciar una clase + Bicicleta excursion = new Bicicleta(); + + // Llama métodos del objeto + excursion.aumentarVelocidad(3); // Siempre deberías usar metodos 'set' (establecer) y 'get' (obtener) + excursion.setRitmo(100); + + // 'toString' es una convención para mostrar los valores de este objeto. + System.out.println("informacion de la excursion: " + excursion.toString()); + + } // Fin del método 'main' +} // Fin de la clase AprendeJava + + +// Puedes incluir otras clases no públicas en un archivo .java + + +// Sintaxis de declaración de clases: +// class { +// //variables_de_clase, constructores, todas las funciones. +// //las funciones son llamadas como métodos en Java. +// } + +class Bicicleta { + + // Campos/Variables de Bicicleta + public int ritmo; // Public: Puede ser accedido desde cualquier parte + private int velocidad; // Private: Accesible sólo desde esta clase + protected int engranaje; // Protected: Accesible desde esta clases y sus subclases + String nombre; // default: Sólo accesible desde este paquete + + // Constructores son la manera de crear clases + // Este es un constructor por defecto + public Bicicleta() { + engranaje = 1; + ritmo = 50; + velocidad = 5; + nombre = "Bontrager"; + } + + // Este es un constructor específico (contiene argumentos) + public Bicicleta(int ritmoInicial, int velocidadInicial, int engranajeInicial, String nombre) { + this.engranaje = engranajeInicial; + this.ritmo = ritmoInicial; + this.velocidad = velocidadInicial; + this.nombre = nombre; + } + + // Sintaxis de función: + // () + + // Las clases de Java usualmente implementan métodos 'get' (obtener) y 'set' (establecer) para sus campos + + // Sintaxis de declaración de métodos + // () + public int getRitmo() { + return ritmo; + } + + // Métodos void no requieren retornar + public void setRitmo(int nuevoValor) { + ritmo = nuevoValor; + } + + public void setEngranaje(int nuevoValor) { + engranaje = nuevoValor; + } + + public void aumentarVelocidad(int incremento) { + velocidad += incremento; + } + + public void disminuirVelocidad(int reduccion) { + velocidad -= reduccion; + } + + public void setNombre(String nuevoNombre) { + nombre = nuevoNombre; + } + + public String getNombre() { + return nombre; + } + + //Método para mostrar los valores de los atributos de este objeto. + @Override + public String toString() { + return "engranaje: " + engranaje + + " ritmo: " + ritmo + + " velocidad: " + velocidad + + " nombre: " + nombre; + } +} // fin clase Bicicleta + +// PennyFarthing es una subclase de Bicicleta +class PennyFarthing extends Bicicleta { + // (Penny Farthings son esas bicicletas con una gran rueda forntal. + // No tienen engranajes.) + + public PennyFarthing(int ritmoInicial, int velocidadInicial){ + // Llama al constructor del padre con super + super(ritmoInicial, velocidadInicial, 0, "PennyFarthing"); + } + + // Deberías marcar un método que estás sobre escribiendo con una @anotacion + // Para aprender más sobre que son y el propósito de las anotaciones + // echa un vistazo acá: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setEngranaje(int engranaje) { + engranaje = 0; + } + +} + +``` + +## Más Lectura + +Estos links son sólo para tener un entendimiento del tema, no dudes en +usar Google y encontrar ejemplos más específicos + +Otros temas a investigar: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) -- cgit v1.2.3 From 674e8a0eebfa15afe51c6960cec9712fa186ef45 Mon Sep 17 00:00:00 2001 From: John Cowie Date: Thu, 8 Aug 2013 17:38:06 +0100 Subject: Explain git pull default behaviour and the use of --rebase flag. By far the pull command I use the most is 'git pull --rebase', so wanted to add some info to make it clear that that's possible. --- git.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index 00f38d60..d8537300 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -310,7 +310,12 @@ Pulls from a repository and merges it with another branch. # Update your local repo, by merging in new changes # from the remote "origin" and "master" branch. # git pull +# git pull => implicitly defaults to => git pull origin master $ git pull origin master + +# Merge in changes from remote branch and rebase +# branch commits onto your local repo, like: "git pull , git rebase " +$ git pull origin master --rebase ``` ### push -- cgit v1.2.3 From 29bbaff5a6ed60f40cc710a6ad79434de4d95d75 Mon Sep 17 00:00:00 2001 From: i Date: Thu, 8 Aug 2013 14:52:59 -0400 Subject: wording Compiling in LaTeX isn't that easy, actually... --- r.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/r.html.markdown b/r.html.markdown index 0240e8fb..3339a07e 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -5,7 +5,7 @@ contributors: filename: learnr.r --- -R is a statistical computing language. It has lots of good built-in functions for uploading and cleaning data sets, running common statistical tests, and making graphs. You can also easily compile it within a LaTeX document. +R is a statistical computing language. It has lots of libraries for uploading and cleaning data sets, running statistical procedures, and making graphs. You can also run `R`commands within a LaTeX document. ```python -- cgit v1.2.3 From 946a450995d874c807faa16a5df817ca80a7ecb0 Mon Sep 17 00:00:00 2001 From: i Date: Thu, 8 Aug 2013 15:05:01 -0400 Subject: '/' is a character Do you mean no letters? --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index be7d8669..9847ef2a 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -131,7 +131,7 @@ add 1 2 -- 3 -- with backticks: 1 `add` 2 -- 3 --- You can also define functions that have no characters! This lets +-- You can also define functions that have no letters! This lets -- you define your own operators! Here's an operator that does -- integer division (//) a b = a `div` b -- cgit v1.2.3 From ee1b3546ad1a1a0601f2dc413d0b96f345c27ad9 Mon Sep 17 00:00:00 2001 From: i Date: Thu, 8 Aug 2013 17:50:52 -0400 Subject: Update r.html.markdown significant changes. style changes (no !, no =>). content additions. start by showing off R's non-programming features before getting to the language per se. --- r.html.markdown | 311 ++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 246 insertions(+), 65 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index 0240e8fb..61140be5 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -16,61 +16,242 @@ R is a statistical computing language. It has lots of good built-in functions fo # Hit COMMAND-ENTER to execute a line + +################################################################### +# Stuff you can do without understanding anything about programming +################################################################### + +data() # Browse pre-loaded data sets +data(rivers) # Lengths of Major North American Rivers +ls() # Notice that "rivers" appears in the workspace +head(rivers) # peek at the dataset +# 735 320 325 392 524 450 +length(rivers) # how many rivers were measured? +# 141 +summary(rivers) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 +stem(rivers) #stem-and-leaf plot (like a histogram) +# +# The decimal point is 2 digit(s) to the right of the | +# +# 0 | 4 +# 2 | 011223334555566667778888899900001111223333344455555666688888999 +# 4 | 111222333445566779001233344567 +# 6 | 000112233578012234468 +# 8 | 045790018 +# 10 | 04507 +# 12 | 1471 +# 14 | 56 +# 16 | 7 +# 18 | 9 +# 20 | +# 22 | 25 +# 24 | 3 +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | +# 36 | 1 + + +stem(log(rivers)) #Notice that the data are neither normal nor log-normal! Take that, Bell Curve fundamentalists. + +# The decimal point is 1 digit(s) to the left of the | +# +# 48 | 1 +# 50 | +# 52 | 15578 +# 54 | 44571222466689 +# 56 | 023334677000124455789 +# 58 | 00122366666999933445777 +# 60 | 122445567800133459 +# 62 | 112666799035 +# 64 | 00011334581257889 +# 66 | 003683579 +# 68 | 0019156 +# 70 | 079357 +# 72 | 89 +# 74 | 84 +# 76 | 56 +# 78 | 4 +# 80 | +# 82 | 2 + + +hist(rivers, col="#333333", border="white", breaks=25) #play around with these parameters +hist(log(rivers), col="#333333", border="white", breaks=25) #you'll do more plotting later + +#Here's another neat data set that comes pre-loaded. R has tons of these. data() +data(discoveries) +plot(discoveries, col="#333333", lwd=3, xlab="Year", main="Number of important discoveries per year") +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", main="Number of important discoveries per year") + + +#rather than leaving the default ordering (by year) we could also sort to see what's typical +sort(discoveries) +# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 +# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 +# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 +# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 + +stem(discoveries, scale=2) +# +# The decimal point is at the | +# +# 0 | 000000000 +# 1 | 000000000000 +# 2 | 00000000000000000000000000 +# 3 | 00000000000000000000 +# 4 | 000000000000 +# 5 | 0000000 +# 6 | 000000 +# 7 | 0000 +# 8 | 0 +# 9 | 0 +# 10 | 0 +# 11 | +# 12 | 0 + +max(discoveries) +# 12 + +summary(discoveries) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 + + + + +#Basic statistical operations don't require any programming knowledge either + +#roll a die a few times +round(runif(7, min=.5, max=6.5)) +# 1 4 6 1 4 6 4 + +#your numbers will differ from mine unless we set the same random.seed(31337) + + +#draw from a standard Gaussian 9 times +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + + + + + + + ######################### -# The absolute basics +# Basic programming stuff ######################### # NUMBERS -# We've got doubles! Behold the "numeric" class -5 # => [1] 5 -class(5) # => [1] "numeric" -# We've also got integers! They look suspiciously similar, -# but indeed are different -5L # => [1] 5 -class(5L) # => [1] "integer" +# "numeric" means double-precision floating-point numbers +5 # 5 +class(5) # "numeric" +5e4 # 50000 #handy when dealing with large,small,or variable orders of magnitude +6.02e23 # Avogadro's number +1.6e-35 # Planck length + +# long-storage integers are written with L +5L # 5 +class(5L) # "integer" + # Try ?class for more information on the class() function -# In fact, you can look up the documentation on just about anything with ? +# In fact, you can look up the documentation on `xyz` with ?xyz +# or see the source for `xyz` by evaluating xyz + +# Arithmetic +10 + 66 # 76 +53.2 - 4 # 49.2 +2 * 2.0 # 4 +3L / 4 # 0.75 +3 %% 2 # 1 + +# Weird number types +class(NaN) # "numeric" +class(Inf) # "numeric" +class(-Inf) # "numeric" #used in for example integrate( dnorm(x), 3, Inf ) -- which obviates Z-score tables + +# but beware, NaN isn't the only weird type... +class(NA) # see below +class(NULL) # NULL + + +# SIMPLE LISTS +c(6, 8, 7, 5, 3, 0, 9) # 6 8 7 5 3 0 9 +c('alef', 'bet', 'gimmel', 'dalet', 'he') # "alef" "bet" "gimmel" "dalet" "he" +c('Z', 'o', 'r', 'o') == "Zoro" # FALSE FALSE FALSE FALSE + +#some more nice built-ins +5:15 # 5 6 7 8 9 10 11 12 13 14 15 + +seq(from=0, to=31337, by=1337) +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 + +letters +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" + +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" + + +# Access the n'th element of a list with list.name[n] or sometimes list.name[[n]] +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 -# All the normal operations! -10 + 66 # => [1] 76 -53.2 - 4 # => [1] 49.2 -2 * 2.0 # => [1] 4 -3L / 4 # => [1] 0.75 -3 %% 2 # => [1] 1 -# Finally, we've got not-a-numbers! They're numerics too -class(NaN) # => [1] "numeric" # CHARACTERS -# We've (sort of) got strings! Behold the "character" class -"plugh" # => [1] "plugh" -class("plugh") # "character" # There's no difference between strings and characters in R +"Horatio" # "Horatio" +class("Horatio") # "character" +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." + + + # LOGICALS -# We've got booleans! Behold the "logical" class -class(TRUE) # => [1] "logical" -class(FALSE) # => [1] "logical" +# booleans +class(TRUE) # "logical" +class(FALSE) # "logical" # Behavior is normal -TRUE == TRUE # => [1] TRUE -TRUE == FALSE # => [1] FALSE -FALSE != FALSE # => [1] FALSE -FALSE != TRUE # => [1] TRUE +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE # Missing data (NA) is logical, too -class(NA) # => [1] "logical" +class(NA) # "logical" + + # FACTORS # The factor class is for categorical data -# It has an attribute called levels that describes all the possible categories -factor("dog") -# => -# [1] dog -# Levels: dog -# (This will make more sense once we start talking about vectors) +# which can be ordered (like childrens' grade levels) +# or unordered (like gender) +levels(factor(c("female", "male", "male", "female", "NA", "female"))) # "female" "male" "NA" + +factor(c("female", "female", "male", "NA", "female")) +# female female male NA female +# Levels: female male NA + +data(infert) #Infertility after Spontaneous and Induced Abortion +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + + # VARIABLES @@ -80,8 +261,8 @@ y <- "1" # this is preferred TRUE -> z # this works but is weird # We can use coerce variables to different classes -as.numeric(y) # => [1] 1 -as.character(x) # => [1] "5" +as.numeric(y) # 1 +as.character(x) # "5" # LOOPS @@ -122,7 +303,7 @@ myFunc <- function(x) { } # Called like any other R function: -myFunc(5) # => [1] 19 +myFunc(5) # 19 ######################### # Fun with data: vectors, matrices, data frames, and arrays @@ -132,35 +313,35 @@ myFunc(5) # => [1] 19 # You can vectorize anything, so long as all components have the same type vec <- c(8, 9, 10, 11) -vec # => [1] 8 9 10 11 +vec # 8 9 10 11 # The class of a vector is the class of its components -class(vec) # => [1] "numeric" +class(vec) # "numeric" # If you vectorize items of different classes, weird coercions happen -c(TRUE, 4) # => [1] 1 4 -c("dog", TRUE, 4) # => [1] "dog" "TRUE" "4" +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" # We ask for specific components like so (R starts counting from 1) -vec[1] # => [1] 8 +vec[1] # 8 # We can also search for the indices of specific components, -which(vec %% 2 == 0) # => [1] 1 3 +which(vec %% 2 == 0) # 1 3 # or grab just the first or last entry in the vector -head(vec, 1) # => [1] 8 -tail(vec, 1) # => [1] 11 +head(vec, 1) # 8 +tail(vec, 1) # 11 # If an index "goes over" you'll get NA: -vec[6] # => [1] NA +vec[6] # NA # You can find the length of your vector with length() -length(vec) # => [1] 4 +length(vec) # 4 # You can perform operations on entire vectors or subsets of vectors -vec * 4 # => [1] 16 20 24 28 -vec[2:3] * 5 # => [1] 25 30 +vec * 4 # 16 20 24 28 +vec[2:3] * 5 # 25 30 # and there are many built-in functions to summarize vectors -mean(vec) # => [1] 9.5 -var(vec) # => [1] 1.666667 -sd(vec) # => [1] 1.290994 -max(vec) # => [1] 11 -min(vec) # => [1] 8 -sum(vec) # => [1] 38 +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 # TWO-DIMENSIONAL (ALL ONE CLASS) @@ -175,11 +356,11 @@ mat # Unlike a vector, the class of a matrix is "matrix", no matter what's in it class(mat) # => "matrix" # Ask for the first row -mat[1,] # => [1] 1 4 +mat[1,] # 1 4 # Perform operation on the first column -3 * mat[,1] # => [1] 3 6 9 +3 * mat[,1] # 3 6 9 # Ask for a specific cell -mat[3,2] # => [1] 6 +mat[3,2] # 6 # Transpose the whole matrix t(mat) # => @@ -196,7 +377,7 @@ mat2 # [2,] "2" "cat" # [3,] "3" "bird" # [4,] "4" "dog" -class(mat2) # => [1] matrix +class(mat2) # matrix # Again, note what happened! # Because matrices must contain entries all of the same class, # everything got converted to the character class @@ -216,7 +397,7 @@ mat3 # For columns of different classes, use the data frame dat <- data.frame(c(5,2,1,4), c("dog", "cat", "bird", "dog")) names(dat) <- c("number", "species") # name the columns -class(dat) # => [1] "data.frame" +class(dat) # "data.frame" dat # => # number species @@ -224,14 +405,14 @@ dat # 2 2 cat # 3 1 bird # 4 4 dog -class(dat$number) # => [1] "numeric" -class(dat[,2]) # => [1] "factor" +class(dat$number) # "numeric" +class(dat[,2]) # "factor" # The data.frame() function converts character vectors to factor vectors # There are many twisty ways to subset data frames, all subtly unalike -dat$number # => [1] 5 2 1 4 -dat[,1] # => [1] 5 2 1 4 -dat[,"number"] # => [1] 5 2 1 4 +dat$number # 5 2 1 4 +dat[,1] # 5 2 1 4 +dat[,"number"] # 5 2 1 4 # MULTI-DIMENSIONAL (ALL OF ONE CLASS) -- cgit v1.2.3 From fbfca446ff92ab9dec38569cecf250b82ab4aabc Mon Sep 17 00:00:00 2001 From: i Date: Thu, 8 Aug 2013 17:51:32 -0400 Subject: Update r.html.markdown ...only in Windows --- r.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/r.html.markdown b/r.html.markdown index 61140be5..5f143150 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -14,7 +14,7 @@ R is a statistical computing language. It has lots of good built-in functions fo # You can't make a multi-line comment per se, # but you can stack multiple comments like so. -# Hit COMMAND-ENTER to execute a line +# in Windows, hit COMMAND-ENTER to execute a line ################################################################### -- cgit v1.2.3 From cba396af816e75a281fbcd557c055379675e6d57 Mon Sep 17 00:00:00 2001 From: Jon Smock Date: Fri, 9 Aug 2013 09:33:57 -0400 Subject: Add ruby-ecosystem to tools section --- ruby-ecosystem.html.markdown | 127 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 ruby-ecosystem.html.markdown diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown new file mode 100644 index 00000000..779cd29e --- /dev/null +++ b/ruby-ecosystem.html.markdown @@ -0,0 +1,127 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http:#github.com/jonsmock"] +filename: + +--- + +People using ruby generally have a way to install different ruby versions, +manage their packages (or gems), and manage their gem dependencies. + +## Ruby Managers + +Some platforms have ruby pre-installed or available as a package. Most rubyists +do not use these, or if they do, they only use them to bootstrap another ruby +installer or implementation. Instead rubyists tend to install a ruby manager to +install and switch between many versions of ruby and their projects' ruby +environments. + +The following are the popular ruby/environment managers: + +* [RVM](https://rvm.io/) - Installs and switches between rubies. RVM also has + the concept of gemsets to isolate projects' environments completely. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Only installs + rubies. Use this for finer control over your rubies' installations. +* [rbenv](https://github.com/sstephenson/rbenv) - Only switches between rubies. + Used with ruby-build. Use this for finer control over how rubies load. +* [chruby](https://github.com/postmodern/chruby) - Only switches between rubies. + Similar in spirit to rbenv. Unopinionated about how rubies are installed. + +## Ruby Versions + +Ruby was created by Yukihiro "Matz" Matsumoto, who remains somewhat of a +[BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), although +that is changing recently. As a result, the reference implementation of ruby is +called MRI (Matz' Reference Implementation), and when you hear a ruby version, +it is referring to the release version of MRI. + +The three major version of ruby in use are: + +* 2.0.0 - Released in February 2013. Most major libraries and frameworks support + 2.0.0. +* 1.9.3 - Released in October 2011. This is the version most rubyists use + currently. +* 1.8.7 - Ruby 1.8.7 has been + [retired](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +The change between 1.8.7 to 1.9.x is a much larger change than 1.9.3 to 2.0.0. +For instance, the 1.9 series introduced encodings and a bytecode VM. There +are projects still on 1.8.7, but they are becoming a small minority, as most of +the community has moved to at least 1.9.2 or 1.9.3. + +## Ruby Implementations + +The ruby ecosystem enjoys many different implementations of ruby, each with +unique strengths and states of compatability. To be clear, the different +implementations are written in different languages, but *they are all ruby*. +Each implementation has special hooks and extra features, but they all run +normal ruby files well. For instance, JRuby is written in Java, but you do +not need to know Java to use it. + +Very mature/compatible: + +* MRI - Written in C, this is the reference implementation of ruby. By + definition it is 100% compatible (with itself). All other rubies +maintain capatability with MRI (see RubySpec below). +* JRuby - Written in Java and ruby, this robust implementation is quite fast. + Most importantly, JRuby's strength is JVM/Java interop, leveraging existing +JVM tools, projects, and languages. +* Rubinius - Written primarily in ruby itself with a C++ bytecode VM. Also + mature and fast. Because it is implemented in ruby itself, it exposes many VM +features into rubyland. + +Medium mature/compatible: + +* Maglev - Built on top of Gemstone, a Smalltalk VM. Smalltalk has some + impressive tooling, and this project tries to bring that into ruby +development. +* RubyMotion - Brings ruby to iOS development. + +Less mature/compatible: + +* Topaz - Written in RPython (using the PyPy toolchain), Topaz is fairly young + and not yet compatable. It shows promise to be a high-performance ruby +implementation. +* IronRuby - Written in C# targeting the .NET platform, work on IronRuby seems + to have stopped since Microsoft pulled their support. + +Ruby implementations may have their own release version numbers, but they always +target a specific version of MRI for compatability. Many implementations have +the ability to enter different modes (for example, 1.8 or 1.9 mode) to specify +which MRI version to target. + +## RubySpec + +Most ruby implementations rely heavily on (RubySpec)[http://rubyspec.org/]. Ruby +has no official specification, so the community has written executable specs in +ruby to test their implementations' compatability with MRI. + +## RubyGems + +(RubyGems)[http://rubygems.org/] is a community-run package manager for ruby. +RubyGems ships with ruby, so there is no need to download it separately. + +Ruby packages are called "gems," and they can be hosted by the community at +RubyGems.org. Each gem contains its source code and some metadata, including +things like version, dependencies, author(s), and license(s). + +## Bundler + +(Bundler)[http://bundler.io/] is a gem dependency resolver. It uses a project's +Gemfile to find dependencies, and then fetches those dependencies' dependencies +recursively. It does this until all dependencies are resolved and downloaded, or +it will stop if a conflict has been found. + +Bundler will raise an error if it finds conflicting dependencies. For example, +if gem A requires version 3 or greater of gem Z, but gem B requires version 2, +Bundler will notify you of the conflict. This becomes extremely helpful as many +gems refer to other gems (which refer to other gems), which can form a large +dependency graph to resolve. + +## Be Nice + +The ruby community takes pride in being an open, diverse, welcoming community. +Matz himself is extremely friendly, and the generosity of rubyists on the whole +is amazing. -- cgit v1.2.3 From 31860e69c96344120ab69b1cf7266cddc1f812ed Mon Sep 17 00:00:00 2001 From: Jon Smock Date: Fri, 9 Aug 2013 09:56:46 -0400 Subject: Fix url --- ruby-ecosystem.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 779cd29e..4bcbf7ac 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -2,7 +2,7 @@ category: tool tool: ruby ecosystem contributors: - - ["Jon Smock", "http:#github.com/jonsmock"] + - ["Jon Smock", "http://github.com/jonsmock"] filename: --- -- cgit v1.2.3 From 15d93899e0ed1fad2be71678e898e58ceb270928 Mon Sep 17 00:00:00 2001 From: Jon Smock Date: Fri, 9 Aug 2013 09:56:51 -0400 Subject: Add testing section to ruby-ecosystem --- ruby-ecosystem.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 4bcbf7ac..5647e518 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -120,6 +120,17 @@ Bundler will notify you of the conflict. This becomes extremely helpful as many gems refer to other gems (which refer to other gems), which can form a large dependency graph to resolve. +# Testing + +Testing is a large of ruby culture. Ruby comes with its own Unit-style testing +framework called minitest (Or TestUnit for ruby version 1.8.x). There are many +testing libraries with different goals. + +* TestUnit - Ruby 1.8's built-in "Unit-style" testing framework +* minitest - Ruby 1.9/2.0's built-in testing framework +* RSpec - A testing framework that focuses on expressivity +* Cucumber - A BDD testing framework that parses Gherkin formatted tests + ## Be Nice The ruby community takes pride in being an open, diverse, welcoming community. -- cgit v1.2.3 From c4caaf42aab215e642f1212befb18f288511b542 Mon Sep 17 00:00:00 2001 From: Eran Medan Date: Fri, 9 Aug 2013 14:58:39 -0400 Subject: Updated most requested languages :) --- README.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.markdown b/README.markdown index 77e09abd..efc2fa07 100644 --- a/README.markdown +++ b/README.markdown @@ -16,8 +16,9 @@ properly! The most requested languages are: -* Scala -* Javascript +* Go +* ~~Scala~~ +* ~~Javascript~~ ... but there are many more requests to do "every language", so don't let that stop you. -- cgit v1.2.3 From f0d771ddea5537e98ef47462c5c8c41b0314f856 Mon Sep 17 00:00:00 2001 From: i Date: Fri, 9 Aug 2013 18:13:08 -0400 Subject: =?UTF-8?q?Bender=20Bending=20Rodr=C3=ADguez?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Let's make the function example do something a little more interesting. --- r.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index dd94072b..e7921299 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -2,6 +2,7 @@ language: R contributors: - ["e99n09", "http://github.com/e99n09"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] filename: learnr.r --- @@ -296,14 +297,13 @@ if (4 > 3) { # FUNCTIONS # Defined like so: -myFunc <- function(x) { - x <- x * 4 - x <- x - 1 +jiggle <- function(x) { + x+ rnorm(x, sd=.1) #add in a bit of (controlled) noise return(x) } # Called like any other R function: -myFunc(5) # 19 +jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 ######################### # Fun with data: vectors, matrices, data frames, and arrays -- cgit v1.2.3 From 8d0a2e6b79533856e82a8541b5b866ebd6fdeb4e Mon Sep 17 00:00:00 2001 From: hanguokai Date: Sat, 10 Aug 2013 06:31:51 +0800 Subject: add translation for dart. --- zh-cn/dart-cn.html.markdown | 509 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 509 insertions(+) create mode 100644 zh-cn/dart-cn.html.markdown diff --git a/zh-cn/dart-cn.html.markdown b/zh-cn/dart-cn.html.markdown new file mode 100644 index 00000000..47b1a93b --- /dev/null +++ b/zh-cn/dart-cn.html.markdown @@ -0,0 +1,509 @@ +--- +language: dart +filename: learndart.dart +contributors: + - ["Joao Pedrosa", "https://github.com/jpedrosa/"] +translators: + - ["Guokai Han", "https://github.com/hanguokai/"] +--- + +Dart 是编程语言王国的新人。 +它借鉴了许多其他主流语言,并且不会偏离它的兄弟语言 JavaScript 太多。 +就像 JavaScript,Dart 的目标是提供良好的浏览器集成。 + +Dart 最有争议的特性必然是它的可选类型。 + +```javascript +import "dart:collection"; +import "dart:math" as DM; + +// Welcome to Learn Dart in 15 minutes. http://www.dartlang.org/ +// This is an executable tutorial. You can run it with Dart or on +// the Try Dart! site if you copy/paste it there. http://try.dartlang.org/ + +// Function declaration and method declaration look the same. Function +// declarations can be nested. The declaration takes the form of +// name() {} or name() => singleLineExpression; +// The fat arrow function declaration has an implicit return for the result of +// the expression. +example1() { + example1nested1() { + example1nested2() => print("Example1 nested 1 nested 2"); + example1nested2(); + } + example1nested1(); +} + +// Anonymous functions don't include a name. +example2() { + example2nested1(fn) { + fn(); + } + example2nested1(() => print("Example2 nested 1")); +} + +// When a function parameter is declared, the declaration can include the +// number of parameters the function takes by specifying the names of the +// parameters it takes. +example3() { + example3nested1(fn(informSomething)) { + fn("Example3 nested 1"); + } + example3planB(fn) { // Or don't declare number of parameters. + fn("Example3 plan B"); + } + example3nested1((s) => print(s)); + example3planB((s) => print(s)); +} + +// Functions have closure access to outer variables. +var example4Something = "Example4 nested 1"; +example4() { + example4nested1(fn(informSomething)) { + fn(example4Something); + } + example4nested1((s) => print(s)); +} + +// Class declaration with a sayIt method, which also has closure access +// to the outer variable as though it were a function as seen before. +var example5method = "Example5 sayIt"; +class Example5Class { + sayIt() { + print(example5method); + } +} +example5() { + // Create an anonymous instance of the Example5Class and call the sayIt + // method on it. + new Example5Class().sayIt(); +} + +// Class declaration takes the form of class name { [classBody] }. +// Where classBody can include instance methods and variables, but also +// class methods and variables. +class Example6Class { + var example6InstanceVariable = "Example6 instance variable"; + sayIt() { + print(example6InstanceVariable); + } +} +example6() { + new Example6Class().sayIt(); +} + +// Class methods and variables are declared with "static" terms. +class Example7Class { + static var example7ClassVariable = "Example7 class variable"; + static sayItFromClass() { + print(example7ClassVariable); + } + sayItFromInstance() { + print(example7ClassVariable); + } +} +example7() { + Example7Class.sayItFromClass(); + new Example7Class().sayItFromInstance(); +} + +// Literals are great, but there's a restriction for what literals can be +// outside of function/method bodies. Literals on the outer scope of class +// or outside of class have to be constant. Strings and numbers are constant +// by default. But arrays and maps are not. They can be made constant by +// declaring them "const". +var example8A = const ["Example8 const array"], + example8M = const {"someKey": "Example8 const map"}; +example8() { + print(example8A[0]); + print(example8M["someKey"]); +} + +// Loops in Dart take the form of standard for () {} or while () {} loops, +// slightly more modern for (.. in ..) {}, or functional callbacks with many +// supported features, starting with forEach. +var example9A = const ["a", "b"]; +example9() { + for (var i = 0; i < example9A.length; i++) { + print("Example9 for loop '${example9A[i]}'"); + } + var i = 0; + while (i < example9A.length) { + print("Example9 while loop '${example9A[i]}'"); + i++; + } + for (var e in example9A) { + print("Example9 for-in loop '${e}'"); + } + example9A.forEach((e) => print("Example9 forEach loop '${e}'")); +} + +// To loop over the characters of a string or to extract a substring. +var example10S = "ab"; +example10() { + for (var i = 0; i < example10S.length; i++) { + print("Example10 String character loop '${example10S[i]}'"); + } + for (var i = 0; i < example10S.length; i++) { + print("Example10 substring loop '${example10S.substring(i, i + 1)}'"); + } +} + +// Int and double are the two supported number formats. +example11() { + var i = 1 + 320, d = 3.2 + 0.01; + print("Example11 int ${i}"); + print("Example11 double ${d}"); +} + +// DateTime provides date/time arithmetic. +example12() { + var now = new DateTime.now(); + print("Example12 now '${now}'"); + now = now.add(new Duration(days: 1)); + print("Example12 tomorrow '${now}'"); +} + +// Regular expressions are supported. +example13() { + var s1 = "some string", s2 = "some", re = new RegExp("^s.+?g\$"); + match(s) { + if (re.hasMatch(s)) { + print("Example13 regexp matches '${s}'"); + } else { + print("Example13 regexp doesn't match '${s}'"); + } + } + match(s1); + match(s2); +} + +// Boolean expressions need to resolve to either true or false, as no +// implicit conversions are supported. +example14() { + var v = true; + if (v) { + print("Example14 value is true"); + } + v = null; + try { + if (v) { + // Never runs + } else { + // Never runs + } + } catch (e) { + print("Example14 null value causes an exception: '${e}'"); + } +} + +// try/catch/finally and throw are used for exception handling. +// throw takes any object as parameter; +example15() { + try { + try { + throw "Some unexpected error."; + } catch (e) { + print("Example15 an exception: '${e}'"); + throw e; // Re-throw + } + } catch (e) { + print("Example15 catch exception being re-thrown: '${e}'"); + } finally { + print("Example15 Still run finally"); + } +} + +// To be efficient when creating a long string dynamically, use +// StringBuffer. Or you could join a string array. +example16() { + var sb = new StringBuffer(), a = ["a", "b", "c", "d"], e; + for (e in a) { sb.write(e); } + print("Example16 dynamic string created with " + "StringBuffer '${sb.toString()}'"); + print("Example16 join string array '${a.join()}'"); +} + +// Strings can be concatenated by just having string literals next to +// one another with no further operator needed. +example17() { + print("Example17 " + "concatenate " + "strings " + "just like that"); +} + +// Strings have single-quote or double-quote for delimiters with no +// actual difference between the two. The given flexibility can be good +// to avoid the need to escape content that matches the delimiter being +// used. For example, double-quotes of HTML attributes if the string +// contains HTML content. +example18() { + print('Example18 ' + "Don't can't I'm Etc" + ''); +} + +// Strings with triple single-quotes or triple double-quotes span +// multiple lines and include line delimiters. +example19() { + print('''Example19 +Example19 Don't can't I'm Etc +Example19 '''); +} + +// Strings have the nice interpolation feature with the $ character. +// With $ { [expression] }, the return of the expression is interpolated. +// $ followed by a variable name interpolates the content of that variable. +// $ can be escaped like so \$ to just add it to the string instead. +example20() { + var s1 = "'\${s}'", s2 = "'\$s'"; + print("Example20 \$ interpolation ${s1} or $s2 works."); +} + +// Optional types allow for the annotation of APIs and come to the aid of +// IDEs so the IDEs can better refactor, auto-complete and check for +// errors. So far we haven't declared any types and the programs have +// worked just fine. In fact, types are disregarded during runtime. +// Types can even be wrong and the program will still be given the +// benefit of the doubt and be run as though the types didn't matter. +// There's a runtime parameter that checks for type errors which is +// the checked mode, which is said to be useful during development time, +// but which is also slower because of the extra checking and is thus +// avoided during deployment runtime. +class Example21 { + List _names; + Example21() { + _names = ["a", "b"]; + } + List get names => _names; + set names(List list) { + _names = list; + } + int get length => _names.length; + void add(String name) { + _names.add(name); + } +} +void example21() { + Example21 o = new Example21(); + o.add("c"); + print("Example21 names '${o.names}' and length '${o.length}'"); + o.names = ["d", "e"]; + print("Example21 names '${o.names}' and length '${o.length}'"); +} + +// Class inheritance takes the form of class name extends AnotherClassName {}. +class Example22A { + var _name = "Some Name!"; + get name => _name; +} +class Example22B extends Example22A {} +example22() { + var o = new Example22B(); + print("Example22 class inheritance '${o.name}'"); +} + +// Class mixin is also available, and takes the form of +// class name extends SomeClass with AnotherClassName {}. +// It's necessary to extend some class to be able to mixin another one. +// The template class of mixin cannot at the moment have a constructor. +// Mixin is mostly used to share methods with distant classes, so the +// single inheritance doesn't get in the way of reusable code. +// Mixins follow the "with" statement during the class declaration. +class Example23A {} +class Example23Utils { + addTwo(n1, n2) { + return n1 + n2; + } +} +class Example23B extends Example23A with Example23Utils { + addThree(n1, n2, n3) { + return addTwo(n1, n2) + n3; + } +} +example23() { + var o = new Example23B(), r1 = o.addThree(1, 2, 3), + r2 = o.addTwo(1, 2); + print("Example23 addThree(1, 2, 3) results in '${r1}'"); + print("Example23 addTwo(1, 2) results in '${r2}'"); +} + +// The Class constructor method uses the same name of the class and +// takes the form of SomeClass() : super() {}, where the ": super()" +// part is optional and it's used to delegate constant parameters to the +// super-parent's constructor. +class Example24A { + var _value; + Example24A({value: "someValue"}) { + _value = value; + } + get value => _value; +} +class Example24B extends Example24A { + Example24B({value: "someOtherValue"}) : super(value: value); +} +example24() { + var o1 = new Example24B(), + o2 = new Example24B(value: "evenMore"); + print("Example24 calling super during constructor '${o1.value}'"); + print("Example24 calling super during constructor '${o2.value}'"); +} + +// There's a shortcut to set constructor parameters in case of simpler classes. +// Just use the this.parameterName prefix and it will set the parameter on +// an instance variable of same name. +class Example25 { + var value, anotherValue; + Example25({this.value, this.anotherValue}); +} +example25() { + var o = new Example25(value: "a", anotherValue: "b"); + print("Example25 shortcut for constructor '${o.value}' and " + "'${o.anotherValue}'"); +} + +// Named parameters are available when declared between {}. +// Parameter order can be optional when declared between {}. +// Parameters can be made optional when declared between []. +example26() { + var _name, _surname, _email; + setConfig1({name, surname}) { + _name = name; + _surname = surname; + } + setConfig2(name, [surname, email]) { + _name = name; + _surname = surname; + _email = email; + } + setConfig1(surname: "Doe", name: "John"); + print("Example26 name '${_name}', surname '${_surname}', " + "email '${_email}'"); + setConfig2("Mary", "Jane"); + print("Example26 name '${_name}', surname '${_surname}', " + "email '${_email}'"); +} + +// Variables declared with final can only be set once. +// In case of classes, final instance variables can be set via constant +// constructor parameter. +class Example27 { + final color1, color2; + // A little flexibility to set final instance variables with syntax + // that follows the : + Example27({this.color1, color2}) : color2 = color2; +} +example27() { + final color = "orange", o = new Example27(color1: "lilac", color2: "white"); + print("Example27 color is '${color}'"); + print("Example27 color is '${o.color1}' and '${o.color2}'"); +} + +// To import a library, use import "libraryPath" or if it's a core library, +// import "dart:libraryName". There's also the "pub" package management with +// its own convention of import "package:packageName". +// See import "dart:collection"; at the top. Imports must come before +// other code declarations. IterableBase comes from dart:collection. +class Example28 extends IterableBase { + var names; + Example28() { + names = ["a", "b"]; + } + get iterator => names.iterator; +} +example28() { + var o = new Example28(); + o.forEach((name) => print("Example28 '${name}'")); +} + +// For control flow we have: +// * standard switch with must break statements +// * if-else if-else and ternary ..?..:.. operator +// * closures and anonymous functions +// * break, continue and return statements +example29() { + var v = true ? 30 : 60; + switch (v) { + case 30: + print("Example29 switch statement"); + break; + } + if (v < 30) { + } else if (v > 30) { + } else { + print("Example29 if-else statement"); + } + callItForMe(fn()) { + return fn(); + } + rand() { + v = new DM.Random().nextInt(50); + return v; + } + while (true) { + print("Example29 callItForMe(rand) '${callItForMe(rand)}'"); + if (v != 30) { + break; + } else { + continue; + } + // Never gets here. + } +} + +// Parse int, convert double to int, or just keep int when dividing numbers +// by using the ~/ operation. Let's play a guess game too. +example30() { + var gn, tooHigh = false, + n, n2 = (2.0).toInt(), top = int.parse("123") ~/ n2, bottom = 0; + top = top ~/ 6; + gn = new DM.Random().nextInt(top + 1); // +1 because nextInt top is exclusive + print("Example30 Guess a number between 0 and ${top}"); + guessNumber(i) { + if (n == gn) { + print("Example30 Guessed right! The number is ${gn}"); + } else { + tooHigh = n > gn; + print("Example30 Number ${n} is too " + "${tooHigh ? 'high' : 'low'}. Try again"); + } + return n == gn; + } + n = (top - bottom) ~/ 2; + while (!guessNumber(n)) { + if (tooHigh) { + top = n - 1; + } else { + bottom = n + 1; + } + n = bottom + ((top - bottom) ~/ 2); + } +} + +// Programs have only one entry point in the main function. +// Nothing is expected to be executed on the outer scope before a program +// starts running with what's in its main function. +// This helps with faster loading and even lazily loading of just what +// the program needs to startup with. +main() { + print("Learn Dart in 15 minutes!"); + [example1, example2, example3, example4, example5, example6, example7, + example8, example9, example10, example11, example12, example13, example14, + example15, example16, example17, example18, example19, example20, + example21, example22, example23, example24, example25, example26, + example27, example28, example29, example30 + ].forEach((ef) => ef()); +} + +``` + +## 延伸阅读 + +Dart 有一个全面的网站。它涵盖了 API 参考、入门向导、文章以及更多, +包括一个有用的 Dart 在线试用。 +http://www.dartlang.org/ +http://try.dartlang.org/ + + + -- cgit v1.2.3 From c5c76b4a5d36b729bd782d3e3695aa1a7083a129 Mon Sep 17 00:00:00 2001 From: hanguokai Date: Sat, 10 Aug 2013 06:35:01 +0800 Subject: add translation for dart. --- zh-cn/dart-cn.html.markdown | 205 +++++++++++++++++++++----------------------- 1 file changed, 97 insertions(+), 108 deletions(-) diff --git a/zh-cn/dart-cn.html.markdown b/zh-cn/dart-cn.html.markdown index 47b1a93b..64663b21 100644 --- a/zh-cn/dart-cn.html.markdown +++ b/zh-cn/dart-cn.html.markdown @@ -9,7 +9,7 @@ translators: Dart 是编程语言王国的新人。 它借鉴了许多其他主流语言,并且不会偏离它的兄弟语言 JavaScript 太多。 -就像 JavaScript,Dart 的目标是提供良好的浏览器集成。 +就像 JavaScript 一样,Dart 的目标是提供良好的浏览器集成。 Dart 最有争议的特性必然是它的可选类型。 @@ -17,15 +17,14 @@ Dart 最有争议的特性必然是它的可选类型。 import "dart:collection"; import "dart:math" as DM; -// Welcome to Learn Dart in 15 minutes. http://www.dartlang.org/ -// This is an executable tutorial. You can run it with Dart or on -// the Try Dart! site if you copy/paste it there. http://try.dartlang.org/ +// 欢迎进入15分钟的 Dart 学习。 http://www.dartlang.org/ +// 这是一个可实际执行的向导。你可以用 Dart 运行它 +// 或者在线执行! 可以把代码复制/粘贴到这个网站。 http://try.dartlang.org/ -// Function declaration and method declaration look the same. Function -// declarations can be nested. The declaration takes the form of -// name() {} or name() => singleLineExpression; -// The fat arrow function declaration has an implicit return for the result of -// the expression. +// 函数声明和方法声明看起来一样。 +// 函数声明可以嵌套。声明使用这种 name() {} 的形式, +// 或者 name() => 单行表达式; 的形式。 +// 右箭头的声明形式会隐式地返回表达式的结果。 example1() { example1nested1() { example1nested2() => print("Example1 nested 1 nested 2"); @@ -34,7 +33,7 @@ example1() { example1nested1(); } -// Anonymous functions don't include a name. +// 匿名函数没有函数名。 example2() { example2nested1(fn) { fn(); @@ -42,21 +41,20 @@ example2() { example2nested1(() => print("Example2 nested 1")); } -// When a function parameter is declared, the declaration can include the -// number of parameters the function takes by specifying the names of the -// parameters it takes. +// 当声明函数类型的参数的时候,声明中可以包含 +// 函数参数需要的参数,指定所需的参数名即可。 example3() { example3nested1(fn(informSomething)) { fn("Example3 nested 1"); } - example3planB(fn) { // Or don't declare number of parameters. + example3planB(fn) { // 或者不声明函数参数的参数 fn("Example3 plan B"); } example3nested1((s) => print(s)); example3planB((s) => print(s)); } -// Functions have closure access to outer variables. +// 函数有可以访问到外层变量的闭包。 var example4Something = "Example4 nested 1"; example4() { example4nested1(fn(informSomething)) { @@ -65,8 +63,8 @@ example4() { example4nested1((s) => print(s)); } -// Class declaration with a sayIt method, which also has closure access -// to the outer variable as though it were a function as seen before. +// 下面这个包含 sayIt 方法的类声明,同样有一个可以访问外层变量的闭包, +// 就像前面的函数一样。 var example5method = "Example5 sayIt"; class Example5Class { sayIt() { @@ -74,14 +72,14 @@ class Example5Class { } } example5() { - // Create an anonymous instance of the Example5Class and call the sayIt - // method on it. + // 创建一个 Example5Class 类的匿名实例, + // 并调用它的 sayIt 方法。 new Example5Class().sayIt(); } -// Class declaration takes the form of class name { [classBody] }. -// Where classBody can include instance methods and variables, but also -// class methods and variables. +// 类的声明使用这种形式 class name { [classBody] }. +// classBody 中可以包含实例方法和变量, +// 还可以包含类方法和变量。 class Example6Class { var example6InstanceVariable = "Example6 instance variable"; sayIt() { @@ -92,7 +90,7 @@ example6() { new Example6Class().sayIt(); } -// Class methods and variables are declared with "static" terms. +// 类方法和变量使用 static 关键词声明。 class Example7Class { static var example7ClassVariable = "Example7 class variable"; static sayItFromClass() { @@ -107,11 +105,10 @@ example7() { new Example7Class().sayItFromInstance(); } -// Literals are great, but there's a restriction for what literals can be -// outside of function/method bodies. Literals on the outer scope of class -// or outside of class have to be constant. Strings and numbers are constant -// by default. But arrays and maps are not. They can be made constant by -// declaring them "const". +// 字面量非常方便,但是对于在函数/方法的外层的字面量有一个限制, +// 类的外层或外面的字面量必需是常量。 +// 字符串和数字默认是常量。 +// 但是 array 和 map 不是。他们需要用 "const" 声明为常量。 var example8A = const ["Example8 const array"], example8M = const {"someKey": "Example8 const map"}; example8() { @@ -119,9 +116,9 @@ example8() { print(example8M["someKey"]); } -// Loops in Dart take the form of standard for () {} or while () {} loops, -// slightly more modern for (.. in ..) {}, or functional callbacks with many -// supported features, starting with forEach. +// Dart 中的循环使用标准的 for () {} 或 while () {} 的形式, +// 以及更加现代的 for (.. in ..) {} 的形式, 或者 +// 以 forEach 开头并具有许多特性支持的函数回调的形式。 var example9A = const ["a", "b"]; example9() { for (var i = 0; i < example9A.length; i++) { @@ -138,7 +135,7 @@ example9() { example9A.forEach((e) => print("Example9 forEach loop '${e}'")); } -// To loop over the characters of a string or to extract a substring. +// 遍历字符串中的每个字符或者提取其子串。 var example10S = "ab"; example10() { for (var i = 0; i < example10S.length; i++) { @@ -149,14 +146,14 @@ example10() { } } -// Int and double are the two supported number formats. +// 支持两种数字格式 int 和 double 。 example11() { var i = 1 + 320, d = 3.2 + 0.01; print("Example11 int ${i}"); print("Example11 double ${d}"); } -// DateTime provides date/time arithmetic. +// DateTime 提供了日期/时间的算法。 example12() { var now = new DateTime.now(); print("Example12 now '${now}'"); @@ -164,7 +161,7 @@ example12() { print("Example12 tomorrow '${now}'"); } -// Regular expressions are supported. +// 支持正则表达式。 example13() { var s1 = "some string", s2 = "some", re = new RegExp("^s.+?g\$"); match(s) { @@ -178,8 +175,8 @@ example13() { match(s2); } -// Boolean expressions need to resolve to either true or false, as no -// implicit conversions are supported. +// 布尔表达式必需被解析为 true 或 false, +// 因为不支持隐式转换。 example14() { var v = true; if (v) { @@ -188,17 +185,17 @@ example14() { v = null; try { if (v) { - // Never runs + // 不会执行 } else { - // Never runs + // 不会执行 } } catch (e) { print("Example14 null value causes an exception: '${e}'"); } } -// try/catch/finally and throw are used for exception handling. -// throw takes any object as parameter; +// try/catch/finally 和 throw 语句用于异常处理。 +// throw 语句可以使用任何对象作为参数。 example15() { try { try { @@ -214,8 +211,8 @@ example15() { } } -// To be efficient when creating a long string dynamically, use -// StringBuffer. Or you could join a string array. +// 要想有效地动态创建长字符串, +// 应该使用 StringBuffer。 或者 join 一个字符串的数组。 example16() { var sb = new StringBuffer(), a = ["a", "b", "c", "d"], e; for (e in a) { sb.write(e); } @@ -224,8 +221,8 @@ example16() { print("Example16 join string array '${a.join()}'"); } -// Strings can be concatenated by just having string literals next to -// one another with no further operator needed. +// 字符串连接只需让相邻的字符串字面量挨着, +// 不需要额外的操作符。 example17() { print("Example17 " "concatenate " @@ -233,44 +230,41 @@ example17() { "just like that"); } -// Strings have single-quote or double-quote for delimiters with no -// actual difference between the two. The given flexibility can be good -// to avoid the need to escape content that matches the delimiter being -// used. For example, double-quotes of HTML attributes if the string -// contains HTML content. +// 字符串使用单引号或双引号做分隔符,二者并没有实际的差异。 +// 这种灵活性可以很好地避免内容中需要转义分隔符的情况。 +// 例如,字符串内容里的 HTML 属性使用了双引号。 example18() { print('Example18 ' "Don't can't I'm Etc" ''); } -// Strings with triple single-quotes or triple double-quotes span -// multiple lines and include line delimiters. +// 用三个单引号或三个双引号表示的字符串 +// 可以跨越多行,并且包含行分隔符。 example19() { print('''Example19 Example19 Don't can't I'm Etc Example19 '''); } -// Strings have the nice interpolation feature with the $ character. -// With $ { [expression] }, the return of the expression is interpolated. -// $ followed by a variable name interpolates the content of that variable. -// $ can be escaped like so \$ to just add it to the string instead. +// 字符串可以使用 $ 字符插入内容。 +// 使用 $ { [expression] } 的形式,表达式的值会被插入到字符串中。 +// $ 跟着一个变量名会插入变量的值。 +// 如果要在字符串中插入 $ ,可以使用 \$ 的转义形式代替。 example20() { var s1 = "'\${s}'", s2 = "'\$s'"; print("Example20 \$ interpolation ${s1} or $s2 works."); } -// Optional types allow for the annotation of APIs and come to the aid of -// IDEs so the IDEs can better refactor, auto-complete and check for -// errors. So far we haven't declared any types and the programs have -// worked just fine. In fact, types are disregarded during runtime. -// Types can even be wrong and the program will still be given the -// benefit of the doubt and be run as though the types didn't matter. -// There's a runtime parameter that checks for type errors which is -// the checked mode, which is said to be useful during development time, -// but which is also slower because of the extra checking and is thus -// avoided during deployment runtime. +// 可选类型允许作为 API 的标注,并且可以辅助 IDE, +// 这样 IDE 可以更好地提供重构、自动完成和错误检测功能。 +// 目前为止我们还没有声明任何类型,并且程序运行地很好。 +// 事实上,类型在运行时会被忽略。 +// 类型甚至可以是错的,并且程序依然可以执行, +// 好像和类型完全无关一样。 +// 有一个运行时参数可以让程序进入检查模式,它会在运行时检查类型错误。 +// 这在开发时很有用,但是由于增加了额外的检查会使程序变慢, +// 因此应该避免在部署时使用。 class Example21 { List _names; Example21() { @@ -293,7 +287,7 @@ void example21() { print("Example21 names '${o.names}' and length '${o.length}'"); } -// Class inheritance takes the form of class name extends AnotherClassName {}. +// 类的继承形式是 class name extends AnotherClassName {} 。 class Example22A { var _name = "Some Name!"; get name => _name; @@ -304,13 +298,13 @@ example22() { print("Example22 class inheritance '${o.name}'"); } -// Class mixin is also available, and takes the form of +// 类也可以使用 mixin 的形式 : // class name extends SomeClass with AnotherClassName {}. -// It's necessary to extend some class to be able to mixin another one. -// The template class of mixin cannot at the moment have a constructor. -// Mixin is mostly used to share methods with distant classes, so the -// single inheritance doesn't get in the way of reusable code. -// Mixins follow the "with" statement during the class declaration. +// 必需继承某个类才能 mixin 另一个类。 +// 当前 mixin 的模板类不能有构造函数。 +// Mixin 主要是用来和辅助的类共享方法的, +// 这样单一继承就不会影响代码复用。 +// Mixin 声明在类定义的 "with" 关键词后面。 class Example23A {} class Example23Utils { addTwo(n1, n2) { @@ -329,10 +323,9 @@ example23() { print("Example23 addTwo(1, 2) results in '${r2}'"); } -// The Class constructor method uses the same name of the class and -// takes the form of SomeClass() : super() {}, where the ": super()" -// part is optional and it's used to delegate constant parameters to the -// super-parent's constructor. +// 类的构造函数名和类名相同,形式为 +// SomeClass() : super() {}, 其中 ": super()" 的部分是可选的, +// 它用来传递参数给父类的构造函数。 class Example24A { var _value; Example24A({value: "someValue"}) { @@ -350,9 +343,9 @@ example24() { print("Example24 calling super during constructor '${o2.value}'"); } -// There's a shortcut to set constructor parameters in case of simpler classes. -// Just use the this.parameterName prefix and it will set the parameter on -// an instance variable of same name. +// 对于简单的类,有一种设置构造函数参数的快捷方式。 +// 只需要使用 this.parameterName 的前缀, +// 它就会把参数设置为同名的实例变量。 class Example25 { var value, anotherValue; Example25({this.value, this.anotherValue}); @@ -363,9 +356,9 @@ example25() { "'${o.anotherValue}'"); } -// Named parameters are available when declared between {}. -// Parameter order can be optional when declared between {}. -// Parameters can be made optional when declared between []. +// 可以在大括号 {} 中声明命名参数。 +// 大括号 {} 中声明的参数的顺序是随意的。 +// 在中括号 [] 中声明的参数也是可选的。 example26() { var _name, _surname, _email; setConfig1({name, surname}) { @@ -385,13 +378,11 @@ example26() { "email '${_email}'"); } -// Variables declared with final can only be set once. -// In case of classes, final instance variables can be set via constant -// constructor parameter. +// 使用 final 声明的变量只能被设置一次。 +// 在类里面,final 实例变量可以通过常量的构造函数参数设置。 class Example27 { final color1, color2; - // A little flexibility to set final instance variables with syntax - // that follows the : + // 更灵活一点的方法是在冒号 : 后面设置 final 实例变量。 Example27({this.color1, color2}) : color2 = color2; } example27() { @@ -400,11 +391,11 @@ example27() { print("Example27 color is '${o.color1}' and '${o.color2}'"); } -// To import a library, use import "libraryPath" or if it's a core library, -// import "dart:libraryName". There's also the "pub" package management with -// its own convention of import "package:packageName". -// See import "dart:collection"; at the top. Imports must come before -// other code declarations. IterableBase comes from dart:collection. +// 要导入一个库,使用 import "libraryPath" 的形式,或者如果要导入的是 +// 核心库使用 import "dart:libraryName" 。还有一个称为 "pub" 的包管理工具, +// 它使用 import "package:packageName" 的约定形式。 +// 看下这个文件顶部的 import "dart:collection"; 语句。 +// 导入语句必需在其它代码声明之前出现。IterableBase 来自于 dart:collection 。 class Example28 extends IterableBase { var names; Example28() { @@ -417,11 +408,11 @@ example28() { o.forEach((name) => print("Example28 '${name}'")); } -// For control flow we have: -// * standard switch with must break statements -// * if-else if-else and ternary ..?..:.. operator -// * closures and anonymous functions -// * break, continue and return statements +// 对于控制流语句,我们有: +// * 必需带 break 的标准 switch 语句 +// * if-else 和三元操作符 ..?..:.. +// * 闭包和匿名函数 +// * break, continue 和 return 语句 example29() { var v = true ? 30 : 60; switch (v) { @@ -448,12 +439,12 @@ example29() { } else { continue; } - // Never gets here. + // 不会到这里。 } } -// Parse int, convert double to int, or just keep int when dividing numbers -// by using the ~/ operation. Let's play a guess game too. +// 解析 int,把 double 转成 int,或者使用 ~/ 操作符在除法计算时仅保留整数位。 +// 让我们也来场猜数游戏吧。 example30() { var gn, tooHigh = false, n, n2 = (2.0).toInt(), top = int.parse("123") ~/ n2, bottom = 0; @@ -481,11 +472,9 @@ example30() { } } -// Programs have only one entry point in the main function. -// Nothing is expected to be executed on the outer scope before a program -// starts running with what's in its main function. -// This helps with faster loading and even lazily loading of just what -// the program needs to startup with. +// 程序的唯一入口点是 main 函数。 +// 在程序开始执行 main 函数之前,不期望执行任何外层代码。 +// 这样可以帮助程序更快地加载,甚至仅惰性加载程序启动时需要的部分。 main() { print("Learn Dart in 15 minutes!"); [example1, example2, example3, example4, example5, example6, example7, @@ -500,8 +489,8 @@ main() { ## 延伸阅读 -Dart 有一个全面的网站。它涵盖了 API 参考、入门向导、文章以及更多, -包括一个有用的 Dart 在线试用。 +Dart 有一个综合性网站。它涵盖了 API 参考、入门向导、文章以及更多, +还包括一个有用的在线试用 Dart 页面。 http://www.dartlang.org/ http://try.dartlang.org/ -- cgit v1.2.3 From ad00ab70880df0eaaa356866dc9ed19f883977ba Mon Sep 17 00:00:00 2001 From: Vilson Vieira Date: Fri, 9 Aug 2013 22:30:21 -0300 Subject: pt-br translation to python --- pt-br/python-pt.html.markdown | 509 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 509 insertions(+) create mode 100644 pt-br/python-pt.html.markdown diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown new file mode 100644 index 00000000..c365ba96 --- /dev/null +++ b/pt-br/python-pt.html.markdown @@ -0,0 +1,509 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Vilson Vieira", "http://automata.cc"] +lang: pt-bf +filename: learnpython.py +--- + +Python foi criado por Guido Van Rossum no começo dos anos 90. Atualmente é uma +das linguagens de programação mais populares. Eu me apaixonei por Python, por +sua clareza de sintaxe. É basicamente pseudocódigo executável. + +Comentários serão muito apreciados! Você pode me contactar em +[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [arroba] +[serviço de email do google] + +Nota: Este artigo usa Python 2.7 especificamente, mas deveria ser aplicável a +qualquer Python 2.x. Logo haverá uma versão abordando Python 3! + +```python +# Comentários de uma linha começam com cerquilha (ou sustenido) +""" Strings de várias linhas podem ser escritas + usando três ", e são comumente usadas + como comentários +""" + +#################################################### +## 1. Tipos de dados primitivos e operadores +#################################################### + +# Você usa números normalmente +3 #=> 3 + +# Operadores matemáticos são aqueles que você já está acostumado +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# A divisão é um pouco estranha. A divisão de números inteiros arredonda +# para baixo o resultado, automaticamente +5 / 2 #=> 2 + +# Para concertar a divisão, precisamos aprender sobre números de ponto +# flutuante (conhecidos como 'float'). +2.0 # Isso é um 'float' +11.0 / 4.0 #=> 2.75 ahhh... muito melhor + +# Forçamos a precedência de operadores usando parênteses +(1 + 3) * 2 #=> 8 + +# Valores booleanos (ou 'boolean') são também tipos primitivos +True +False + +# Negamos usando 'not' +not True #=> False +not False #=> True + +# Testamos igualdade usando '==' +1 == 1 #=> True +2 == 1 #=> False + +# E desigualdade com '!=' +1 != 1 #=> False +2 != 1 #=> True + +# Mais comparações +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# As comparações podem ser encadeadas! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings são criadas com " ou ' +"Isso é uma string." +'Isso também é uma string.' + +# Strings podem ser somadas (ou melhor, concatenadas)! +"Olá " + "mundo!" #=> "Olá mundo!" + +# Uma string pode ser tratada como uma lista de caracteres +"Esta é uma string"[0] #=> 'E' + +# O caractere % pode ser usado para formatar strings, desta forma: +"%s podem ser %s" % ("strings", "interpoladas") + +# Um jeito novo de formatar strings é usando o método 'format'. +# Esse método é o jeito mais usado +"{0} podem ser {1}".format("strings", "formatadas") +# Você pode usar palavras-chave (ou 'keywords') se você não quiser contar. +"{nome} quer comer {comida}".format(nome="João", comida="lasanha") + +# 'None' é um objeto +None #=> None + +# Não use o operador de igualdade `==` para comparar objetos com 'None' +# Ao invés disso, use `is` +"etc" is None #=> False +None is None #=> True + +# O operador 'is' teste a identidade de um objeto. Isso não é +# muito útil quando estamos lidando com valores primitivos, mas é +# muito útil quando lidamos com objetos. + +# None, 0, e strings/listas vazias são todas interpretadas como 'False'. +# Todos os outros valores são 'True' +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Variáveis e Coleções +#################################################### + +# Imprimir na tela é muito fácil +print "Eu sou o Python. Prazer em te conhecer!" + + +# Nós não precisamos declarar variáveis antes de usá-las, basta usar! +alguma_variavel = 5 # A convenção é usar caixa_baixa_com_sobrescritos +alguma_variavel #=> 5 + +# Acessar uma variável que não teve nenhum valor atribuído anteriormente é +# uma exceção. +# Veja a seção 'Controle' para aprender mais sobre tratamento de exceção. +outra_variavel # Gera uma exceção de erro de nome + +# 'if' pode ser usado como uma expressão +"uepa!" if 3 > 2 else 2 #=> "uepa!" + +# Listas armazenam sequências de elementos +lista = [] +# Você pode inicializar uma lista com valores +outra_lista = [4, 5, 6] + +# Adicione elementos no final da lista usando 'append' +lista.append(1) # lista é agora [1] +lista.append(2) # lista é agora [1, 2] +lista.append(4) # lista é agora [1, 2, 4] +lista.append(3) # lista é agora [1, 2, 4, 3] +# Remova elementos do fim da lista usando 'pop' +lista.pop() #=> 3 e lista é agora [1, 2, 4] +# Vamos adicionar o elemento novamente +lista.append(3) # lista agora é [1, 2, 4, 3] novamente. + +# Acesse elementos de uma lista através de seu índices +lista[0] #=> 1 +# Acesse o último elemento com índice negativo! +lista[-1] #=> 3 + +# Tentar acessar um elemento fora dos limites da lista gera uma exceção +# do tipo 'IndexError' +lista[4] # Gera uma exceção 'IndexError' + +# Você pode acessar vários elementos ao mesmo tempo usando a sintaxe de +# limites +# (Para quem gosta de matemática, isso é um limite fechado/aberto) +lista[1:3] #=> [2, 4] +# Você pode omitir o fim se quiser os elementos até o final da lista +lista[2:] #=> [4, 3] +# O mesmo para o início +lista[:3] #=> [1, 2, 4] + +# Remova um elemento qualquer de uma lista usando 'del' +del lista[2] # lista agora é [1, 2, 3] + +# Você pode somar listas (obs: as listas originais não são modificadas) +lista + outra_lista #=> [1, 2, 3, 4, 5, 6] + +# Você também pode concatenar usando o método 'extend' (lista será modificada!) +lista.extend(outra_lista) # Agora lista é [1, 2, 3, 4, 5, 6] + +# Para checar se um elemento pertence a uma lista, use 'in' +1 in lista #=> True + +# Saiba quantos elementos uma lista possui com 'len' +len(lista) #=> 6 + + +# Tuplas são iguais a listas, mas são imutáveis +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Isso gera uma exceção do tipo TypeError + +# Você pode fazer nas tuplas todas aquelas coisas fez com a lista +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Você pode 'desempacotar' tuplas (ou listas) em variáveis, associando cada +# elemento da tupla/lista a uma variável correspondente +a, b, c = (1, 2, 3) # a agora é 1, b agora é 2, c agora é 3 +# Tuplas são criadas por padrão, mesmo se você não usar parênteses +d, e, f = 4, 5, 6 +# Sabendo disso, veja só como é fácil trocar os valores de duas variáveis! +e, d = d, e # d agora é 5, e agora é 4 + + +# Dicionários armazenam 'mapeamentos' (do tipo chave-valor) +dicionario_vazio = {} +# Aqui criamos um dicionário já contendo valores +dicionario = {"um": 1, "dois": 2, "três": 3} + +# Acesse valores usando [] +dicionario["um"] #=> 1 + +# Retorna uma lista com todas as chaves do dicionário +dicionario.keys() #=> ["três", "dois", "um"] +# Nota: A ordem das chaves não é garantida. +# O resultado no seu interpretador não necessariamente será igual a esse. + +# Retorna uma lista com todos os valores do dicionário +dicionario.values() #=> [3, 2, 1] +# Nota: A mesma nota acima sobre a ordenação é válida aqui. + +# Veja se uma chave qualquer está em um dicionário usando 'in' +"um" in dicionario #=> True +1 in dicionario #=> False + +# Tentar acessar uma chave que não existe gera uma exceção do tipo 'KeyError' +dicionario["quatro"] # Gera uma exceção KeyError + +# Você pode usar o método 'get' para evitar gerar a exceção 'KeyError'. +# Ao invés de gerar essa exceção, irá retornar 'None' se a chave não existir. +dicionario.get("um") #=> 1 +dicionario.get("quatro") #=> None +# O método 'get' suporta um argumento que diz qual valor deverá ser +# retornado se a chave não existir (ao invés de 'None'). +dicionario.get("um", 4) #=> 1 +dicionario.get("quatro", 4) #=> 4 + +# O método 'setdefault' é um jeito seguro de adicionar um novo par +# chave-valor a um dicionário, associando um valor padrão imutável à uma chave +dicionario.setdefault("cinco", 5) # dicionario["cinco"] é definido como 5 +dicionario.setdefault("cinco", 6) # dicionario["cinco"] ainda é igual a 5 + + +# Conjuntos (ou sets) armazenam ... bem, conjuntos +# Nota: lembre-se que conjuntos não admitem elementos repetidos! +conjunto_vazio = set() +# Podemos inicializar um conjunto com valores +conjunto = set([1, 2, 2, 3, 4]) # conjunto é set([1, 2, 3, 4]), sem repetição! + +# Desde o Python 2.7, {} pode ser usado para declarar um conjunto +conjunto = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Adicione mais ítens a um conjunto com 'add' +conjunto.add(5) # conjunto agora é {1, 2, 3, 4, 5} + +# Calcule a intersecção de dois conjuntos com & +outro_conj = {3, 4, 5, 6} +conjunto & outro_conj #=> {3, 4, 5} + +# Calcule a união de dois conjuntos com | +conjunto | outro_conj #=> {1, 2, 3, 4, 5, 6} + +# E a diferença entre dois conjuntos com - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Veja se um elemento existe em um conjunto usando 'in' +2 in conjunto #=> True +10 in conjunto #=> False + + +#################################################### +## 3. Controle +#################################################### + +# Para começar, vamos apenas criar uma variável +alguma_var = 5 + +# Aqui está uma expressão 'if'. Veja como a identação é importante em Python! +# Esses comandos irão imprimir "alguma_var é menor que 10" +if alguma_var > 10: + print "some_var é maior que 10." +elif some_var < 10: # Esse 'elif' é opcional + print "some_var é menor que 10." +else: # Esse 'else' também é opcional + print "some_var é igual a 10." + + +""" +Laços (ou loops) 'for' iteram em listas. +Irá imprimir: + cachorro é um mamífero + gato é um mamífero + rato é um mamífero +""" +for animal in ["cachorro", "gato", "rato"]: + # Você pode usar % para interpolar strings formatadas + print "%s é um mamífero" % animal + +""" +A função `range(um número)` retorna uma lista de números +do zero até o número dado. +Irá imprimir: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +Laços 'while' executam enquanto uma condição dada for verdadeira. +Irá imprimir: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Isso é um atalho para a expressão x = x + 1 + +# Tratamos excessões usando o bloco try/except +# Funciona em Python 2.6 e versões superiores: + +try: + # Use 'raise' para gerar um erro + raise IndexError("Isso é um erro de índice") +except IndexError as e: + pass # Pass é um operador que não faz nada, deixa passar. + # Usualmente você iria tratar a exceção aqui... + + +#################################################### +## 4. Funções +#################################################### + +# Use 'def' para definir novas funções +def soma(x, y): + print "x é %s e y é %s" % (x, y) + return x + y # Retorne valores usando 'return' + +# Chamando funções com parâmetros +soma(5, 6) #=> imprime "x é 5 e y é 6" e retorna o valor 11 + +# Um outro jeito de chamar funções é especificando explicitamente os valores +# de cada parâmetro com chaves +soma(y=6, x=5) # Argumentos com chaves podem vir em qualquer ordem. + +# Você pode definir funções que recebem um número qualquer de argumentos +# (respeitando a sua ordem) +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Você também pode definir funções que recebem um número qualquer de argumentos +# com chaves +def args_com_chaves(**ch_args): + return ch_args + +# Vamos chamar essa função para ver o que acontece +args_com_chaves(pe="grande", lago="Ness") #=> {"pe": "grande", "lago": "Ness"} + +# Você pode fazer as duas coisas ao mesmo tempo, se desejar +def todos_args(*args, **ch_wargs): + print args + print ch_args +""" +todos_args(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando você chamar funções, pode fazer o oposto do que fizemos até agora! +# Podemos usar * para expandir tuplas de argumentos e ** para expandir +# dicionários de argumentos com chave. +args = (1, 2, 3, 4) +ch_args = {"a": 3, "b": 4} +todos_args(*args) # equivalente a todos_args(1, 2, 3, 4) +todos_args(**ch_args) # equivalente a todos_args(a=3, b=4) +todos_args(*args, **ch_args) # equivalente a todos_args(1, 2, 3, 4, a=3, b=4) + +# Em Python, funções são elementos de primeira ordem (são como objetos, +# strings ou números) +def cria_somador(x): + def somador(y): + return x + y + return somador + +soma_10 = cria_somador(10) +soma_10(3) #=> 13 + +# Desta forma, existem também funções anônimas +(lambda x: x > 2)(3) #=> True + +# E existem funções de alta ordem por padrão +map(soma_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] +reduce(lambda x, y: x + y, [3, 4, 5, 6, 7]) #=> 25 + +# Nós podemos usar compreensão de listas para mapear e filtrar também +[soma_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 +#################################################### + +# Para criar uma nova classe, devemos herdar de 'object' +class Humano(object): + + # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa + # classe + especie = "H. sapiens" + + # Definimos um inicializador básico + def __init__(self, nome): + # Atribui o valor de argumento dado a um atributo da instância + self.nome = nome + + # Um método de instância. Todos os métodos levam 'self' como primeiro + # argumento + def diga(self, msg): + return "%s: %s" % (self.nome, msg) + + # Um método de classe é compartilhado por todas as instâncias + # Eles são chamados passando o nome da classe como primeiro argumento + @classmethod + def get_especie(cls): + return cls.especie + + # Um método estático é chamado sem uma referência a classe ou instância + @staticmethod + def ronca(): + return "*arrrrrrr*" + + +# Instancie uma classe +i = Humano(nome="Ivone") +print i.diga("oi") # imprime "Ivone: oi" + +j = Human("Joel") +print j.say("olá") #prints out "Joel: olá" + +# Chame nosso método de classe +i.get_especie() #=> "H. sapiens" + +# Modifique um atributo compartilhado +Humano.especie = "H. neanderthalensis" +i.get_especie() #=> "H. neanderthalensis" +j.get_especie() #=> "H. neanderthalensis" + +# Chame o método estático +Humano.ronca() #=> "*arrrrrrr*" + + +#################################################### +## 6. Módulos +#################################################### + +# Você pode importar módulos +import math +print math.sqrt(16) #=> 4 + +# Você pode importar funções específicas de um módulo +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Você também pode importar todas as funções de um módulo +# Atenção: isso não é recomendado! +from math import * + +# Você pode usar apelidos para os módulos, encurtando seus nomes +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Módulos em Python são apenas arquivos Python. Você +# pode escrever o seu próprio módulo e importá-lo. O nome do +# módulo será o mesmo que o nome do arquivo. + +# Você pode descobrir quais funções e atributos +# estão definidos em um módulo qualquer. +import math +dir(math) + + +``` + +## Pronto para mais? + +### Online e gratuito + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Livros impressos + +* [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 082dffc69714418456966bd7932f8e1b1fc8fcb0 Mon Sep 17 00:00:00 2001 From: pdn Date: Sun, 11 Aug 2013 01:49:33 -0700 Subject: Adding Common Lisp --- common-lisp.html.markdown | 531 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 531 insertions(+) create mode 100644 common-lisp.html.markdown diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown new file mode 100644 index 00000000..757b6a14 --- /dev/null +++ b/common-lisp.html.markdown @@ -0,0 +1,531 @@ +--- + +language: commonlisp +filename: commonlisp.lisp +contributors: + - ["Paul Nathan", "https://github.com/pnathan"] +--- + +ANSI Common Lisp is a general purpose, multi-paradigm programming +language suited for a wide variety of industry applications. It is +frequently referred to a programmable programming language. + +The classic starting point is [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/) + +Another popular and recent book is +[Land of Lisp](http://landoflisp.com/). + + + +```commonlisp + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 0. Syntax +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; General form. + +;; Lisp has two fundamental pieces of syntax: the ATOM and the +;; S-expression. Typically, grouped S-expressions are called `forms`. + +10 ; an atom; it evaluates to itself + +:THING ;Another atom; evaluating to the symbol :thing. + +t ; another atom, denoting true. + +(+ 1 2 3 4) ; an s-expression + +'(4 :foo t) ;another one + + +;;; Comments + +;; Single line comments start with a semicolon; use two for normal +;; comments, three for section comments, and four for file-level +;; comments. + +#| Block comments + can span multiple lines and... + #| + they can be nested! + |# +|# + +;;; Environment. + +;; A variety of implementations exist; most are +;; standard-conformant. CLISP is a good starting one. + +;; Libraries are managed through Quicklisp.org's Quicklisp system. + +;; Common Lisp is usually developed with a text editor and a REPL +;; (Read Evaluate Print Loop) running at the same time. The REPL +;; allows for interactive exploration of the program as it is "live" +;; in the system. + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 1. Primitive Datatypes and Operators +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Symbols + +'foo ; => FOO + +(intern "AAAA") ; => AAAA + +;;; Numbers +9999999999999999999999 ; integers +#b111 ; binary => 7 +#o111 ; octal => 73 +#x111 ; hexadecimal => 273 +3.14159 ; floating point +1/2 ; ratios +#C(1 2) ; complex numbers + + +;; Function application is written (f x y z ...) +;; where f is a function and x, y, z, ... are operands +;; If you want to create a literal list of data, use ' to stop it from +;; being evaluated - literally, "quote" the data. +'(+ 1 2) ; => (+ 1 2) +;; You can also call a function manually: +(funcall #'+ 1 2 3) ; => 6 +;; Some arithmetic operations +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + +;;; Booleans +t ; for true (any not-nil value is true) +nil ; for false +(not nil) ; => t +(and 0 t) ; => t +(or 0 nil) ; => 0 + +;;; Characters +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + +;;; Strings are fixed-length simple-arrays of characters. +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; backslash is an escaping character + +;; Strings can be concatenated too! +(concatenate 'string "Hello " "world!") ; => "Hello world!" + +;; A string can be treated like a list of characters +(elt "Apple" 0) ; => #\A + +;; format can be used to format strings: +(format nil "~a can be ~a" "strings" "formatted") + +;; Printing is pretty easy +(format t "Common Lisp is groovy. Dude.\n") + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variables +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; You can create a global (dynamically scoped) using defparameter +;; a variable name can use any character except: ()[]{}",'`;#|\ +(defparameter *some-var* 5) +*some-var* ; => 5 + +;; You can also use unicode characters. Not very easy to use though... +(defparameter *foo#\u03BBooo* nil) + + +;; Accessing a previously unassigned variable is an undefined +;; behavior (but possible). Don't do it. + +;; Local binding: `me` is bound to "dance with you" only within the +;; (let ...). Let always returns the value of the last `form` in the +;; let form. + +(let ((me "dance with you")) + me) +;; => "dance with you" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Structs and Collections +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Structs +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) +(dog-p *rover*) ; => t ;; ewww) +(dog-name *rover*) ; => "rover" + +;;; Pairs +;; `cons' constructs pairs, `car' and `cdr' extract the first +;; and second elements +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + +;;; Lists + +;; Lists are linked-list data structures, made of `cons' pairs and end +;; with a `nil' (or '()) to mark the end of the list +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) +;; `list' is a convenience variadic constructor for lists +(list 1 2 3) ; => '(1 2 3) +;; and a quote can also be used for a literal list value +'(1 2 3) ; => '(1 2 3) + +;; Can still use `cons' to add an item to the beginning of a list +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; Use `append' to add lists together +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; Lists are a very basic type, so there is a wide variety of functionality for +;; them, a few examples: +(mapcar #1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => nil +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; Vectors + +;; Vectors are fixed-length arrays +#(1 2 3) ; => #(1 2 3) + +;; Use concatenate to add vectors together +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; Arrays + +;; Both vectors and strings are special-cases of arrays. + +;; 2D arrays + +(make-array (list 2 2)) + +; => #2A((0 0) (0 0)) + +(make-array (list 2 2 2)) + +; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + + +; access the element at 1,1,1, +(aref (make-array (list 2 2 2)) 1 1 1) + +; => 0 + +;;; Sets are just lists: + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;;; Dictionaries are implemented as hash tables. + +;; Create a hash table +(defparameter m (hash-table)) + +;; set a value +(setf (gethash 'a hash-table 1)) + +;; Retrieve a value +(gethash 'a m) ; => 1 + +;; Retrieving a non-present value returns a nil + (gethash m 'd) ;=> nil + +;; You can provide a default value for missing keys +(gethash m 'd :not-found) ; => :NOT-FOUND + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Functions +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `lambda' to create anonymous functions. +;; A function always returns the value of its last expression +(lambda () "Hello World") ; => # + +;; Use funcall to call lambda functions +(funcall (lambda () "Hello World")) ; => "Hello World" + +;; De-anonymize the function +(defun hello-world () "Hello World") +(hello-world) ; => "Hello World" + +;; The () in the above is the list of arguments for the function +(defun hello (name) + (format nil "Hello, ~a " name)) +(hello "Steve") ; => "Hello, Steve" + +;; Functions can have optional arguments; they default to nil + +(defun hello (name &optional from) + (if from + (format t "Hello, ~a, from ~a" name from) + (format t "Hello, ~a" name))) + + (hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas + +;; And the defaults can be set... +(defun hello (name &optional (from "The world")) + (format t "Hello, ~a, from ~a" name from)) + + +;; And of course, keywords are allowed as well... usually more +;; flexible than &optional. + +(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) + (format t "Hello, ~a ~a, from ~a" honorific name from)) + +(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world + +(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") +; => Hello, Mr Jim, from the alpacas you met last summer + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Equality +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Common Lisp has a sophisticated equality system. + +;; for numbers use `=' +(= 3 3.0) ; => t +(= 2 1) ; => nil + +;; for object identity (approximately) use `eq?' +(eql 3 3) ; => t +(eql 3 3.0) ; => nil +(eql (list 3) (list 3)) ; => nil + +;; for collections use `equal' +(equal (list 'a 'b) (list 'a 'b)) ; => t +(equal (list 'a 'b) (list 'b 'a)) ; => nil + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Control Flow +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Conditionals + +(if t ; test expression + "this is true" ; then expression + "this is false") ; else expression +; => "this is true" + +;; In conditionals, all non-nil values are treated as true +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;; `cond' chains a series of tests to select a result +(cond ((> 2 2) (error "wrong!")) + ((< 2 2) (error "wrong again!")) + (t 'ok)) ; => 'OK + +;; Typecase switches on the type of the value +(typecase 1 + (string :string) + (integer :int)) + +; => :int + +;;; Iteration + +;; Of course recursion is supported: + +(defun walker (n) + (if (= n 0) + :walked + (walker (1- n)))) + +(walker) ; => :walked + +;; Most of the time, we use DOLIST or LOOP + + +(dolist (i '(1 2 3 4)) + (format t "~a" i)) + +; => 1234 + +(loop for i from 0 below 10 + collect i) + +; => (0 1 2 3 4 5 6 7 8 9) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutation +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `setf' to assign a new value to an existing variable. This was +;; demonstrated earlier in the hash table example. + +(let ((variable 10)) + (setf variable 10)) + ; => 10 + + +;; Good Lisp style is to minimize destructive functions and to avoid +;; mutation when reasonable. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Classes and Objects +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; No more Animal classes, let's have Human-Powered Mechanical +;; Conveyances. + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency) + :initarg :average-efficiency) + (:documentation "A human powered conveyance")) + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + +;; Calling DESCRIBE on the human-powered-conveyance class in the REPL gives: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;; Note the reflective behavior available to you! Common Lisp is +;; designed to be an interactive system + +;; To define a method, let's find out what our circumference of the +;; bike turns out to be using the equation: C = d * pi + +(defmethod circumference ((object bicycle)) + (* 3.14159 (wheel-size object))) + +;; Let's suppose we find out that the efficiency value of the number +;; of rowers in a canoe is roughly logarithmic. This should probably be set +;; in the constructor/initializer. + +;; Here's how to initialize your instance after Common Lisp gets done +;; constructing it: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + +;; Then to construct an instance and check the average efficiency... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros let you extend the syntax of the language + +;; Common Lisp doesn't come with a WHILE loop- let's add one. +;; If we obey our assembler instincts, we wind up with: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. + +`condition` is tested prior to each execution of `body`" + (let ((block-name (gensym))) + `(tagbody + (when (not ,condition) + (go ,block-name)) + (progn + ,@body) + ,block-name))) + +;; Let's look at the high-level version of this: + + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. + +`condition` is tested prior to each execution of `body`" + `(loop while ,condition + do + ,@body)) + +;; However, with a modern compiler, this is not required; the LOOP +;; form compiles equally well and is easier to read. + +;; Note that ` is used, as well as , and @. ` is a quote-type operator +;; known as quasiquote; it allows the use of ,. , allows "unquoting" +;; variables. @ interpolates lists. + +;; Gensym creates a unique symbol guaranteed to not exist elsewhere in +;; the system. This is because macros are expanded at compile time and +;; variables declared in the macro can collide with variables used in +;; regular code. + +;; See Practical Common Lisp for more information on macros. + + +## Further Reading + +[Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/) + + +## Credits. + +Lots of thanks to the Scheme people for rolling up a great starting +point which could be easily moved to Common Lisp. -- cgit v1.2.3 From 2f1db5d8ae8a8c437e9c225211dadaf7b1f0c58d Mon Sep 17 00:00:00 2001 From: Johannes Choo Date: Sun, 11 Aug 2013 20:11:44 +0800 Subject: fixed wrong sample output in r.htl.markdown --- r.html.markdown | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index dd94072b..e4adb5dc 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -428,15 +428,17 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # => # , , 1 # -# [,1] [,2] -# [1,] 1 4 -# [2,] 2 5 +# [,1] [,2] +# [1,] 2 8 +# [2,] 300 9 +# [3,] 4 0 # # , , 2 # # [,1] [,2] -# [1,] 8 1 -# [2,] 9 2 +# [1,] 5 66 +# [2,] 60 7 +# [3,] 0 847 # LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES) -- cgit v1.2.3 From 80ea89b58a470f9b1a4ce7710f4de6ac69dee5ee Mon Sep 17 00:00:00 2001 From: Camilo Garrido Date: Sun, 11 Aug 2013 12:45:31 -0400 Subject: Ruby file translated to spanish --- es-es/ruby-es.html.markdown | 377 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 377 insertions(+) create mode 100644 es-es/ruby-es.html.markdown diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown new file mode 100644 index 00000000..fa039676 --- /dev/null +++ b/es-es/ruby-es.html.markdown @@ -0,0 +1,377 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] +translators: + - ["Camilo Garrido", "http://www.twitter.com/hirohope"] +lang: es-es +--- + +```ruby +# Esto es un comentario + +=begin +Este es un comentario multilínea +Nadie los usa. +Tu tampoco deberías +=end + +# Lo primero y principal: Todo es un objeto + +# Los números son objetos + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Un poco de aritmética básica +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# La aritmética es sólo azúcar sintáctico +# para llamar un método de un objeto +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Los valores especiales son objetos +nil # Nada que ver aqui +true # Verdadero +false # Falso + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Igualdad +1 == 1 #=> true +2 == 1 #=> false + +# Desigualdad +1 != 1 #=> false +2 != 1 #=> true +!true #=> false +!false #=> true + +# Además de 'false', 'nil' es otro valor falso + +!nil #=> true +!false #=> true +!0 #=> false + +# Más comparaciones +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Los strings son objetos + +'Soy un string'.class #=> String +"Soy un string también".class #=> String + +referente = "usar interpolacion de strings" +"Yo puedo #{referente} usando strings de comillas dobles" +#=> "Yo puedo usar interpolacion de strings usando strings de comillas dobles" + + +# Imprime a la salida estándar +puts "¡Estoy imprimiendo!" + +# Variables +x = 25 #=> 25 +x #=> 25 + +# Nota que la asignación retorna el valor asignado +# Esto significa que puedes hacer múltiples asignaciones: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Por convención, usa snake_case para nombres de variables +snake_case = true + +# Usa nombres de variables descriptivos +ruta_para_la_raiz_de_un_projecto = '/buen/nombre/' +ruta = '/mal/nombre/' + +# Los símbolos (son objetos) +# Los símbolos son inmutables, constantes reusables representadas internamente por un +# valor entero. Son usalmente usados en vez de strings para expresar eficientemente +# valores específicos y significativos + +:pendiente.class #=> Symbol + +status = :pendiente + +status == :pendiente #=> true + +status == 'pendiente' #=> false + +status == :aprovado #=> false + +# Arreglos + +# Esto es un arreglo +[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Arreglos pueden contener elementos de distintos tipos + +arreglo = [1, "hola", false] #=> => [1, "hola", false] + +# Arreglos pueden ser indexados +# Desde el frente +arreglo[0] #=> 1 +arreglo[12] #=> nil + +# Tal como la aritmética, el acceso como variable[índice] +# es sólo azúcar sintáctica +# para llamar el método [] de un objeto +arreglo.[] 0 #=> 1 +arreglo.[] 12 #=> nil + +# Desde el final +arreglo[-1] #=> 5 + +# Con un índice de inicio y final +arreglo[2, 4] #=> [3, 4, 5] + +# O con rango +arreglo[1..3] #=> [2, 3, 4] + +# Añade elementos a un arreglo así +arreglo << 6 #=> [1, 2, 3, 4, 5, 6] + +# Hashes son los diccionarios principales de Ruby con pares llave/valor. +# Hashes se denotan con llaves: +hash = {'color' => 'verde', 'numero' => 5} + +hash.keys #=> ['color', 'numero'] + +# Hashes pueden buscar rápidamente una llave: +hash['color'] #=> 'verde' +hash['numero'] #=> 5 + +# Preguntarle a un hash por una llave que no existe retorna 'nil': +hash['nada aqui'] #=> nil + +# Itera sobre un hash con el método 'each': +hash.each do |k, v| + puts "#{k} is #{v}" +end + +# Desde Ruby 1.9, hay una sintaxis especial cuando se usa un símbolo como llave: + +nuevo_hash = { defcon: 3, accion: true} + +nuevo_hash.keys #=> [:defcon, :accion] + +# Tip: Tanto los arreglos como los hashes son Enumerable (enumerables) +# Comparten muchos métodos útiles tales como 'each', 'map', 'count', y más + +# Estructuras de Control + +if true + "declaracion 'if'" +elsif false + "else if, opcional" +else + "else, tambien opcional" +end + +for contador in 1..5 + puts "iteracion #{contador}" +end +#=> iteracion 1 +#=> iteracion 2 +#=> iteracion 3 +#=> iteracion 4 +#=> iteracion 5 + +# Aunque +# Nadie usa los ciclos `for` +# Usa `each`, así: + +(1..5).each do |contador| + puts "iteracion #{contador}" +end +#=> iteracion 1 +#=> iteracion 2 +#=> iteracion 3 +#=> iteracion 4 +#=> iteracion 5 + +counter = 1 +while counter <= 5 do + puts "iteracion #{counter}" + counter += 1 +end +#=> iteracion 1 +#=> iteracion 2 +#=> iteracion 3 +#=> iteracion 4 +#=> iteracion 5 + +nota = 'B' + +case nota +when 'A' + puts "Muy bien muchacho" +when 'B' + puts "Mejor suerte para la proxima" +when 'C' + puts "Puedes hacerlo mejor" +when 'D' + puts "Sobreviviendo" +when 'F' + puts "¡Reprobaste!" +else + puts "Sistema alternativo de notas, ¿eh?" +end + +# Funciones + +def doble(x) + x * 2 +end + +# Funciones (y todos los bloques) implícitamente retornan el valor de la última instrucción +doble(2) #=> 4 + +# Paréntesis son opcionales cuando el resultado es ambiguo +doble 3 #=> 6 + +doble doble 3 #=> 12 + +def suma(x,y) + x + y +end + +# Arguméntos del método son separados por coma +suma 3, 4 #=> 7 + +suma suma(3,4), 5 #=> 12 + +# yield +# Todos los métodos tienen un parámetro de bloqueo opcional e implícitp +# puede llamarse con la palabra clave 'yield' + +def alrededor + puts "{" + yield + puts "}" +end + +alrededor { puts 'hola mundo' } + +# { +# hola mundo +# } + + +# Define una clase con la palabra clave 'class' +class Humano + + # Una variable de clase. Es compartida por todas las instancias de la clase. + @@species = "H. sapiens" + + # Inicializador Básico + def initialize(nombre, edad=0) + # Asigna el argumento a la variable de instancia 'nombre' + @nombre = nombre + # Si no dan edad, se usará el valor por defecto en la lista de argumentos. + @edad = edad + end + + # Método 'setter' (establecer) básico + def nombre=(nombre) + @nombre = nombre + end + + # Método 'getter' (obtener) básico + def nombre + @nombre + end + + # Un método de clase usa 'self' (sí mismo) para distinguirse de métodos de instancia. + # Sólo puede ser llamado en la clase, no por una instancia. + def self.decir(mensaje) + puts "#{mensaje}" + end + + def especie + @@especie + end + +end + + +# Instancia una clase +jim = Humano.new("Jim Halpert") + +dwight = Humano.new("Dwight K. Schrute") + +# Llamemos un par de métodos +jim.especie #=> "H. sapiens" +jim.nombre #=> "Jim Halpert" +jim.nombre = "Jim Halpert II" #=> "Jim Halpert II" +jim.nombre #=> "Jim Halpert II" +dwight.especie #=> "H. sapiens" +dwight.nombre #=> "Dwight K. Schrute" + +# Llama el método de clase +Humano.decir("Hi") #=> "Hi" + +# Las clases también son un objeto en ruby. Por lo cual, las clases también pueden tener variables de instancia. +# Variables de clase son compartidas a través de la clase y todos sus descendientes. + +# clase base +class Humano + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(valor) + @@foo = valor + end +end + +# clase derivada +class Trabajador < Humano +end + +Humano.foo # 0 +Trabajador.foo # 0 + +Humano.foo = 2 # 2 +Trabajador.foo # 2 + +# Las variables de instancia de la clase no son compartidas por los descendientes de la clase. + +class Humano + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(valor) + @bar = valor + end +end + +class Doctor < Humano +end + +Human.bar # 0 +Doctor.bar # nil + +``` -- cgit v1.2.3 From f39aa6adfb98086e98773f7871c3ba70f97c5771 Mon Sep 17 00:00:00 2001 From: pdn Date: Sun, 11 Aug 2013 10:39:13 -0700 Subject: Fixes based on pkh's comments. --- common-lisp.html.markdown | 251 ++++++++++++++++++++++++++++++---------------- 1 file changed, 162 insertions(+), 89 deletions(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 757b6a14..9f2c9957 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -71,16 +71,21 @@ t ; another atom, denoting true. ;;; Symbols -'foo ; => FOO +'foo ; => FOO Notice that the symbol is upper-cased automatically. + +;; Intern manually creates a symbol from a string. (intern "AAAA") ; => AAAA +(intern "aaa") ; => |aaa| + ;;; Numbers 9999999999999999999999 ; integers #b111 ; binary => 7 #o111 ; octal => 73 #x111 ; hexadecimal => 273 -3.14159 ; floating point +3.14159s0 ; single +3.14159d0 ; double 1/2 ; ratios #C(1 2) ; complex numbers @@ -93,42 +98,42 @@ t ; another atom, denoting true. ;; You can also call a function manually: (funcall #'+ 1 2 3) ; => 6 ;; Some arithmetic operations -(+ 1 1) ; => 2 -(- 8 1) ; => 7 -(* 10 2) ; => 20 -(expt 2 3) ; => 8 -(mod 5 2) ; => 1 -(/ 35 5) ; => 7 -(/ 1 3) ; => 1/3 +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 (+ #C(1 2) #C(6 -4)) ; => #C(7 -2) -;;; Booleans -t ; for true (any not-nil value is true) -nil ; for false -(not nil) ; => t -(and 0 t) ; => t -(or 0 nil) ; => 0 + ;;; Booleans +t ; for true (any not-nil value is true) +nil ; for false - and the empty list +(not nil) ; => t +(and 0 t) ; => t +(or 0 nil) ; => 0 -;;; Characters -#\A ; => #\A -#\λ ; => #\GREEK_SMALL_LETTER_LAMDA -#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + ;;; Characters +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA -;;; Strings are fixed-length simple-arrays of characters. +;;; Strings are fixed-length arrays of characters. "Hello, world!" "Benjamin \"Bugsy\" Siegel" ; backslash is an escaping character ;; Strings can be concatenated too! (concatenate 'string "Hello " "world!") ; => "Hello world!" -;; A string can be treated like a list of characters +;; A string can be treated like a sequence of characters (elt "Apple" 0) ; => #\A ;; format can be used to format strings: (format nil "~a can be ~a" "strings" "formatted") -;; Printing is pretty easy -(format t "Common Lisp is groovy. Dude.\n") +;; Printing is pretty easy; ~% is the format specifier for newline. +(format t "Common Lisp is groovy. Dude.~%") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -136,22 +141,26 @@ nil ; for false ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; You can create a global (dynamically scoped) using defparameter ;; a variable name can use any character except: ()[]{}",'`;#|\ + +;; Dynamically scoped variables should have earmuffs in their name! + (defparameter *some-var* 5) *some-var* ; => 5 -;; You can also use unicode characters. Not very easy to use though... -(defparameter *foo#\u03BBooo* nil) +;; You can also use unicode characters. +(defparameter *AΛB* nil) -;; Accessing a previously unassigned variable is an undefined -;; behavior (but possible). Don't do it. +;; Accessing a previously unbound variable is an +;; undefined behavior (but possible). Don't do it. + ;; Local binding: `me` is bound to "dance with you" only within the ;; (let ...). Let always returns the value of the last `form` in the ;; let form. (let ((me "dance with you")) - me) + me) ;; => "dance with you" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -165,9 +174,12 @@ nil ; for false :breed "collie" :age 5)) *rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) + (dog-p *rover*) ; => t ;; ewww) (dog-name *rover*) ; => "rover" +;; Dog-p, make-dog, and dog-name are all created by defstruct! + ;;; Pairs ;; `cons' constructs pairs, `car' and `cdr' extract the first ;; and second elements @@ -188,17 +200,21 @@ nil ; for false ;; Can still use `cons' to add an item to the beginning of a list (cons 4 '(1 2 3)) ; => '(4 1 2 3) -;; Use `append' to add lists together +;; Use `append' to - surprisingly - append lists together (append '(1 2) '(3 4)) ; => '(1 2 3 4) -;; Lists are a very basic type, so there is a wide variety of functionality for +;; Or use concatenate - + +(concatenate + +;; Lists are a very central type, so there is a wide variety of functionality for ;; them, a few examples: -(mapcar #1+ '(1 2 3)) ; => '(2 3 4) -(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) -(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) -(every #'evenp '(1 2 3 4)) ; => nil -(some #'oddp '(1 2 3 4)) ; => T -(butlast '(subject verb object)) ; => (SUBJECT VERB) +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => nil +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) ;;; Vectors @@ -217,60 +233,96 @@ nil ; for false (make-array (list 2 2)) +;; (make-array '(2 2)) works as well. + ; => #2A((0 0) (0 0)) (make-array (list 2 2 2)) ; => #3A(((0 0) (0 0)) ((0 0) (0 0))) +;; Caution- the default initial values are +;; implementation-defined. Here's how to define them: -; access the element at 1,1,1, +(make-array '(2) :initial-element 'unset) + +; => #(UNSET UNSET) + +;; And, to access the element at 1,1,1 - (aref (make-array (list 2 2 2)) 1 1 1) ; => 0 -;;; Sets are just lists: +;;; Naively, sets are just lists: (set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) (intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 (union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) (adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) +;; But you'll want to use a better data structure than a linked list +;; for performant work! + ;;; Dictionaries are implemented as hash tables. ;; Create a hash table -(defparameter m (hash-table)) +(defparameter *m* (make-hash-table)) ;; set a value -(setf (gethash 'a hash-table 1)) +(setf (gethash 'a *m*) 1) ;; Retrieve a value -(gethash 'a m) ; => 1 +(gethash 'a *m*) ; => 1, t -;; Retrieving a non-present value returns a nil - (gethash m 'd) ;=> nil +;; Detail - Common Lisp has multiple return values possible. gethash +;; returns t in the second value if anything was found, and nil if +;; not. + +;; Retrieving a non-present value returns nil + (gethash *m* 'd) ;=> nil, nil ;; You can provide a default value for missing keys -(gethash m 'd :not-found) ; => :NOT-FOUND +(gethash *m* 'd :not-found) ; => :NOT-FOUND + +;; Let's handle the multiple return values here in code. + +(multiple-value-bind + (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind + (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 3. Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Use `lambda' to create anonymous functions. -;; A function always returns the value of its last expression -(lambda () "Hello World") ; => # +;; A function always returns the value of its last expression. +;; The exact printable representation of a function will vary... + +(lambda () "Hello World") ; => # ;; Use funcall to call lambda functions (funcall (lambda () "Hello World")) ; => "Hello World" +;; Or Apply +(apply (lambda () "Hello World") nil) ; => "Hello World" + ;; De-anonymize the function -(defun hello-world () "Hello World") +(defun hello-world () + "Hello World") (hello-world) ; => "Hello World" ;; The () in the above is the list of arguments for the function (defun hello (name) - (format nil "Hello, ~a " name)) + (format nil "Hello, ~a " name)) + (hello "Steve") ; => "Hello, Steve" ;; Functions can have optional arguments; they default to nil @@ -286,6 +338,12 @@ nil ; for false (defun hello (name &optional (from "The world")) (format t "Hello, ~a, from ~a" name from)) +(hello "Steve") +; => Hello, Steve, from The world + +(hello "Steve" "the alpacas") +; => Hello, Steve, from the alpacas + ;; And of course, keywords are allowed as well... usually more ;; flexible than &optional. @@ -302,18 +360,18 @@ nil ; for false ;; 4. Equality ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Common Lisp has a sophisticated equality system. +;; Common Lisp has a sophisticated equality system. A couple are covered yere. ;; for numbers use `=' (= 3 3.0) ; => t (= 2 1) ; => nil -;; for object identity (approximately) use `eq?' +;; for object identity (approximately) use `eql` (eql 3 3) ; => t (eql 3 3.0) ; => nil (eql (list 3) (list 3)) ; => nil -;; for collections use `equal' +;; for lists, strings, and bit-vectors use `equal' (equal (list 'a 'b) (list 'a 'b)) ; => t (equal (list 'a 'b) (list 'b 'a)) ; => nil @@ -342,8 +400,8 @@ nil ; for false ;; Typecase switches on the type of the value (typecase 1 - (string :string) - (integer :int)) + (string :string) + (integer :int)) ; => :int @@ -352,9 +410,9 @@ nil ; for false ;; Of course recursion is supported: (defun walker (n) - (if (= n 0) - :walked - (walker (1- n)))) + (if (zerop 0) + :walked + (walker (1- n)))) (walker) ; => :walked @@ -362,12 +420,12 @@ nil ; for false (dolist (i '(1 2 3 4)) - (format t "~a" i)) + (format t "~a" i)) ; => 1234 (loop for i from 0 below 10 - collect i) + collect i) ; => (0 1 2 3 4 5 6 7 8 9) @@ -380,8 +438,8 @@ nil ; for false ;; demonstrated earlier in the hash table example. (let ((variable 10)) - (setf variable 10)) - ; => 10 + (setf variable 2)) + ; => 2 ;; Good Lisp style is to minimize destructive functions and to avoid @@ -395,34 +453,44 @@ nil ; for false ;; Conveyances. (defclass human-powered-conveyance () - ((velocity - :accessor velocity - :initarg :velocity) - (average-efficiency - :accessor average-efficiency) - :initarg :average-efficiency) - (:documentation "A human powered conveyance")) + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency) + :initarg :average-efficiency) + (:documentation "A human powered conveyance")) + +;; defclass, followed by name, followed by the superclass list, +;; followed by slot list, followed by optional qualities such as +;; :documentation. + +;; When no superclass list is set, the empty list defaults to the +;; standard-object class. This *can* be changed, but not until you +;; know what you're doing. Look up the Art of the Metaobject Protocol +;; for more information. (defclass bicycle (human-powered-conveyance) - ((wheel-size - :accessor wheel-size - :initarg :wheel-size - :documentation "Diameter of the wheel.") - (height - :accessor height - :initarg :height))) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) (defclass recumbent (bicycle) - ((chain-type - :accessor chain-type - :initarg :chain-type))) + ((chain-type + :accessor chain-type + :initarg :chain-type))) (defclass unicycle (human-powered-conveyance) nil) (defclass canoe (human-powered-conveyance) - ((number-of-rowers - :accessor number-of-rowers - :initarg :number-of-rowers))) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + ;; Calling DESCRIBE on the human-powered-conveyance class in the REPL gives: @@ -438,7 +506,7 @@ nil ; for false ; Direct superclasses: STANDARD-OBJECT ; Direct subclasses: UNICYCLE, BICYCLE, CANOE ; Not yet finalized. -; Direct slots: +(defparameter *foo#\u03BBooo* nil) ; Direct slots: ; VELOCITY ; Readers: VELOCITY ; Writers: (SETF VELOCITY) @@ -450,14 +518,16 @@ nil ; for false ;; designed to be an interactive system ;; To define a method, let's find out what our circumference of the -;; bike turns out to be using the equation: C = d * pi +;; bike wheel turns out to be using the equation: C = d * pi (defmethod circumference ((object bicycle)) - (* 3.14159 (wheel-size object))) + (* pi (wheel-size object))) + +;; pi is defined in Lisp already for us! ;; Let's suppose we find out that the efficiency value of the number -;; of rowers in a canoe is roughly logarithmic. This should probably be set -;; in the constructor/initializer. +;; of rowers in a canoe is roughly logarithmic. This should probably be set +;; in the constructor/initializer. ;; Here's how to initialize your instance after Common Lisp gets done ;; constructing it: @@ -488,7 +558,7 @@ nil ; for false `condition` is tested prior to each execution of `body`" (let ((block-name (gensym))) `(tagbody - (when (not ,condition) + (unless ,condition (go ,block-name)) (progn ,@body) @@ -503,13 +573,14 @@ nil ; for false `condition` is tested prior to each execution of `body`" `(loop while ,condition do - ,@body)) + (progn + ,@body))) ;; However, with a modern compiler, this is not required; the LOOP ;; form compiles equally well and is easier to read. -;; Note that ` is used, as well as , and @. ` is a quote-type operator -;; known as quasiquote; it allows the use of ,. , allows "unquoting" +;; Note that ``` is used, as well as `,` and `@`. ``` is a quote-type operator +;; known as quasiquote; it allows the use of `,` . `,` allows "unquoting" ;; variables. @ interpolates lists. ;; Gensym creates a unique symbol guaranteed to not exist elsewhere in @@ -529,3 +600,5 @@ nil ; for false Lots of thanks to the Scheme people for rolling up a great starting point which could be easily moved to Common Lisp. + +- [Paul Khoung](https://github.com/pkhuong) for some great reviewing. -- cgit v1.2.3 From fa910a4bc9044b4ac60c57e568fcd265657f2bcc Mon Sep 17 00:00:00 2001 From: pdn Date: Sun, 11 Aug 2013 10:40:51 -0700 Subject: Foolishness borne of haste --- common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 9f2c9957..24b6947f 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -410,7 +410,7 @@ nil ; for false - and the empty list ;; Of course recursion is supported: (defun walker (n) - (if (zerop 0) + (if (zerop n) :walked (walker (1- n)))) -- cgit v1.2.3 From 00b25ad4575948574b47adda0f672d6bd93528b5 Mon Sep 17 00:00:00 2001 From: lpy Date: Mon, 12 Aug 2013 11:09:08 +0800 Subject: Add Scala zh-cn translation and add link to Scala documentation in scala.html.markdown --- scala.html.markdown | 4 +- zh-cn/scala-cn.html.markdown | 411 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 413 insertions(+), 2 deletions(-) create mode 100644 zh-cn/scala-cn.html.markdown diff --git a/scala.html.markdown b/scala.html.markdown index fef09404..e6720c02 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -408,9 +408,9 @@ for(line <- Source.fromPath("myfile.txt").getLines()) [Scala for the impatient](http://horstmann.com/scala/) -[Twitter Scala school(http://twitter.github.io/scala_school/) +[Twitter Scala school](http://twitter.github.io/scala_school/) -[The scala documentation] +[The scala documentation](http://www.scala-lang.org/documentation/) Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown new file mode 100644 index 00000000..419f0fb2 --- /dev/null +++ b/zh-cn/scala-cn.html.markdown @@ -0,0 +1,411 @@ +--- +language: Scala +filename: learnscala.scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] +translators: + - ["Peiyong Lin", ""] +filename: learn.scala +lang: zh-cn +--- + +Scala - 一门可拓展性的语言 + +```cpp + +/* + 自行设置: + + 1) 下载 Scala - http://www.scala-lang.org/downloads + 2) unzip/untar 到你喜欢的地方,放在路径中的 bin 目录下 + 3) 在终端输入 scala,开启 Scala 的 REPL,你会看到提示符: + + scala> + + 这就是所谓的 REPL,你现在可以在其中运行命令,让我们做到这一点: +*/ + +println(10) // 打印整数 10 + +println("Boo!") // 打印字符串 "BOO!" + + +// 一些基础 + +// 打印并强制换行 +println("Hello world!") +// 没有强制换行的打印 +print("Hello world") + +// 通过 var 或者 val 来声明变量 +// val 声明是不可变的,var 声明是可修改的。不可变性是好事。 +val x = 10 // x 现在是 10 +x = 20 // 错误: 对 val 声明的变量重新赋值 +var x = 10 +x = 20 // x 现在是 20 + +// 单行注释开始于两个斜杠 +/* +多行注释看起来像这样。 +*/ + +// 布尔值 +true +false + +// 布尔操作 +!true // false +!false // true +true == false // false +10 > 5 // true + +// 数学运算像平常一样 +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 + + +// 在 REPL 计算一个命令会返回给你结果的类型和值 + +1 + 7 + +/* 上行的结果是: + + scala> 1 + 7 + res29: Int = 8 + + 这意味着计算 1 + 7 的结果是一个 Int 类型的对象,其值为 8 + + 1+7 的结果是一样的 +*/ + + +// 包括函数在内,每一个事物都是对象。在 REPL 中输入: + +7 // 结果 res30: Int = 7 (res30 是一个生成的结果的 var 命名) + +// 下一行给你一个接收一个 Int 类型并返回该数的平方的函数 +(x:Int) => x * x + +// 你可以分配给函数一个标识符,像这样: +val sq = (x:Int) => x * x + +/* 上面的例子说明 + + sq: Int => Int = + + 意味着这次我们给予了 sq 这样一个显式的名字给一个接受一个 Int 类型值并返回 一个 Int 类型值的函数 + + sq 可以像下面那样被执行: +*/ + +sq(10) // 返回给你:res33: Int = 100. + +// 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 a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // 这会抛出一个异常 + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // 这会抛出一个异常 + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* 查看 map 的文档 + * 点击[这里](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map) + * 确保你可以读它 + */ + + +// 元组 + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(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 + +d._2 + + + +// 选择器 + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + +// 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)) + + +// Scala 的 foreach 方法定义在特定的接受一个类型的集合上 +// 返回 Unit(一个 void 方法) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + + + + +// For 包含 + +for { n <- s } yield sq(n) + +val nSquared2 = for { n <- s } yield sq(n) + +for { n <- nSquared2 if n < 10 } yield n + +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + +/* 注意:这些不是 for 循环. 一个 for 循环的语义是 '重复'('repeat'), + 然而,一个 for-包含 定义了一个两个数据结合间的关系 */ + + + +// 循环和迭代 + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// 注意:Scala 是相当宽容的当它遇到点和括号 - 分别地学习这些规则。 +// 这帮助你编写读起来像英语的 DSLs 和 APIs + +(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 then 10"); + x += 1 +} while (x < 10) + +// 在 Scala中,尾递归是一种惯用的执行循环的方式。 +// 递归函数需要显示的返回类型,编译器不能推断出类型。 +// 这里它是 Unit。 +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} + + + +// 条件语句 + +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" + +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + + + +// 面向对象特性 + +// 类名是 Dog +class Dog { + //bark 方法,返回字符串 + def bark: String = { + // the body of the method + "Woof, woof!" + } +} + +// 类可以包含几乎其它的构造,包括其它的类, +// 函数,方法,对象,case 类,特性等等。 + + + +// Case 类 + +case class Person(name:String, phoneNumber:String) + +Person("George", "1234") == Person("Kate", "1236") + + + + +// 模式匹配 + +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..." } + +me match { case Person("George", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + +val kate = Person("Kate", "1234") + +kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + + + +// 正则表达式 + +val email = "(.*)@(.*)".r // 在字符串上调用 r 会使它变成一个正则表达式 + +val email(user, domain) = "henry@zkpr.com" + +"mrbean@pyahoo.com" match { + case email(name, domain) => "I know your name, " + name +} + + + +// 字符串 + +"Scala 字符串被双引号包围" // +'a' // Scala 字符 +'单引号的字符串不存在' // 错误 +"字符串拥有通常的 Java 方法定义在其上".length +"字符串也有额外的 Scala 方法".reverse + +// 参见: scala.collection.immutable.StringOps + +println("ABCDEF".length) +println("ABCDEF".substring(2, 6)) +println("ABCDEF".replace("C", "3")) + +val n = 45 +println(s"We have $n apples") + +val a = Array(11, 9, 6) +println(s"My second daughter is ${a(2-1)} years old") + +// 一些字符需要被转义,举例来说,字符串中的双引号: +val a = "They stood outside the \"Rose and Crown\"" + +// 三个双引号使得字符串可以跨行并且可以包含引号(无需转义) + +val html = """ +

Press belo', Joe

+ | + """ + + + +// 应用结果和组织 + +// 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 类: +import scala.collection.immutable.{Map => _, Set => _, _} + +// 在 scala 源文件中,你的程序入口点使用一个拥有单一方法 main 的对象来定义: + +object Application { + def main(args: Array[String]): Unit = { + // stuff goes here. + } +} + +// 文件可以包含多个类和对象。由 scalac 来编译 + + + + +// 输入和输出 + +// 一行一行读取文件 +import scala.io.Source +for(line <- Source.fromPath("myfile.txt").getLines()) + println(line) + +// 使用 Java 的 PrintWriter 来写文件 + + +``` + +## 更多的资源 + +[为没耐心的人准备的 Scala](http://horstmann.com/scala/) + +[Twitter Scala school](http://twitter.github.io/scala_school/) + +[The scala documentation](http://www.scala-lang.org/documentation/) + +加入 [Scala 用户组](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From 2f7a3afda056eeebdccfef9ed1259e2e17639fe8 Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 11 Aug 2013 22:46:23 -0700 Subject: Merged some stuff --- ruby-ecosystem.html.markdown | 1 - zh-cn/dart-cn.html.markdown | 1 + zh-cn/ruby-cn.html.markdown | 1 + 3 files changed, 2 insertions(+), 1 deletion(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 5647e518..a31f552d 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -3,7 +3,6 @@ category: tool tool: ruby ecosystem contributors: - ["Jon Smock", "http://github.com/jonsmock"] -filename: --- diff --git a/zh-cn/dart-cn.html.markdown b/zh-cn/dart-cn.html.markdown index 64663b21..1b0cceb9 100644 --- a/zh-cn/dart-cn.html.markdown +++ b/zh-cn/dart-cn.html.markdown @@ -1,5 +1,6 @@ --- language: dart +lang: zh-cn filename: learndart.dart contributors: - ["Joao Pedrosa", "https://github.com/jpedrosa/"] diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index f66d1a03..16c0ed67 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -1,6 +1,7 @@ --- language: ruby filename: learnruby.rb +lang: zh-cn contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] -- cgit v1.2.3 From 6bc415464e74328868a61fba7d928ecbd404f319 Mon Sep 17 00:00:00 2001 From: lpy Date: Mon, 12 Aug 2013 11:09:08 +0800 Subject: Add Scala zh-cn translation and add link to Scala documentation in scala.html.markdown --- zh-cn/scala-cn.html.markdown | 411 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 411 insertions(+) create mode 100644 zh-cn/scala-cn.html.markdown diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown new file mode 100644 index 00000000..419f0fb2 --- /dev/null +++ b/zh-cn/scala-cn.html.markdown @@ -0,0 +1,411 @@ +--- +language: Scala +filename: learnscala.scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] +translators: + - ["Peiyong Lin", ""] +filename: learn.scala +lang: zh-cn +--- + +Scala - 一门可拓展性的语言 + +```cpp + +/* + 自行设置: + + 1) 下载 Scala - http://www.scala-lang.org/downloads + 2) unzip/untar 到你喜欢的地方,放在路径中的 bin 目录下 + 3) 在终端输入 scala,开启 Scala 的 REPL,你会看到提示符: + + scala> + + 这就是所谓的 REPL,你现在可以在其中运行命令,让我们做到这一点: +*/ + +println(10) // 打印整数 10 + +println("Boo!") // 打印字符串 "BOO!" + + +// 一些基础 + +// 打印并强制换行 +println("Hello world!") +// 没有强制换行的打印 +print("Hello world") + +// 通过 var 或者 val 来声明变量 +// val 声明是不可变的,var 声明是可修改的。不可变性是好事。 +val x = 10 // x 现在是 10 +x = 20 // 错误: 对 val 声明的变量重新赋值 +var x = 10 +x = 20 // x 现在是 20 + +// 单行注释开始于两个斜杠 +/* +多行注释看起来像这样。 +*/ + +// 布尔值 +true +false + +// 布尔操作 +!true // false +!false // true +true == false // false +10 > 5 // true + +// 数学运算像平常一样 +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 + + +// 在 REPL 计算一个命令会返回给你结果的类型和值 + +1 + 7 + +/* 上行的结果是: + + scala> 1 + 7 + res29: Int = 8 + + 这意味着计算 1 + 7 的结果是一个 Int 类型的对象,其值为 8 + + 1+7 的结果是一样的 +*/ + + +// 包括函数在内,每一个事物都是对象。在 REPL 中输入: + +7 // 结果 res30: Int = 7 (res30 是一个生成的结果的 var 命名) + +// 下一行给你一个接收一个 Int 类型并返回该数的平方的函数 +(x:Int) => x * x + +// 你可以分配给函数一个标识符,像这样: +val sq = (x:Int) => x * x + +/* 上面的例子说明 + + sq: Int => Int = + + 意味着这次我们给予了 sq 这样一个显式的名字给一个接受一个 Int 类型值并返回 一个 Int 类型值的函数 + + sq 可以像下面那样被执行: +*/ + +sq(10) // 返回给你:res33: Int = 100. + +// 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 a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // 这会抛出一个异常 + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // 这会抛出一个异常 + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* 查看 map 的文档 + * 点击[这里](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map) + * 确保你可以读它 + */ + + +// 元组 + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(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 + +d._2 + + + +// 选择器 + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + +// 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)) + + +// Scala 的 foreach 方法定义在特定的接受一个类型的集合上 +// 返回 Unit(一个 void 方法) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + + + + +// For 包含 + +for { n <- s } yield sq(n) + +val nSquared2 = for { n <- s } yield sq(n) + +for { n <- nSquared2 if n < 10 } yield n + +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + +/* 注意:这些不是 for 循环. 一个 for 循环的语义是 '重复'('repeat'), + 然而,一个 for-包含 定义了一个两个数据结合间的关系 */ + + + +// 循环和迭代 + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// 注意:Scala 是相当宽容的当它遇到点和括号 - 分别地学习这些规则。 +// 这帮助你编写读起来像英语的 DSLs 和 APIs + +(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 then 10"); + x += 1 +} while (x < 10) + +// 在 Scala中,尾递归是一种惯用的执行循环的方式。 +// 递归函数需要显示的返回类型,编译器不能推断出类型。 +// 这里它是 Unit。 +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} + + + +// 条件语句 + +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" + +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + + + +// 面向对象特性 + +// 类名是 Dog +class Dog { + //bark 方法,返回字符串 + def bark: String = { + // the body of the method + "Woof, woof!" + } +} + +// 类可以包含几乎其它的构造,包括其它的类, +// 函数,方法,对象,case 类,特性等等。 + + + +// Case 类 + +case class Person(name:String, phoneNumber:String) + +Person("George", "1234") == Person("Kate", "1236") + + + + +// 模式匹配 + +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..." } + +me match { case Person("George", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + +val kate = Person("Kate", "1234") + +kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + + + +// 正则表达式 + +val email = "(.*)@(.*)".r // 在字符串上调用 r 会使它变成一个正则表达式 + +val email(user, domain) = "henry@zkpr.com" + +"mrbean@pyahoo.com" match { + case email(name, domain) => "I know your name, " + name +} + + + +// 字符串 + +"Scala 字符串被双引号包围" // +'a' // Scala 字符 +'单引号的字符串不存在' // 错误 +"字符串拥有通常的 Java 方法定义在其上".length +"字符串也有额外的 Scala 方法".reverse + +// 参见: scala.collection.immutable.StringOps + +println("ABCDEF".length) +println("ABCDEF".substring(2, 6)) +println("ABCDEF".replace("C", "3")) + +val n = 45 +println(s"We have $n apples") + +val a = Array(11, 9, 6) +println(s"My second daughter is ${a(2-1)} years old") + +// 一些字符需要被转义,举例来说,字符串中的双引号: +val a = "They stood outside the \"Rose and Crown\"" + +// 三个双引号使得字符串可以跨行并且可以包含引号(无需转义) + +val html = """
+

Press belo', Joe

+ | +
""" + + + +// 应用结果和组织 + +// 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 类: +import scala.collection.immutable.{Map => _, Set => _, _} + +// 在 scala 源文件中,你的程序入口点使用一个拥有单一方法 main 的对象来定义: + +object Application { + def main(args: Array[String]): Unit = { + // stuff goes here. + } +} + +// 文件可以包含多个类和对象。由 scalac 来编译 + + + + +// 输入和输出 + +// 一行一行读取文件 +import scala.io.Source +for(line <- Source.fromPath("myfile.txt").getLines()) + println(line) + +// 使用 Java 的 PrintWriter 来写文件 + + +``` + +## 更多的资源 + +[为没耐心的人准备的 Scala](http://horstmann.com/scala/) + +[Twitter Scala school](http://twitter.github.io/scala_school/) + +[The scala documentation](http://www.scala-lang.org/documentation/) + +加入 [Scala 用户组](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From ec0a187f8160d425c6462fff8d3140f64c50909b Mon Sep 17 00:00:00 2001 From: lpy Date: Mon, 12 Aug 2013 14:11:45 +0800 Subject: Add new link into scala-cn.html.markdown --- zh-cn/scala-cn.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 419f0fb2..9f776090 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -406,6 +406,8 @@ for(line <- Source.fromPath("myfile.txt").getLines()) [Twitter Scala school](http://twitter.github.io/scala_school/) -[The scala documentation](http://www.scala-lang.org/documentation/) +[The Scala documentation](http://www.scala-lang.org/documentation/) + +[在浏览器尝试 Scala](http://scalatutorials.com/tour/) 加入 [Scala 用户组](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From 7f4b100fa813f71879fbefaec6c4cabe35ce719a Mon Sep 17 00:00:00 2001 From: Severin Schoepke Date: Mon, 12 Aug 2013 16:17:37 +0200 Subject: Fixed broken links --- ruby-ecosystem.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index a31f552d..cae55cd3 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -93,13 +93,13 @@ which MRI version to target. ## RubySpec -Most ruby implementations rely heavily on (RubySpec)[http://rubyspec.org/]. Ruby +Most ruby implementations rely heavily on [RubySpec](http://rubyspec.org/). Ruby has no official specification, so the community has written executable specs in ruby to test their implementations' compatability with MRI. ## RubyGems -(RubyGems)[http://rubygems.org/] is a community-run package manager for ruby. +[RubyGems](http://rubygems.org/) is a community-run package manager for ruby. RubyGems ships with ruby, so there is no need to download it separately. Ruby packages are called "gems," and they can be hosted by the community at @@ -108,7 +108,7 @@ things like version, dependencies, author(s), and license(s). ## Bundler -(Bundler)[http://bundler.io/] is a gem dependency resolver. It uses a project's +[Bundler](http://bundler.io/) is a gem dependency resolver. It uses a project's Gemfile to find dependencies, and then fetches those dependencies' dependencies recursively. It does this until all dependencies are resolved and downloaded, or it will stop if a conflict has been found. -- cgit v1.2.3 From 46ce57a23cfc9518c79c264ba867c6025ca54bdd Mon Sep 17 00:00:00 2001 From: lyuehh Date: Mon, 12 Aug 2013 22:56:50 +0800 Subject: Add Chinese Translation for racket --- zh-cn/racket-cn.html.markdown | 607 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 607 insertions(+) create mode 100644 zh-cn/racket-cn.html.markdown diff --git a/zh-cn/racket-cn.html.markdown b/zh-cn/racket-cn.html.markdown new file mode 100644 index 00000000..9370d300 --- /dev/null +++ b/zh-cn/racket-cn.html.markdown @@ -0,0 +1,607 @@ +--- + +language: racket +filename: learnracket.rkt +contributors: + - ["th3rac25", "https://github.com/voila"] + - ["Eli Barzilay", "https://github.com/elibarzilay"] + - ["Gustavo Schmidt", "https://github.com/gustavoschmidt"] +translators: + - ["lyuehh", "https://github.com/lyuehh"] +--- + +Racket是Lisp/Scheme家族中的一个通用的,多范式的编程语言。 +非常期待您的反馈!你可以通过[@th3rac25](http://twitter.com/th3rac25)或以用户名为th3rac25的Google游戏爱你过服务 + +```racket +#lang racket ; 声明我们使用的语言 + +;;; 注释 + +;; 单行注释以分号开始 + +#| 块注释 + 可以横跨很多行而且... + #| + 可以嵌套 + |# +|# + +;; S表达式注释忽略剩下的表达式 +;; 在调试的时候会非常有用 +#; (被忽略的表达式) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. 原始数据类型和操作符 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 数字 +9999999999999999999999 ; 整数 +#b111 ; 二进制数字 => 7 +#o111 ; 八进制数字 => 73 +#x111 ; 十六进制数字 => 273 +3.14 ; 实数 +6.02e+23 +1/2 ; 有理数 +1+2i ; 复数 + +;; 函数调用写作(f x y z ...) +;; 在这里 f 是一个函数, x, y, z, ... 是参数 +;; 如果你想创建一个列表数据的字面量, 使用 ' 来阻止它们 +;; 被求值 +'(+ 1 2) ; => (+ 1 2) +;; 接下来,是一些数学运算 +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(quotient 5 2) ; => 2 +(remainder 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(exact->inexact 1/3) ; => 0.3333333333333333 +(+ 1+2i 2-3i) ; => 3-1i + +;;; 布尔类型 +#t ; 为真 +#f ; 为假,#f 之外的任何值都是真 +(not #t) ; => #f +(and 0 #f (error "doesn't get here")) ; => #f +(or #f 0 (error "doesn't get here")) ; => 0 + +;;; 字符 +#\A ; => #\A +#\λ ; => #\λ +#\u03BB ; => #\λ + +;;; 字符串是字符组成的定长数组 +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; \是转义字符 +"Foo\tbar\41\x21\u0021\a\r\n" ; 包含C语言的转义字符,和Unicode +"λx:(μα.α→α).xx" ; 字符串可以包含Unicode字符 + +;; 字符串可以相加 +(string-append "Hello " "world!") ; => "Hello world!" + +;; 一个字符串可以看做是一个包含字符的列表 +(string-ref "Apple" 0) ; => #\A + +;; format 可以用来格式化字符串 +(format "~a can be ~a" "strings" "formatted") + +;; 打印字符串非常简单 +(printf "I'm Racket. Nice to meet you!\n") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. 变量 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 你可以使用 define 定义一个变量 +;; 变量的名字可以使用任何字符除了: ()[]{}",'`;#|\ +(define some-var 5) +some-var ; => 5 + +;; 你也可以使用Unicode字符 +(define ⊆ subset?) +(⊆ (set 3 2) (set 1 2 3)) ; => #t + +;; 访问未赋值的变量会引发一个异常 +; x ; => x: undefined ... + +;; 本地绑定: `me' 被绑定到 "Bob",并且只在 let 中生效 +(let ([me "Bob"]) + "Alice" + me) ; => "Bob" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. 结构和集合 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 结构体 +(struct dog (name breed age)) +(define my-pet + (dog "lassie" "collie" 5)) +my-pet ; => # +(dog? my-pet) ; => #t +(dog-name my-pet) ; => "lassie" + +;;; 对 (不可变的) +;; `cons' 函数返回对, `car' 和 `cdr' 从对中提取第1个 +;; 和第2个元素 +(cons 1 2) ; => '(1 . 2) +(car (cons 1 2)) ; => 1 +(cdr (cons 1 2)) ; => 2 + +;;; 列表 + +;; 列表由链表构成, 由 `cons' 函数的结果 +;; 和一个 `null' (或者 '()) 构成,后者标记了这个列表的结束 +(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) +;; `list' 给列表提供了一个非常方便的可变参数的生成器 +(list 1 2 3) ; => '(1 2 3) +;; 一个单引号也可以用来表示一个列表字面量 +'(1 2 3) ; => '(1 2 3) + +;; 仍然可以使用 `cons' 函数在列表的开始处添加一项 +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; `append' 函数可以将两个列表合并 +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; 列表是非常基础的类型,所以有*很多*操作列表的方法 +;; 下面是一些例子: +(map add1 '(1 2 3)) ; => '(2 3 4) +(map + '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(filter even? '(1 2 3 4)) ; => '(2 4) +(count even? '(1 2 3 4)) ; => 2 +(take '(1 2 3 4) 2) ; => '(1 2) +(drop '(1 2 3 4) 2) ; => '(3 4) + +;;; 向量 + +;; 向量是定长的数组 +#(1 2 3) ; => '#(1 2 3) + +;; 使用 `vector-append' 方法将2个向量合并 +(vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; Set(翻译成集合也不太合适,所以不翻译了..) + +;; 从一个列表创建一个Set +(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) + +;; 使用 `set-add' 函数增加一个成员 +;; (函数式特性: 这里会返回一个扩展后的Set,而不是修改输入的值) +(set-add (set 1 2 3) 4) ; => (set 1 2 3 4) + +;; 使用 `set-remove' 函数移除一个成员 +(set-remove (set 1 2 3) 1) ; => (set 2 3) + +;; 使用 `set-member?' 函数测试成员是否存在 +(set-member? (set 1 2 3) 1) ; => #t +(set-member? (set 1 2 3) 4) ; => #f + +;;; 散列表 + +;; 创建一个不变的散列表 (可变散列表的例子在下面) +(define m (hash 'a 1 'b 2 'c 3)) + +;; 根据键取得值 +(hash-ref m 'a) ; => 1 + +;; 获取一个不存在的键是一个异常 +; (hash-ref m 'd) => 没有找到元素 + +;; 你可以给不存在的键提供一个默认值 +(hash-ref m 'd 0) ; => 0 + +;; 使用 `hash-set' 函数来扩展一个不可变的散列表 +;; (返回的是扩展后的散列表而不是修改它) +(define m2 (hash-set m 'd 4)) +m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) + +;; 记住,使用 `hash` 函数创建的散列表是不可变的 +m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' + +;; 使用 `hash-remove' 函数移除一个键值对 (函数式特性,m并不变) +(hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. 函数 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 使用 `lambda' 创建函数 +;; 函数总是返回它最后一个表达式的值 +(lambda () "Hello World") ; => # +;; 也可以使用 Unicode 字符 `λ' +(λ () "Hello World") ; => 同样的函数 + +;; 使用括号调用一个函数,也可以直接调用一个 lambda 表达式 +((lambda () "Hello World")) ; => "Hello World" +((λ () "Hello World")) ; => "Hello World" + +;; 将函数赋值为一个变量 +(define hello-world (lambda () "Hello World")) +(hello-world) ; => "Hello World" + +;; 你可以使用函数定义的语法糖来简化代码 +(define (hello-world2) "Hello World") + +;; `()`是函数的参数列表 +(define hello + (lambda (name) + (string-append "Hello " name))) +(hello "Steve") ; => "Hello Steve" +;; 同样的,可以使用语法糖来定义: +(define (hello2 name) + (string-append "Hello " name)) + +;; 你也可以使用可变参数, `case-lambda' +(define hello3 + (case-lambda + [() "Hello World"] + [(name) (string-append "Hello " name)])) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" +;; ... 或者给参数指定一个可选的默认值 +(define (hello4 [name "World"]) + (string-append "Hello " name)) + +;; 函数可以将多余的参数放到一个列表里 +(define (count-args . args) + (format "You passed ~a args: ~a" (length args) args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" +;; ... 也可以使用不带语法糖的 `lambda' 形式: +(define count-args2 + (lambda args + (format "You passed ~a args: ~a" (length args) args))) + +;; 你可以混用两种用法 +(define (hello-count name . args) + (format "Hello ~a, you passed ~a extra args" name (length args))) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" +;; ... 不带语法糖的形式: +(define hello-count2 + (lambda (name . args) + (format "Hello ~a, you passed ~a extra args" name (length args)))) + +;; 使用关键字 +(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) + (format "~a ~a, ~a extra args" g name (length args))) +(hello-k) ; => "Hello World, 0 extra args" +(hello-k 1 2 3) ; => "Hello World, 3 extra args" +(hello-k #:greeting "Hi") ; => "Hi World, 0 extra args" +(hello-k #:name "Finn" #:greeting "Hey") ; => "Hey Finn, 0 extra args" +(hello-k 1 2 3 #:greeting "Hi" #:name "Finn" 4 5 6) + ; => "Hi Finn, 6 extra args" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. 判断是否相等 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 判断数字使用 `=' +(= 3 3.0) ; => #t +(= 2 1) ; => #f + +;; 判断对象使用 `eq?' +(eq? 3 3) ; => #t +(eq? 3 3.0) ; => #f +(eq? (list 3) (list 3)) ; => #f + +;; 判断集合使用 `equal?' +(equal? (list 'a 'b) (list 'a 'b)) ; => #t +(equal? (list 'a 'b) (list 'b 'a)) ; => #f + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. 控制结构 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 条件判断 + +(if #t ; 测试表达式 + "this is true" ; 为真的表达式 + "this is false") ; 为假的表达式 +; => "this is true" + +;; 注意, 除 `#f` 之外的所有值都认为是真 +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(Groucho Zeppo) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'yep + +;; `cond' 会进行一系列的判断来选择一个结果 +(cond [(> 2 2) (error "wrong!")] + [(< 2 2) (error "wrong again!")] + [else 'ok]) ; => 'ok + +;;; 模式匹配 + +(define (fizzbuzz? n) + (match (list (remainder n 3) (remainder n 5)) + [(list 0 0) 'fizzbuzz] + [(list 0 _) 'fizz] + [(list _ 0) 'buzz] + [_ #f])) + +(fizzbuzz? 15) ; => 'fizzbuzz +(fizzbuzz? 37) ; => #f + +;;; 循环 + +;; 循环可以使用递归(尾递归) +(define (loop i) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) +(loop 5) ; => i=5, i=6, ... + +;; 类似的,可以使用 `let` 定义 +(let loop ((i 0)) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) ; => i=0, i=1, ... + +;; 看上面的例子怎么增加一个新的 `loop' 形式, 但是 Racket 已经有了一个非常 +;; 灵活的 `for' 了: +(for ([i 10]) + (printf "i=~a\n" i)) ; => i=0, i=1, ... +(for ([i (in-range 5 10)]) + (printf "i=~a\n" i)) ; => i=5, i=6, ... + +;;; 其他形式的迭代 +;; `for' 允许在很多数据结构中迭代: +;; 列表, 向量, 字符串, Set, 散列表, 等... + +(for ([i (in-list '(l i s t))]) + (displayln i)) + +(for ([i (in-vector #(v e c t o r))]) + (displayln i)) + +(for ([i (in-string "string")]) + (displayln i)) + +(for ([i (in-set (set 'x 'y 'z))]) + (displayln i)) + +(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))]) + (printf "key:~a value:~a\n" k v)) + +;;; 更多复杂的迭代 + +;; 并行扫描多个序列 (遇到长度小的就停止) +(for ([i 10] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x 1:y 2:z + +;; 嵌套循环 +(for* ([i 2] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x, 0:y, 0:z, 1:x, 1:y, 1:z + +;; 带有条件判断的 `for` +(for ([i 1000] + #:when (> i 5) + #:unless (odd? i) + #:break (> i 10)) + (printf "i=~a\n" i)) +; => i=6, i=8, i=10 + +;;; 更多的例子帮助你加深理解.. +;; 和 `for' 循环非常像 -- 收集结果 + +(for/list ([i '(1 2 3)]) + (add1 i)) ; => '(2 3 4) + +(for/list ([i '(1 2 3)] #:when (even? i)) + i) ; => '(2) + +(for/list ([i 10] [j '(x y z)]) + (list i j)) ; => '((0 x) (1 y) (2 z)) + +(for/list ([i 1000] #:when (> i 5) #:unless (odd? i) #:break (> i 10)) + i) ; => '(6 8 10) + +(for/hash ([i '(1 2 3)]) + (values i (number->string i))) +; => '#hash((1 . "1") (2 . "2") (3 . "3")) + +;; 也有很多其他的内置方法来收集循环中的值: +(for/sum ([i 10]) (* i i)) ; => 285 +(for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000 +(for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t +(for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t +;; 如果需要合并计算结果, 使用 `for/fold' +(for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 +;; (这个函数可以在大部分情况下替代普通的命令式循环) + +;;; 异常 + +;; 要捕获一个异常,使用 `with-handlers' 形式 +(with-handlers ([exn:fail? (lambda (exn) 999)]) + (+ 1 "2")) ; => 999 +(with-handlers ([exn:break? (lambda (exn) "no time")]) + (sleep 3) + "phew") ; => "phew", 如果你打断了它,那么结果 => "no time" + +;; 使用 `raise' 抛出一个异常后者其他任何值 +(with-handlers ([number? ; 捕获抛出的数字类型的值 + identity]) ; 将它们作为普通值 + (+ 1 (raise 2))) ; => 2 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. 可变的值 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 使用 `set!' 给一个已经存在的变量赋一个新值 +(define n 5) +(set! n (add1 n)) +n ; => 6 + +;; 给那些明确的需要变化的值使用 `boxes` (在其他语言里类似指针 +;; 或者引用) +(define n* (box 5)) +(set-box! n* (add1 (unbox n*))) +(unbox n*) ; => 6 + +;; 很多 Racket 诗句类型是不可变的 (对,列表,等),有一些既是可变的 +;; 又是不可变的 (字符串,向量,散列表 +;; 等...) + +;; 使用 `vector' 或者 `make-vector' 创建一个可变的向量 +(define vec (vector 2 2 3 4)) +(define wall (make-vector 100 'bottle-of-beer)) +;; 使用 `vector-set!` 更新一项 +(vector-set! vec 0 1) +(vector-set! wall 99 'down) +vec ; => #(1 2 3 4) + +;; 创建一个空的可变散列表,然后操作它 +(define m3 (make-hash)) +(hash-set! m3 'a 1) +(hash-set! m3 'b 2) +(hash-set! m3 'c 3) +(hash-ref m3 'a) ; => 1 +(hash-ref m3 'd 0) ; => 0 +(hash-remove! m3 'a) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. 模块 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 模块让你将你的代码组织为多个文件,成为可重用的模块, +;; 在这里,我们使用嵌套在本文的整个大模块 +;; 里的子模块(从 "#lang" 这一行开始) + +(module cake racket/base ; 基于 racket/base 定义一个 `cake` 模块 + + (provide print-cake) ; 这个模块导出的函数 + + (define (print-cake n) + (show " ~a " n #\.) + (show " .-~a-. " n #\|) + (show " | ~a | " n #\space) + (show "---~a---" n #\-)) + + (define (show fmt n ch) ; 内部函数 + (printf fmt (make-string n ch)) + (newline))) + +;; 使用 `require` 从模块中得到所有 `provide` 的函数 +(require 'cake) ; 这里的 `'`表示是本地的子模块 +(print-cake 3) +; (show "~a" 1 #\A) ; => 报错, `show' 没有被导出,不存在 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. 类和对象 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 创建一个 fish% 类(%是给类绑定用的) +(define fish% + (class object% + (init size) ; 初始化的参数 + (super-new) ; 父类的初始化 + ;; 域 + (define current-size size) + ;; 公共方法 + (define/public (get-size) + current-size) + (define/public (grow amt) + (set! current-size (+ amt current-size))) + (define/public (eat other-fish) + (grow (send other-fish get-size))))) + +;; 创建一个 fish% 类的示例 +(define charlie + (new fish% [size 10])) + +;; 使用 `send' 调用一个对象的方法 +(send charlie get-size) ; => 10 +(send charlie grow 6) +(send charlie get-size) ; => 16 + +;; `fish%' 是一个普通的值,我们可以用它来混入 +(define (add-color c%) + (class c% + (init color) + (super-new) + (define my-color color) + (define/public (get-color) my-color))) +(define colored-fish% (add-color fish%)) +(define charlie2 (new colored-fish% [size 10] [color 'red])) +(send charlie2 get-color) +;; 或者,不带名字 +(send (new (add-color fish%) [size 10] [color 'red]) get-color) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 9. 宏 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 宏让你扩展这门语言的语法 + +;; 让我们定义一个while循环 +(define-syntax-rule (while condition body ...) + (let loop () + (when condition + body ... + (loop)))) + +(let ([i 0]) + (while (< i 10) + (displayln i) + (set! i (add1 i)))) + +;; 宏是安全的,你不能修改现有的变量 +(define-syntax-rule (swap! x y) ; !表示会修改 + (let ([tmp x]) + (set! x y) + (set! y tmp))) + +(define tmp 2) +(define other 3) +(swap! tmp other) +(printf "tmp = ~a; other = ~a\n" tmp other) +;; 变量 `tmp` 被重命名为 `tmp_1` +;; 避免名字冲突 +;; (let ([tmp_1 tmp]) +;; (set! tmp other) +;; (set! other tmp_1)) + +;; 但它们仍然会导致错误代码,比如: +(define-syntax-rule (bad-while condition body ...) + (when condition + body ... + (bad-while condition body ...))) +;; 这个宏会挂掉,它产生了一个无限循环,如果你试图去使用它 +;; 编译器会进入死循环 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 10. 契约 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 契约限制变量从模块中导入 + +(module bank-account racket + (provide (contract-out + [deposit (-> positive? any)] ; 数量一直是正值 + [balance (-> positive?)])) + + (define amount 0) + (define (deposit a) (set! amount (+ amount a))) + (define (balance) amount) + ) + +(require 'bank-account) +(deposit 5) + +(balance) ; => 5 + +;; 客户端尝试存储一个负值时会出错 +;; (deposit -5) ; => deposit: contract violation +;; expected: positive? +;; given: -5 +;; more details.... +``` + +## 进一步阅读 + +想知道更多吗? 尝试 [Getting Started with Racket](http://docs.racket-lang.org/getting-started/) -- cgit v1.2.3 From 73e700e0138d7b4c953d8f5990118d9c55ecfa41 Mon Sep 17 00:00:00 2001 From: lyuehh Date: Mon, 12 Aug 2013 23:02:44 +0800 Subject: fix typo --- zh-cn/racket-cn.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/zh-cn/racket-cn.html.markdown b/zh-cn/racket-cn.html.markdown index 9370d300..e17aedda 100644 --- a/zh-cn/racket-cn.html.markdown +++ b/zh-cn/racket-cn.html.markdown @@ -11,7 +11,7 @@ translators: --- Racket是Lisp/Scheme家族中的一个通用的,多范式的编程语言。 -非常期待您的反馈!你可以通过[@th3rac25](http://twitter.com/th3rac25)或以用户名为th3rac25的Google游戏爱你过服务 +非常期待您的反馈!你可以通过[@th3rac25](http://twitter.com/th3rac25)或以用户名为 th3rac25 的Google邮箱服务和我取得联系 ```racket #lang racket ; 声明我们使用的语言 @@ -125,7 +125,7 @@ my-pet ; => # (dog-name my-pet) ; => "lassie" ;;; 对 (不可变的) -;; `cons' 函数返回对, `car' 和 `cdr' 从对中提取第1个 +;; `cons' 返回对, `car' 和 `cdr' 从对中提取第1个 ;; 和第2个元素 (cons 1 2) ; => '(1 . 2) (car (cons 1 2)) ; => 1 @@ -133,7 +133,7 @@ my-pet ; => # ;;; 列表 -;; 列表由链表构成, 由 `cons' 函数的结果 +;; 列表由链表构成, 由 `cons' 的结果 ;; 和一个 `null' (或者 '()) 构成,后者标记了这个列表的结束 (cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) ;; `list' 给列表提供了一个非常方便的可变参数的生成器 @@ -141,7 +141,7 @@ my-pet ; => # ;; 一个单引号也可以用来表示一个列表字面量 '(1 2 3) ; => '(1 2 3) -;; 仍然可以使用 `cons' 函数在列表的开始处添加一项 +;; 仍然可以使用 `cons' 在列表的开始处添加一项 (cons 4 '(1 2 3)) ; => '(4 1 2 3) ;; `append' 函数可以将两个列表合并 @@ -169,14 +169,14 @@ my-pet ; => # ;; 从一个列表创建一个Set (list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) -;; 使用 `set-add' 函数增加一个成员 +;; 使用 `set-add' 增加一个成员 ;; (函数式特性: 这里会返回一个扩展后的Set,而不是修改输入的值) (set-add (set 1 2 3) 4) ; => (set 1 2 3 4) -;; 使用 `set-remove' 函数移除一个成员 +;; 使用 `set-remove' 移除一个成员 (set-remove (set 1 2 3) 1) ; => (set 2 3) -;; 使用 `set-member?' 函数测试成员是否存在 +;; 使用 `set-member?' 测试成员是否存在 (set-member? (set 1 2 3) 1) ; => #t (set-member? (set 1 2 3) 4) ; => #f @@ -194,15 +194,15 @@ my-pet ; => # ;; 你可以给不存在的键提供一个默认值 (hash-ref m 'd 0) ; => 0 -;; 使用 `hash-set' 函数来扩展一个不可变的散列表 +;; 使用 `hash-set' 来扩展一个不可变的散列表 ;; (返回的是扩展后的散列表而不是修改它) (define m2 (hash-set m 'd 4)) m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) -;; 记住,使用 `hash` 函数创建的散列表是不可变的 +;; 记住,使用 `hash` 创建的散列表是不可变的 m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' -;; 使用 `hash-remove' 函数移除一个键值对 (函数式特性,m并不变) +;; 使用 `hash-remove' 移除一个键值对 (函数式特性,m并不变) (hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -437,7 +437,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' (set! n (add1 n)) n ; => 6 -;; 给那些明确的需要变化的值使用 `boxes` (在其他语言里类似指针 +;; 给那些明确地需要变化的值使用 `boxes` (在其他语言里类似指针 ;; 或者引用) (define n* (box 5)) (set-box! n* (add1 (unbox n*))) -- cgit v1.2.3 From 45ddaf5f46ea2e59bb8d8ad9038182d99a2c9550 Mon Sep 17 00:00:00 2001 From: hbc Date: Mon, 12 Aug 2013 23:13:20 +0800 Subject: Improved some translations, added a line break --- zh-cn/ruby-cn.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 16c0ed67..fcc60162 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -94,7 +94,7 @@ x = y = 10 #=> 10 x #=> 10 y #=> 10 -# 按照惯例,用snake_case 作为变量名 +# 按照惯例,用 snake_case 作为变量名 snake_case = true # 使用具有描述性的运算符 @@ -102,7 +102,8 @@ path_to_project_root = '/good/name/' path = '/bad/name/' # 符号(Symbols,也是对象) -# 符号是不可变的,内部用整数类型表示的可重用的值。通常用它代替字符串来有效地表达有意义的值 +# 符号是不可变的,内部用整数类型表示的可重用的值。 +# 通常用它代替字符串来有效地表示有意义的值。 :pending.class #=> Symbol -- cgit v1.2.3 From 76526895ff276939dbd4a8f36f631588459584ba Mon Sep 17 00:00:00 2001 From: Xiao Chuan Yu Date: Mon, 12 Aug 2013 11:17:37 -0400 Subject: Update haskell.html.markdown Just a typo. https://github.com/adambard/learnxinyminutes-docs/issues/190 --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 9847ef2a..e3ec3f38 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -84,7 +84,7 @@ not False -- True -- rest of the elements of this "infinite" list don't exist yet! Haskell won't -- actually evaluate them until it needs to. -- joining two lists +-- joining two lists [1..5] ++ [6..10] -- adding to the head of a list -- cgit v1.2.3 From bd48b7062c51aff7d27114326f64fde505cea49c Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 12 Aug 2013 09:53:40 -0700 Subject: Updated translation filenames to prevent collisions --- es-es/c-es.html.markdown | 2 +- es-es/elisp-es.html.markdown | 2 +- es-es/java-es.html.markdown | 2 +- es-es/python-es.html.markdown | 2 +- es-es/ruby-es.html.markdown | 2 +- pt-br/python-pt.html.markdown | 2 +- zh-cn/c-cn.html.markdown | 2 +- zh-cn/dart-cn.html.markdown | 2 +- zh-cn/elisp-cn.html.markdown | 2 +- zh-cn/git-cn.html.markdown | 1 - zh-cn/haskell-cn.html.markdown | 4 ++-- zh-cn/java-cn.html.markdown | 2 +- zh-cn/javascript-cn.html.markdown | 1 + zh-cn/php-cn.html.markdown | 2 +- zh-cn/python-cn.html.markdown | 2 +- zh-cn/ruby-cn.html.markdown | 2 +- zh-cn/scala-cn.html.markdown | 2 +- 17 files changed, 17 insertions(+), 17 deletions(-) diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown index 0624f4be..b109f761 100644 --- a/es-es/c-es.html.markdown +++ b/es-es/c-es.html.markdown @@ -1,6 +1,6 @@ --- language: c -filename: learnc.c +filename: learnc-es.c contributors: - ["Adam Bard", "http://adambard.com/"] translators: diff --git a/es-es/elisp-es.html.markdown b/es-es/elisp-es.html.markdown index 431ea794..a6cd3934 100644 --- a/es-es/elisp-es.html.markdown +++ b/es-es/elisp-es.html.markdown @@ -5,7 +5,7 @@ contributors: translators: - ["Guillermo Vayá", "http://willyfrog.es"] lang: es-es -filename: learn-emacs-lisp.el +filename: learn-emacs-lisp-es.el --- ```scheme diff --git a/es-es/java-es.html.markdown b/es-es/java-es.html.markdown index 90a43935..b34dca8d 100644 --- a/es-es/java-es.html.markdown +++ b/es-es/java-es.html.markdown @@ -5,7 +5,7 @@ contributors: translators: - ["Camilo Garrido", "http://www.twitter.com/hirohope"] lang: es-es -filename: LearnJava.java +filename: LearnJava-es.java --- Java es un lenguage de programación de propósito general, concurrente, basado en clases y diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown index 1ec8d7e4..f92f5cde 100644 --- a/es-es/python-es.html.markdown +++ b/es-es/python-es.html.markdown @@ -5,7 +5,7 @@ contributors: translators: - ["Camilo Garrido", "http://www.twitter.com/hirohope"] lang: es-es -filename: learnpython.py +filename: learnpython-es.py --- Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown index fa039676..66a5d0fe 100644 --- a/es-es/ruby-es.html.markdown +++ b/es-es/ruby-es.html.markdown @@ -1,6 +1,6 @@ --- language: ruby -filename: learnruby.rb +filename: learnruby-es.rb contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown index c365ba96..e08bb5a8 100644 --- a/pt-br/python-pt.html.markdown +++ b/pt-br/python-pt.html.markdown @@ -5,7 +5,7 @@ contributors: translators: - ["Vilson Vieira", "http://automata.cc"] lang: pt-bf -filename: learnpython.py +filename: learnpython-pt.py --- Python foi criado por Guido Van Rossum no começo dos anos 90. Atualmente é uma diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown index f8a8e0bd..b4bff8fc 100755 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -1,6 +1,6 @@ --- language: c -filename: learnc.c +filename: learnc-cn.c contributors: - ["Adam Bard", "http://adambard.com/"] translators: diff --git a/zh-cn/dart-cn.html.markdown b/zh-cn/dart-cn.html.markdown index 1b0cceb9..6a6562bc 100644 --- a/zh-cn/dart-cn.html.markdown +++ b/zh-cn/dart-cn.html.markdown @@ -1,7 +1,7 @@ --- language: dart lang: zh-cn -filename: learndart.dart +filename: learndart-cn.dart contributors: - ["Joao Pedrosa", "https://github.com/jpedrosa/"] translators: diff --git a/zh-cn/elisp-cn.html.markdown b/zh-cn/elisp-cn.html.markdown index c3a2f927..d303c2e8 100755 --- a/zh-cn/elisp-cn.html.markdown +++ b/zh-cn/elisp-cn.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Bastien Guerry", "http://bzg.fr"] translators: - ["Chenbo Li", "http://binarythink.net"] -filename: learn-emacs-lisp.el +filename: learn-emacs-lisp-zh.el lang: zh-cn --- diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown index 8c24f0b8..86952eba 100755 --- a/zh-cn/git-cn.html.markdown +++ b/zh-cn/git-cn.html.markdown @@ -5,7 +5,6 @@ contributors: - ["Jake Prather", "http://github.com/JakeHP"] translators: - ["Chenbo Li", "http://binarythink.net"] -filename: LearnGit.txt lang: zh-cn --- diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index cb0de467..8d51f144 100755 --- a/zh-cn/haskell-cn.html.markdown +++ b/zh-cn/haskell-cn.html.markdown @@ -1,6 +1,6 @@ --- language: haskell -filename: learn-haskell.hs +filename: learn-haskell-zh.hs contributors: - ["Adit Bhargava", "http://adit.io"] translators: @@ -404,4 +404,4 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater 你可以从优秀的 [Learn you a Haskell](http://learnyouahaskell.com/) 或者 [Real World Haskell](http://book.realworldhaskell.org/) -找到优雅不少的入门介绍。 \ No newline at end of file +找到优雅不少的入门介绍。 diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index b9ccf61a..9422ac2f 100755 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -3,7 +3,7 @@ name: java category: language language: java lang: zh-cn -filename: LearnJava.java +filename: LearnJava-zh.java contributors: - ["Jake Prather", "http://github.com/JakeHP"] translators: diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 3b5cfa94..89fc256e 100755 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -2,6 +2,7 @@ language: javascript category: language name: javascript +filename: javascript-zh.js contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] translators: diff --git a/zh-cn/php-cn.html.markdown b/zh-cn/php-cn.html.markdown index 3b242ce1..c6ebb515 100755 --- a/zh-cn/php-cn.html.markdown +++ b/zh-cn/php-cn.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Trismegiste", "https://github.com/Trismegiste"] translators: - ["Chenbo Li", "http://binarythink.net"] -filename: learnphp.php +filename: learnphp-zh.php lang: zh-cn --- diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown index 259e4ed8..764eed54 100755 --- a/zh-cn/python-cn.html.markdown +++ b/zh-cn/python-cn.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - ["Chenbo Li", "http://binarythink.net"] -filename: learnpython.py +filename: learnpython-zh.py lang: zh-cn --- diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 16c0ed67..6530b520 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -1,6 +1,6 @@ --- language: ruby -filename: learnruby.rb +filename: learnruby-zh.rb lang: zh-cn contributors: - ["David Underwood", "http://theflyingdeveloper.com"] diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 9f776090..1ce41ac6 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -1,6 +1,6 @@ --- language: Scala -filename: learnscala.scala +filename: learnscala-zh.scala contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] -- cgit v1.2.3 From 5424b31848e85e40ea78afb4582e8f33845e1b01 Mon Sep 17 00:00:00 2001 From: Tristan Hume Date: Mon, 12 Aug 2013 14:53:00 -0400 Subject: Explain blocks better --- ruby.html.markdown | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 861a94ad..52321ff6 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -5,6 +5,7 @@ contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] --- ```ruby @@ -158,11 +159,6 @@ hash['number'] #=> 5 # Asking a hash for a key that doesn't exist returns nil: hash['nothing here'] #=> nil -# Iterate over hashes with the #each method: -hash.each do |k, v| - puts "#{k} is #{v}" -end - # Since Ruby 1.9, there's a special syntax when using symbols as keys: new_hash = { defcon: 3, action: true} @@ -193,7 +189,12 @@ end # HOWEVER # No-one uses for loops -# Use `each` instead, like this: +# Under the hood for loops use the each method which takes a "block". +# A block is a bunch of code that you can pass to a method like each. +# It is analogous to lambdas, anonymous functions or closures in other programming languages. + +# The each method runs the block multiple times passing a counter. +# You can iterate over a range like this: (1..5).each do |counter| puts "iteration #{counter}" @@ -204,6 +205,17 @@ end #=> iteration 4 #=> iteration 5 +# You can also surround blocks in curly brackets: +(1..5).each {|counter| puts "iteration #{counter}"} + +# You can also iterate over the contents of data structures using each. +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + counter = 1 while counter <= 5 do puts "iteration #{counter}" -- cgit v1.2.3 From 5c5c8d3c4a0aea7c1c7a8150f428e354d0a12a6c Mon Sep 17 00:00:00 2001 From: Tristan Hume Date: Mon, 12 Aug 2013 15:05:00 -0400 Subject: Tidy up wording --- ruby.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 52321ff6..68c5b524 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -187,14 +187,14 @@ end #=> iteration 4 #=> iteration 5 -# HOWEVER -# No-one uses for loops -# Under the hood for loops use the each method which takes a "block". -# A block is a bunch of code that you can pass to a method like each. +# HOWEVER, No-one uses for loops. +# Instead you should use the "each" method and pass it a block. +# A block is a bunch of code that you can pass to a method like "each". # It is analogous to lambdas, anonymous functions or closures in other programming languages. - -# The each method runs the block multiple times passing a counter. -# You can iterate over a range like this: +# +# The "each" method of a range runs the block once for each element of the range. +# The block is passed a counter as a parameter. +# Calling the "each" method with a block looks like this: (1..5).each do |counter| puts "iteration #{counter}" @@ -208,7 +208,7 @@ end # You can also surround blocks in curly brackets: (1..5).each {|counter| puts "iteration #{counter}"} -# You can also iterate over the contents of data structures using each. +# The contents of data structures can also be iterated using each. array.each do |element| puts "#{element} is part of the array" end -- cgit v1.2.3 From 55ded27c4f755c36e1ec09d681e76a7df418e6a9 Mon Sep 17 00:00:00 2001 From: daturkel Date: Mon, 12 Aug 2013 17:57:23 -0400 Subject: added markdown --- markdown.html.markdown | 224 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 224 insertions(+) create mode 100644 markdown.html.markdown diff --git a/markdown.html.markdown b/markdown.html.markdown new file mode 100644 index 00000000..8820c555 --- /dev/null +++ b/markdown.html.markdown @@ -0,0 +1,224 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +filename: markdown.md +--- + +Markdown was created by JohnGruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). + +Give me as much feedback as you want! / Feel free to fork and pull request! + + +```markdown + + + + + + +# This is an

+## This is an

+### This is an

+#### This is an

+##### This is an

+###### This is an
+ + +This is an h1 +============= + +This is an h2 +------------- + + + + +*This text is in italics.* +_And so is this text._ + +**This text is in bold.** +__And so is this text.__ + +***This text is in both.*** +**_As is this!_** +*__And this!__* + + + +~~This text is rendered with strikethrough.~~ + + + +This is a paragraph. I'm tryping in a paragraph isn't this fun? + +Now I'm in paragraph 2. +I'm still in paragraph 2 too! + + +I'm in paragraph three! + + + +I end with two spaces (highlight me to see them). + +There's a
above me! + + + +> This is a block quote. You can either +> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrapp on their own and it doesn't make a difference so long as they start with a `>`. + +> You can also use more than one level +>> of indentation? +> How neat is that? + + + + +* Item +* Item +* Another item + +or + ++ Item ++ Item ++ One more item + +or + +- Item +- Item +- One last item + + + +1. Item one +2. Item two +3. Item three + + + +1. Item one +1. Item two +1. Item three + + + + +1. Item one +2. Item two +3. Item three + * Sub-item + * Sub-item +4. Item four + + + + + This is code + So is this + + + + my_array.each do |item| + puts item + end + + + +John didn't even know what the `go_to()` function did! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + +<-- The above text doesn't require indenting, plus Github will use syntax highlighting of the language you specify after the ``` --> + + + + +*** +--- +- - - +**************** + + + + + +[Click me!](http://test.com/) + + + +[Click me!](http://test.com/ "Link to Test.com") + + + +[Go to music](/music/). + + + +[Click this link][link1] for more info about it! [Also check out this link][foobar] if you want to. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Alright!" + + + + + +[This][] is a link. + +[this]: http://thisisalink.com/ + + + + + + +![This is hover-text (alt text) for my image](http://imgur.com/myimage.jpg "An optional title") + + + +![This is the hover-text.][myimage] + +[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" + + + + + is equivalent to [http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. + + + + +| Col1 | Col2 | Col3 | +| :----------- | :------: | ------------: | +| Left-aligned | Centered | Right-aligned | +| blah | blah | blah | + +or, for the same results + +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ugh this is so ugly | make it | stop + + + +``` + +For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From bbb8c837457eecc95ac3a66db150ed595ff7bb33 Mon Sep 17 00:00:00 2001 From: Rob Vella Date: Mon, 12 Aug 2013 17:34:17 -0700 Subject: Added visibility to static variable declarations --- php.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index ce228870..083574ee 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -440,6 +440,11 @@ class MyClass static $staticVar = 'static'; + // Static variables and their visibility + public static $publicStaticVar = 'publicStatic'; + private static $privateStaticVar = 'privateStatic'; // Accessible within the class only + protected static $protectedStaticVar = 'protectedStatic'; // Accessible from the class and subclasses + // Properties must declare their visibility public $property = 'public'; public $instanceProp; -- cgit v1.2.3 From e17ef8b1802c558ab9d77bd03569816dadabd750 Mon Sep 17 00:00:00 2001 From: Irfan Charania Date: Mon, 12 Aug 2013 17:54:53 -0700 Subject: Add C# Language Based on the Java one --- csharp.html.markdown | 550 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 550 insertions(+) create mode 100644 csharp.html.markdown diff --git a/csharp.html.markdown b/csharp.html.markdown new file mode 100644 index 00000000..d67f6c74 --- /dev/null +++ b/csharp.html.markdown @@ -0,0 +1,550 @@ +--- + +language: c# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] +filename: LearnCSharp.cs + +--- + +C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. + +[Read more here.](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) + +```c# +// Single-line comments start with // +/* +Multi-line comments look like this +*/ +/// +/// This is an XML documentation comment +/// + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +// defines scope to organize code into "packages" +namespace Learning +{ + // Each .cs file should at least contain a class with the same name as the file + // you're allowed to do otherwise, but shouldn't for sanity. + public class LearnCSharp + { + // A console application must have a main method as an entry point + public static void Main(string[] args) + { + // Use Console.WriteLine to print lines + Console.WriteLine("Hello World"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // To print without a new line, use Console.Write + Console.Write("Hello "); + Console.Write("World"); + + + /////////////////////////////////////////////////// + // Types & Variables + // + // Declare a variable using + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - Signed 16-bit integer + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Ushort - Unsigned 16-bit integer + // (0 <= ushort <= 65,535) + ushort fooUshort = 10000; + + // Integer - Signed 32-bit integer + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Uinteger - Unsigned 32-bit integer + // (0 <= uint <= 4,294,967,295) + uint fooUint = 1; + + // Long - Signed 64-bit integer + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L is used to denote that this variable value is of type long or ulong + // anything without is treated as int or uint depending on size. + + // Ulong - Unsigned 64-bit integer + // (0 <= ulong <= 18,446,744,073,709,551,615) + ulong fooUlong = 100000L; + + // Float - Single-precision 32-bit IEEE 754 Floating Point + // Precision: 7 digits + float fooFloat = 234.5f; + // f is used to denote that this variable value is of type float; + // otherwise it is treated as double. + + // Double - Double-precision 64-bit IEEE 754 Floating Point + // Precision: 15-16 digits + double fooDouble = 123.4; + + // Bool - true & false + bool fooBoolean = true; + bool barBoolean = false; + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // Strings + string fooString = "My string is here!"; + Console.WriteLine(fooString); + + // formatting + string fooFormattedString = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + Console.WriteLine(fooFormattedString); + + // formatting dates + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // \n is an escaped character that starts a new line + string barString = "Printing on a new line?\nNo Problem!"; + Console.WriteLine(barString); + + // it can be written prettier by using the @ symbol + string bazString = @"Here's some stuff + on a new line!"; + Console.WriteLine(bazString); + + // quotes need to be escaped + // use \" normally + string quotedString = "some \"quoted\" stuff"; + Console.WriteLine(quotedString); + + // use "" when strings start with @ + string quotedString2 = @"some MORE ""quoted"" stuff"; + Console.WriteLine(quotedString2); + + // Use const or read-only to make a variable immutable + // const values are calculated at compile time + const int HOURS_I_WORK_PER_WEEK = 9001; + + // Nullable types + // any type can be made nullable by suffixing a ? + // ? = + int? nullable = null; + Console.WriteLine("Nullable variable: " + nullable); + + // ?? is syntactic sugar for specifying default value + // in case variable is null + int notNullable = nullable ?? 0; + Console.WriteLine("Not nullable variable: " + notNullable); + + // Var - compiler will choose the most appropriate type based on value + var fooImplicit = true; + + /////////////////////////////////////////////////// + // Data Structures + /////////////////////////////////////////////////// + Console.WriteLine("\n->Data Structures"); + + // Arrays + // The array size must be decided upon declaration + // The format for declaring an array is follows: + // [] = new []; + int[] intArray = new int[10]; + string[] stringArray = new string[1]; + bool[] boolArray = new bool[100]; + + // Another way to declare & initialize an array + int[] y = { 9000, 1000, 1337 }; + + // Indexing an array - Accessing an element + Console.WriteLine("intArray @ 0: " + intArray[0]); + + // Arrays are zero-indexed and mutable. + intArray[1] = 1; + Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1 + + // Lists + // Lists are used more frequently than arrays as they are more flexible + // The format for declaring a list is follows: + // List = new List(); + List intList = new List(); + List stringList = new List(); + + // Another way to declare & initialize a list + List z = new List { 9000, 1000, 1337 }; + + // Indexing a list - Accessing an element + // Lists are zero-indexed and mutable. + Console.WriteLine("z @ 0: " + z[2]); + + // Lists don't default to a value; + // A value must be added before accessing the index + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + + // Others data structures to check out: + // + // Stack/Queue + // Dictionary + // Read-only Collections + // Tuple (.Net 4+) + + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + Console.WriteLine("1+2 = " + (i1 + i2)); // => 3 + Console.WriteLine("2-1 = " + (i2 - i1)); // => 1 + Console.WriteLine("2*1 = " + (i2 * i1)); // => 2 + Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Comparison operators + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + >>> Unsigned right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Ternary operators + // A simple if/else can be written as follows + // ? : + string isTrue = (true) ? "True" : "False"; + Console.WriteLine("Ternary demo: " + isTrue); + + + // While loop + int fooWhile = 0; + while (fooWhile < 100) + { + //Console.WriteLine(fooWhile); + //Increment the counter + //Iterated 99 times, fooWhile 0->99 + fooWhile++; + } + Console.WriteLine("fooWhile Value: " + fooWhile); + + // Do While Loop + int fooDoWhile = 0; + do + { + //Console.WriteLine(fooDoWhile); + //Increment the counter + //Iterated 99 times, fooDoWhile 0->99 + fooDoWhile++; + } while (fooDoWhile < 100); + Console.WriteLine("fooDoWhile Value: " + fooDoWhile); + + // For Loop + int fooFor; + //for loop structure => for(; ; ) + for (fooFor = 0; fooFor < 10; fooFor++) + { + //Console.WriteLine(fooFor); + //Iterated 10 times, fooFor 0->9 + } + Console.WriteLine("fooFor Value: " + fooFor); + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), + // the String class, and a few special classes that wrap + // primitive types: Character, Byte, Short, and Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + default: + monthString = "Some other month"; + break; + } + Console.WriteLine("Switch Case Result: " + monthString); + + + /////////////////////////////////////// + // Converting Data Types And Typcasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + // this will throw an Exception on failure + int.Parse("123");//returns an integer version of "123" + + // try parse will default to type default on failure + // in this case: 0 + int tryInt; + int.TryParse("123", out tryInt); + + // Convert Integer To String + // Convert class has a number of methods to facilitate conversions + Convert.ToString(123); + + /////////////////////////////////////// + // Classes And Functions + /////////////////////////////////////// + + Console.WriteLine("\n->Classes & Functions"); + + // (definition of the Bicycle class follows) + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.speedUp(3); // You should always use setter and getter methods + trek.setCadence(100); + + // ToString is a convention to display the value of this Object. + Console.WriteLine("trek info: " + trek.ToString()); + + // Instantiate another new Bicycle + Bicycle octo = new Bicycle(5, 10); + Console.WriteLine("octo info: " + octo.ToString()); + + // Instantiate a new Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.ToString()); + + Console.Read(); + } // End main method + + + } // End LearnCSharp class + + // You can include other classes in a .cs file + + + // Class Declaration Syntax: + // class { + // //data fields, constructors, functions all inside. + // //functions are called as methods in Java. + // } + + public class Bicycle + { + // Bicycle's Fields/Variables + public int cadence; // Public: Can be accessed from anywhere + private int _speed; // Private: Only accessible from within the class + protected int gear; // Protected: Accessible from the class and subclasses + internal int wheels; // Internal: Accessible from within the assembly + string name; // default: Only accessible from within this class + + // readonly values are set at run time + // they can only be assigned upon declaration or in a constructor + readonly bool hasCardsInSpokes = false; // read-only private + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() + { + gear = 1; + cadence = 50; + _speed = 5; + name = "Bontrager"; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes) + { + this.gear = startGear; + this.cadence = startCadence; + this._speed = startSpeed; + this.name = name; + this.hasCardsInSpokes = hasCardsInSpokes; + } + + // Constructors can be chained + public Bicycle(int startCadence, int startSpeed) : + this(startCadence, startSpeed, 0, "big wheels", true) + { + } + + // Function Syntax: + // () + + // classes can implement getters and setters for their fields + // or they can implement properties + + // Method declaration syntax: + // () + public int getCadence() + { + return cadence; + } + + // void methods require no return statement + public void setCadence(int newValue) + { + cadence = newValue; + } + + // virtual keyword indicates this method can be overridden + public virtual void setGear(int newValue) + { + gear = newValue; + } + + public void speedUp(int increment) + { + _speed += increment; + } + + public void slowDown(int decrement) + { + _speed -= decrement; + } + + // properties get/set values + // when only data needs to be accessed, consider using properties. + // properties may have either get or set, or both + private bool _hasTassles; // private variable + public bool hasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + private int _frameSize; + public int FrameSize + { + get { return _frameSize; } + // you are able to specify access modifiers for either get or set + // this means only Bicycle class can call set on Framesize + private set { _frameSize = value; } + } + + //Method to display the attribute values of this Object. + public override string ToString() + { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + _speed + + " name: " + name + + " cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + } // end class Bicycle + + // PennyFarthing is a subclass of Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + // calling parent constructor + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true) + { + } + + public override void setGear(int gear) + { + gear = 0; + } + } +} // End Namespace + +``` + +## Topics Not Covered + + * Enums, Flags + * Attributes + * Generics (T), Delegates, Func, Actions, lambda expressions + * Exceptions, Interfaces, Abstraction + * LINQ + * ASP.NET (Web Forms/MVC/WebMatrix) + * Winforms + * Windows Presentation Foundation (WPF) + + + +## Further Reading + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + + + +[C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) -- cgit v1.2.3 From bf1f9d811cfc41c33cfeaabca68034ad531a097d Mon Sep 17 00:00:00 2001 From: Irfan Charania Date: Mon, 12 Aug 2013 18:04:11 -0700 Subject: Clean up namespace in C# --- csharp.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index d67f6c74..e079571e 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -20,12 +20,10 @@ Multi-line comments look like this /// This is an XML documentation comment /// - +// Specify namespaces application will be using using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + // defines scope to organize code into "packages" namespace Learning -- cgit v1.2.3 From 6dab86ce9d6df4211328e64afadb94a64fd955bb Mon Sep 17 00:00:00 2001 From: Bruno Henrique Date: Mon, 12 Aug 2013 23:31:46 -0300 Subject: for review --- pt-br/ruby-pt.html.markdown | 598 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 598 insertions(+) create mode 100644 pt-br/ruby-pt.html.markdown diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown new file mode 100644 index 00000000..cedd2db1 --- /dev/null +++ b/pt-br/ruby-pt.html.markdown @@ -0,0 +1,598 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["Bruno Henrique - Garu", "http://garulab.com"] +--- + +```ruby +# Isso é um comentario + +=begin +This is a multiline comment +No-one uses them +You shouldn't either + +Isso é um comentario multilinha +Ninguém os usa + +=end + +# First and foremost: Everything is an object. +# Primeiro e principal: Tudo é um objeto. + +# Numbers are objects +# Números são objetos + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Some basic arithmetic +# Aritmética básica + +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Arithmetic is just syntactic sugar +# for calling a method on an object +# Arithmetic é apenas açúcar semântico +# para chamar um métoddo de um objeto +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Special values are objects +# Valores especiais são obejetos +nil # Nothing to see here +nil # Nada para ver aqui +true # truth +true # verdadeiro +false # falsehood +false # falso + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Equality +# Igualdade +1 == 1 #=> true +2 == 1 #=> false + +# Inequality +# Desigualdade +1 != 1 #=> false +2 != 1 #=> true +!true #=> false +!false #=> true + +# apart from false itself, nil is the only other 'falsey' value +# além de 'false', 'nil' é o único outro valor falso + +!nil #=> true +!false #=> true +!0 #=> false + +# More comparisons +# Mais comparações +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Strings are objects +# Strings são obejetos + +'I am a string'.class #=> String +'Eu sou uma string'.class #=> String +"I am a string too".class #=> String +"Eu também sou uma string".class #=> String + +placeholder = "use string interpolation" +placeholder = "usar interpolação de string" +"I can #{placeholder} when using double quoted strings" +"Eu posso #{placeholder} quando estiver usando aspas duplas" +#=> "I can use string interpolation when using double quoted strings" +#=> "Eu posso usar insterpolação de string quando estiver usando aspas duplas" + + +# print to the output +# imprime para output (saida) +puts "I'm printing!" +puts "Estou imprimindo" + +# Variables +# Variáveis +x = 25 #=> 25 +x #=> 25 + +# Note that assignment returns the value assigned +# Note que uma atribuição retorna o valor atribuido +# This means you can do multiple assignment: +# Isso significa que você pode fazer multiplas atribuições: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# By convention, use snake_case for variable names +# Por convenção, use snake_case para nomes de variáveis +snake_case = true + +# Use descriptive variable names +# Use nomes de variáveis descrivos +path_to_project_root = '/good/name/' +caminho_para_a_raiz_do_projeto = '/bom/nome/' +path = '/bad/name/' +caminho = '/nome/ruim/' + +# Symbols (are objects) +# Simbolos (são objetos) +# Symbols are immutable, reusable constants represented internally by an +# Simbolos são imultáveis, são constantes reutilizáveis representadadas internamente por um +# integer value. They're often used instead of strings to efficiently convey +# valor inteiro. Eles são frequentemente usados no lugar de strings para transmitir com eficiência os valores +# specific, meaningful values +# específicos e significativos + +:pending.class #=> Symbol +:pendente.class #=> Symbol + +status = :pending +status = :pendente + +status == :pending #=> true +status == :pendente #=> true + +status == 'pending' #=> false +status == 'pendente' #=> false + +status == :approved #=> false +status == :aprovado #=> false + +# Arrays + +# This is an array +# Isso é um array +[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Arrays can contain different types of items +# Arrays podem conter diferentes tipos de itens + +array = [1, "hello", false] #=> => [1, "hello", false] +array = [1, "Oi", false] #=> => [1, "Oi", false] + +# Arrays can be indexed +# Arrays podem ser indexados +# From the front +# a partir do começo +array[0] #=> 1 +array[12] #=> nil + +# Like arithmetic, [var] access +# Como aritimetica, o acesso via [var] +# is just syntactic sugar +# é apenas açúcar sintático +# for calling a method [] on an object +# para chamar o método [] de um objeto +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# From the end +# a partir do final +array[-1] #=> 5 + +# With a start and end index +# Com um índice de começo e fim +array[2, 4] #=> [3, 4, 5] + +# Or with a range +# Ou com um intervalo de valores +array[1..3] #=> [2, 3, 4] + +# Add to an array like this +# Adicionar a um array como este +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# Hashes are Ruby's primary dictionary with keys/value pairs. +# Hashes são dicionário com um par de chave(key)/valor(value) +# Hashes are denoted with curly braces: +# Hashes são simbolizados com chaves "{}" +hash = {'color' => 'green', 'number' => 5} +hash = {'cor' => 'verde', 'numero' => 5} + +hash.keys #=> ['cor', 'numero'] + +# Hashes can be quickly looked up by key: +# Hashes podem ser rapidamente pesquisado pela chave (key) +hash['cor'] #=> 'verde' +hash['numero'] #=> 5 + +# Asking a hash for a key that doesn't exist returns nil: +# Procurar em um hash por uma chave que não existe retorna nil: +hash['nothing here'] #=> nil +hash['nada aqui'] #=> nil + +# Iterate over hashes with the #each method: +# Interar sobre hashes com o método #each: +hash.each do |k, v| + puts "#{k} is #{v}" +end + +hash.each do |k, v| + puts "#{k} é #{v}" +end + +# Since Ruby 1.9, there's a special syntax when using symbols as keys: +# Desde o Ruby 1.9, temos uma sintaxe especial quando usamos simbolos como chaves (keys) + +new_hash = { defcon: 3, action: true} +novo_hash = { defcon: 3, acao: true} + +new_hash.keys #=> [:defcon, :action] +novo_hash.keys #=> [:defcon, :acao] + +# Tip: Both Arrays and Hashes are Enumerable +# Dica: Tanto Arrays quanto Hashes são Enumerable +# They share a lot of useful methods such as each, map, count, and more +# Eles compartilham um monte de métodos úteis como each, map, count e mais + +# Control structures +# Estruturas de controle + +if true + "if statement" +elsif false + "else if, optional" +else + "else, also optional" +end + +if true + "Se verdadeiro" +elsif false + "else if, opicional" +else + "else, também é opicional" +end + +for counter in 1..5 + puts "iteration #{counter}" +end + +for contador in 1..5 + puts "interação #{contador}" +end +#=> contador 1 +#=> contador 2 +#=> contador 3 +#=> contador 4 +#=> contador 5 + +# HOWEVER +# PORÉM +# No-one uses for loops +# Ninguém usa para loops +# Use `each` instead, like this: +# Use "each" em vez, dessa forma: + +(1..5).each do |counter| + puts "iteration #{counter}" +end + +(1..5).each do |contador| + puts "interação #{contador}" +end +#=> contador 1 +#=> contador 2 +#=> contador 3 +#=> contador 4 +#=> contador 5 + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end + +contador = 1 +while contador <= 5 do + puts "interação #{contador}" + contador += 1 +end +#=> contador 1 +#=> contador 2 +#=> contador 3 +#=> contador 4 +#=> contador 5 + +grade = 'B' + +case grade +when 'A' + puts "Way to go kiddo" +when 'B' + puts "Better luck next time" +when 'C' + puts "You can do better" +when 'D' + puts "Scraping through" +when 'F' + puts "You failed!" +else + puts "Alternative grading system, eh?" +end + +grau = 'B' + +case grau +when 'A' + puts "Um longo caminho a percorrer pequeno gafanhoto" +when 'B' + puts "Melhor sorte da próxima vez" +when 'C' + puts "Você pode fazer melhor" +when 'D' + puts "Scraping through" +when 'F' + puts "Você falhou" +else + puts "Alternative grading system, eh?" +end + +# Functions +# Funções + +def dobrar(x) + x * 2 +end + +# Functions (and all blocks) implcitly return the value of the last statement +# Funções (e todos os blocos) retornam implicitamente o valor da última linha +double(2) #=> 4 +dobrar(2) #=> 4 + +# Parentheses are optional where the result is unambiguous +# Parênteses são opicionais onde o resultado é claro +double 3 #=> 6 +dobrar 3 #=> 6 + +double double 3 #=> 12 +dobrar dobrar 3 #=> 12 + +def sum(x,y) + x + y +end + +def somar(x,y) + x + y +end + +# Method arguments are separated by a comma +# Argumentos de métodos são separados por uma virgula +sum 3, 4 #=> 7 +somar 3, 4 #=> 7 + +somar somar(3,4), 5 #=> 12 + +# yield +# All methods have an implicit, optional block parameter +# Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco +# it can be called with the 'yield' keyword +# ele pode ser chamado com a palavra chave 'yield' + +def surround + puts "{" + yield + puts "}" +end + +surround { puts 'hello world' } + + +def ao_redor + puts "{" + yield + puts "}" +end + +ao_redor { puts 'Olá mundo' } + +# { +# Olá mundo +# } + + +# Define a class with the class keyword +# Define uma classe com a palavra chave 'class' +class Human + + # A class variable. It is shared by all instances of this class. + @@species = "H. sapiens" + + # Basic initializer + def initialize(name, age=0) + # Assign the argument to the "name" instance variable for the instance + @name = name + # If no age given, we will fall back to the default in the arguments list. + @age = age + end + + # Basic setter method + def name=(name) + @name = name + end + + # Basic getter method + def name + @name + end + + # A class method uses self to distinguish from instance methods. + # It can only be called on the class, not an instance. + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end + +end + + +class Humano + + # Uma variavel de classe. Ela é compartilhada por todas as instancias dessa classe + @@especies = "H. sapiens" + + # Inicialização básica (contructor) + def initialize(nome, idade=0) + # Atribui o argumento para a variavel de instacia "nome" do objeto + @nome = nome + # Se a idade não for passada, nós definimos um valor padrão na lista de argumentos + @idade = idade + end + + # Método básico para atribuir valor + def nome=(nome) + @nome = nome + end + + # Método básico de resgatar valor + def nome + @nome + end + + # Um método de classe usa a palavra chave self para se defenciar dos métodos de instancia. + # Ele só pode ser chamado na classe, não na instancia + def self.diz(msg) + puts "#{msg}" + end + + def especies + @@especies + end + +end + + +# Instantiate a class +# Instaciando uma classe +jim = Human.new("Jim Halpert") +jim = Humano.new("Jim Halpert") + +dwight = Human.new("Dwight K. Schrute") +dwight = Humano.new("Dwight K. Schrute") + +# Let's call a couple of methods +# Vamos chamar um par de métodos +jim.species #=> "H. sapiens" +jim.especies #=> "H. sapiens" + +jim.name #=> "Jim Halpert" +jim.nome #=> "Jim Halpert" + +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.nome = "Jim Halpert II" #=> "Jim Halpert II" + +jim.name #=> "Jim Halpert II" +jim.nome #=> "Jim Halpert II" + +dwight.species #=> "H. sapiens" +dwight.especies #=> "H. sapiens" + +dwight.name #=> "Dwight K. Schrute" +dwight.nome #=> "Dwight K. Schrute" + +# Call the class method +# Chamar o método de classe +Human.say("Hi") #=> "Hi" +Humano.diz("Oi") #=> "Oi" + +# Class also is object in ruby. So class can have instance variables. +# Uma classe também é objeto em Ruby. Então uma classe pode possuir um variavel de instancia +# Class variable is shared among the class and all of its descendants. +# Variavies de classe são compartilhadas entre a classe e todos os seus descendentes. + +# base class +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + + +# Classe base +class Humano + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# classe filha +class Trabalhador < Humano +end + +Human.foo # 0 +Humano.foo # 0 +Worker.foo # 0 +Trabalhador.foo # 0 + +Human.foo = 2 # 2 +Humano.foo = 2 # 2 +Worker.foo # 2 +Trabalhador.foo # 2 + +# Class instance variable is not shared by the class's descendants. +# Uma variavel de instancia não é compartilhada por suas classes decendentes. + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Humano + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +class Doutor < Humano +end + +Humano.bar # 0 +Doutor.bar # nil + +``` -- cgit v1.2.3 From 04c0b273b03b9417c895f687bcd67e7e58d71a38 Mon Sep 17 00:00:00 2001 From: wikibook Date: Tue, 13 Aug 2013 15:42:33 +0900 Subject: korean version of javascript and lua tutorials added --- ko-kr/javascript-kr.html.markdown | 435 ++++++++++++++++++++++++++++++++++++++ ko-kr/lua-kr.html.markdown | 423 ++++++++++++++++++++++++++++++++++++ 2 files changed, 858 insertions(+) create mode 100644 ko-kr/javascript-kr.html.markdown create mode 100644 ko-kr/lua-kr.html.markdown diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown new file mode 100644 index 00000000..d9e0afe8 --- /dev/null +++ b/ko-kr/javascript-kr.html.markdown @@ -0,0 +1,435 @@ +--- +language: javascript +category: language +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] +translators: + - ["wikibook", "http://wikibook.co.kr"] +lang: ko-kr +--- + +ڹٽũƮ ݽ 귻 ũ(Brendan Eich) 1995⿡ ϴ. + ڹٽũƮ Ʈ ܼ ũƮ  ǥ µ, + ø̼ ڹٸ ϴ ̾ + ȣۿ п Ʈ忡 +ڹٺ ξ ̰ ƽϴ. + +׷ ڹٽũƮ ѵ ʽϴ. ũ V8 ڹٽũƮ + Ÿ ϴ Node.js α⸦ ֽϴ. + +ǵ ֽø ϰڽϴ! [@adambrenecki](https://twitter.com/adambrenecki) +[adam@brenecki.id.au](mailto:adam@brenecki.id.au) ֽϴ. + +```js +// ּ C մϴ. ¥ ּ ÷ ϰ, +/* ּ ǥ ؼ + ǥ ÷ ϴ. */ + +// ݷ(;) ֽϴ. +doStuff(); + +// ׷ ʿ µ, Ư 츦 ϰ +// ݷ ڵ ԵDZ Դϴ. +doStuff() + +// ⼭ ݷ ϰڽϴ. ݷ δ +// ̳ Ʈ Ÿ ̵带 ϴ. + +/////////////////////////////////// +// 1. , ڿ, + +// ڹٽũƮ ϳ Ÿ(64Ʈ IEEE 754 ) +// ֽϴ. +3 // = 3 +1.5 // = 1.5 + +// մϴ. +1 + 1 // = 2 +8 - 1 // = 7 +10 * 2 // = 20 +35 / 5 // = 7 + +// ʴ Ե˴ϴ. +5 / 2 // = 2.5 + +// Ʈ 굵 ˴ϴ. float Ʈ ϸ +// 32Ʈ ȣ ִ int ȯ˴ϴ. +1 << 2 // = 4 + +// ȣ ̿ϸ 켱 ֽϴ. +(1 + 3) * 2 // = 8 + +// ڰ ƴ Ư ֽϴ. +Infinity // 1/0 1/0 +-Infinity // -1/0 +NaN // 0/0 + +// Ҹ ŸԵ ֽϴ. +true +false + +// ڿ ' " մϴ. +'abc' +"Hello, world" + +// 꿡 ! ȣ ̿մϴ. +!true // = false +!false // = true + +// ϼ == +1 == 1 // = true +2 == 1 // = false + +// ġ != +1 != 1 // = false +2 != 1 // = true + +// +1 < 10 // = true +1 > 10 // = false +2 <= 2 // = true +2 >= 2 // = true + +// ڿ + ֽϴ. +"Hello " + "world!" // = "Hello world!" + +// ׸ < > ֽϴ. +"a" < "b" // = true + +// Ÿ ȯ ˴ϴ. +"5" == 5 // = true + +// === ʴ´ٸ . +"5" === 5 // = false + +// charAt ̿ϸ ڿ ڿ ֽϴ. +"This is a string".charAt(0) + +// null undefined ֽϴ. +null // ǵ ƴ Ÿ մϴ. +undefined // Ÿ մϴ. + +// null, undefinded, NaN, 0, "" ̸, ٸ Դϴ. +// 0 ̸, "0" Դϴ( 0 == "0"̴). + +/////////////////////////////////// +// 2. , 迭, ü + +// var Ű մϴ. ڹٽũƮ Ÿ +// Ÿ ʿ䰡 ϴ. Ҵ = ϳ մϴ. +var someVar = 5 + +// var Ű带 ʾƵ ߻ ʽϴ. +someOtherVar = 10 + +// ׷ ȿ ƴ϶ +// ȿ ˴ϴ. + +// Ҵ ä undefined ˴ϴ. +var someThirdVar // = undefined + +// ϴ ǥ ϴ. +someVar += 5 // someVar = someVar + 5; . someVar 10. +someVar *= 10 // somVar 100 + +// 1 ϰų ξ ª ǥ ֽϴ. +someVar++ // someVar 101 +someVar-- // ٽ 100 ǵư + +// 迭 Ÿ Դϴ. +var myArray = ["Hello", 45, true] + +// 迭 ȣ ѷ ε ̿ ֽϴ. +// 迭 ε 0 մϴ. +myArray[1] // = 45 + +// ڹٽũƮ ü ٸ ''̳ '' ϴ. +// , Ű- ÷Դϴ. +{key1: "Hello", key2: "World"} + +// Ű ڿ ȿ ڹٽũƮ ĺ +// ǥ ʿ ʽϴ.  Ÿ̵ ֽϴ. +var myObj = {myKey: "myValue", "my other key": 4} + +// ü Ӽ ε ̿ ֽϴ. +myObj["my other key"] // = 4 + +// Ǵ Ű ȿ ĺ ǥ ̿ ֽϴ. +myObj.myKey // = "myValue" + +// ü մϴ. , ϰų Ű ߰ ֽϴ. +myObj.myThirdKey = true + +// Ϸ ϸ undefined ȯ˴ϴ. +myObj.myFourthKey // = undefined + +/////////////////////////////////// +// 3. + +// if մϴ. +var count = 1 +if (count == 3){ + // count 3 򰡵 +} else if (count == 4) { + // count 4 򰡵 +} else { + // count 3̳ 4 ƴ 쿡 򰡵 +} + +// while Դϴ. +while (true) { + // ! +} + +// do-while ׻ ּ ȴٴ ϸ +// while մϴ. +var input +do { + input = getInput() +} while (!isValid(input)) + +// for C ڹ for ϴ. +// ʱȭ; ; +for (var i = 0; i < 5; i++){ + // 5 +} + +// && and̰ || orԴϴ. +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear" +} +if (colour == "red" || colour == "blue"){ + // ̰ų Ķ +} + +// && || " " ϴµ, ⺻ մϴ. +var name = otherName || "default" + +/////////////////////////////////// +// 4. Լ, ȿ, Ŭ + +// ڹٽũƮ Լ function Ű մϴ. +function myFunction(thing){ + return thing.toUpperCase() +} +myFunction("foo") // = "FOO" + +// Լ "͸", ̸ ֽϴ. +function(thing){ + return thing.toLowerCase() +} +// (Լ Ű ̸ Լ ȣ ϴ) + +// ڹٽũƮ Լ ϱ ü̹Ƿ ٸ Ҵϰ +// ٸ Լ ڷ ֽϴ. , ̺Ʈ ڵ鷯 +function myFunction(){ + // ڵ 5 ȣ +} +setTimeout(myFunction, 5000) + +// ٸ Լ ȣ Լ ۼ ֽϴ. + +setTimeout(function myFunction(){ + // ڵ 5 ȣ +}, 5000) + +// ڹٽũƮ Լ ȿ ֽϴ. +// Լ ü ȿ ٸ ȿ ʽϴ. +if (true){ + var i = 5 +} +i // = 5 - ȿ ϴ  undefined ƴմϴ. + +// ̰ " Ǵ ͸ Լ" ̾µ, +// ӽ ȿ Ǵ մϴ. +(function(){ + var temporary = 5 + // ' ü' Ҵϴ ȿ ִµ, + // ü ׻ 'window'Դϴ. ü + // Node.js ƴ ȯ濡 ٸ ̸ ֽϴ. + window.permanent = 10 + // Ǵ տ ߴٽ var Ű带 ֽϴ. + permanent2 = 15 +})() +temporary // ReferenceError ߻ +permanent // = 10 +permanent2 // = 15 + +// ڹٽũƮ ϳ Ŭ(closure)Դϴ. +// Լ ٸ Լ ȿ ǵǸ ʿ ǵ Լ ٱ Լ +// ֽϴ. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!" + function inner(){ + alert(prompt) + } + setTimeout(inner, 5000) + // setTimeout 񵿱 ϹǷ Լ 5 + // ٸ ʰ Ĩϴ. 5ʰ inner + // prompt ֽϴ. +} +sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s + +/////////////////////////////////// +// 5. ü ȭ; ڿ Ÿ + +// ü Լ ֽϴ. +var myObj = { + myFunc: function(){ + return "Hello world!" + } +} +myObj.myFunc() // = "Hello world!" + +// ü Ե Լ ȣǸ Լ this Ű带 ̿ +// ش Լ Ե ü ֽϴ. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString + } +} +myObj.myFunc() // = "Hello world!" + +// ⼭ Լ ǵ ƴ Լ ȣǴ +// İ ֽϴ. ׷ Ʒ Լ ü ؽƮ +// ȣ ʽϴ. +var myFunc = myObj.myFunc +myFunc() // = undefined + +// ݴ Լ ü Ҵϰ this ش ü ֽϴ. +// Լ ü ߰ ʾҴ Դϴ. +var myOtherFunc = function(){ + return this.myString.toUpperCase() +} +myObj.myOtherFunc = myOtherFunc +myObj.myOtherFunc() // = "HELLO WORLD!" + +// new Ű Լ ȣϸ ο ü ǰ this +// Լ ְ ˴ϴ. ̷ Լ ڶ մϴ. + +var MyConstructor = function(){ + this.myNumber = 5 +} +myNewObj = new MyConstructor() // = {myNumber: 5} +myNewObj.myNumber // = 5 + +// ڹٽũƮ ü 'prototype' ֽϴ.  ü +// ü ʴ Ƽ ϸ ʹ ηŸԿ +// ش Ƽ ãϴ. + +// Ϻ ڹٽũƮ ü __proto__ Ƽ +// ü ŸԿ ϴ ϱ⵵ մϴ. Ÿ +// ϱ⿡ ̷ 뵵 ǰ __proto__ ǥؿ Ե +// ʽϴ. ߿ Ÿ ϴ ǥ 캸ڽϴ. +var myObj = { + myString: "Hello world!", +} +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +} +myObj.__proto__ = myPrototype +myObj.meaningOfLife // = 42 + +// Լ մϴ. +myObj.myFunc() // = "hello world!" + +// Ƽ ŸԿ +// Ÿ Ÿ ã ˴ϴ. +myPrototype.__proto__ = { + myBoolean: true +} +myObj.myBoolean // = true + +// ⼭ Ͼ ʽϴ. ü ŸԿ +// ֽϴ. ̴ Ÿ ϸ +// ݿȴٴ ǹԴϴ. +myPrototype.meaningOfLife = 43 +myObj.meaningOfLife // = 43 + +// տ __proto__ ǥؿ Ե ʴٰ ̾߱ߴµ, +// ü Ÿ ϴ ǥ ϴ. +// Ư Ÿ ο ü ϴ +// ֽϴ. + +// ù ° Object.create ̿ϴ ε, +// Object.create ֱٿ ڹٽũƮ ߰ ̶ +// ü ̿ ִ ƴմϴ. +var myObj = Object.create(myPrototype) +myObj.meaningOfLife // = 43 + +// ° 𼭳 ϴ ε, ڿ ֽϴ. +// ڿ prototype̶ Ƽ ֽϴ. Ƽ +// Լ ü Ÿ *ƴϰ* ڿ new Ű带 ̿ +// ü ο ü ޴ ŸԴϴ. +myConstructor.prototype = { + getMyNumber: function(){ + return this.myNumber + } +} +var myNewObj2 = new myConstructor() +myNewObj2.getMyNumber() // = 5 + +// ڿ ڿ ŸԿ ü +// ϴ ڰ ֽϴ. +var myNumber = 12 +var myNumberObj = new Number(12) +myNumber == myNumberObj // = true + +// Ȯ ʽϴ. +typeof(myNumber) // = 'number' +typeof(myNumberObj) // = 'object' +myNumber === myNumberObj // = false +if (0){ + // 0 ̶ ڵ ʽϴ. +} +if (Number(0)){ + // Number(0) ̶ ڵ *˴ϴ*. +} + +// ü Ϲ Լ Ÿ ϱ +// ڿ ߰ ֽϴ. +String.prototype.firstCharacter = function(){ + return this.charAt(0) +} +"abc".firstCharacter() // = "a" + +// ̷ ڹٽũƮ ڹٽũƮ +// ο ϴ "(polyfilling)" ̿ǹǷ +// ȯ濡 ֽϴ. + +// , Object.create ü ƴ϶ +// Ʒ ̿ Object.create ֽϴ. +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // ùٸ Ÿ ӽ ڸ + var Constructor = function(){} + Constructor.prototype = proto + // ׷ ӽ ڸ ̿ ο Ÿ + // ü + return new Constructor() + } +} +``` + +## Ÿ ڷ + +[ Ʈũ](https://developer.mozilla.org/en-US/docs/Web/JavaScript) +ڹٽũƮ Ǹ մϴ. Ҿ Ű ̶ + Ǹ и ν ٸ 鿡 ֽϴ. + +MDN ['ڹٽũƮ Թ'](https://developer.mozilla.org/ko/docs/A_re-introduction_to_JavaScript) +⼭ ٷ ڼ ٷ ֽϴ. ڷῡ ڹٽũƮ ü +ؼ ϰ ٷϴ. ڹٽũƮ ϴ ʹٸ +[ ü (Document Object Model)](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + ϱ ٶϴ. + +[ڹٽũƮ ](http://bonsaiden.github.io/JavaScript-Garden/) ڹٽũƮ  + ߳ κе ɵ ְ ٷϴ. + +Ҿ ۿ ⿩ е, Ϻδ Ʈ ִ + (Louie Dihn) ̽ Ʃ丮 Ʈũ ִ +[ڹٽũƮ Ʃ丮](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) ߽ϴ. \ No newline at end of file diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown new file mode 100644 index 00000000..50458f88 --- /dev/null +++ b/ko-kr/lua-kr.html.markdown @@ -0,0 +1,423 @@ +--- +language: lua +category: language +contributors: + - ["Tyler Neylon", "http://tylerneylon.com/"] +translators: + - ["wikibook", "http://wikibook.co.kr"] +lang: ko-kr +--- + +```lua +-- ¥ ּ ǹմϴ. + +--[[ + [ ] ߰ϸ ּ ˴ϴ. +--]] + +---------------------------------------------------- +-- 1. 帧 +---------------------------------------------------- + +num = 42 -- ڴ doubleԴϴ. +-- ʿ ϴ. 64Ʈ double +-- Ȯ int ϱ 52Ʈ +-- ֽϴ. 52Ʈ int ؼ +-- е õ ʽϴ. + +s = 'walternate' -- ̽ Һ ڿ +t = "ūǥ ᵵ ˴ϴ" +u = [[ ȣ + ڿ + Ÿϴ.]] +t = nil -- t. ƴ ÷ մϴ. + +-- do/end Ű Ÿϴ: +while num < 50 do + num = num + 1 -- ++ += ڴ ϴ. +end + +-- If : +if num > 40 then + print('40 ̻') +elseif s ~= 'walternate' then -- ~= ' ʴ'Դϴ. + -- ϼ ˻ ̽ ==Դϴ. + -- ڿ ֽϴ. + io.write('not over 40\n') -- ⺻ stdout ϴ. +else + -- ⺻ Դϴ. + thisIsGlobal = 5 -- Ÿ ǥ ϹԴϴ. + + -- ϴ: + local line = io.read() -- stdin нϴ + + -- ڿ ῡ .. ڸ ϴ: + print('ܿ ֽϴ, ' .. line) +end + +-- nil ȯմϴ. +-- ڵ带 ص ʽϴ: +foo = anUnknownVariable -- foo nilԴϴ. + +aBoolValue = false + +-- nil false Դϴ; 0 '' Դϴ! +if not aBoolValue then print('twas false') end + +-- 'or' 'and' (short-circuit)˴ϴ. +-- ڵ C/ڹٽũƮ a?b:c ڿ մϴ: +ans = aBoolValue and 'yes' or 'no' --> 'no' + +karlSum = 0 +for i = 1, 100 do -- ҵ Ե˴ϴ. + karlSum = karlSum + i +end + +-- īƮ ٿ "100, 1, -1" ϴ. +fredSum = 0 +for j = 100, 1, -1 do fredSum = fredSum + j end + +-- Ϲ begin, end[, step]Դϴ. + +-- ٸ ݺ ϴ: +repeat + print('̷ ') + num = num - 1 +until num == 0 + + +---------------------------------------------------- +-- 2. Լ +---------------------------------------------------- + +function fib(n) + if n < 2 then return n end + return fib(n - 2) + fib(n - 1) +end + +-- Ŭ ͸ Լ ֽϴ: +function adder(x) + -- ȯ Լ adder ȣ ǰ x + -- ˴ϴ: + return function (y) return x + y end +end +a1 = adder(9) +a2 = adder(36) +print(a1(16)) --> 25 +print(a2(64)) --> 100 + +-- ȯ, Լ ȣ, Ҵ繮 ̰ ٸ +-- Ʈ ؼ մϴ. +-- Ʈ nil Ҵ/ȯǰ +-- Ʈ ϴ. + +x, y, z = 1, 2, 3, 4 +-- x = 1, y = 2, z = 3̰ 4 ϴ. + +function bar(a, b, c) + print(a, b, c) + return 4, 8, 15, 16, 23, 42 +end + +x, y = bar('zaphod') --> "zaphod nil nil" +-- x = 4, y = 8̰ 15~42 ϴ. + +-- Լ ϱ ṵ̈, / ȿ +-- ֽϴ. Ʒ Լ ϴ: +function f(x) return x * x end +f = function (x) return x * x end + +-- ׸ Ʒ Լ Դϴ: +local function g(x) return math.sin(x) end +local g; g = function (x) return math.sin(x) end +-- 'local g' ϸ g Լ ϴ. + +-- ׳ ﰢ Լ մϴ. + +-- Լ ȣ ڿ Ű ϳ Ѵٸ +-- ȣ ʾƵ ˴ϴ: +print 'hello' -- մϴ. + + +---------------------------------------------------- +-- 3. ̺ +---------------------------------------------------- + +-- ̺ = ڷᱸμ, 迭Դϴ. +-- PHP 迭̳ ڹٽũƮ ü ϸ, +-- Ʈε ִ ؽ ųʸԴϴ. + +-- ̺ ųʸ/ ϱ: + +-- ųʸ ͷ ⺻ ڿ Ű ϴ: +t = {key1 = 'value1', key2 = false} + +-- ڿ Ű ڹٽũƮ ǥ ֽϴ: +print(t.key1) -- 'value1' . +t.newKey = {} -- Ű/ ߰. +t.key2 = nil -- ̺ key2 . + +-- (nil ƴ) Ű ϴ ͷ ǥ: +u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} +print(u[6.28]) -- "tau" + +-- Ű Ī ⺻ ڿ ڿ ؼ +-- ̺ ؼ ĺڷ մϴ. +a = u['@!#'] -- Now a = 'qbert'. +b = u[{}] -- We might expect 1729, but it's nil: +a = u['@!#'] -- a 'qbert'Դϴ. +b = u[{}] -- 1729 ߰ nilԴϴ: +-- Ž ϱ b nilԴϴ. Ž ϴ +-- Ű Ű ü ƴϱ +-- Դϴ. ڿ ڰ ̽ļ ִ ŰԴϴ. + +-- ̺ ϳ Ű ϴ Լ ȣ ȣ ʿ ʽϴ: +function h(x) print(x.key1) end +h{key1 = 'Sonmi~451'} -- 'Sonmi~451' . + +for key, val in pairs(u) do -- ̺ ȸ + print(key, val) +end + +-- _G Ư ̺Դϴ. +print(_G['_G'] == _G) -- 'true' + +-- ̺ Ʈ/迭 ϱ: + +-- Ʈ ͷ Ϲ int Ű ˴ϴ: +v = {'value1', 'value2', 1.21, 'gigawatts'} +for i = 1, #v do -- #v Ʈ v ũԴϴ. + print(v[i]) -- ε 1 մϴ!! ƴմϴ! +end +-- 'list' Ÿ ƴմϴ. v ӵ Ű Ե +-- ̺̰ Ʈ ޵ Դϴ. + +---------------------------------------------------- +-- 3.1 Ÿ̺ Ÿ޼ +---------------------------------------------------- + +-- ̺ ̺ ε ϰ ϴ Ÿ̺ +-- ֽϴ. ߿ Ÿ̺  ڹٽũƮ +-- Ÿ԰ ϴ 캸ڽϴ. + +f1 = {a = 1, b = 2} -- м a/b ǥ +f2 = {a = 2, b = 3} + +-- ڵ մϴ: +-- s = f1 + f2 + +metafraction = {} +function metafraction.__add(f1, f2) + sum = {} + sum.b = f1.b * f2.b + sum.a = f1.a * f2.b + f2.a * f1.b + return sum +end + +setmetatable(f1, metafraction) +setmetatable(f2, metafraction) + +s = f1 + f2 -- f1 Ÿ̺ __add(f1, f2) ȣ + +-- f1 f2 ڹٽũƮ Ÿ԰ ޸ Ÿ̺ +-- Ű  getmetatable(f1) ޾ƿ; մϴ. +-- Ÿ̺ __add ư ˰ ִ Ű Ϲ ̺Դϴ. + +-- ׷ s Ÿ̺ ʱ մϴ. +-- t = s + s +-- Ʒ Ŭ ̷ ߻ ʽϴ. + +-- Ÿ̺ __index ̿ Ž εմϴ: +defaultFavs = {animal = 'gru', food = 'donuts'} +myFavs = {food = 'pizza'} +setmetatable(myFavs, {__index = defaultFavs}) +eatenBy = myFavs.animal -- մϴ! , Ÿ̺! + +-- Ÿ̺ Ž Ÿ̺ __index ̿ +-- õϰ, ̷ ݺ˴ϴ. + +-- __index ȭ Ž function(tbl, key) +-- ֽϴ. + +-- __index, __add, ... Ÿ޼ մϴ. +-- Ÿ޼带 ̺ ü Դϴ. + +-- __add(a, b) for a + b +-- __sub(a, b) for a - b +-- __mul(a, b) for a * b +-- __div(a, b) for a / b +-- __mod(a, b) for a % b +-- __pow(a, b) for a ^ b +-- __unm(a) for -a +-- __concat(a, b) for a .. b +-- __len(a) for #a +-- __eq(a, b) for a == b +-- __lt(a, b) for a < b +-- __le(a, b) for a <= b +-- __index(a, b) for a.b +-- __newindex(a, b, c) for a.b = c +-- __call(a, ...) for a(...) + +---------------------------------------------------- +-- 3.2 Ŭ ̺ +---------------------------------------------------- + +-- ƿ Ŭ , ̺ Ÿ̺ +-- ̿ Ŭ پ ֽϴ. + +-- ϴ մϴ. + +Dog = {} -- 1. + +function Dog:new() -- 2. + newObj = {sound = 'woof'} -- 3. + self.__index = self -- 4. + return setmetatable(newObj, self) -- 5. +end + +function Dog:makeSound() -- 6. + print('I say ' .. self.sound) +end + +mrDog = Dog:new() -- 7. +mrDog:makeSound() -- 'I say woof' -- 8. + +-- 1. Dog Ŭó մϴ. δ ̺Դϴ. +-- 2. function ̺:fn(...) +-- function ̺.fn(self, ...) ϴ. +-- : self ù ° ڸ ߰ Դϴ. +-- self  ñϴٸ Ʒ 7 8 о. +-- 3. newObj Dog Ŭ νϽ ˴ϴ. +-- 4. self = νϽȭǴ Ŭ. +-- ַ self = Dog ̿ϸ ̰ ٲ ֽϴ. +-- newObj Ÿ̺ self __index self ϸ +-- newObj self Լ ˴ϴ. +-- 5. : setmetatable ù ° ڸ ȯմϴ. +-- 6. : 2 Ͱ ̹ self +-- Ŭ ƴ νϽ ֽϴ. +-- 7. Dog.new(Dog) Ƿ new() self = DogԴϴ. +-- 8. mrDog.makeSound(mrDog) Ƿ self = mrDogԴϴ. + +---------------------------------------------------- + +-- : + +LoudDog = Dog:new() -- 1. + +function LoudDog:makeSound() + s = self.sound .. ' ' -- 2. + print(s .. s .. s) +end + +seymour = LoudDog:new() -- 3. +seymour:makeSound() -- 'woof woof woof' -- 4. + +-- 1. LoudDog Dog ޼ ˴ϴ. +-- 2. self new() 'sound' Ű ϴ. 3 ϼ. +-- 3. LoudDog.new(LoudDog) , LoudDog 'new' Ű +-- Ÿ̺ __index = Dog̱ Dog.new(LoudDog) +-- ȯ˴ϴ. +-- : seymour Ÿ̺ LoudDog̰ LoudDog.__index +-- LoudDogԴϴ. seymour.key seymour.key, +-- LoudDog.key, Dog.key ̸, Ű  ̺ +-- Դϴ. +-- 4. 'makeSound' Ű LoudDog ߰ ֽϴ. +-- ̰ LoudDog.makeSound(seymour) ϴ. + +-- ʿ , Ŭ new() Ŭ new() մϴ. +function LoudDog:new() + newObj = {} + -- set up newObj + self.__index = self + return setmetatable(newObj, self) +end + +---------------------------------------------------- +-- 4. +---------------------------------------------------- + + +--[[ ⼭ ּ ϸ ũƮ κ +-- ° ˴ϴ. +``` + +```lua +-- mod.lua ٰ ô. +local M = {} + +local function sayMyName() + print('̼ҷ') +end + +function M.sayHello() + print('ȳϼ') + sayMyName() +end + +return M + +-- ٸ Ͽ mod.lua ̿ ֽϴ. +local mod = require('mod') -- mod.lua + +-- require ԽŰ ǥȭ Դϴ. +-- require մϴ: (ij̵ . ϴ ) +local mod = (function () + +end)() +-- mod.lua Լ ó ǹǷ mod.lua +-- ۿ ϴ. + +-- ڵ尡 ϴ mod mod.lua M Դϴ. +mod.sayHello() -- ̼ҷ λ縦 dzܴϴ. + +-- ڵ带 ϸ ߻մϴ. +-- sayMyName mod.lua ȿ ϱ Դϴ: +mod.sayMyName() -- + +-- require ȯ ij̵ǹǷ require ص +-- ִ ˴ϴ. + +-- mod2.lua "print('Hi')" ִٰ ô. +local a = require('mod2') -- Hi! +local b = require('mod2') -- print . a=b + +-- dofile require ij ʽϴ: +dofile('mod2') --> Hi! +dofile('mod2') --> Hi! (require ޸ ٽ ѹ ) + +-- loadfile о ʽϴ +f = loadfile('mod2') -- f() ȣؾ mod2.lua ˴ϴ. + +-- loadstring ڿ loadfileԴϴ. +g = loadstring('print(343)') -- Լ ȯմϴ. +g() -- 343 µ˴ϴ. ƹ͵ µ ʽϴ. + +--]] + +``` +## ڷ + +Ƹ ߴ Love 2D ̿ + ־ Դϴ. ̰ Ƹ Դϴ. + + BlackBulletIV "α׷Ӹ " +߽ϴ. ״ "α׷ " å оϴ. +׷ Ƹ ϴ. + +lua-users.org ִ ª ۷ +оθ 𸣰ڽϴ. + +⼭ ǥ ̺귯 ؼ ٷ ʾҽϴ. + +* string ̺귯 +* table ̺귯 +* math ̺귯 +* io ̺귯 +* os ̺귯 + +׳ ü ȿ α׷Դϴ. +learn.lua "lua learn.lua" ! + + tylerneylon.com ó ẻ ̸, +Github Gist Ȯ ֽϴ. +Ʒ ſ ð ! \ No newline at end of file -- cgit v1.2.3 From cd104ee855e7d4e9b3e0ff8c3f6c080646409830 Mon Sep 17 00:00:00 2001 From: wikibook Date: Tue, 13 Aug 2013 15:47:49 +0900 Subject: change encoding of files --- ko-kr/javascript-kr.html.markdown | 346 +++++++++++++++++----------------- ko-kr/lua-kr.html.markdown | 382 +++++++++++++++++++------------------- 2 files changed, 364 insertions(+), 364 deletions(-) diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index d9e0afe8..79f5d88b 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -8,272 +8,272 @@ translators: lang: ko-kr --- -ڹٽũƮ ݽ 귻 ũ(Brendan Eich) 1995⿡ ϴ. - ڹٽũƮ Ʈ ܼ ũƮ  ǥ µ, - ø̼ ڹٸ ϴ ̾ - ȣۿ п Ʈ忡 -ڹٺ ξ ̰ ƽϴ. +자바스크립트는 넷스케이프의 브렌던 아이크(Brendan Eich)가 1995년에 만들었습니다. +원래 자바스크립트는 웹사이트를 위한 단순한 스크립트 언어를 목표로 만들어졌는데, +좀 더 복잡한 웹 애플리케이션을 만들기 위해 자바를 보완하는 역할이었지만 +웹 페이지와의 긴밀한 상호작용과 브라우저에 대한 지원 기능 덕분에 웹 프론트엔드에서 +자바보다 훨씬 더 보편적으로 쓰이게 됐습니다. -׷ ڹٽũƮ ѵ ʽϴ. ũ V8 ڹٽũƮ - Ÿ ϴ Node.js α⸦ ֽϴ. +그렇지만 자바스크립트는 웹 브라우저에만 국한되지 않습니다. 구글 크롬의 V8 자바스크립트 +엔진을 위한 독립형 런타임을 제공하는 Node.js는 점점 인기를 얻고 있습니다. -ǵ ֽø ϰڽϴ! [@adambrenecki](https://twitter.com/adambrenecki) -[adam@brenecki.id.au](mailto:adam@brenecki.id.au) ֽϴ. +피드백 주시면 대단히 감사하겠습니다! [@adambrenecki](https://twitter.com/adambrenecki)나 +[adam@brenecki.id.au](mailto:adam@brenecki.id.au)를 통해 저와 만나실 수 있습니다. ```js -// ּ C մϴ. ¥ ּ ÷ ϰ, -/* ּ ǥ ؼ - ǥ ÷ ϴ. */ +// 주석은 C와 비슷합니다. 한 줄짜리 주석은 두 개의 슬래시로 시작하고, +/* 여러 줄 주석은 슬래시 별표로 시작해서 + 별표 슬래시로 끝납니다. */ -// ݷ(;) ֽϴ. +// 구문은 세미콜론(;)으로 끝낼 수 있습니다. doStuff(); -// ׷ ʿ µ, Ư 츦 ϰ -// ݷ ڵ ԵDZ Դϴ. +// 하지만 꼭 그럴 필요는 없는데, 특정 경우를 제외하고 +// 새 줄이 시작할 때마다 세미콜론이 자동으로 삽입되기 때문입니다. doStuff() -// ⼭ ݷ ϰڽϴ. ݷ δ -// ̳ Ʈ Ÿ ̵带 ϴ. +// 여기서는 세미콜론을 생략하겠습니다. 세미콜론을 생략할지 여부는 +// 개인적인 취향이나 프로젝트의 스타일 가이드를 따릅니다. /////////////////////////////////// -// 1. , ڿ, +// 1. 숫자, 문자열, 연산자 -// ڹٽũƮ ϳ Ÿ(64Ʈ IEEE 754 ) -// ֽϴ. +// 자바스크립트에는 단 하나의 숫자 타입(64비트 IEEE 754 배정도 숫자)만이 +// 있습니다. 3 // = 3 1.5 // = 1.5 -// մϴ. +// 모든 기초 산술 연산은 기대한 대로 동작합니다. 1 + 1 // = 2 8 - 1 // = 7 10 * 2 // = 20 35 / 5 // = 7 -// ʴ Ե˴ϴ. +// 나누어 떨어지지 않는 나눗셈도 포함됩니다. 5 / 2 // = 2.5 -// Ʈ 굵 ˴ϴ. float Ʈ ϸ -// 32Ʈ ȣ ִ int ȯ˴ϴ. +// 비트 연산도 지원됩니다. float을 대상으로 비트 연산을 수행하면 +// 32비트까지 부호가 있는 int로 변환됩니다. 1 << 2 // = 4 -// ȣ ̿ϸ 켱 ֽϴ. +// 괄호를 이용하면 우선순위를 지정할 수 있습니다. (1 + 3) * 2 // = 8 -// ڰ ƴ Ư ֽϴ. -Infinity // 1/0 1/0 --Infinity // -1/0 -NaN // 0/0 +// 실제 숫자가 아닌 특별한 세 가지 값이 있습니다. +Infinity // 1/0 1/0과 같은 연산의 결과 +-Infinity // -1/0과 같은 연산의 결과 +NaN // 0/0과 같은 연산의 결과 -// Ҹ ŸԵ ֽϴ. +// 불린 타입도 있습니다. true false -// ڿ ' " մϴ. +// 문자열은 '나 "로 생성합니다. 'abc' "Hello, world" -// 꿡 ! ȣ ̿մϴ. +// 부정 연산에는 ! 기호를 이용합니다. !true // = false !false // = true -// ϼ == +// 동일성 연산은 == 1 == 1 // = true 2 == 1 // = false -// ġ != +// 불일치 연산은 != 1 != 1 // = false 2 != 1 // = true -// +// 그 밖의 비교 연산 1 < 10 // = true 1 > 10 // = false 2 <= 2 // = true 2 >= 2 // = true -// ڿ + ֽϴ. +// 문자열은 +로 연결할 수 있습니다. "Hello " + "world!" // = "Hello world!" -// ׸ < > ֽϴ. +// 그리고 <와 >로 비교할 수 있습니다. "a" < "b" // = true -// Ÿ ȯ ˴ϴ. +// 비교 시 타입 강제변환이 수행됩니다. "5" == 5 // = true -// === ʴ´ٸ . +// ===를 쓰지 않는다면 말이죠. "5" === 5 // = false -// charAt ̿ϸ ڿ ڿ ֽϴ. +// charAt을 이용하면 문자열 내의 문자에 접근할 수 있습니다. "This is a string".charAt(0) -// null undefined ֽϴ. -null // ǵ ƴ Ÿ մϴ. -undefined // Ÿ մϴ. +// null과 undefined도 있습니다. +null // 의도적으로 값이 아님을 나타내는 데 사용합니다. +undefined // 값이 아직 설정되지 않음을 나타내는 데 사용합니다. -// null, undefinded, NaN, 0, "" ̸, ٸ Դϴ. -// 0 ̸, "0" Դϴ( 0 == "0"̴). +// null, undefinded, NaN, 0, ""은 거짓이며, 그 밖의 다른 모든 값은 참입니다. +// 참고로 0은 거짓이며, "0"은 참입니다(심지어 0 == "0"이더라도). /////////////////////////////////// -// 2. , 迭, ü +// 2. 변수, 배열, 객체 -// var Ű մϴ. ڹٽũƮ Ÿ -// Ÿ ʿ䰡 ϴ. Ҵ = ϳ մϴ. +// 변수는 var 키워드로 선언합니다. 자바스크립트는 동적 타입 언어라서 +// 타입을 지정할 필요가 없습니다. 값을 할당할 때는 = 문자 하나를 사용합니다. var someVar = 5 -// var Ű带 ʾƵ ߻ ʽϴ. +// var 키워드를 지정하지 않아도 오류는 발생하지 않습니다. someOtherVar = 10 -// ׷ ȿ ƴ϶ -// ȿ ˴ϴ. +// 그렇지만 변수가 여러분이 정의한 유효범위가 아니라 +// 전역 유효범위에 생성됩니다. -// Ҵ ä undefined ˴ϴ. +// 값을 할당하지 않은 채로 선언한 변수는 undefined로 설정됩니다. var someThirdVar // = undefined -// ϴ ǥ ϴ. -someVar += 5 // someVar = someVar + 5; . someVar 10. -someVar *= 10 // somVar 100 +// 변수에 수학 연산을 수행하는 축약형 표현은 다음과 같습니다. +someVar += 5 // someVar = someVar + 5;와 같음. 이제 someVar는 10. +someVar *= 10 // somVar는 100 -// 1 ϰų ξ ª ǥ ֽϴ. -someVar++ // someVar 101 -someVar-- // ٽ 100 ǵư +// 1을 더하거나 빼는 훨씬 더 짧은 표현도 있습니다. +someVar++ // 이제 someVar는 101 +someVar-- // 다시 100으로 되돌아감 -// 迭 Ÿ Դϴ. +// 배열은 순차적인 임의 타입 값의 목록입니다. var myArray = ["Hello", 45, true] -// 迭 ȣ ѷ ε ̿ ֽϴ. -// 迭 ε 0 մϴ. +// 배열의 멤버는 대괄호로 둘러싼 인덱스를 이용해 접근할 수 있습니다. +// 배열의 인덱스는 0부터 시작합니다. myArray[1] // = 45 -// ڹٽũƮ ü ٸ ''̳ '' ϴ. -// , Ű- ÷Դϴ. +// 자바스크립트의 객체는 다른 언어의 '사전'이나 '맵'과 같습니다. +// 즉, 키-값 쌍으로 구성된 비순차 컬렉션입니다. {key1: "Hello", key2: "World"} -// Ű ڿ ȿ ڹٽũƮ ĺ -// ǥ ʿ ʽϴ.  Ÿ̵ ֽϴ. +// 키는 문자열이지만 유효한 자바스크립트 식별자일 경우 +// 작은따옴표는 필요하지 않습니다. 값은 어떤 타입이든 사용할 수 있습니다. var myObj = {myKey: "myValue", "my other key": 4} -// ü Ӽ ε ̿ ֽϴ. +// 객체 속성에도 인덱스를 이용해 접근할 수 있습니다. myObj["my other key"] // = 4 -// Ǵ Ű ȿ ĺ ǥ ̿ ֽϴ. +// 또는 키가 유효한 식별자일 경우 점 표기법을 이용해 접근할 수 있습니다. myObj.myKey // = "myValue" -// ü մϴ. , ϰų Ű ߰ ֽϴ. +// 객체는 변경 가능합니다. 즉, 값을 변경하거나 새 키를 추가할 수 있습니다. myObj.myThirdKey = true -// Ϸ ϸ undefined ȯ˴ϴ. +// 설정되지 않은 값에 접근하려고 하면 undefined가 반환됩니다. myObj.myFourthKey // = undefined /////////////////////////////////// -// 3. +// 3. 로직과 제어 구조 -// if մϴ. +// if 구조는 여러분이 예상한 대로 동작합니다. var count = 1 if (count == 3){ - // count 3 򰡵 + // count가 3일 경우 평가됨 } else if (count == 4) { - // count 4 򰡵 + // count가 4일 경우 평가됨 } else { - // count 3̳ 4 ƴ 쿡 򰡵 + // count가 3이나 4가 아닌 경우에 평가됨 } -// while Դϴ. +// while도 마찬가지입니다. while (true) { - // ! + // 무한 루프! } -// do-while ׻ ּ ȴٴ ϸ -// while մϴ. +// do-while 문은 항상 최소 한 번은 실행된다는 점을 제외하면 +// while 문과 비슷합니다. var input do { input = getInput() } while (!isValid(input)) -// for C ڹ for ϴ. -// ʱȭ; ; +// for 문은 C와 자바의 for 문과 같습니다. +// 초기화식; 지속 조건; 증감식 for (var i = 0; i < 5; i++){ - // 5 + // 5번 실행됨 } -// && and̰ || orԴϴ. +// &&는 논리 and이고 ||는 논리 or입니다. if (house.size == "big" && house.colour == "blue"){ house.contains = "bear" } if (colour == "red" || colour == "blue"){ - // ̰ų Ķ + // 색은 빨강이거나 파랑 } -// && || " " ϴµ, ⺻ մϴ. +// &&와 ||은 "단축 평가"를 수행하는데, 기본값을 설정할 때 유용합니다. var name = otherName || "default" /////////////////////////////////// -// 4. Լ, ȿ, Ŭ +// 4. 함수, 유효범위, 클로저 -// ڹٽũƮ Լ function Ű մϴ. +// 자바스크립트 함수는 function 키워드로 선언합니다. function myFunction(thing){ return thing.toUpperCase() } myFunction("foo") // = "FOO" -// Լ "͸", ̸ ֽϴ. +// 함수는 "익명"으로, 즉 이름 없이 정의할 수도 있습니다. function(thing){ return thing.toLowerCase() } -// (Լ Ű ̸ Լ ȣ ϴ) +// (함수를 가리키는 이름이 없기 때문에 함수를 호출할 수 없습니다) -// ڹٽũƮ Լ ϱ ü̹Ƿ ٸ Ҵϰ -// ٸ Լ ڷ ֽϴ. , ̺Ʈ ڵ鷯 +// 자바스크립트 함수는 일급 객체이므로 다른 변수에 재할당하고 +// 다른 함수에 인자로 전달할 수 있습니다. 가령, 이벤트 핸들러를 만들 경우 function myFunction(){ - // ڵ 5 ȣ + // 이 코드는 5초 내에 호출됨 } setTimeout(myFunction, 5000) -// ٸ Լ ȣ Լ ۼ ֽϴ. +// 다른 함수를 호출할 때 직접적으로 함수 구문을 작성할 수도 있습니다. setTimeout(function myFunction(){ - // ڵ 5 ȣ + // 이 코드는 5초 내에 호출됨 }, 5000) -// ڹٽũƮ Լ ȿ ֽϴ. -// Լ ü ȿ ٸ ȿ ʽϴ. +// 자바스크립트에는 함수 유효범위가 있습니다. +// 함수는 자체적인 유효범위를 가지지만 다른 블록은 유효범위를 가지지 않습니다. if (true){ var i = 5 } -i // = 5 - ȿ ϴ  undefined ƴմϴ. +i // = 5 - 블록 유효범위를 지원하는 언어에서는 undefined가 아닙니다. -// ̰ " Ǵ ͸ Լ" ̾µ, -// ӽ ȿ Ǵ մϴ. +// 이것은 "즉시 실행되는 익명 함수"라는 공통 패턴으로 이어지는데, +// 이 패턴은 임시 변수가 전역 유효범위로 유출되는 것을 방지합니다. (function(){ var temporary = 5 - // ' ü' Ҵϴ ȿ ִµ, - // ü ׻ 'window'Դϴ. ü - // Node.js ƴ ȯ濡 ٸ ̸ ֽϴ. + // '전역 객체'에 할당하는 식으로 전역 유효범위에 접근할 수 있는데, + // 브라우저에서 전역 객체는 항상 'window'입니다. 전역 객체는 + // Node.js와 같은 브라우저가 아닌 환경에서는 다른 이름일 수도 있습니다. window.permanent = 10 - // Ǵ տ ߴٽ var Ű带 ֽϴ. + // 또는 앞에서 언급했다시피 var 키워드를 뺄 수도 있습니다. permanent2 = 15 })() -temporary // ReferenceError ߻ +temporary // ReferenceError 발생 permanent // = 10 permanent2 // = 15 -// ڹٽũƮ ϳ Ŭ(closure)Դϴ. -// Լ ٸ Լ ȿ ǵǸ ʿ ǵ Լ ٱ Լ -// ֽϴ. +// 자바스크립트의 강력한 기능 중 하나는 클로저(closure)입니다. +// 함수가 다른 함수 안에서 정의되면 안쪽에 정의된 함수는 바깥 함수의 +// 모든 변수에 접근할 수 있습니다. function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!" function inner(){ alert(prompt) } setTimeout(inner, 5000) - // setTimeout 񵿱 ϹǷ Լ 5 - // ٸ ʰ Ĩϴ. 5ʰ inner - // prompt ֽϴ. + // setTimeout은 비동기적으로 동작하므로 이 함수는 5초 동안 + // 기다리지 않고 실행을 마칩니다. 하지만 5초가 지나면 inner에서도 + // prompt의 값에 접근할 수 있습니다. } sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s /////////////////////////////////// -// 5. ü ȭ; ڿ Ÿ +// 5. 객체 심화; 생성자와 프로토타입 -// ü Լ ֽϴ. +// 객체는 함수를 포함할 수 있습니다. var myObj = { myFunc: function(){ return "Hello world!" @@ -281,8 +281,8 @@ var myObj = { } myObj.myFunc() // = "Hello world!" -// ü Ե Լ ȣǸ Լ this Ű带 ̿ -// ش Լ Ե ü ֽϴ. +// 객체에 포함된 함수가 호출되면 함수에서는 this 키워드를 이용해 +// 해당 함수가 포함된 객체에 접근할 수 있습니다. myObj = { myString: "Hello world!", myFunc: function(){ @@ -291,22 +291,22 @@ myObj = { } myObj.myFunc() // = "Hello world!" -// ⼭ Լ ǵ ƴ Լ ȣǴ -// İ ֽϴ. ׷ Ʒ Լ ü ؽƮ -// ȣ ʽϴ. +// 여기서 설정한 것은 함수가 정의된 곳이 아닌 함수가 호출되는 +// 방식과 관련이 있습니다. 그래서 아래 함수는 객체 컨텍스트에서 +// 호출되지 않으면 동작하지 않습니다. var myFunc = myObj.myFunc myFunc() // = undefined -// ݴ Լ ü Ҵϰ this ش ü ֽϴ. -// Լ ü ߰ ʾҴ Դϴ. +// 반대로 함수는 객체에 할당하고 this를 통해 해당 객체에 접근할 수 있습니다. +// 함수를 정의할 때 객체에 추가되지 않았더라도 마찬가지입니다. var myOtherFunc = function(){ return this.myString.toUpperCase() } myObj.myOtherFunc = myOtherFunc myObj.myOtherFunc() // = "HELLO WORLD!" -// new Ű Լ ȣϸ ο ü ǰ this -// Լ ְ ˴ϴ. ̷ Լ ڶ մϴ. +// new 키워드로 함수를 호출하면 새로운 객체가 생성되고 this를 통해 +// 함수에서 사용할 수 있게 됩니다. 이런 식으로 설계된 함수를 생성자라 합니다. var MyConstructor = function(){ this.myNumber = 5 @@ -314,14 +314,14 @@ var MyConstructor = function(){ myNewObj = new MyConstructor() // = {myNumber: 5} myNewObj.myNumber // = 5 -// ڹٽũƮ ü 'prototype' ֽϴ.  ü -// ü ʴ Ƽ ϸ ʹ ηŸԿ -// ش Ƽ ãϴ. +// 모든 자바스크립트 객체는 'prototype'을 가지고 있습니다. 어떤 객체에 대해 +// 실제 객체에는 존재하지 않는 프로퍼티에 접근하면 인터프리터는 프로로타입에서 +// 해당 프로퍼티를 찾습니다. -// Ϻ ڹٽũƮ ü __proto__ Ƽ -// ü ŸԿ ϴ ϱ⵵ մϴ. Ÿ -// ϱ⿡ ̷ 뵵 ǰ __proto__ ǥؿ Ե -// ʽϴ. ߿ Ÿ ϴ ǥ 캸ڽϴ. +// 일부 자바스크립트 구현체에서는 __proto__라는 마법의 프로퍼티로 +// 객체의 프로토타입에 접근하는 것을 허용하기도 합니다. 프로토타입을 +// 설명하기에는 이런 내용도 도움되겠지만 __proto__는 표준에 포함돼 +// 있지 않습니다. 나중에 프로토타입을 사용하는 표준 방법을 살펴보겠습니다. var myObj = { myString: "Hello world!", } @@ -334,37 +334,37 @@ var myPrototype = { myObj.__proto__ = myPrototype myObj.meaningOfLife // = 42 -// Լ մϴ. +// 이 방법은 함수에도 통합니다. myObj.myFunc() // = "hello world!" -// Ƽ ŸԿ -// Ÿ Ÿ ã ˴ϴ. +// 물론 프로퍼티가 프로토타입에 존재하지 않으면 +// 프로토타입의 프로토타입을 찾는 식으로 진행됩니다. myPrototype.__proto__ = { myBoolean: true } myObj.myBoolean // = true -// ⼭ Ͼ ʽϴ. ü ŸԿ -// ֽϴ. ̴ Ÿ ϸ -// ݿȴٴ ǹԴϴ. +// 여기서 복사는 일어나지 않습니다. 각 객체에는 프로토타입에 대한 +// 참조가 보관돼 있습니다. 이는 프로토타입을 변경하면 변경사항이 +// 모든 곳에 반영된다는 의미입니다. myPrototype.meaningOfLife = 43 myObj.meaningOfLife // = 43 -// տ __proto__ ǥؿ Ե ʴٰ ̾߱ߴµ, -// ü Ÿ ϴ ǥ ϴ. -// Ư Ÿ ο ü ϴ -// ֽϴ. +// 앞에서 __proto__가 표준에 포함돼 있지 않다고 이야기했는데, +// 기존 객체의 프로토타입을 변경하는 표준 방법은 없습니다. +// 하지만 특정 프로토타입을 가지고 새로운 객체를 생성하는 두 가지 +// 방법이 있습니다. -// ù ° Object.create ̿ϴ ε, -// Object.create ֱٿ ڹٽũƮ ߰ ̶ -// ü ̿ ִ ƴմϴ. +// 첫 번째 방법은 Object.create를 이용하는 것인데, +// Object.create는 최근에 자바스크립트에 추가된 것이라서 아직까지 +// 모든 구현체에서 이용할 수 있는 것은 아닙니다. var myObj = Object.create(myPrototype) myObj.meaningOfLife // = 43 -// ° 𼭳 ϴ ε, ڿ ֽϴ. -// ڿ prototype̶ Ƽ ֽϴ. Ƽ -// Լ ü Ÿ *ƴϰ* ڿ new Ű带 ̿ -// ü ο ü ޴ ŸԴϴ. +// 두 번째 방법은 어디서나 통하는 방법인데, 생성자와 관련이 있습니다. +// 생성자에는 prototype이라는 프로퍼티가 있습니다. 이 프로퍼티는 +// 생성자 함수 자체의 프로토타입이 *아니고* 생성자와 new 키워드를 이용해 +// 객체가 생성될 때 새로운 객체가 받는 프로토타입입니다. myConstructor.prototype = { getMyNumber: function(){ return this.myNumber @@ -373,63 +373,63 @@ myConstructor.prototype = { var myNewObj2 = new myConstructor() myNewObj2.getMyNumber() // = 5 -// ڿ ڿ ŸԿ ü -// ϴ ڰ ֽϴ. +// 문자열과 숫자와 같은 내장 타입에도 동등한 래퍼 객체를 +// 생성하는 생성자가 있습니다. var myNumber = 12 var myNumberObj = new Number(12) myNumber == myNumberObj // = true -// Ȯ ʽϴ. +// 하지만 정확히 같지는 않습니다. typeof(myNumber) // = 'number' typeof(myNumberObj) // = 'object' myNumber === myNumberObj // = false if (0){ - // 0 ̶ ڵ ʽϴ. + // 0은 거짓이라서 이 코드는 실행되지 않습니다. } if (Number(0)){ - // Number(0) ̶ ڵ *˴ϴ*. + // Number(0)은 참이라서 이 코드는 *실행됩니다*. } -// ü Ϲ Լ Ÿ ϱ -// ڿ ߰ ֽϴ. +// 하지만 래퍼 객체와 일반 내장 함수는 프로토타입을 공유하기 때문에 +// 가령 문자열에 실제로 기능을 추가할 수 있습니다. String.prototype.firstCharacter = function(){ return this.charAt(0) } "abc".firstCharacter() // = "a" -// ̷ ڹٽũƮ ڹٽũƮ -// ο ϴ "(polyfilling)" ̿ǹǷ -// ȯ濡 ֽϴ. +// 이러한 사실은 기존 자바스크립트 버전에서 자바스크립트의 +// 새로운 기능을 구현하는 "폴리필(polyfilling)"에 자주 이용되므로 +// 오래된 버전의 브라우저와 같이 기존 환경에서 사용될 수 있습니다. -// , Object.create ü ƴ϶ -// Ʒ ̿ Object.create ֽϴ. +// 예를 들어, Object.create가 모든 구현체에서 사용 가능한 것은 아니라고 +// 했지만 아래의 폴리필을 이용해 Object.create를 여전히 사용할 수 있습니다. if (Object.create === undefined){ // don't overwrite it if it exists Object.create = function(proto){ - // ùٸ Ÿ ӽ ڸ + // 올바른 프로토타입을 가지고 임시 생성자를 만듬 var Constructor = function(){} Constructor.prototype = proto - // ׷ ӽ ڸ ̿ ο Ÿ - // ü + // 그런 다음 임시 생성자를 이용해 새로운 적절한 프로토타입을 + // 포함한 객체를 생성 return new Constructor() } } ``` -## Ÿ ڷ +## 기타 참고 자료 -[ Ʈũ](https://developer.mozilla.org/en-US/docs/Web/JavaScript) -ڹٽũƮ Ǹ մϴ. Ҿ Ű ̶ - Ǹ и ν ٸ 鿡 ֽϴ. +[모질라 개발자 네트워크](https://developer.mozilla.org/en-US/docs/Web/JavaScript)에서는 +자바스크립트에 대한 훌륭한 문서를 제공합니다. 더불어 위키 형식이라서 좀 더 많은 사항을 +배우게 되면 여러분만의 지식을 공유함으로써 다른 사람들에게 도움을 줄 수도 있습니다. -MDN ['ڹٽũƮ Թ'](https://developer.mozilla.org/ko/docs/A_re-introduction_to_JavaScript) -⼭ ٷ ڼ ٷ ֽϴ. ڷῡ ڹٽũƮ ü -ؼ ϰ ٷϴ. ڹٽũƮ ϴ ʹٸ -[ ü (Document Object Model)](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) - ϱ ٶϴ. +MDN의 ['자바스크립트 재입문'](https://developer.mozilla.org/ko/docs/A_re-introduction_to_JavaScript)에서는 +여기서 다룬 개념의 상당수를 더욱 자세히 다루고 있습니다. 이 자료에서는 자바스크립트 언어 자체에 +대해서만 상당히 신중하게 다뤘습니다. 웹 페이지에서 자바스크립트를 사용하는 방법을 배우고 싶다면 +[문서 객체 모델(Document Object Model)](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)에 +관해 배우는 것으로 시작하길 바랍니다. -[ڹٽũƮ ](http://bonsaiden.github.io/JavaScript-Garden/) ڹٽũƮ  - ߳ κе ɵ ְ ٷϴ. +[자바스크립트 가든](http://bonsaiden.github.io/JavaScript-Garden/)에서는 자바스크립트 언어에서 +직관에 어긋나는 모든 부분들을 심도 있게 다룹니다. -Ҿ ۿ ⿩ е, Ϻδ Ʈ ִ - (Louie Dihn) ̽ Ʃ丮 Ʈũ ִ -[ڹٽũƮ Ʃ丮](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) ߽ϴ. \ No newline at end of file +더불어 이 글에 직접적으로 기여한 분들로, 내용 중 일부는 이 사이트에 있는 +루이 딘(Louie Dihn)의 파이썬 튜토리얼과 모질라 개발자 네트워크에 있는 +[자바스크립트 튜토리얼](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)을 참고했습니다. \ No newline at end of file diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index 50458f88..3f6223d6 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -9,85 +9,85 @@ lang: ko-kr --- ```lua --- ¥ ּ ǹմϴ. +-- 대시 두 개는 한 줄짜리 주석을 의미합니다. --[[ - [ ] ߰ϸ ּ ˴ϴ. + [와 ]를 두 개씩 추가하면 여러 줄 주석이 됩니다. --]] ---------------------------------------------------- --- 1. 帧 +-- 1. 변수와 흐름 제어 ---------------------------------------------------- -num = 42 -- ڴ doubleԴϴ. --- ʿ ϴ. 64Ʈ double --- Ȯ int ϱ 52Ʈ --- ֽϴ. 52Ʈ int ؼ --- е õ ʽϴ. +num = 42 -- 모든 숫자는 double입니다. +-- 놀랄 필요는 없습니다. 64비트 double은 +-- 정확한 int 값을 저장하기 위해 52비트로 구성돼 +-- 있습니다. 52비트 이하의 int 값에 대해서는 +-- 장비 정밀도와 관련된 문제가 생기지 않습니다. -s = 'walternate' -- ̽ Һ ڿ -t = "ūǥ ᵵ ˴ϴ" -u = [[ ȣ - ڿ - Ÿϴ.]] -t = nil -- t. ƴ ÷ մϴ. +s = 'walternate' -- 파이썬과 같은 불변 문자열 +t = "큰따옴표를 써도 됩니다" +u = [[ 이중 대괄호는 + 여러 줄 문자열을 + 나타냅니다.]] +t = nil -- 미정의 t. 루아는 가비지 컬렉션을 지원합니다. --- do/end Ű Ÿϴ: +-- 블록은 do/end와 같은 키워드로 나타냅니다: while num < 50 do - num = num + 1 -- ++ += ڴ ϴ. + num = num + 1 -- ++나 += 유형의 연산자는 쓸 수 없습니다. end --- If : +-- If 절: if num > 40 then - print('40 ̻') -elseif s ~= 'walternate' then -- ~= ' ʴ'Դϴ. - -- ϼ ˻ ̽ ==Դϴ. - -- ڿ ֽϴ. - io.write('not over 40\n') -- ⺻ stdout ϴ. + print('40 이상') +elseif s ~= 'walternate' then -- ~=은 '같지 않다'입니다. + -- 동일성 검사는 파이썬과 마찬가지로 ==입니다. + -- 문자열에도 쓸 수 있습니다. + io.write('not over 40\n') -- 기본적으로 stdout에 씁니다. else - -- ⺻ Դϴ. - thisIsGlobal = 5 -- Ÿ ǥ ϹԴϴ. + -- 변수는 기본적으로 전역 변수입니다. + thisIsGlobal = 5 -- 낙타 표기법이 일반적입니다. - -- ϴ: - local line = io.read() -- stdin нϴ + -- 변수를 지역 변수로 만드는 방법은 다음과 같습니다: + local line = io.read() -- 다음 stdin 줄을 읽습니다 - -- ڿ ῡ .. ڸ ϴ: - print('ܿ ֽϴ, ' .. line) + -- 문자열 연결에는 .. 연산자를 씁니다: + print('겨울이 오고 있습니다, ' .. line) end --- nil ȯմϴ. --- ڵ带 ص ʽϴ: -foo = anUnknownVariable -- foo nilԴϴ. +-- 미정의 변수는 nil을 반환합니다. +-- 다음 코드를 실행해도 오류가 나지 않습니다: +foo = anUnknownVariable -- 이제 foo는 nil입니다. aBoolValue = false --- nil false Դϴ; 0 '' Դϴ! +-- nil과 false만이 거짓값입니다; 0과 ''은 참입니다! if not aBoolValue then print('twas false') end --- 'or' 'and' (short-circuit)˴ϴ. --- ڵ C/ڹٽũƮ a?b:c ڿ մϴ: +-- 'or'와 'and'는 단축 평가(short-circuit)됩니다. +-- 다음 코드는 C/자바스크립트의 a?b:c 연산자와 비슷합니다: ans = aBoolValue and 'yes' or 'no' --> 'no' karlSum = 0 -for i = 1, 100 do -- ҵ Ե˴ϴ. +for i = 1, 100 do -- 범위에는 마지막 요소도 포함됩니다. karlSum = karlSum + i end --- īƮ ٿ "100, 1, -1" ϴ. +-- 카운트 다운을 할 때는 "100, 1, -1"을 범위로 씁니다. fredSum = 0 for j = 100, 1, -1 do fredSum = fredSum + j end --- Ϲ begin, end[, step]Դϴ. +-- 일반적으로 범위는 begin, end[, step]입니다. --- ٸ ݺ ϴ: +-- 또 다른 반복문 구문은 다음과 같습니다: repeat - print('̷ ') + print('미래의 방식') num = num - 1 until num == 0 ---------------------------------------------------- --- 2. Լ +-- 2. 함수 ---------------------------------------------------- function fib(n) @@ -95,10 +95,10 @@ function fib(n) return fib(n - 2) + fib(n - 1) end --- Ŭ ͸ Լ ֽϴ: +-- 클로저와 익명 함수도 사용할 수 있습니다: function adder(x) - -- ȯ Լ adder ȣ ǰ x - -- ˴ϴ: + -- 반환된 함수는 adder가 호출될 때 생성되고 x의 + -- 값이 유지됩니다: return function (y) return x + y end end a1 = adder(9) @@ -106,104 +106,104 @@ a2 = adder(36) print(a1(16)) --> 25 print(a2(64)) --> 100 --- ȯ, Լ ȣ, Ҵ繮 ̰ ٸ --- Ʈ ؼ մϴ. --- Ʈ nil Ҵ/ȯǰ --- Ʈ ϴ. +-- 반환문, 함수 호출, 할당문은 길이가 다른 +-- 값의 리스트에 대해서도 모두 동작합니다. +-- 리스트에 값이 더 적을 때는 nil이 할당/반환되고 +-- 리스트에 값이 더 많을 때는 나머지 값은 버려집니다. x, y, z = 1, 2, 3, 4 --- x = 1, y = 2, z = 3̰ 4 ϴ. +-- 이제 x = 1, y = 2, z = 3이고 4는 버려집니다. function bar(a, b, c) print(a, b, c) return 4, 8, 15, 16, 23, 42 end -x, y = bar('zaphod') --> "zaphod nil nil" --- x = 4, y = 8̰ 15~42 ϴ. +x, y = bar('zaphod') --> "zaphod nil nil"가 출력 +-- 이제 x = 4, y = 8이고 15~42의 값은 버려집니다. --- Լ ϱ ṵ̈, / ȿ --- ֽϴ. Ʒ Լ ϴ: +-- 함수는 일급 객체이고, 지역/전역 유효범위를 가질 +-- 수 있습니다. 아래의 두 함수는 같습니다: function f(x) return x * x end f = function (x) return x * x end --- ׸ Ʒ Լ Դϴ: +-- 그리고 아래의 두 함수도 마찬가지입니다: local function g(x) return math.sin(x) end local g; g = function (x) return math.sin(x) end --- 'local g' ϸ g Լ ϴ. +-- 'local g'라고 선언하면 g를 지역 함수로 만듭니다. --- ׳ ﰢ Լ մϴ. +-- 그나저나 삼각 함수는 라디안 단위로 동작합니다. --- Լ ȣ ڿ Ű ϳ Ѵٸ --- ȣ ʾƵ ˴ϴ: -print 'hello' -- մϴ. +-- 함수를 호출할 때 문자열 매개변수를 하나만 전달한다면 +-- 괄호를 쓰지 않아도 됩니다: +print 'hello' -- 잘 동작합니다. ---------------------------------------------------- --- 3. ̺ +-- 3. 테이블 ---------------------------------------------------- --- ̺ = ڷᱸμ, 迭Դϴ. --- PHP 迭̳ ڹٽũƮ ü ϸ, --- Ʈε ִ ؽ ųʸԴϴ. +-- 테이블 = 루아의 유일한 복합 자료구조로서, 연관 배열입니다. +-- PHP의 배열이나 자바스크립트의 객체와 비슷하며, +-- 리스트로도 사용할 수 있는 해시 기반의 딕셔너리입니다. --- ̺ ųʸ/ ϱ: +-- 테이블을 딕셔너리/맵으로 사용하기: --- ųʸ ͷ ⺻ ڿ Ű ϴ: +-- 딕셔너리 리터럴은 기본적으로 문자열 키를 가집니다: t = {key1 = 'value1', key2 = false} --- ڿ Ű ڹٽũƮ ǥ ֽϴ: -print(t.key1) -- 'value1' . -t.newKey = {} -- Ű/ ߰. -t.key2 = nil -- ̺ key2 . +-- 문자열 키에는 자바스크립트와 유사한 점 표기법을 쓸 수 있습니다: +print(t.key1) -- 'value1'을 출력. +t.newKey = {} -- 새 키/값 쌍을 추가. +t.key2 = nil -- 테이블에서 key2를 제거. --- (nil ƴ) Ű ϴ ͷ ǥ: +-- (nil이 아닌) 값을 키로 사용하는 리터럴 표기법: u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} -print(u[6.28]) -- "tau" +print(u[6.28]) -- "tau"가 출력 --- Ű Ī ⺻ ڿ ڿ ؼ --- ̺ ؼ ĺڷ մϴ. +-- 키 매칭은 기본적으로 숫자와 문자열에 대해서는 값으로 하지만 +-- 테이블에 대해서는 식별자로 합니다. a = u['@!#'] -- Now a = 'qbert'. b = u[{}] -- We might expect 1729, but it's nil: -a = u['@!#'] -- a 'qbert'Դϴ. -b = u[{}] -- 1729 ߰ nilԴϴ: --- Ž ϱ b nilԴϴ. Ž ϴ --- Ű Ű ü ƴϱ --- Դϴ. ڿ ڰ ̽ļ ִ ŰԴϴ. +a = u['@!#'] -- 이제 a는 'qbert'입니다. +b = u[{}] -- 1729를 예상했겠지만 nil입니다: +-- 탐색이 실패하기 때문에 b는 nil입니다. 탐색이 실패하는 이유는 +-- 사용된 키가 원본 값을 저장할 때 사용한 키와 동일한 객체가 아니기 +-- 때문입니다. 따라서 문자열 및 숫자가 좀 더 이식성 있는 키입니다. --- ̺ ϳ Ű ϴ Լ ȣ ȣ ʿ ʽϴ: +-- 테이블 하나를 매개변수로 취하는 함수를 호출할 때는 괄호가 필요하지 않습니다: function h(x) print(x.key1) end -h{key1 = 'Sonmi~451'} -- 'Sonmi~451' . +h{key1 = 'Sonmi~451'} -- 'Sonmi~451'를 출력. -for key, val in pairs(u) do -- ̺ ȸ +for key, val in pairs(u) do -- 테이블 순회 print(key, val) end --- _G Ư ̺Դϴ. -print(_G['_G'] == _G) -- 'true' +-- _G는 모든 전역 멤버에 대한 특별한 테이블입니다. +print(_G['_G'] == _G) -- 'true'가 출력 --- ̺ Ʈ/迭 ϱ: +-- 테이블을 리스트/배열로 사용하기: --- Ʈ ͷ Ϲ int Ű ˴ϴ: +-- 리스트 리터럴은 암묵적으로 int 키로 설정됩니다: v = {'value1', 'value2', 1.21, 'gigawatts'} -for i = 1, #v do -- #v Ʈ v ũԴϴ. - print(v[i]) -- ε 1 մϴ!! ƴմϴ! +for i = 1, #v do -- #v는 리스트 v의 크기입니다. + print(v[i]) -- 인덱스가 1에서 시작합니다!! 제정신이 아닙니다! end --- 'list' Ÿ ƴմϴ. v ӵ Ű Ե --- ̺̰ Ʈ ޵ Դϴ. +-- 'list'는 실제 타입이 아닙니다. v는 연속된 정수형 키가 포함된 +-- 테이블이고 리스트로 취급될 뿐입니다. ---------------------------------------------------- --- 3.1 Ÿ̺ Ÿ޼ +-- 3.1 메타테이블과 메타메서드 ---------------------------------------------------- --- ̺ ̺ ε ϰ ϴ Ÿ̺ --- ֽϴ. ߿ Ÿ̺  ڹٽũƮ --- Ÿ԰ ϴ 캸ڽϴ. +-- 테이블은 테이블에 연산자 오버로딩을 가능하게 하는 메타테이블을 +-- 가질 수 있습니다. 나중에 메타테이블이 어떻게 자바스크립트 +-- 프로토타입과 같은 행위를 지원하는지 살펴보겠습니다. -f1 = {a = 1, b = 2} -- м a/b ǥ +f1 = {a = 1, b = 2} -- 분수 a/b를 표현 f2 = {a = 2, b = 3} --- ڵ մϴ: +-- 다음 코드는 실패합니다: -- s = f1 + f2 metafraction = {} @@ -217,30 +217,30 @@ end setmetatable(f1, metafraction) setmetatable(f2, metafraction) -s = f1 + f2 -- f1 Ÿ̺ __add(f1, f2) ȣ +s = f1 + f2 -- f1의 메타테이블을 대상으로 __add(f1, f2)를 호출 --- f1 f2 ڹٽũƮ Ÿ԰ ޸ Ÿ̺ --- Ű  getmetatable(f1) ޾ƿ; մϴ. --- Ÿ̺ __add ư ˰ ִ Ű Ϲ ̺Դϴ. +-- f1과 f2는 자바스크립트의 프로토타입과 달리 각 메타테이블에 대한 +-- 키가 없어서 getmetatable(f1)과 같이 받아와야 합니다. +-- 메타테이블은 __add 같은 루아가 알고 있는 키가 지정된 일반 테이블입니다. --- ׷ s Ÿ̺ ʱ մϴ. +-- 그렇지만 다음 줄은 s가 메타테이블을 가지고 있지 않기 때문에 실패합니다. -- t = s + s --- Ʒ Ŭ ̷ ߻ ʽϴ. +-- 아래와 같이 클래스와 유사한 패턴은 이러한 문제가 발생하지 않습니다. --- Ÿ̺ __index ̿ Ž εմϴ: +-- 메타테이블에 대한 __index는 점을 이용한 탐색을 오버로드합니다: defaultFavs = {animal = 'gru', food = 'donuts'} myFavs = {food = 'pizza'} setmetatable(myFavs, {__index = defaultFavs}) -eatenBy = myFavs.animal -- մϴ! , Ÿ̺! +eatenBy = myFavs.animal -- 동작합니다! 고마워요, 메타테이블! --- Ÿ̺ Ž Ÿ̺ __index ̿ --- õϰ, ̷ ݺ˴ϴ. +-- 직접적인 메타테이블 탐색이 실패할 경우 메타테이블의 __index 값을 이용해 +-- 재시도하고, 이런 과정이 반복됩니다. --- __index ȭ Ž function(tbl, key) --- ֽϴ. +-- __index 값은 좀 더 세분화된 탐색을 위해 function(tbl, key)가 +-- 될 수도 있습니다. --- __index, __add, ... Ÿ޼ մϴ. --- Ÿ޼带 ̺ ü Դϴ. +-- __index, __add, ...의 값을 메타메서드라고 합니다. +-- 다음은 메타메서드를 가진 테이블의 전체 목록입니다. -- __add(a, b) for a + b -- __sub(a, b) for a - b @@ -254,18 +254,18 @@ eatenBy = myFavs.animal -- -- __eq(a, b) for a == b -- __lt(a, b) for a < b -- __le(a, b) for a <= b --- __index(a, b) for a.b +-- __index(a, b) for a.b -- __newindex(a, b, c) for a.b = c -- __call(a, ...) for a(...) ---------------------------------------------------- --- 3.2 Ŭ ̺ +-- 3.2 클래스 형태의 테이블과 상속 ---------------------------------------------------- --- ƿ Ŭ , ̺ Ÿ̺ --- ̿ Ŭ پ ֽϴ. +-- 루아에는 클래스가 내장돼 있지 않으며, 테이블과 메타테이블을 +-- 이용해 클래스를 만드는 다양한 방법이 있습니다. --- ϴ մϴ. +-- 다음 예제에 대한 설명은 하단을 참조합니다. Dog = {} -- 1. @@ -282,25 +282,25 @@ end mrDog = Dog:new() -- 7. mrDog:makeSound() -- 'I say woof' -- 8. --- 1. Dog Ŭó մϴ. δ ̺Դϴ. --- 2. function ̺:fn(...) --- function ̺.fn(self, ...) ϴ. --- : self ù ° ڸ ߰ Դϴ. --- self  ñϴٸ Ʒ 7 8 о. --- 3. newObj Dog Ŭ νϽ ˴ϴ. --- 4. self = νϽȭǴ Ŭ. --- ַ self = Dog ̿ϸ ̰ ٲ ֽϴ. --- newObj Ÿ̺ self __index self ϸ --- newObj self Լ ˴ϴ. --- 5. : setmetatable ù ° ڸ ȯմϴ. --- 6. : 2 Ͱ ̹ self --- Ŭ ƴ νϽ ֽϴ. --- 7. Dog.new(Dog) Ƿ new() self = DogԴϴ. --- 8. mrDog.makeSound(mrDog) Ƿ self = mrDogԴϴ. +-- 1. Dog는 클래스처럼 동작합니다. 실제로는 테이블입니다. +-- 2. function 테이블명:fn(...)은 +-- function 테이블명.fn(self, ...)과 같습니다. +-- :는 self라는 첫 번째 인자를 추가할 뿐입니다. +-- self가 값을 어떻게 얻는지 궁금하다면 아래의 7과 8을 읽어보세요. +-- 3. newObj는 Dog 클래스의 인스턴스가 됩니다. +-- 4. self = 인스턴스화되는 클래스. +-- 주로 self = Dog이지만 상속을 이용하면 이것을 바꿀 수 있습니다. +-- newObj의 메타테이블과 self의 __index를 모두 self에 설정하면 +-- newObj가 self의 함수를 갖게 됩니다. +-- 5. 참고: setmetatable은 첫 번째 인자를 반환합니다. +-- 6. :는 2에서 설명한 것과 같이 동작하지만 이번에는 self가 +-- 클래스가 아닌 인스턴스라고 예상할 수 있습니다. +-- 7. Dog.new(Dog)과 같으므로 new()에서는 self = Dog입니다. +-- 8. mrDog.makeSound(mrDog)과 같으므로 self = mrDog입니다. ---------------------------------------------------- --- : +-- 상속 예제: LoudDog = Dog:new() -- 1. @@ -312,19 +312,19 @@ end seymour = LoudDog:new() -- 3. seymour:makeSound() -- 'woof woof woof' -- 4. --- 1. LoudDog Dog ޼ ˴ϴ. --- 2. self new() 'sound' Ű ϴ. 3 ϼ. --- 3. LoudDog.new(LoudDog) , LoudDog 'new' Ű --- Ÿ̺ __index = Dog̱ Dog.new(LoudDog) --- ȯ˴ϴ. --- : seymour Ÿ̺ LoudDog̰ LoudDog.__index --- LoudDogԴϴ. seymour.key seymour.key, --- LoudDog.key, Dog.key ̸, Ű  ̺ --- Դϴ. --- 4. 'makeSound' Ű LoudDog ߰ ֽϴ. --- ̰ LoudDog.makeSound(seymour) ϴ. - --- ʿ , Ŭ new() Ŭ new() մϴ. +-- 1. LoudDog은 Dog의 메서드와 변수를 갖게 됩니다. +-- 2. self는 new()에서 'sound' 키를 가집니다. 3을 참고하세요. +-- 3. LoudDog.new(LoudDog)과 같고, LoudDog은 'new' 키가 없지만 +-- 메타테이블에서 __index = Dog이기 때문에 Dog.new(LoudDog)으로 +-- 변환됩니다. +-- 결과: seymour의 메타테이블은 LoudDog이고 LoudDog.__index는 +-- LoudDog입니다. 따라서 seymour.key는 seymour.key, +-- LoudDog.key, Dog.key와 같을 것이며, 지정한 키에 어떤 테이블이 +-- 오든 상관없을 것입니다. +-- 4. 'makeSound' 키는 LoudDog에서 발견할 수 있습니다. +-- 이것은 LoudDog.makeSound(seymour)와 같습니다. + +-- 필요할 경우, 하위 클래스의 new()는 기반 클래스의 new()와 유사합니다. function LoudDog:new() newObj = {} -- set up newObj @@ -333,91 +333,91 @@ function LoudDog:new() end ---------------------------------------------------- --- 4. +-- 4. 모듈 ---------------------------------------------------- ---[[ ⼭ ּ ϸ ũƮ κ --- ° ˴ϴ. +--[[ 여기서 주석을 제거하면 이 스크립트의 나머지 부분은 +-- 실행 가능한 상태가 됩니다. ``` ```lua --- mod.lua ٰ ô. +-- mod.lua 파일의 내용이 다음과 같다고 가정해 봅시다. local M = {} local function sayMyName() - print('̼ҷ') + print('이소룡') end function M.sayHello() - print('ȳϼ') + print('안녕하세요') sayMyName() end return M --- ٸ Ͽ mod.lua ̿ ֽϴ. -local mod = require('mod') -- mod.lua +-- 또 다른 파일에서는 mod.lua의 기능을 이용할 수 있습니다. +local mod = require('mod') -- mod.lua 파일을 실행 --- require ԽŰ ǥȭ Դϴ. --- require մϴ: (ij̵ . ϴ ) +-- require는 모듈을 포함시키는 표준화된 방법입니다. +-- require는 다음과 같이 동작합니다: (캐싱돼 있지 않을 경우. 하단 참조) local mod = (function () - + end)() --- mod.lua Լ ó ǹǷ mod.lua --- ۿ ϴ. +-- mod.lua가 함수의 본문처럼 되므로 mod.lua 안의 지역 멤버는 +-- 밖에서 볼 수 없습니다. --- ڵ尡 ϴ mod mod.lua M Դϴ. -mod.sayHello() -- ̼ҷ λ縦 dzܴϴ. +-- 다음 코드가 동작하는 것은 mod가 mod.lua의 M과 같기 때문입니다. +mod.sayHello() -- 이소룡 씨에게 인사를 건넵니다. --- ڵ带 ϸ ߻մϴ. --- sayMyName mod.lua ȿ ϱ Դϴ: -mod.sayMyName() -- +-- 다음 코드를 실행하면 오류가 발생합니다. +-- sayMyName는 mod.lua 안에서만 존재하기 때문입니다: +mod.sayMyName() -- 오류 --- require ȯ ij̵ǹǷ require ص --- ִ ˴ϴ. +-- require의 반환값은 캐싱되므로 require를 여러 번 실행해도 +-- 파일은 최대 한 번만 실행됩니다. --- mod2.lua "print('Hi')" ִٰ ô. -local a = require('mod2') -- Hi! -local b = require('mod2') -- print . a=b +-- mod2.lua에 "print('Hi')"가 들어 있다고 가정해 봅시다. +local a = require('mod2') -- Hi!를 출력 +local b = require('mod2') -- print를 실행하지 않음. a=b --- dofile require ij ʽϴ: +-- dofile은 require와 비슷하지만 캐싱을 하지 않습니다: dofile('mod2') --> Hi! -dofile('mod2') --> Hi! (require ޸ ٽ ѹ ) +dofile('mod2') --> Hi! (require와 달리 다시 한번 실행됨) --- loadfile о ʽϴ -f = loadfile('mod2') -- f() ȣؾ mod2.lua ˴ϴ. +-- loadfile은 루아 파일을 읽어들이지만 실행하지는 않습니다 +f = loadfile('mod2') -- f()를 호출해야 mod2.lua가 실행됩니다. --- loadstring ڿ loadfileԴϴ. -g = loadstring('print(343)') -- Լ ȯմϴ. -g() -- 343 µ˴ϴ. ƹ͵ µ ʽϴ. +-- loadstring은 문자열에 대한 loadfile입니다. +g = loadstring('print(343)') -- 함수를 반환합니다. +g() -- 343이 출력됩니다. 그전까지는 아무것도 출력되지 않습니다. --]] ``` -## ڷ +## 참고자료 -Ƹ ߴ Love 2D ̿ - ־ Դϴ. ̰ Ƹ Դϴ. +루아를 배우는 일이 흥미진진했던 이유는 Love 2D 게임 엔진을 이용해 +게임을 만들 수 있었기 때문입니다. 이것이 제가 루아를 배운 이유입니다. - BlackBulletIV "α׷Ӹ " -߽ϴ. ״ "α׷ " å оϴ. -׷ Ƹ ϴ. +저는 BlackBulletIV의 "프로그래머를 위한 루아"로 +시작했습니다. 그다음으로 공식 "프로그래밍 루아" 책을 읽었습니다. +그렇게 루아를 배웠습니다. -lua-users.org ִ ª ۷ -оθ 𸣰ڽϴ. +lua-users.org에 있는 짧은 루아 레퍼런스를 +읽어두면 도움될지도 모르겠습니다. -⼭ ǥ ̺귯 ؼ ٷ ʾҽϴ. +여기서는 표준 라이브러리에 관해서는 다루지 않았습니다. -* string ̺귯 -* table ̺귯 -* math ̺귯 -* io ̺귯 -* os ̺귯 +* string 라이브러리 +* table 라이브러리 +* math 라이브러리 +* io 라이브러리 +* os 라이브러리 -׳ ü ȿ α׷Դϴ. -learn.lua "lua learn.lua" ! +그나저나 이 파일 전체는 유효한 루아 프로그램입니다. 이 파일을 +learn.lua로 저장한 후 "lua learn.lua"를 실행해 보세요! - tylerneylon.com ó ẻ ̸, -Github Gist Ȯ ֽϴ. -Ʒ ſ ð ! \ No newline at end of file +이 글은 tylerneylon.com에 처음으로 써본 글이며, +Github의 Gist에서도 확인할 수 있습니다. +루아로 즐거운 시간을 보내세요! \ No newline at end of file -- cgit v1.2.3 From 4283f0c964f55295f024e535a2373ef8d04e4069 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 14:32:20 +0200 Subject: [FIX] filename --- objective-c.html.markdown | 99 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 objective-c.html.markdown diff --git a/objective-c.html.markdown b/objective-c.html.markdown new file mode 100644 index 00000000..787a9219 --- /dev/null +++ b/objective-c.html.markdown @@ -0,0 +1,99 @@ +--- +language: Objectiv-C +author: Eugene Yagrushkin +author_url: www.about.me/yagrushkin +filename: learnc.Objectiv-C +--- + +Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch. +It's is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. + +```Objective-C +// Single-line comments start with // + +/* +Multi-line comments look like this. +*/ + +##Basic types +// all the primitive variable types are the same as in C +// char, int, long, double, float + + +// Simple, common classes +// number +NSNumber *firstNumber = @1; +NSNumber *secondNumber = @23.0; +NSNumber *boolNumber = @YES; + +// string +NSString *aString = @"some string"; + +// array +NSArray *array = @[ @1, @2]; + +// dictionary +NSDictionay *dictionary = @{ @"aKey" : @"aValue", @"aKey2" : @"aValue2" }; + +// Import headers with #import +#import +#import "SomeAppDelegate.h" + +##Coding classes + +// Declare your class in a header(.h) file: + +@interface UserObject : NSObject{ +// instance variables +} + +// Class method + + (NSString*) ClassMethod; + +// Instance method + - (NSString*) instanceMethodWithParmeter:(NSString*)string; + +@end + +// Add class methods in an implementation (.m) file: + +@implementation UserObject + ++ (NSString*) ClassMethod{ + return @"SomeString"; +} + +- (NSString*) instanceMethodWithParmeter:(NSString*)string; +{ + return @"New string"; +} + +- (NSString*) otherMethodWithString:(NSString*)string; +{ + return [NSString stringWithString:string]; +} +@end + +// Create an object instance by allocating memory and initializing it. An object is not fully functional until both steps have been completed. +UserObject *someObject = [[UserObject alloc] init]; + +##Calling Methods + +// The Objective-C model of object-oriented programming is based on message passing to object instances. +// In Objective-C one does not simply call a method; one sends a message. + +[someObject instanceMethodWithParmeter:@"Steve Jobs"]; + +##Nested Messages +// nested messages look like this: + +[someObject instanceMethodWithParmeter:[someObject otherMethodWithString:@"Jony Ive"]]; + +``` +## Further Reading + +[Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) + +[Objectively Speaking: A Crash Course in Objective-C](http://www.raywenderlich.com/12444/objectively-speaking-a-crash-course-in-objective-c) + +[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From 6d48842ce96919774e468093e7460ef9779ab341 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 14:32:57 +0200 Subject: [FIX] filename --- objvectiv-C.html.markdown | 99 ----------------------------------------------- 1 file changed, 99 deletions(-) delete mode 100644 objvectiv-C.html.markdown diff --git a/objvectiv-C.html.markdown b/objvectiv-C.html.markdown deleted file mode 100644 index 787a9219..00000000 --- a/objvectiv-C.html.markdown +++ /dev/null @@ -1,99 +0,0 @@ ---- -language: Objectiv-C -author: Eugene Yagrushkin -author_url: www.about.me/yagrushkin -filename: learnc.Objectiv-C ---- - -Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch. -It's is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. - -```Objective-C -// Single-line comments start with // - -/* -Multi-line comments look like this. -*/ - -##Basic types -// all the primitive variable types are the same as in C -// char, int, long, double, float - - -// Simple, common classes -// number -NSNumber *firstNumber = @1; -NSNumber *secondNumber = @23.0; -NSNumber *boolNumber = @YES; - -// string -NSString *aString = @"some string"; - -// array -NSArray *array = @[ @1, @2]; - -// dictionary -NSDictionay *dictionary = @{ @"aKey" : @"aValue", @"aKey2" : @"aValue2" }; - -// Import headers with #import -#import -#import "SomeAppDelegate.h" - -##Coding classes - -// Declare your class in a header(.h) file: - -@interface UserObject : NSObject{ -// instance variables -} - -// Class method - + (NSString*) ClassMethod; - -// Instance method - - (NSString*) instanceMethodWithParmeter:(NSString*)string; - -@end - -// Add class methods in an implementation (.m) file: - -@implementation UserObject - -+ (NSString*) ClassMethod{ - return @"SomeString"; -} - -- (NSString*) instanceMethodWithParmeter:(NSString*)string; -{ - return @"New string"; -} - -- (NSString*) otherMethodWithString:(NSString*)string; -{ - return [NSString stringWithString:string]; -} -@end - -// Create an object instance by allocating memory and initializing it. An object is not fully functional until both steps have been completed. -UserObject *someObject = [[UserObject alloc] init]; - -##Calling Methods - -// The Objective-C model of object-oriented programming is based on message passing to object instances. -// In Objective-C one does not simply call a method; one sends a message. - -[someObject instanceMethodWithParmeter:@"Steve Jobs"]; - -##Nested Messages -// nested messages look like this: - -[someObject instanceMethodWithParmeter:[someObject otherMethodWithString:@"Jony Ive"]]; - -``` -## Further Reading - -[Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) - -[Objectively Speaking: A Crash Course in Objective-C](http://www.raywenderlich.com/12444/objectively-speaking-a-crash-course-in-objective-c) - -[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From 5b182eb5e99be7d04071cdb04466ccdae7b2fde9 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 14:38:39 +0200 Subject: [UPDATE] Authors --- objective-c.html.markdown | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 787a9219..df789677 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -1,8 +1,11 @@ --- -language: Objectiv-C -author: Eugene Yagrushkin -author_url: www.about.me/yagrushkin -filename: learnc.Objectiv-C + +language: Objective-C +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] +filename: LearnObjectiveC.m + --- Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch. -- cgit v1.2.3 From d842eb4f819568c1503c26e494e271f1cd179542 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 14:45:49 +0200 Subject: minor fixes --- objective-c.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index df789677..21460632 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -8,8 +8,8 @@ filename: LearnObjectiveC.m --- -Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch. -It's is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. +Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. +It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. ```Objective-C // Single-line comments start with // @@ -97,6 +97,6 @@ UserObject *someObject = [[UserObject alloc] init]; [Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) -[Objectively Speaking: A Crash Course in Objective-C](http://www.raywenderlich.com/12444/objectively-speaking-a-crash-course-in-objective-c) +[Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From 48fcef441fce2235e5dcd0d7c052b44f315504a5 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 14:56:09 +0200 Subject: [ADD] Hello World! --- objective-c.html.markdown | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 21460632..63aa64f1 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -18,7 +18,26 @@ It is a general-purpose, object-oriented programming language that adds Smalltal Multi-line comments look like this. */ -##Basic types +// Imports the Foundation headers with #import +#import + +// Your program's entry point is a function called +// main with an integer return type. +int main (int argc, const char * argv[]) +{ + // Create an autorelease pool to manage the memory into your program + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + // Print "Hello World!" to the console + NSLog(@"Hello World!"); + + // Clean up the memory you used into your program + [pool drain]; + + // End your program + return 0; +} + // all the primitive variable types are the same as in C // char, int, long, double, float -- cgit v1.2.3 From a29c4ee753894d1b58fa398d9f49567d098d6221 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 15:25:47 +0200 Subject: [Refactoring] Literals --- objective-c.html.markdown | 80 ++++++++++++++++++++++++++--------------------- 1 file changed, 44 insertions(+), 36 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 63aa64f1..2b8e9874 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -28,72 +28,80 @@ int main (int argc, const char * argv[]) // Create an autorelease pool to manage the memory into your program NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - // Print "Hello World!" to the console - NSLog(@"Hello World!"); + // Use NSLog to print lines to the console + NSLog(@"Hello World!"); // Print "Hello World!" - // Clean up the memory you used into your program - [pool drain]; - - // End your program - return 0; -} + // character literals + NSNumber *theLetterZ = @'Z'; -// all the primitive variable types are the same as in C -// char, int, long, double, float + // integral literals + NSNumber *fortyTwo = @42; + NSNumber *fortyTwoUnsigned = @42U; + NSNumber *fortyTwoLong = @42L; + NSNumber *fortyTwoLongLong = @42LL; + // floating point literals + NSNumber *piFloat = @3.141592654F; + NSNumber *piDouble = @3.1415926535; -// Simple, common classes -// number -NSNumber *firstNumber = @1; -NSNumber *secondNumber = @23.0; -NSNumber *boolNumber = @YES; + // BOOL literals + NSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES] + NSNumber *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO] -// string -NSString *aString = @"some string"; + // strings + NSString *helloString = @"hello"; -// array -NSArray *array = @[ @1, @2]; + // array + NSArray *anArray = @[@1, @2]; -// dictionary -NSDictionay *dictionary = @{ @"aKey" : @"aValue", @"aKey2" : @"aValue2" }; + // dictionary + NSDictionay *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; -// Import headers with #import -#import -#import "SomeAppDelegate.h" + // Clean up the memory you used into your program + [pool drain]; + + // End your program + return 0; +} -##Coding classes +/////////////////////////////////////// +// Classes And Functions +/////////////////////////////////////// // Declare your class in a header(.h) file: -@interface UserObject : NSObject{ -// instance variables +@interface UserObject : NSObject +{ + // instance variables } // Class method - + (NSString*) ClassMethod; ++ (NSString *)classMethod; // Instance method - - (NSString*) instanceMethodWithParmeter:(NSString*)string; +- (NSString *)instanceMethodWithParmeter:(NSString *)string; @end -// Add class methods in an implementation (.m) file: +// Implement the methods in an implementation (.m) file: @implementation UserObject -+ (NSString*) ClassMethod{ - return @"SomeString"; ++ (NSString *)classMethod +{ + return @"SomeString"; } -- (NSString*) instanceMethodWithParmeter:(NSString*)string; +- (NSString *)instanceMethodWithParmeter:(NSString *)string { - return @"New string"; + return @"New string"; } -- (NSString*) otherMethodWithString:(NSString*)string; +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number { - return [NSString stringWithString:string]; + return @42; } + @end // Create an object instance by allocating memory and initializing it. An object is not fully functional until both steps have been completed. -- cgit v1.2.3 From 0bd403fdb935331c3c391ffd79f0245032dee3b5 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 15:50:09 +0200 Subject: [UPDATE] Literals Examples --- objective-c.html.markdown | 63 ++++++++++++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 2b8e9874..284eca92 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -29,33 +29,52 @@ int main (int argc, const char * argv[]) NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // Use NSLog to print lines to the console - NSLog(@"Hello World!"); // Print "Hello World!" + NSLog(@"Hello World!"); // Print the string "Hello World!" - // character literals + // String object + NSString *worldString = @"World"; + // %@ is an object + NSLog(@"Hello %@!", worldString); // Print "Hello World!" + + // Character literals NSNumber *theLetterZ = @'Z'; + NSLog(@"%c", [theLetterZ charValue]); - // integral literals - NSNumber *fortyTwo = @42; - NSNumber *fortyTwoUnsigned = @42U; - NSNumber *fortyTwoLong = @42L; - NSNumber *fortyTwoLongLong = @42LL; - - // floating point literals - NSNumber *piFloat = @3.141592654F; - NSNumber *piDouble = @3.1415926535; + // Integral literals + NSNumber *fortyTwoNumber = @42; + int fortyTwo = [fortyTwo intValue]; + NSLog(@"%i", fortyTwo); + + NSNumber *fortyTwoUnsignedNumber = @42U; + unsigned int fortyTwoUnsigned = [fortyTwoUnsigned unsignedIntValue]; + NSLog(@"%u", fortyTwoUnsigned); + + NSNumber *fortyTwoLongNumber = @42L; + long fortyTwoLong = [aLong longValue]; + NSLog(@"%li", fortyTwoLong); + + // Floating point literals + NSNumber *piFloatNumber = @3.141592654F; + float piFloat = [piFloat floatValue]; + NSLog(@"%f", piFloat); + + NSNumber *piDoubleNumber = @3.1415926535; + piDouble = [piDouble doubleValue]; + NSLog(@"%f", piDouble); // BOOL literals - NSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES] - NSNumber *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO] - - // strings - NSString *helloString = @"hello"; - - // array - NSArray *anArray = @[@1, @2]; - - // dictionary - NSDictionay *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSNumber *yesNumber = @YES; + NSNumber *noNumber = @NO; + + // Array object + NSArray *anArray = @[@1, @2, @3, @4]; + NSNumber *thirdNumber = anArray[2]; + NSLog(@"Third number = %@", thirdObject); // Print "Third number = 3" + + // Dictionary object + NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSObject *valueObject = aDictionary[@"A Key"]; + NSLog(@"Object = %@", valueObject); // Print "Object = (null)" // Clean up the memory you used into your program [pool drain]; -- cgit v1.2.3 From 947c137680c2699bdb118b63460c560bac1fdd3c Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 15:52:11 +0200 Subject: minor fixes --- objective-c.html.markdown | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 284eca92..fc4b2900 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -37,29 +37,30 @@ int main (int argc, const char * argv[]) NSLog(@"Hello %@!", worldString); // Print "Hello World!" // Character literals - NSNumber *theLetterZ = @'Z'; - NSLog(@"%c", [theLetterZ charValue]); + NSNumber *theLetterZNumber = @'Z'; + char theLetterZ = [theLetterZNumber charValue]; + NSLog(@"%c", theLetterZ); // Integral literals NSNumber *fortyTwoNumber = @42; - int fortyTwo = [fortyTwo intValue]; + int fortyTwo = [fortyTwoNumber intValue]; NSLog(@"%i", fortyTwo); NSNumber *fortyTwoUnsignedNumber = @42U; - unsigned int fortyTwoUnsigned = [fortyTwoUnsigned unsignedIntValue]; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; NSLog(@"%u", fortyTwoUnsigned); NSNumber *fortyTwoLongNumber = @42L; - long fortyTwoLong = [aLong longValue]; + long fortyTwoLong = [fortyTwoLongNumber longValue]; NSLog(@"%li", fortyTwoLong); // Floating point literals NSNumber *piFloatNumber = @3.141592654F; - float piFloat = [piFloat floatValue]; + float piFloat = [piFloatNumber floatValue]; NSLog(@"%f", piFloat); NSNumber *piDoubleNumber = @3.1415926535; - piDouble = [piDouble doubleValue]; + piDouble = [piDoubleNumber doubleValue]; NSLog(@"%f", piDouble); // BOOL literals -- cgit v1.2.3 From 0040ce616b4e27a182834cd2fd03aacc2561a198 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:04:20 +0200 Subject: [UPDATE] Object Declaration --- objective-c.html.markdown | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index fc4b2900..c3df514b 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -25,15 +25,28 @@ Multi-line comments look like this. // main with an integer return type. int main (int argc, const char * argv[]) { - // Create an autorelease pool to manage the memory into your program + // Create an autorelease pool to manage the memory into the program NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // Use NSLog to print lines to the console NSLog(@"Hello World!"); // Print the string "Hello World!" - // String object - NSString *worldString = @"World"; + /////////////////////////////////////// + // Types & Variables + /////////////////////////////////////// + + // Primitive declarations + int myPrimitive; + + // Object declarations + // Put the * in front of the variable names for strongly-typed object declarations + MyClass *myObject1; // Strong typing + id myObject2; // Weak typing // %@ is an object + NSLog(@"%@ and %@", myObject1, myObject2); // Print "(null) and (null)" + + // String + NSString *worldString = @"World"; NSLog(@"Hello %@!", worldString); // Print "Hello World!" // Character literals @@ -50,6 +63,10 @@ int main (int argc, const char * argv[]) 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); @@ -77,10 +94,14 @@ int main (int argc, const char * argv[]) NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // Print "Object = (null)" + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + // Clean up the memory you used into your program [pool drain]; - // End your program + // End the program return 0; } -- cgit v1.2.3 From 25f4c7e80a4682db35daed75d42ca91eb1504736 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:07:58 +0200 Subject: minor fixes --- objective-c.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index c3df514b..ad2bedf9 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -36,14 +36,16 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Primitive declarations - int myPrimitive; + int myPrimitive1; + long myPrimitive2; // Object declarations // Put the * in front of the variable names for strongly-typed object declarations MyClass *myObject1; // Strong typing id myObject2; // Weak typing // %@ is an object - NSLog(@"%@ and %@", myObject1, myObject2); // Print "(null) and (null)" + // 'description' is a convention to display the value of the Objects + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // Print "(null) and (null)" // String NSString *worldString = @"World"; -- cgit v1.2.3 From 0970cb8010e590332b86de26a4746c7202c22363 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:09:38 +0200 Subject: minor update --- objective-c.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index ad2bedf9..7f87da6f 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -36,13 +36,13 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Primitive declarations - int myPrimitive1; - long myPrimitive2; + int myPrimitive1 = 1; + long myPrimitive2 = 234554664565; // Object declarations // Put the * in front of the variable names for strongly-typed object declarations - MyClass *myObject1; // Strong typing - id myObject2; // Weak typing + MyClass *myObject1 = nil; // Strong typing + id myObject2 = nil; // Weak typing // %@ is an object // 'description' is a convention to display the value of the Objects NSLog(@"%@ and %@", myObject1, [myObject2 description]); // Print "(null) and (null)" -- cgit v1.2.3 From 24d9cde4883202d4b7c5db7dad8981b4a4000125 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:22:40 +0200 Subject: [NEW] Statements --- objective-c.html.markdown | 72 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 7f87da6f..ebae2fc7 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -99,6 +99,78 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Operators /////////////////////////////////////// + + // The operators works like in the C language + // For example: + 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)) + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + + // If-Else statement + if (NO) + { + NSLog(@"I am never run"); + } else if (0) + { + NSLog(@"I am also never run"); + } else + { + NSLog(@"I print"); + } + + // Switch statement + 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 loops exist + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value. + } // => prints "0, + 1, + 2, + 3," + + // For loops too + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", ii++); + } // => prints "0, + 1, + 2, + 3," + + // Foreach + NSArray *values = @[@0, @1, @2, @3]; + for (NSNumber *value in values) + { + NSLog(@"%@,", value); + } // => prints "0, + 1, + 2, + 3," // Clean up the memory you used into your program [pool drain]; -- cgit v1.2.3 From 5d800b25e427417c589f3cf2c3b19c18c178a11f Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:32:16 +0200 Subject: [NEW] Try-Catch-Finally --- objective-c.html.markdown | 49 +++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index ebae2fc7..479d9ad5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -102,6 +102,8 @@ int main (int argc, const char * argv[]) // The operators works like in the C language // For example: + 2 + 5; // => 7 + 4.2f + 5.1f; // => 9.3f 3 == 2; // => 0 (NO) 3 != 2; // => 1 (YES) 1 && 1; // => 1 (Logical and) @@ -127,7 +129,8 @@ int main (int argc, const char * argv[]) } // Switch statement - switch (2) { + switch (2) + { case 0: { NSLog(@"I am never run"); @@ -142,36 +145,50 @@ int main (int argc, const char * argv[]) } break; } - // While loops exist + // While loops statements int ii = 0; while (ii < 4) { NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value. - } // => prints "0, - 1, - 2, - 3," + } // => prints "0," + "1," + "2," + "3," - // For loops too + // For loops statements int jj; for (jj=0; jj < 4; jj++) { NSLog(@"%d,", ii++); - } // => prints "0, - 1, - 2, - 3," + } // => prints "0," + "1," + "2," + "3," - // Foreach + // Foreach statements NSArray *values = @[@0, @1, @2, @3]; for (NSNumber *value in values) { NSLog(@"%@,", value); - } // => prints "0, - 1, - 2, - 3," + } // => prints "0," + "1," + "2," + "3," + // Try-Catch-Finally statements + @try + { + // Your statements here + @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; + } @catch (NSException * e) + { + NSLog(@"Exception: %@", e); + } @finally + { + NSLog(@"Finally"); + } // => prints "Exception: File Not Found on System" + "Finally" + // Clean up the memory you used into your program [pool drain]; -- cgit v1.2.3 From 50c3526247810078b6c63e2cbaf79bc226e873dc Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:34:12 +0200 Subject: minor updates --- objective-c.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 479d9ad5..6eac69a8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -151,9 +151,9 @@ int main (int argc, const char * argv[]) { NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value. } // => prints "0," - "1," - "2," - "3," + // "1," + // "2," + // "3," // For loops statements int jj; @@ -161,9 +161,9 @@ int main (int argc, const char * argv[]) { NSLog(@"%d,", ii++); } // => prints "0," - "1," - "2," - "3," + // "1," + // "2," + // "3," // Foreach statements NSArray *values = @[@0, @1, @2, @3]; @@ -171,9 +171,9 @@ int main (int argc, const char * argv[]) { NSLog(@"%@,", value); } // => prints "0," - "1," - "2," - "3," + // "1," + // "2," + // "3," // Try-Catch-Finally statements @try @@ -187,7 +187,7 @@ int main (int argc, const char * argv[]) { NSLog(@"Finally"); } // => prints "Exception: File Not Found on System" - "Finally" + // "Finally" // Clean up the memory you used into your program [pool drain]; -- cgit v1.2.3 From b61eba73fbb5ab8283e4cff337affe15bda35a2d Mon Sep 17 00:00:00 2001 From: Korjavin Ivan Date: Tue, 13 Aug 2013 20:37:52 +0600 Subject: beta perl --- perl.html.markdown | 122 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 perl.html.markdown diff --git a/perl.html.markdown b/perl.html.markdown new file mode 100644 index 00000000..7e0b1183 --- /dev/null +++ b/perl.html.markdown @@ -0,0 +1,122 @@ +--- +name: perl +category: language +language: perl +filename: learnperl.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] +--- + +Perl 5 is a highly capable, feature-rich programming language with over 25 years of development. + +Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects. + +```perl +# Single line comments start with a hash. + +/* +Multi-line comments look like this. +*/ + + +#### Perl variable types + +# Variables begin with the $ symbol. +# A valid variable name starts with a letter or underscore, +# followed by any number of letters, numbers, or underscores. + +### Perl has three main variable types: scalars, arrays, and hashes. + +## Scalars +# A scalar represents a single value: +my $animal = "camel"; +my $answer = 42; + +# Scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required. + +## Arrays +# An array represents a list of values: +my @animals = ("camel", "llama", "owl"); +my @numbers = (23, 42, 69); +my @mixed = ("camel", 42, 1.23); + + + +## Hashes +# A hash represents a set of key/value pairs: + +my %fruit_color = ("apple", "red", "banana", "yellow"); + +# You can use whitespace and the "=>" operator to lay them out more nicely: + +my %fruit_color = ( + apple => "red", + banana => "yellow", + ); +# Scalars, arrays and hashes are documented more fully in perldata. (perldoc perldata). + +# More complex data types can be constructed using references, which allow you to build lists and hashes within lists and hashes. + +#### Conditional and looping constructs + +# Perl has most of the usual conditional and looping constructs. + +if ( $var ) { + ... +} elsif ( $var eq 'bar' ) { + ... +} else { + ... +} + +unless ( condition ) { + ... + } +# This is provided as a more readable version of "if (!condition)" + +# the Perlish post-condition way +print "Yow!" if $zippy; +print "We have no bananas" unless $bananas; + +# while + while ( condition ) { + ... + } + + +# for and foreach +for ($i = 0; $i <= $max; $i++) { + ... + } + +foreach (@array) { + print "This element is $_\n"; + } + + +#### Regular expressions + +# Perl's regular expression support is both broad and deep, and is the subject of lengthy documentation in perlrequick, perlretut, and elsewhere. However, in short: + +# Simple matching +if (/foo/) { ... } # true if $_ contains "foo" +if ($a =~ /foo/) { ... } # true if $a contains "foo" + +# Simple substitution + +$a =~ s/foo/bar/; # replaces foo with bar in $a +$a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $a + + +``` + +#### Using Perl modules + +# Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). A number of popular modules are included with the Perl distribution itself. + +# perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use. + +#### Further Reading + +[Learn at www.perl.com](http://www.perl.org/learn.html) + and perldoc perlintro -- cgit v1.2.3 From 90b79ea04a242f6b5bbb6dae3b41c0d5b2b4aea9 Mon Sep 17 00:00:00 2001 From: Korjavin Ivan Date: Tue, 13 Aug 2013 20:39:25 +0600 Subject: md fix --- perl.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index 7e0b1183..fec4ce05 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -112,9 +112,9 @@ $a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $a #### Using Perl modules -# Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). A number of popular modules are included with the Perl distribution itself. +Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). A number of popular modules are included with the Perl distribution itself. -# perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use. +perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use. #### Further Reading -- cgit v1.2.3 From 3f92d3345f31246e5d547ca47e9c725be2a193b4 Mon Sep 17 00:00:00 2001 From: Korjavin Ivan Date: Tue, 13 Aug 2013 20:42:22 +0600 Subject: mistake fix --- perl.html.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index fec4ce05..024bd851 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -14,10 +14,6 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f ```perl # Single line comments start with a hash. -/* -Multi-line comments look like this. -*/ - #### Perl variable types -- cgit v1.2.3 From 0d41a6405627b50f2839df3a3b019836f361ecc0 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:46:16 +0200 Subject: [UPDATE] Object Creation --- objective-c.html.markdown | 46 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 36 insertions(+), 10 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 6eac69a8..f43081cf 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -201,27 +201,56 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Declare your class in a header(.h) file: - -@interface UserObject : NSObject +// Class Declaration Syntax: +// @interface : +// { +// Member variable declarations; +// } +// -/+ (type) Method declarations; +// @end +@interface MyClass : NSObject { - // instance variables + int count; + id data; + NSString *name; } +// Create the public getter/setter for the variable count +@property(assign) int count; + +// Methods ++/- (return type)methodSignature:(Parameter Type *)parameterName; -// Class method +// + for class method + (NSString *)classMethod; -// Instance method +// - for instance method - (NSString *)instanceMethodWithParmeter:(NSString *)string; - +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; +- @end // Implement the methods in an implementation (.m) file: @implementation UserObject +// Constructors are a way of creating classes +// This is a default constructor +- (id)init +{ + if ((self = [super init])) + { + self.count = 1; + + // Create an object instance by allocating memory and initializing it. + // An object is not fully functional until both steps have been completed. + UserObject *someObject = [[UserObject alloc] init]; + } + return self; +} + + (NSString *)classMethod { - return @"SomeString"; + return [[self alloc] init]; } - (NSString *)instanceMethodWithParmeter:(NSString *)string @@ -236,9 +265,6 @@ int main (int argc, const char * argv[]) @end -// Create an object instance by allocating memory and initializing it. An object is not fully functional until both steps have been completed. -UserObject *someObject = [[UserObject alloc] init]; - ##Calling Methods // The Objective-C model of object-oriented programming is based on message passing to object instances. -- cgit v1.2.3 From 3fe1c3c8a562427533439f385df952a00b36a998 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:49:23 +0200 Subject: minor update --- objective-c.html.markdown | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index f43081cf..22791659 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -189,6 +189,18 @@ int main (int argc, const char * argv[]) } // => prints "Exception: File Not Found on System" // "Finally" + /////////////////////////////////////// + // Objects + /////////////////////////////////////// + + // Create an object instance by allocating memory and initializing it. + // An object is not fully functional until both steps have been completed. + MyClass *myObject = [[MyClass alloc] init]; + + // The Objective-C model of object-oriented programming is based on message passing to object instances. + // In Objective-C one does not simply call a method; one sends a message. + [myObject instanceMethodWithParmeter:@"Steve Jobs"]; + // Clean up the memory you used into your program [pool drain]; @@ -240,10 +252,6 @@ int main (int argc, const char * argv[]) if ((self = [super init])) { self.count = 1; - - // Create an object instance by allocating memory and initializing it. - // An object is not fully functional until both steps have been completed. - UserObject *someObject = [[UserObject alloc] init]; } return self; } @@ -265,18 +273,6 @@ int main (int argc, const char * argv[]) @end -##Calling Methods - -// The Objective-C model of object-oriented programming is based on message passing to object instances. -// In Objective-C one does not simply call a method; one sends a message. - -[someObject instanceMethodWithParmeter:@"Steve Jobs"]; - -##Nested Messages -// nested messages look like this: - -[someObject instanceMethodWithParmeter:[someObject otherMethodWithString:@"Jony Ive"]]; - ``` ## Further Reading -- cgit v1.2.3 From 664d592bc79c7dcc6c429bcee79965ef3df464f5 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:50:22 +0200 Subject: minor change --- objective-c.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 22791659..9d1178e1 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -20,6 +20,7 @@ Multi-line comments look like this. // Imports the Foundation headers with #import #import +#import "MyClass.h" // Your program's entry point is a function called // main with an integer return type. @@ -212,7 +213,7 @@ int main (int argc, const char * argv[]) // Classes And Functions /////////////////////////////////////// -// Declare your class in a header(.h) file: +// Declare your class in a header(MyClass.h) file: // Class Declaration Syntax: // @interface : // { @@ -241,7 +242,7 @@ int main (int argc, const char * argv[]) - @end -// Implement the methods in an implementation (.m) file: +// Implement the methods in an implementation (MyClass.m) file: @implementation UserObject -- cgit v1.2.3 From 0932765947b14407aa41fbe7ded00ca37a25f5c6 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:58:13 +0200 Subject: [NEW] Protocol Implementation --- objective-c.html.markdown | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 9d1178e1..187ea30a 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -215,20 +215,22 @@ int main (int argc, const char * argv[]) // Declare your class in a header(MyClass.h) file: // Class Declaration Syntax: -// @interface : +// @interface ClassName : ParentClassName // { // Member variable declarations; // } // -/+ (type) Method declarations; // @end -@interface MyClass : NSObject +@interface MyClass : NSObject { int count; id data; NSString *name; } -// Create the public getter/setter for the variable count -@property(assign) int count; +// Convenience notation to auto generate public getter and setter +@property int count; +@property (copy) NSString *name; // Copy the object during assignment. +@property (readonly) id data; // Declare only a getter method. // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; @@ -246,8 +248,13 @@ int main (int argc, const char * argv[]) @implementation UserObject +// Call when the object is releasing +- (void)dealloc +{ +} + // Constructors are a way of creating classes -// This is a default constructor +// This is a default constructor which is call when the object is creating - (id)init { if ((self = [super init])) @@ -272,8 +279,25 @@ int main (int argc, const char * argv[]) return @42; } +// Methods declared into MyProtocol +- (void)myProtocolMethod +{ + // statements +} + @end +/* + * A protocol declares methods that can be implemented by any class. + * Protocols are not classes themselves. They simply define an interface + * that other objects are responsible for implementing. + * / +@protocol MyProtocol + - (void)myProtocolMethod; +@end + + + ``` ## Further Reading -- cgit v1.2.3 From dbf07b80ac03648ebcec89d07eac279faa1d0cb6 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 13 Aug 2013 08:19:56 -0700 Subject: Scheme encoding for cl --- common-lisp.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 24b6947f..e174e0df 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -17,7 +17,7 @@ Another popular and recent book is -```commonlisp +```scheme ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; 0. Syntax @@ -589,6 +589,7 @@ nil ; for false - and the empty list ;; regular code. ;; See Practical Common Lisp for more information on macros. +``` ## Further Reading -- cgit v1.2.3 From 93fc8f5e8044c404d1feb600cf50eb932b596325 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 13 Aug 2013 10:10:49 -0700 Subject: Line length edits to C# --- csharp.html.markdown | 973 ++++++++++++++++++++++++++------------------------- 1 file changed, 487 insertions(+), 486 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index e079571e..c254b5a9 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -28,492 +28,493 @@ using System.Collections.Generic; // defines scope to organize code into "packages" namespace Learning { - // Each .cs file should at least contain a class with the same name as the file - // you're allowed to do otherwise, but shouldn't for sanity. - public class LearnCSharp - { - // A console application must have a main method as an entry point - public static void Main(string[] args) - { - // Use Console.WriteLine to print lines - Console.WriteLine("Hello World"); - Console.WriteLine( - "Integer: " + 10 + - " Double: " + 3.14 + - " Boolean: " + true); - - // To print without a new line, use Console.Write - Console.Write("Hello "); - Console.Write("World"); - - - /////////////////////////////////////////////////// - // Types & Variables - // - // Declare a variable using - /////////////////////////////////////////////////// - - // Sbyte - Signed 8-bit integer - // (-128 <= sbyte <= 127) - sbyte fooSbyte = 100; - - // Byte - Unsigned 8-bit integer - // (0 <= byte <= 255) - byte fooByte = 100; - - // Short - Signed 16-bit integer - // (-32,768 <= short <= 32,767) - short fooShort = 10000; - - // Ushort - Unsigned 16-bit integer - // (0 <= ushort <= 65,535) - ushort fooUshort = 10000; - - // Integer - Signed 32-bit integer - // (-2,147,483,648 <= int <= 2,147,483,647) - int fooInt = 1; - - // Uinteger - Unsigned 32-bit integer - // (0 <= uint <= 4,294,967,295) - uint fooUint = 1; - - // Long - Signed 64-bit integer - // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - long fooLong = 100000L; - // L is used to denote that this variable value is of type long or ulong - // anything without is treated as int or uint depending on size. - - // Ulong - Unsigned 64-bit integer - // (0 <= ulong <= 18,446,744,073,709,551,615) - ulong fooUlong = 100000L; - - // Float - Single-precision 32-bit IEEE 754 Floating Point - // Precision: 7 digits - float fooFloat = 234.5f; - // f is used to denote that this variable value is of type float; - // otherwise it is treated as double. - - // Double - Double-precision 64-bit IEEE 754 Floating Point - // Precision: 15-16 digits - double fooDouble = 123.4; - - // Bool - true & false - bool fooBoolean = true; - bool barBoolean = false; - - // Char - A single 16-bit Unicode character - char fooChar = 'A'; - - // Strings - string fooString = "My string is here!"; - Console.WriteLine(fooString); - - // formatting - string fooFormattedString = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); - Console.WriteLine(fooFormattedString); - - // formatting dates - DateTime fooDate = DateTime.Now; - Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - - // \n is an escaped character that starts a new line - string barString = "Printing on a new line?\nNo Problem!"; - Console.WriteLine(barString); - - // it can be written prettier by using the @ symbol - string bazString = @"Here's some stuff - on a new line!"; - Console.WriteLine(bazString); - - // quotes need to be escaped - // use \" normally - string quotedString = "some \"quoted\" stuff"; - Console.WriteLine(quotedString); - - // use "" when strings start with @ - string quotedString2 = @"some MORE ""quoted"" stuff"; - Console.WriteLine(quotedString2); - - // Use const or read-only to make a variable immutable - // const values are calculated at compile time - const int HOURS_I_WORK_PER_WEEK = 9001; - - // Nullable types - // any type can be made nullable by suffixing a ? - // ? = - int? nullable = null; - Console.WriteLine("Nullable variable: " + nullable); - - // ?? is syntactic sugar for specifying default value - // in case variable is null - int notNullable = nullable ?? 0; - Console.WriteLine("Not nullable variable: " + notNullable); - - // Var - compiler will choose the most appropriate type based on value - var fooImplicit = true; - - /////////////////////////////////////////////////// - // Data Structures - /////////////////////////////////////////////////// - Console.WriteLine("\n->Data Structures"); - - // Arrays - // The array size must be decided upon declaration - // The format for declaring an array is follows: - // [] = new []; - int[] intArray = new int[10]; - string[] stringArray = new string[1]; - bool[] boolArray = new bool[100]; - - // Another way to declare & initialize an array - int[] y = { 9000, 1000, 1337 }; - - // Indexing an array - Accessing an element - Console.WriteLine("intArray @ 0: " + intArray[0]); - - // Arrays are zero-indexed and mutable. - intArray[1] = 1; - Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1 - - // Lists - // Lists are used more frequently than arrays as they are more flexible - // The format for declaring a list is follows: - // List = new List(); - List intList = new List(); - List stringList = new List(); - - // Another way to declare & initialize a list - List z = new List { 9000, 1000, 1337 }; - - // Indexing a list - Accessing an element - // Lists are zero-indexed and mutable. - Console.WriteLine("z @ 0: " + z[2]); - - // Lists don't default to a value; - // A value must be added before accessing the index - intList.Add(1); - Console.WriteLine("intList @ 0: " + intList[0]); - - - // Others data structures to check out: - // - // Stack/Queue - // Dictionary - // Read-only Collections - // Tuple (.Net 4+) - - - /////////////////////////////////////// - // Operators - /////////////////////////////////////// - Console.WriteLine("\n->Operators"); - - int i1 = 1, i2 = 2; // Shorthand for multiple declarations - - // Arithmetic is straightforward - Console.WriteLine("1+2 = " + (i1 + i2)); // => 3 - Console.WriteLine("2-1 = " + (i2 - i1)); // => 1 - Console.WriteLine("2*1 = " + (i2 * i1)); // => 2 - Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) - - // Modulo - Console.WriteLine("11%3 = " + (11 % 3)); // => 2 - - // Comparison operators - Console.WriteLine("3 == 2? " + (3 == 2)); // => false - Console.WriteLine("3 != 2? " + (3 != 2)); // => true - Console.WriteLine("3 > 2? " + (3 > 2)); // => true - Console.WriteLine("3 < 2? " + (3 < 2)); // => false - Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true - Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true - - // Bitwise operators! - /* - ~ Unary bitwise complement - << Signed left shift - >> Signed right shift - >>> Unsigned right shift - & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR - */ - - // Incrementations - int i = 0; - Console.WriteLine("\n->Inc/Dec-rementation"); - Console.WriteLine(i++); //i = 1. Post-Incrementation - Console.WriteLine(++i); //i = 2. Pre-Incrementation - Console.WriteLine(i--); //i = 1. Post-Decrementation - Console.WriteLine(--i); //i = 0. Pre-Decrementation - - - /////////////////////////////////////// - // Control Structures - /////////////////////////////////////// - Console.WriteLine("\n->Control Structures"); - - // If statements are c-like - int j = 10; - if (j == 10) - { - Console.WriteLine("I get printed"); - } - else if (j > 10) - { - Console.WriteLine("I don't"); - } - else - { - Console.WriteLine("I also don't"); - } - - // Ternary operators - // A simple if/else can be written as follows - // ? : - string isTrue = (true) ? "True" : "False"; - Console.WriteLine("Ternary demo: " + isTrue); - - - // While loop - int fooWhile = 0; - while (fooWhile < 100) - { - //Console.WriteLine(fooWhile); - //Increment the counter - //Iterated 99 times, fooWhile 0->99 - fooWhile++; - } - Console.WriteLine("fooWhile Value: " + fooWhile); - - // Do While Loop - int fooDoWhile = 0; - do - { - //Console.WriteLine(fooDoWhile); - //Increment the counter - //Iterated 99 times, fooDoWhile 0->99 - fooDoWhile++; - } while (fooDoWhile < 100); - Console.WriteLine("fooDoWhile Value: " + fooDoWhile); - - // For Loop - int fooFor; - //for loop structure => for(; ; ) - for (fooFor = 0; fooFor < 10; fooFor++) - { - //Console.WriteLine(fooFor); - //Iterated 10 times, fooFor 0->9 - } - Console.WriteLine("fooFor Value: " + fooFor); - - // Switch Case - // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), - // the String class, and a few special classes that wrap - // primitive types: Character, Byte, Short, and Integer. - int month = 3; - string monthString; - switch (month) - { - case 1: - monthString = "January"; - break; - case 2: - monthString = "February"; - break; - case 3: - monthString = "March"; - break; - default: - monthString = "Some other month"; - break; - } - Console.WriteLine("Switch Case Result: " + monthString); - - - /////////////////////////////////////// - // Converting Data Types And Typcasting - /////////////////////////////////////// - - // Converting data - - // Convert String To Integer - // this will throw an Exception on failure - int.Parse("123");//returns an integer version of "123" - - // try parse will default to type default on failure - // in this case: 0 - int tryInt; - int.TryParse("123", out tryInt); - - // Convert Integer To String - // Convert class has a number of methods to facilitate conversions - Convert.ToString(123); - - /////////////////////////////////////// - // Classes And Functions - /////////////////////////////////////// - - Console.WriteLine("\n->Classes & Functions"); - - // (definition of the Bicycle class follows) - - // Use new to instantiate a class - Bicycle trek = new Bicycle(); - - // Call object methods - trek.speedUp(3); // You should always use setter and getter methods - trek.setCadence(100); - - // ToString is a convention to display the value of this Object. - Console.WriteLine("trek info: " + trek.ToString()); - - // Instantiate another new Bicycle - Bicycle octo = new Bicycle(5, 10); - Console.WriteLine("octo info: " + octo.ToString()); - - // Instantiate a new Penny Farthing - PennyFarthing funbike = new PennyFarthing(1, 10); - Console.WriteLine("funbike info: " + funbike.ToString()); - - Console.Read(); - } // End main method - - - } // End LearnCSharp class - - // You can include other classes in a .cs file - - - // Class Declaration Syntax: - // class { - // //data fields, constructors, functions all inside. - // //functions are called as methods in Java. - // } - - public class Bicycle - { - // Bicycle's Fields/Variables - public int cadence; // Public: Can be accessed from anywhere - private int _speed; // Private: Only accessible from within the class - protected int gear; // Protected: Accessible from the class and subclasses - internal int wheels; // Internal: Accessible from within the assembly - string name; // default: Only accessible from within this class - - // readonly values are set at run time - // they can only be assigned upon declaration or in a constructor - readonly bool hasCardsInSpokes = false; // read-only private - - // Constructors are a way of creating classes - // This is a default constructor - public Bicycle() - { - gear = 1; - cadence = 50; - _speed = 5; - name = "Bontrager"; - } - - // This is a specified constructor (it contains arguments) - public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes) - { - this.gear = startGear; - this.cadence = startCadence; - this._speed = startSpeed; - this.name = name; - this.hasCardsInSpokes = hasCardsInSpokes; - } - - // Constructors can be chained - public Bicycle(int startCadence, int startSpeed) : - this(startCadence, startSpeed, 0, "big wheels", true) - { - } - - // Function Syntax: - // () - - // classes can implement getters and setters for their fields - // or they can implement properties - - // Method declaration syntax: - // () - public int getCadence() - { - return cadence; - } - - // void methods require no return statement - public void setCadence(int newValue) - { - cadence = newValue; - } - - // virtual keyword indicates this method can be overridden - public virtual void setGear(int newValue) - { - gear = newValue; - } - - public void speedUp(int increment) - { - _speed += increment; - } - - public void slowDown(int decrement) - { - _speed -= decrement; - } - - // properties get/set values - // when only data needs to be accessed, consider using properties. - // properties may have either get or set, or both - private bool _hasTassles; // private variable - public bool hasTassles // public accessor - { - get { return _hasTassles; } - set { _hasTassles = value; } - } - - private int _frameSize; - public int FrameSize - { - get { return _frameSize; } - // you are able to specify access modifiers for either get or set - // this means only Bicycle class can call set on Framesize - private set { _frameSize = value; } - } - - //Method to display the attribute values of this Object. - public override string ToString() - { - return "gear: " + gear + - " cadence: " + cadence + - " speed: " + _speed + - " name: " + name + - " cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") + - "\n------------------------------\n" - ; - } - } // end class Bicycle - - // PennyFarthing is a subclass of Bicycle - class PennyFarthing : Bicycle - { - // (Penny Farthings are those bicycles with the big front wheel. - // They have no gears.) - - // calling parent constructor - public PennyFarthing(int startCadence, int startSpeed) : - base(startCadence, startSpeed, 0, "PennyFarthing", true) - { - } - - public override void setGear(int gear) - { - gear = 0; - } - } + // Each .cs file should at least contain a class with the same name as the file + // you're allowed to do otherwise, but shouldn't for sanity. + public class LearnCSharp + { + // A console application must have a main method as an entry point + public static void Main(string[] args) + { + // Use Console.WriteLine to print lines + Console.WriteLine("Hello World"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // To print without a new line, use Console.Write + Console.Write("Hello "); + Console.Write("World"); + + + /////////////////////////////////////////////////// + // Types & Variables + // + // Declare a variable using + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - Signed 16-bit integer + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Ushort - Unsigned 16-bit integer + // (0 <= ushort <= 65,535) + ushort fooUshort = 10000; + + // Integer - Signed 32-bit integer + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Uinteger - Unsigned 32-bit integer + // (0 <= uint <= 4,294,967,295) + uint fooUint = 1; + + // Long - Signed 64-bit integer + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L is used to denote that this variable value is of type long or ulong + // anything without is treated as int or uint depending on size. + + // Ulong - Unsigned 64-bit integer + // (0 <= ulong <= 18,446,744,073,709,551,615) + ulong fooUlong = 100000L; + + // Float - Single-precision 32-bit IEEE 754 Floating Point + // Precision: 7 digits + float fooFloat = 234.5f; + // f is used to denote that this variable value is of type float; + // otherwise it is treated as double. + + // Double - Double-precision 64-bit IEEE 754 Floating Point + // Precision: 15-16 digits + double fooDouble = 123.4; + + // Bool - true & false + bool fooBoolean = true; + bool barBoolean = false; + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // Strings + string fooString = "My string is here!"; + Console.WriteLine(fooString); + + // formatting + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + Console.WriteLine(fooFormattedString); + + // formatting dates + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // \n is an escaped character that starts a new line + string barString = "Printing on a new line?\nNo Problem!"; + Console.WriteLine(barString); + + // it can be written prettier by using the @ symbol + string bazString = @"Here's some stuff + on a new line!"; + Console.WriteLine(bazString); + + // quotes need to be escaped + // use \" normally + string quotedString = "some \"quoted\" stuff"; + Console.WriteLine(quotedString); + + // use "" when strings start with @ + string quotedString2 = @"some MORE ""quoted"" stuff"; + Console.WriteLine(quotedString2); + + // Use const or read-only to make a variable immutable + // const values are calculated at compile time + const int HOURS_I_WORK_PER_WEEK = 9001; + + // Nullable types + // any type can be made nullable by suffixing a ? + // ? = + int? nullable = null; + Console.WriteLine("Nullable variable: " + nullable); + + // ?? is syntactic sugar for specifying default value + // in case variable is null + int notNullable = nullable ?? 0; + Console.WriteLine("Not nullable variable: " + notNullable); + + // Var - compiler will choose the most appropriate type based on value + var fooImplicit = true; + + /////////////////////////////////////////////////// + // Data Structures + /////////////////////////////////////////////////// + Console.WriteLine("\n->Data Structures"); + + // Arrays + // The array size must be decided upon declaration + // The format for declaring an array is follows: + // [] = new []; + int[] intArray = new int[10]; + string[] stringArray = new string[1]; + bool[] boolArray = new bool[100]; + + // Another way to declare & initialize an array + int[] y = { 9000, 1000, 1337 }; + + // Indexing an array - Accessing an element + Console.WriteLine("intArray @ 0: " + intArray[0]); + + // Arrays are zero-indexed and mutable. + intArray[1] = 1; + Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1 + + // Lists + // Lists are used more frequently than arrays as they are more flexible + // The format for declaring a list is follows: + // List = new List(); + List intList = new List(); + List stringList = new List(); + + // Another way to declare & initialize a list + List z = new List { 9000, 1000, 1337 }; + + // Indexing a list - Accessing an element + // Lists are zero-indexed and mutable. + Console.WriteLine("z @ 0: " + z[2]); + + // Lists don't default to a value; + // A value must be added before accessing the index + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + + // Others data structures to check out: + // + // Stack/Queue + // Dictionary + // Read-only Collections + // Tuple (.Net 4+) + + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + Console.WriteLine("1+2 = " + (i1 + i2)); // => 3 + Console.WriteLine("2-1 = " + (i2 - i1)); // => 1 + Console.WriteLine("2*1 = " + (i2 * i1)); // => 2 + Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Comparison operators + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + >>> Unsigned right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Ternary operators + // A simple if/else can be written as follows + // ? : + string isTrue = (true) ? "True" : "False"; + Console.WriteLine("Ternary demo: " + isTrue); + + + // While loop + int fooWhile = 0; + while (fooWhile < 100) + { + //Console.WriteLine(fooWhile); + //Increment the counter + //Iterated 99 times, fooWhile 0->99 + fooWhile++; + } + Console.WriteLine("fooWhile Value: " + fooWhile); + + // Do While Loop + int fooDoWhile = 0; + do + { + //Console.WriteLine(fooDoWhile); + //Increment the counter + //Iterated 99 times, fooDoWhile 0->99 + fooDoWhile++; + } while (fooDoWhile < 100); + Console.WriteLine("fooDoWhile Value: " + fooDoWhile); + + // For Loop + int fooFor; + //for loop structure => for(; ; ) + for (fooFor = 0; fooFor < 10; fooFor++) + { + //Console.WriteLine(fooFor); + //Iterated 10 times, fooFor 0->9 + } + Console.WriteLine("fooFor Value: " + fooFor); + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), + // the String class, and a few special classes that wrap + // primitive types: Character, Byte, Short, and Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + default: + monthString = "Some other month"; + break; + } + Console.WriteLine("Switch Case Result: " + monthString); + + + /////////////////////////////////////// + // Converting Data Types And Typcasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + // this will throw an Exception on failure + int.Parse("123");//returns an integer version of "123" + + // try parse will default to type default on failure + // in this case: 0 + int tryInt; + int.TryParse("123", out tryInt); + + // Convert Integer To String + // Convert class has a number of methods to facilitate conversions + Convert.ToString(123); + + /////////////////////////////////////// + // Classes And Functions + /////////////////////////////////////// + + Console.WriteLine("\n->Classes & Functions"); + + // (definition of the Bicycle class follows) + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.speedUp(3); // You should always use setter and getter methods + trek.setCadence(100); + + // ToString is a convention to display the value of this Object. + Console.WriteLine("trek info: " + trek.ToString()); + + // Instantiate another new Bicycle + Bicycle octo = new Bicycle(5, 10); + Console.WriteLine("octo info: " + octo.ToString()); + + // Instantiate a new Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.ToString()); + + Console.Read(); + } // End main method + + + } // End LearnCSharp class + + // You can include other classes in a .cs file + + + // Class Declaration Syntax: + // class { + // //data fields, constructors, functions all inside. + // //functions are called as methods in Java. + // } + + public class Bicycle + { + // Bicycle's Fields/Variables + public int cadence; // Public: Can be accessed from anywhere + private int _speed; // Private: Only accessible from within the class + protected int gear; // Protected: Accessible from the class and subclasses + internal int wheels; // Internal: Accessible from within the assembly + string name; // default: Only accessible from within this class + + // readonly values are set at run time + // they can only be assigned upon declaration or in a constructor + readonly bool hasCardsInSpokes = false; // read-only private + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() + { + gear = 1; + cadence = 50; + _speed = 5; + name = "Bontrager"; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes) + { + this.gear = startGear; + this.cadence = startCadence; + this._speed = startSpeed; + this.name = name; + this.hasCardsInSpokes = hasCardsInSpokes; + } + + // Constructors can be chained + public Bicycle(int startCadence, int startSpeed) : + this(startCadence, startSpeed, 0, "big wheels", true) + { + } + + // Function Syntax: + // () + + // classes can implement getters and setters for their fields + // or they can implement properties + + // Method declaration syntax: + // () + public int getCadence() + { + return cadence; + } + + // void methods require no return statement + public void setCadence(int newValue) + { + cadence = newValue; + } + + // virtual keyword indicates this method can be overridden + public virtual void setGear(int newValue) + { + gear = newValue; + } + + public void speedUp(int increment) + { + _speed += increment; + } + + public void slowDown(int decrement) + { + _speed -= decrement; + } + + // properties get/set values + // when only data needs to be accessed, consider using properties. + // properties may have either get or set, or both + private bool _hasTassles; // private variable + public bool hasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + private int _frameSize; + public int FrameSize + { + get { return _frameSize; } + // you are able to specify access modifiers for either get or set + // this means only Bicycle class can call set on Framesize + private set { _frameSize = value; } + } + + //Method to display the attribute values of this Object. + public override string ToString() + { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + _speed + + " name: " + name + + " cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + } // end class Bicycle + + // PennyFarthing is a subclass of Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + // calling parent constructor + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true) + { + } + + public override void setGear(int gear) + { + gear = 0; + } + } } // End Namespace ``` -- cgit v1.2.3 From 10637b0e77cca3daf5bd79e2d1eed2cb250a4192 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 13 Aug 2013 10:14:57 -0700 Subject: Header changes --- common-lisp.html.markdown | 2 +- ko-kr/lua-kr.html.markdown | 5 +++-- zh-cn/racket-cn.html.markdown | 1 + 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index e174e0df..a917304c 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -1,6 +1,6 @@ --- -language: commonlisp +language: "Common Lisp" filename: commonlisp.lisp contributors: - ["Paul Nathan", "https://github.com/pnathan"] diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index 3f6223d6..2badf734 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -1,4 +1,4 @@ ---- +--- language: lua category: language contributors: @@ -395,6 +395,7 @@ g() -- 343이 출력됩니다. 그전까지는 아무것도 출력되지 않습 --]] ``` + ## 참고자료 루아를 배우는 일이 흥미진진했던 이유는 Love 2D 게임 엔진을 이용해 @@ -420,4 +421,4 @@ learn.lua로 저장한 후 "lua learn.lua"를 실행해 보세요! 이 글은 tylerneylon.com에 처음으로 써본 글이며, Github의 Gist에서도 확인할 수 있습니다. -루아로 즐거운 시간을 보내세요! \ No newline at end of file +루아로 즐거운 시간을 보내세요! diff --git a/zh-cn/racket-cn.html.markdown b/zh-cn/racket-cn.html.markdown index e17aedda..d43511ea 100644 --- a/zh-cn/racket-cn.html.markdown +++ b/zh-cn/racket-cn.html.markdown @@ -1,6 +1,7 @@ --- language: racket +lang: zh-cn filename: learnracket.rkt contributors: - ["th3rac25", "https://github.com/voila"] -- cgit v1.2.3 From 50e49eced17ee758d47ca06141ee2b0e27ea2ee8 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 13 Aug 2013 10:30:44 -0700 Subject: Line length edits to objective c --- objective-c.html.markdown | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 187ea30a..2b1b3c67 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -11,7 +11,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```Objective-C +```cpp // Single-line comments start with // /* @@ -180,7 +180,8 @@ int main (int argc, const char * argv[]) @try { // Your statements here - @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"File Not Found on System" userInfo:nil]; } @catch (NSException * e) { NSLog(@"Exception: %@", e); @@ -198,9 +199,10 @@ int main (int argc, const char * argv[]) // An object is not fully functional until both steps have been completed. MyClass *myObject = [[MyClass alloc] init]; - // The Objective-C model of object-oriented programming is based on message passing to object instances. + // The Objective-C model of object-oriented programming is based on message + // passing to object instances. // In Objective-C one does not simply call a method; one sends a message. - [myObject instanceMethodWithParmeter:@"Steve Jobs"]; + [myObject instanceMethodWithParameter:@"Steve Jobs"]; // Clean up the memory you used into your program [pool drain]; @@ -241,7 +243,7 @@ int main (int argc, const char * argv[]) // - for instance method - (NSString *)instanceMethodWithParmeter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; -- + @end // Implement the methods in an implementation (MyClass.m) file: @@ -291,7 +293,7 @@ int main (int argc, const char * argv[]) * A protocol declares methods that can be implemented by any class. * Protocols are not classes themselves. They simply define an interface * that other objects are responsible for implementing. - * / + */ @protocol MyProtocol - (void)myProtocolMethod; @end -- cgit v1.2.3 From de6069d3d60eb2da7ee945c38fbe8d7249c66a6a Mon Sep 17 00:00:00 2001 From: Sonia Keys Date: Tue, 13 Aug 2013 13:52:13 -0400 Subject: Go first draft --- go.html.markdown | 423 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 423 insertions(+) create mode 100644 go.html.markdown diff --git a/go.html.markdown b/go.html.markdown new file mode 100644 index 00000000..9888b37d --- /dev/null +++ b/go.html.markdown @@ -0,0 +1,423 @@ +--- +name: Go +category: language +language: Go +filename: learngo.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] +--- + +Go was created out of the need to get work done. It's not the latest trend +in computer science, but it is the newest fastest way to solve real-world +problems. + +It has familiar concepts of imperative languages with static typing. +It's fast to compile and fast to execute, it adds easy-to-understand +concurrency to leverage today's multi-core CPUs, and has features to +help with large-scale programming. + +Go comes with a great standard library and an enthusiastic community. + +```Go +// Single line comment +/* Multi- + line comment */ + +// A package clause starts every source file. +// Main is a special name declaring an executable rather than a library. +package main + +// An import declaration comes next. It declares library packages referenced +// in this file. The list must be exactly correct! Missing or unused packages +// are errors, not warnings. +import ( + "fmt" // A package in the Go standard library + "net/http" // Yes, a web server! + "strconv" // String conversions +) + +// A function definition. Main is special. It is the entry point for the +// executable program. Love it or hate it, Go uses brace brackets. +func main() { + // Println is a function that outputs a line to stdout. It can be + // called here because fmt has been imported and the function name + // "Println" is upper case. Symbols starting with an upper case letter + // are publicly visible. No other special syntax is needed to export + // something from a package. + // To call Println, qualify it with the package name, fmt. + fmt.Println("Hello world!") + + // Call another function within this package. + beyondHello() +} + +// Idiomatic Go uses camel case. Functions have parameters in parentheses. +// If there are no parameters, empty parens are still required. +func beyondHello() { + var x int // Variable declaration. Variables must be declared before use. + x = 3 // Variable assignment. + // "Short" declarations use := syntax to declare and assign, infering the + // type from the right hand side as much as possible and using some + // defaults where the rhs could be interpreted different ways. + // Idiomatic Go uses short declarations in preference to var keyword. + y := 4 + sum, prod := learnMultiple(x, y) // function returns two values + fmt.Println("sum:", sum, "prod:", prod) // simple output + learnTypes() // < y minutes, learn more! +} + +// Functions can have parameters and (multiple!) return values. +// In declarations, the symbol precedes the type, and the type does not have +// to be repeated if it is the same for multiple symbols in a row. +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // return two values +} + +// Some built-in types and literals. +func learnTypes() { + // Short declaration usually gives you what you want. + s := "Learn Go!" // string type + + s2 := `A "raw" string literal +can include line breaks.` // same string type + + // non-ASCII literal. Go source is UTF-8. + g := 'Σ' // rune type, an alias for uint32, holds a UTF-8 code point + + f := 3.14195 // float64, an IEEE-754 64-bit floating point number + c := 3 + 4i // complex128, represented internally with two float64s + + // You can use var syntax with an initializer if you want + // something other than the default that a short declaration gives you. + var u uint = 7 // unsigned, but implementation dependent size as with int + var pi float32 = 22. / 7 + + // Or more idiomatically, use conversion syntax with a short declaration. + n := byte('\n') // byte is an alias for uint8 + + // Arrays have size fixed at compile time. + var a4 [4]int // an array of 4 ints, initialized to all 0 + a3 := [...]int{3, 1, 5} // an array of 3 ints, initialized as shown + + // Slices have dynamic size. Arrays and slices each have advantages + // but use cases for slices are much more common. + s3 := []int{4, 5, 9} // compare to a3. no ellipsis here + s4 := make([]int, 4) // allocates slice of 4 ints, initialized to all 0 + var d2 [][]float64 // declaration only, nothing allocated here + bs := []byte("a slice") // type conversion syntax + + p, q := learnMemory() // A little side bar. + // Did you read it? This short declaration declares p and q to be of + // type pointer to int. P is now pointing into a block of of 20 ints, but + // the only one accessible is the one that p is pointing at. There is + // no p++ to get at the next one. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + + // Maps are a dynamically growable associative array type, like the + // hash or dictionary types of some other languages. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // Unused variables are an error in Go. + // The underbar lets you "use" a variable but discard its value. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Output of course counts as using a variable. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // back in the flow +} + +// Go is fully garbage collected. It has pointers but no pointer arithmetic. +// You can make a mistake with a nil pointer, but not by incrementing a pointer. +func learnMemory() (p, q *int) { + // Named return values p and q have type pointer to int. They are + // initialized to nil at this point. Evaluating *p or *q here would cause + // a panic--a run time error. + p = new(int) // built-in function new allocates memory. + // The allocated int is initialized to 0, p is no longer nil. + s := make([]int, 20) // allocate 20 ints as a single block of memory + s[3] = 7 // assign one of them + r := -2 // declare another local variable + return &s[3], &r // Oh my. + // The line above returns two values, yes, and both of the expressions + // are valid. & takes the address of an object. Elements of a slice are + // addressable, and so are local variables. Built-in functions new and + // make explicitly allocate memory, but local objects can be allocated + // as needed. Here memory for r will be still be referenced after the + // function returns so it will be allocated as well. The int allocated + // with new on the other hand will no longer be referenced and can be + // garbage collected as needed by the Go runtime. The memory allocated + // with make will still be referenced at that one element, and so it + // cannot be garbage collected. All 20 ints remain in memory because + // one of them is still referenced. +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // If statements require brace brackets, and do not require parens. + if true { + fmt.Println("told ya") + } + // This is how we format the brace brackets. Formatting is standardized + // by the command line command "go fmt." Everybody does it. You will + // suffer endless disparaging remarks until you conform as well. + if false { + // pout + } else { + // gloat + } + // If statements can be chained of course, but it's idiomatic to use + // the handy switch statement instead. + x := 1 + switch x { + case 0: + case 1: + // cases don't "fall through" + case 2: + // unreached + } + // Like if, for doesn't use parens either. The scope of a variable + // declared in the first clause of the for statement is the statement + // and block. This x shadows the x declared above, but goes out of + // scope after the for block. + for x := 0; x < 3; x++ { // ++ is a statement + fmt.Println("iteration", x) + } + // x == 1 here. + + // For is the only loop statement in Go, but it has alternate forms. + for { // infinite loop + break // just kidding + continue // unreached + } + // The initial assignment of the for statement is handy enough that Go + // if statements can have one as well. Just like in the for statement, + // the := here means to declare and assign y first, then test y > x. + // The scope of y is limited to the if statement and block. + if y := expensiveComputation(); y > x { + x = y + } + // Functions are first class objects and function literals are handy. + // Function literals are closures. + xBig := func() bool { + return x > 100 // references x declared above switch statement. + } + fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x) + x /= 1e5 // this makes it == 10 + fmt.Println("xBig:", xBig()) // false now + + // When you need it, you'll love it. Actually Go's goto has been reformed + // a bit to avoid indeterminate states. You can't jump around variable + // declarations and you can't jump into blocks. + goto love +love: + + learnInterfaces() // Good stuff coming up! +} + +// An interface is a list of functionality that a type supports. Notably +// missing from an interface definition is any declaration of which types +// implement the interface. Types simply implement an interface or they don't. +// +// An interface can have any number of methods, but it's actually common +// for an interface to have only single method. It is idiomatic in this +// case for the single method to be named with some action, and for the +// interface name to end in "er." +// +// An interface definition is one kind of a type definition. Interface is +// a built in type. Stringer is defined here as an interface type with one +// method, String. +type Stringer interface { + String() string +} + +// Struct is another built in type. A struct aggregates "fields." +// Pair here has two fields, ints named x and y. +type pair struct { + x, y int +} + +// User defined types can have "methods." These are functions that operate +// in the context of an instance of the user defined type. The instance +// is called the "receiver" and is identified with a declaration just in front +// of the method name. The receiver here is "p." In most ways the receiver +// works just like a function parameter. +// +// This String method has the same name and return value as the String method +// of the Stringer interface. Further, String is the only method of Stringer. +// The pair type thus implements all methods of the Stringer interface and +// we say simply that pair implements Stringer. No other syntax is needed. +func (p pair) String() string { + // Sprintf is another public function in package fmt. + // Dot syntax references fields of p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // Brace syntax is a "struct literal." It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. + p := pair{3, 4} + fmt.Println(p.String()) // call String method of p, of type pair. + var i Stringer // declare i of type Stringer. + i = p // valid because pair implements Stringer + // Call String method of i, of type Stringer. Output same as above. + fmt.Println(i.String()) + // It gets more interesting now. We defined Stringer in this file, + // but the same interface happens to be defined in package fmt. + // Pair thus implements fmt.Stringer as well, and does so with no + // declaration of the fact. The definition of pair doesn't mention + // any interfaces at all, and of course the authors of fmt.Stringer + // had no idea that we were going to define pair. + // + // Functions in the fmt package know how to print some standard built in + // types, and beyond that, they see if a type implements fmt.Stringer. + // If so, they simply call the String method to ask an object for a + // printable representation of itself. + fmt.Println(p) // output same as above. Println calls String method. + fmt.Println(i) // output same as above + + learnErrorHandling() +} + +func learnErrorHandling() { + // Sometimes you just need to know if something worked or not. Go has + // a ", ok" idiom for that. Something, a map expression here, but commonly + // a function, can return a boolean value of ok or not ok as a second + // return value. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // , ok is optional but see how useful it is. + fmt.Println("no one there") + } else { + fmt.Print(x) + } + // An error value communicates not just "ok" but more about the problem. + if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value + // prints "strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // error is a built in type. It is an interface with a single method, + // defined internally as, + // + // type error interface { + // Error() string + // } + // + // The string returned by the Error method is conventionally a printable + // error message. You can define your own error types by simply adding + // an Error method. Your type then automatically implements the error + // interface. We've seen two interfaces now, fmt.Stringer and error. + + // We'll revisit interfaces a little later. Meanwhile, + learnConcurrency() +} + +// Go has concurrency support in the language definition. The element of +// concurrent execution is called a "goroutine" and is similar to a thread +// but "lighter." Goroutines are multiplexed to operating system threads +// and a running Go program can have far more goroutines than available OS +// threads. If a machine has multiple CPU cores, goroutines can run in +// parallel. +// +// Go "Channels" allow communication between goroutines in a way that is +// both powerful and easy to understand. Channel is a type in Go and objects +// of type channel are first class objects--they can be assigned to variables, +// passed around to functions, and so on. A channel works conceptually much +// like a Unix pipe. You put data in at one end and it comes out the other. +// Channel "send" and "receive" operations are goroutine-safe. No locks +// or additional synchronization is needed. + +// Inc increments a number, and sends the result on a channel. The channel +// operation makes this function useful to run concurrently with other +// goroutines. There is no special declaration though that says this function +// is concurrent. It is an ordinary function that happens to have a +// parameter of channel type. +func inc(i int, c chan int) { + c <- i + 1 // <- is the "send" operator when a channel appears on the left. +} + +// We'll use inc to increment some numbers concurrently. +func learnConcurrency() { + // Same make function used earlier to make a slice. Make allocates and + // initializes slices, maps, and channels. + c := make(chan int) + // Start three concurrent goroutines. Numbers will be incremented + // concurrently, perhaps in parallel if the machine is capable and + // properly configured. All three send to the same channel. + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) + // Read three results from the channel and print them out. + // There is no telling in what order the results will arrive! + fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. + + cs := make(chan string) // another channel, this one handles strings. + cc := make(chan chan string) // a channel of channels. + go func() { c <- 84 }() // start a new goroutine just to send a value + go func() { cs <- "wordy" }() // again, for cs this time + // Select has syntax like a switch statement but is doing something + // pretty different. Each case involves a channel operation. In rough + // terms, a case is selected at random out of the cases that are ready to + // communicate. If none are ready, select waits for one to become ready. + select { + case i := <-c: // the value received can be assigned to a variable + fmt.Println("it's a", i) + case <-cs: // or the value received can be discarded + fmt.Println("it's a string") + case <-cc: // empty channel, not ready for communication. + fmt.Println("didn't happen.") + } + // At this point a value was taken from either c or cs. One of the two + // goroutines started above has completed, the other will remain blocked. + + learnWebProgramming() // Go does it. You want to do it too. +} + +// A simple web server can be created with a single function from the standard +// library. ListenAndServe, in package net/http, listens at the specified +// TCP address and uses an object that knows how to serve data. "Knows how" +// means "satisfies an interface." The second parameter is of type interface, +// specifically http.Handler. http.Handler has a single method, ServeHTTP. +func learnWebProgramming() { + err := http.ListenAndServe(":8080", pair{}) + // Error returns are ubiquitous in Go. Always check error returns and + // do something with them. Often it's enough to print it out as an + // indication of what failed. Of course there are better things to do + // in production code: log it, try something else, shut everything down, + // and so on. + fmt.Println(err) +} + +// You can make any type into an http.Hander by implementing ServeHTTP. +// Lets use the pair type we defined earlier, just because we have it +// sitting around. ServeHTTP has two parameters. The request parameter +// is a struct that we'll ignore here. http.ResponseWriter is yet another +// interface! Here it is an object supplied to us with the guarantee that +// it implements its interface, which includes a method Write. +// We call this Write method to serve data. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("You learned Go in Y minutes!")) +} + +// And that's it for a proof-of-concept web server! If you run this program +// it will print out all the lines from the earlier parts of the lesson, then +// start this web server. To hit the web server, just point a browser at +// localhost:8080 and you'll see the message. (Then you can probably press +// ctrl-C to kill it.) +``` + +## Further Reading + +The root of all things Go is the [official Go web site](http://golang.org/). +There you can follow the tutorial, play interactively, and read lots. + +The language definition itself is highly recommended. It's easy to read +and amazingly short (as language definitions go these days.) + +On the reading list for students of Go is the source code to the standard +library. Comprehensively documented, it demonstrates the best of readable +and understandable Go, Go style, and Go idioms. Click on a function name +in the documentation and the source code comes up! + -- cgit v1.2.3 From 49cca911886480d10b071ced3a91c325ec3516f9 Mon Sep 17 00:00:00 2001 From: Lucas Tadeu Teixeira Date: Tue, 13 Aug 2013 16:28:48 -0300 Subject: Add brazilian portuguese translation for elisp tutorial. --- pt-br/elisp-pt.html.markdown | 359 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 359 insertions(+) create mode 100644 pt-br/elisp-pt.html.markdown diff --git a/pt-br/elisp-pt.html.markdown b/pt-br/elisp-pt.html.markdown new file mode 100644 index 00000000..9031cad9 --- /dev/null +++ b/pt-br/elisp-pt.html.markdown @@ -0,0 +1,359 @@ +--- +language: elisp +contributors: + - ["Bastien Guerry", "http://bzg.fr"] +translators: + - ["Lucas Tadeu Teixeira", "http://ltt.me"] +lang: pt-br +filename: learn-emacs-lisp-pt.el +--- + +```scheme +;; Introdução ao Emacs Lisp em 15 minutos (v0.2d) +;; +;; Autor: Bastien / @bzg2 / http://bzg.fr +;; +;; Antes de começar, leia este texto escrito Peter Norvig: +;; http://norvig.com/21-days.html +;; +;; Agora instale GNU Emacs 24.3: +;; +;; Debian: apt-get install emacs (ou veja as instruções da sua distribuição) +;; OSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg +;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip +;; +;; Informações mais gerais podem ser encontradas em: +;; http://www.gnu.org/software/emacs/#Obtaining + +;; Aviso importante: +;; +;; Realizar este tutorial não danificará seu computador, a menos +;; que você fique tão irritado a ponto de jogá-lo no chão. Neste caso, +;; me abstenho de qualquer responsabilidade. Divirta-se! + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Abra o Emacs. +;; +;; Aperte a tecla `q' para ocultar a mensagem de boas vindas. +;; +;; Agora olhe para a linha cinza na parte inferior da janela: +;; +;; "*scratch*" é o nome do espaço de edição em que você se encontra. +;; Este espaço de edição é chamado "buffer". +;; +;; O buffer de rascunho (i.e., "scratch") é o buffer padrão quando +;; o Emacs é aberto. Você nunca está editando arquivos: você está +;; editando buffers que você pode salvar em um arquivo. +;; +;; "Lisp interaction" refere-se a um conjunto de comandos disponíveis aqui. +;; +;; O Emacs possui um conjunto de comandos embutidos (disponíveis em +;; qualquer buffer) e vários subconjuntos de comandos disponíveis +;; quando você ativa um modo específico. Aqui nós utilizamos +;; `lisp-interaction-mode', que possui comandos para interpretar e navegar +;; em código Elisp. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Pontos e vírgulas iniciam comentários em qualquer parte de uma linha. +;; +;; Programas codificados em Elisp são compostos por expressões simbólicas +;; (conhecidas também por "sexps"): +(+ 2 2) + +;; Esta expressão simbólica significa "Some 2 e 2". + +;; "Sexps" são envoltas em parêntese, possivelmente aninhados: +(+ 2 (+ 1 1)) + +;; Uma expressão simbólica contém átomos ou outras expressões +;; simbólicas. Nos exemplos acima, 1 e 2 são átomos; +;; (+ 2 (+ 1 1)) e (+ 1 1) são expressões simbólicas. + +;; No modo `lisp-interaction-mode' você pode interpretar "sexps". +;; Posicione o cursor logo após o parêntese de fechamento e, +;; então, segure apertado Ctrl e aperte a tecla j ("C-j", em resumo). + +(+ 3 (+ 1 2)) +;; ^ posicione o cursor aqui +;; `C-j' => 6 + +;; `C-j' insere o resultado da interpretação da expressão no buffer. + +;; `C-xC-e' exibe o mesmo resultado na linha inferior do Emacs, +;; chamada de "mini-buffer". Nós geralmente utilizaremos `C-xC-e', +;; já que não queremos poluir o buffer com texto desnecessário. + +;; `setq' armazena um valor em uma variável: +(setq my-name "Bastien") +;; `C-xC-e' => "Bastien" (texto exibido no mini-buffer) + +;; `insert' insere "Hello!" na posição em que se encontra seu cursor: +(insert "Hello!") +;; `C-xC-e' => "Hello!" + +;; Nós executamos `insert' com apenas um argumento ("Hello!"), mas +;; mais argumentos podem ser passados -- aqui utilizamos dois: + +(insert "Hello" " world!") +;; `C-xC-e' => "Hello world!" + +;; Você pode utilizar variávies no lugar de strings: +(insert "Hello, I am " my-name) +;; `C-xC-e' => "Hello, I am Bastien" + +;; Você pode combinar "sexps" em funções: +(defun hello () (insert "Hello, I am " my-name)) +;; `C-xC-e' => hello + +;; Você pode interpretar chamadas de funções: +(hello) +;; `C-xC-e' => Hello, I am Bastien + +;; Os parêntesis vazios na definição da função significam que ela +;; não aceita argumentos. Mas sempre utilizar `my-name' é um tédio! +;; Vamos dizer à função para aceitar um argumento (o argumento é +;; chamado "name"): + +(defun hello (name) (insert "Hello " name)) +;; `C-xC-e' => hello + +;; Agora vamos executar a função com a string "you" como o valor +;; para seu único parâmetro: +(hello "you") +;; `C-xC-e' => "Hello you" + +;; Aí sim! + +;; Respire um pouco. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Agora mude para um novo buffer chamado "*test*": + +(switch-to-buffer-other-window "*test*") +;; `C-xC-e' +;; => [a tela exibirá duas janelas e o cursor estará no buffer *test*] + +;; Posicione o mouse sobre a janela superior e clique com o botão +;; esquerdo para voltar. Ou você pode utilizar `C-xo' (i.e. segure +;; ctrl-x e aperte o) para voltar para a outra janela, de forma interativa. + +;; Você pode combinar várias "sexps" com `progn': +(progn + (switch-to-buffer-other-window "*test*") + (hello "you")) +;; `C-xC-e' +;; => [A tela exibirá duas janelas e o cursor estará no buffer *test*] + +;; Agora, se você não se importar, pararei de pedir que você aperte +;; `C-xC-e': faça isso para cada "sexp" que escrevermos. + +;; Sempre volte para o buffer *scratch* com o mouse ou `C-xo'. + +;; Frequentemente, é útil apagar o conteúdo do buffer: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "there")) + +;; Ou voltar para a outra janela: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "you") + (other-window 1)) + +;; Você pode armazenar um valor em uma variável local utilizando `let': +(let ((local-name "you")) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello local-name) + (other-window 1)) + +;; Neste caso, não é necessário utilizar `progn' já que `let' combina +;; várias "sexps". + +;; Vamos formatar uma string: +(format "Hello %s!\n" "visitor") + +;; %s é um espaço reservado para uma string, substituído por "visitor". +;; \n é um caractere de nova linha. + +;; Vamos refinar nossa função utilizando `format': +(defun hello (name) + (insert (format "Hello %s!\n" name))) + +(hello "you") + +;; Vamos criar outra função que utilize `let': +(defun greeting (name) + (let ((your-name "Bastien")) + (insert (format "Hello %s!\n\nI am %s." + name ; the argument of the function + your-name ; the let-bound variable "Bastien" + )))) + +;; E executá-la: +(greeting "you") + +;; Algumas funções são interativas: +(read-from-minibuffer "Enter your name: ") + +;; Ao ser interpretada, esta função retorna o que você digitou no prompt. + +;; Vamos fazer nossa função `greeting' pedir pelo seu nome: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (insert (format "Hello!\n\nI am %s and you are %s." + from-name ; the argument of the function + your-name ; the let-bound var, entered at prompt + )))) + +(greeting "Bastien") + +;; Vamos finalizá-la fazendo-a exibir os resultados em outra janela: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (insert (format "Hello %s!\n\nI am %s." your-name from-name)) + (other-window 1))) + +;; Agora teste-a: +(greeting "Bastien") + +;; Respire um pouco. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Vamos armazenar uma lista de nomes: +(setq list-of-names '("Sarah" "Chloe" "Mathilde")) + +;; Pegue o primeiro elemento desta lista utilizando `car': +(car list-of-names) + +;; Pegue uma lista de todos os elementos, exceto o primeiro, utilizando +;; `cdr': +(cdr list-of-names) + +;; Adicione um elemento ao início da lista com `push': +(push "Stephanie" list-of-names) + +;; NOTA: `car' e `cdr' não modificam a lista, `push' sim. +;; Esta é uma diferença importante: algumas funções não têm qualquer +;; efeito colateral (como `car'), enquanto outras sim (como `push'). + +;; Vamos executar `hello' para cada elemento em `list-of-names': +(mapcar 'hello list-of-names) + +;; Refine `greeting' para saudar todos os nomes em `list-of-names': +(defun greeting () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (mapcar 'hello list-of-names) + (other-window 1)) + +(greeting) + +;; Você se lembra da função `hello' que nós definimos lá em cima? Ela +;; recebe um argumento, um nome. `mapcar' executa `hello', sucessivamente, +;; utilizando cada elemento de `list-of-names' como argumento para `hello'. + +;; Agora vamos arrumar, um pouco, o que nós temos escrito no buffer: + +(defun replace-hello-by-bonjour () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (search-forward "Hello") + (replace-match "Bonjour")) + (other-window 1)) + +;; (goto-char (point-min)) vai para o início do buffer. +;; (search-forward "Hello") busca pela string "Hello". +;; (while x y) interpreta a(s) sexp(s) y enquanto x retornar algo. +;; Se x retornar `nil' (nada), nós saímos do laço. + +(replace-hello-by-bonjour) + +;; Você deveria ver todas as ocorrências de "Hello" no buffer *test* +;; substituídas por "Bonjour". + +;; Você deveria, também, receber um erro: "Search failed: Hello". +;; +;; Para evitar este erro, você precisa dizer ao `search-forward' se ele +;; deveria parar de buscar em algum ponto no buffer, e se ele deveria +;; falhar de forma silenciosa quando nada fosse encontrado: + +;; (search-forward "Hello" nil t) dá conta do recado: + +;; O argumento `nil' diz: a busca não está limitada a uma posição. +;; O argumento `t' diz: falhe silenciosamente quando nada for encontrado. + +;; Nós utilizamos esta "sexp" na função abaixo, que não gera um erro: + +(defun hello-to-bonjour () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + ;; Say hello to names in `list-of-names' + (mapcar 'hello list-of-names) + (goto-char (point-min)) + ;; Replace "Hello" by "Bonjour" + (while (search-forward "Hello" nil t) + (replace-match "Bonjour")) + (other-window 1)) + +(hello-to-bonjour) + +;; Vamos colorir os nomes: + +(defun boldify-names () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (re-search-forward "Bonjour \\(.+\\)!" nil t) + (add-text-properties (match-beginning 1) + (match-end 1) + (list 'face 'bold))) + (other-window 1)) + +;; Esta função introduz `re-search-forward': ao invés de buscar +;; pela string "Bonjour", você busca por um padrão utilizando uma +;; "expressão regular" (abreviada pelo prefixo "re-"). + +;; A expressão regular é "Bonjour \\(.+\\)!" e lê-se: +;; a string "Bonjour ", e +;; um grupo de | que é o \\( ... \\) +;; quaisquer caracteres | que é o . +;; possivelmente repetidos | que é o + +;; e a string "!". + +;; Preparado? Teste! + +(boldify-names) + +;; `add-text-properties' adiciona... propriedades de texto, como uma fonte. + +;; OK, terminamos por aqui. Feliz Hacking! + +;; Se você quiser saber mais sobre uma variável ou função: +;; +;; C-h v uma-variável RET +;; C-h f uma-função RET +;; +;; Para ler o manual de Emacs Lisp que vem com o Emacs: +;; +;; C-h i m elisp RET +;; +;; Para ler uma introdução online ao Emacs Lisp: +;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html + +;; Agradecimentos a estas pessoas por seu feedback e sugestões: +;; - Wes Hardaker +;; - notbob +;; - Kevin Montuori +;; - Arne Babenhauserheide +;; - Alan Schmitt +;; - LinXitoW +;; - Aaron Meurer +``` -- cgit v1.2.3 From cf3149c4bde261aa35cde0cba34432a2f0bf649a Mon Sep 17 00:00:00 2001 From: Lucas Tadeu Teixeira Date: Tue, 13 Aug 2013 16:29:33 -0300 Subject: Fix typo on 'lang' tag. --- pt-br/python-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown index e08bb5a8..5afd46d0 100644 --- a/pt-br/python-pt.html.markdown +++ b/pt-br/python-pt.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - ["Vilson Vieira", "http://automata.cc"] -lang: pt-bf +lang: pt-br filename: learnpython-pt.py --- -- cgit v1.2.3 From a73d5c83c162569d0def8e481d85ece8d517b06a Mon Sep 17 00:00:00 2001 From: Sonia Keys Date: Tue, 13 Aug 2013 17:12:54 -0400 Subject: slashed comments --- go.html.markdown | 198 +++++++++++-------------------------------------------- 1 file changed, 38 insertions(+), 160 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 9888b37d..e7b35926 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -27,9 +27,7 @@ Go comes with a great standard library and an enthusiastic community. // Main is a special name declaring an executable rather than a library. package main -// An import declaration comes next. It declares library packages referenced -// in this file. The list must be exactly correct! Missing or unused packages -// are errors, not warnings. +// Import declaration declares library packages referenced in this file. import ( "fmt" // A package in the Go standard library "net/http" // Yes, a web server! @@ -39,27 +37,20 @@ import ( // A function definition. Main is special. It is the entry point for the // executable program. Love it or hate it, Go uses brace brackets. func main() { - // Println is a function that outputs a line to stdout. It can be - // called here because fmt has been imported and the function name - // "Println" is upper case. Symbols starting with an upper case letter - // are publicly visible. No other special syntax is needed to export - // something from a package. - // To call Println, qualify it with the package name, fmt. + // Println outputs a line to stdout. + // Qualify it with the package name, fmt. fmt.Println("Hello world!") // Call another function within this package. beyondHello() } -// Idiomatic Go uses camel case. Functions have parameters in parentheses. +// Functions have parameters in parentheses. // If there are no parameters, empty parens are still required. func beyondHello() { var x int // Variable declaration. Variables must be declared before use. x = 3 // Variable assignment. - // "Short" declarations use := syntax to declare and assign, infering the - // type from the right hand side as much as possible and using some - // defaults where the rhs could be interpreted different ways. - // Idiomatic Go uses short declarations in preference to var keyword. + // "Short" declarations use := to infer the type, declare, and assign. y := 4 sum, prod := learnMultiple(x, y) // function returns two values fmt.Println("sum:", sum, "prod:", prod) // simple output @@ -67,8 +58,6 @@ func beyondHello() { } // Functions can have parameters and (multiple!) return values. -// In declarations, the symbol precedes the type, and the type does not have -// to be repeated if it is the same for multiple symbols in a row. func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // return two values } @@ -87,12 +76,11 @@ can include line breaks.` // same string type f := 3.14195 // float64, an IEEE-754 64-bit floating point number c := 3 + 4i // complex128, represented internally with two float64s - // You can use var syntax with an initializer if you want - // something other than the default that a short declaration gives you. + // Var syntax with an initializers. var u uint = 7 // unsigned, but implementation dependent size as with int var pi float32 = 22. / 7 - // Or more idiomatically, use conversion syntax with a short declaration. + // Conversion syntax with a short declaration. n := byte('\n') // byte is an alias for uint8 // Arrays have size fixed at compile time. @@ -106,12 +94,8 @@ can include line breaks.` // same string type var d2 [][]float64 // declaration only, nothing allocated here bs := []byte("a slice") // type conversion syntax - p, q := learnMemory() // A little side bar. - // Did you read it? This short declaration declares p and q to be of - // type pointer to int. P is now pointing into a block of of 20 ints, but - // the only one accessible is the one that p is pointing at. There is - // no p++ to get at the next one. - fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + p, q := learnMemory() // declares p, q to be type pointer to int. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. // Maps are a dynamically growable associative array type, like the // hash or dictionary types of some other languages. @@ -130,26 +114,13 @@ can include line breaks.` // same string type // Go is fully garbage collected. It has pointers but no pointer arithmetic. // You can make a mistake with a nil pointer, but not by incrementing a pointer. func learnMemory() (p, q *int) { - // Named return values p and q have type pointer to int. They are - // initialized to nil at this point. Evaluating *p or *q here would cause - // a panic--a run time error. + // Named return values p and q have type pointer to int. p = new(int) // built-in function new allocates memory. // The allocated int is initialized to 0, p is no longer nil. s := make([]int, 20) // allocate 20 ints as a single block of memory s[3] = 7 // assign one of them r := -2 // declare another local variable - return &s[3], &r // Oh my. - // The line above returns two values, yes, and both of the expressions - // are valid. & takes the address of an object. Elements of a slice are - // addressable, and so are local variables. Built-in functions new and - // make explicitly allocate memory, but local objects can be allocated - // as needed. Here memory for r will be still be referenced after the - // function returns so it will be allocated as well. The int allocated - // with new on the other hand will no longer be referenced and can be - // garbage collected as needed by the Go runtime. The memory allocated - // with make will still be referenced at that one element, and so it - // cannot be garbage collected. All 20 ints remain in memory because - // one of them is still referenced. + return &s[3], &r // & takes the address of an object. } func expensiveComputation() int { @@ -161,16 +132,13 @@ func learnFlowControl() { if true { fmt.Println("told ya") } - // This is how we format the brace brackets. Formatting is standardized - // by the command line command "go fmt." Everybody does it. You will - // suffer endless disparaging remarks until you conform as well. + // Formatting is standardized by the command line command "go fmt." if false { // pout } else { // gloat } - // If statements can be chained of course, but it's idiomatic to use - // the handy switch statement instead. + // Use switch in preference to chained if statements. x := 1 switch x { case 0: @@ -179,10 +147,7 @@ func learnFlowControl() { case 2: // unreached } - // Like if, for doesn't use parens either. The scope of a variable - // declared in the first clause of the for statement is the statement - // and block. This x shadows the x declared above, but goes out of - // scope after the for block. + // Like if, for doesn't use parens either. for x := 0; x < 3; x++ { // ++ is a statement fmt.Println("iteration", x) } @@ -193,14 +158,11 @@ func learnFlowControl() { break // just kidding continue // unreached } - // The initial assignment of the for statement is handy enough that Go - // if statements can have one as well. Just like in the for statement, - // the := here means to declare and assign y first, then test y > x. - // The scope of y is limited to the if statement and block. + // As with for, := in an if statement means to declare and assign y first, + // then test y > x. if y := expensiveComputation(); y > x { x = y } - // Functions are first class objects and function literals are handy. // Function literals are closures. xBig := func() bool { return x > 100 // references x declared above switch statement. @@ -209,48 +171,25 @@ func learnFlowControl() { x /= 1e5 // this makes it == 10 fmt.Println("xBig:", xBig()) // false now - // When you need it, you'll love it. Actually Go's goto has been reformed - // a bit to avoid indeterminate states. You can't jump around variable - // declarations and you can't jump into blocks. + // When you need it, you'll love it. goto love love: learnInterfaces() // Good stuff coming up! } -// An interface is a list of functionality that a type supports. Notably -// missing from an interface definition is any declaration of which types -// implement the interface. Types simply implement an interface or they don't. -// -// An interface can have any number of methods, but it's actually common -// for an interface to have only single method. It is idiomatic in this -// case for the single method to be named with some action, and for the -// interface name to end in "er." -// -// An interface definition is one kind of a type definition. Interface is -// a built in type. Stringer is defined here as an interface type with one -// method, String. +// Define Stringer as an interface type with one method, String. type Stringer interface { String() string } -// Struct is another built in type. A struct aggregates "fields." -// Pair here has two fields, ints named x and y. +// Define pair as a struct with two fields, ints named x and y. type pair struct { x, y int } -// User defined types can have "methods." These are functions that operate -// in the context of an instance of the user defined type. The instance -// is called the "receiver" and is identified with a declaration just in front -// of the method name. The receiver here is "p." In most ways the receiver -// works just like a function parameter. -// -// This String method has the same name and return value as the String method -// of the Stringer interface. Further, String is the only method of Stringer. -// The pair type thus implements all methods of the Stringer interface and -// we say simply that pair implements Stringer. No other syntax is needed. -func (p pair) String() string { +// Define a method on type pair. Pair now implements Stringer. +func (p pair) String() string { // p is called the "receiver" // Sprintf is another public function in package fmt. // Dot syntax references fields of p. return fmt.Sprintf("(%d, %d)", p.x, p.y) @@ -261,21 +200,13 @@ func learnInterfaces() { // struct. The := syntax declares and initializes p to this struct. p := pair{3, 4} fmt.Println(p.String()) // call String method of p, of type pair. - var i Stringer // declare i of type Stringer. + var i Stringer // declare i of interface type Stringer. i = p // valid because pair implements Stringer // Call String method of i, of type Stringer. Output same as above. fmt.Println(i.String()) - // It gets more interesting now. We defined Stringer in this file, - // but the same interface happens to be defined in package fmt. - // Pair thus implements fmt.Stringer as well, and does so with no - // declaration of the fact. The definition of pair doesn't mention - // any interfaces at all, and of course the authors of fmt.Stringer - // had no idea that we were going to define pair. - // - // Functions in the fmt package know how to print some standard built in - // types, and beyond that, they see if a type implements fmt.Stringer. - // If so, they simply call the String method to ask an object for a - // printable representation of itself. + + // Functions in the fmt package call the String method to ask an object + // for a printable representation of itself. fmt.Println(p) // output same as above. Println calls String method. fmt.Println(i) // output same as above @@ -283,57 +214,23 @@ func learnInterfaces() { } func learnErrorHandling() { - // Sometimes you just need to know if something worked or not. Go has - // a ", ok" idiom for that. Something, a map expression here, but commonly - // a function, can return a boolean value of ok or not ok as a second - // return value. + // ", ok" idiom used to tell if something worked or not. m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // , ok is optional but see how useful it is. + if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. fmt.Println("no one there") } else { - fmt.Print(x) + fmt.Print(x) // x would be the value, if it were in the map. } // An error value communicates not just "ok" but more about the problem. if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value // prints "strconv.ParseInt: parsing "non-int": invalid syntax" fmt.Println(err) } - // error is a built in type. It is an interface with a single method, - // defined internally as, - // - // type error interface { - // Error() string - // } - // - // The string returned by the Error method is conventionally a printable - // error message. You can define your own error types by simply adding - // an Error method. Your type then automatically implements the error - // interface. We've seen two interfaces now, fmt.Stringer and error. - // We'll revisit interfaces a little later. Meanwhile, learnConcurrency() } -// Go has concurrency support in the language definition. The element of -// concurrent execution is called a "goroutine" and is similar to a thread -// but "lighter." Goroutines are multiplexed to operating system threads -// and a running Go program can have far more goroutines than available OS -// threads. If a machine has multiple CPU cores, goroutines can run in -// parallel. -// -// Go "Channels" allow communication between goroutines in a way that is -// both powerful and easy to understand. Channel is a type in Go and objects -// of type channel are first class objects--they can be assigned to variables, -// passed around to functions, and so on. A channel works conceptually much -// like a Unix pipe. You put data in at one end and it comes out the other. -// Channel "send" and "receive" operations are goroutine-safe. No locks -// or additional synchronization is needed. - -// Inc increments a number, and sends the result on a channel. The channel -// operation makes this function useful to run concurrently with other -// goroutines. There is no special declaration though that says this function -// is concurrent. It is an ordinary function that happens to have a -// parameter of channel type. +// c is a channel, a concurrency-safe communication object. func inc(i int, c chan int) { c <- i + 1 // <- is the "send" operator when a channel appears on the left. } @@ -357,10 +254,9 @@ func learnConcurrency() { cc := make(chan chan string) // a channel of channels. go func() { c <- 84 }() // start a new goroutine just to send a value go func() { cs <- "wordy" }() // again, for cs this time - // Select has syntax like a switch statement but is doing something - // pretty different. Each case involves a channel operation. In rough - // terms, a case is selected at random out of the cases that are ready to - // communicate. If none are ready, select waits for one to become ready. + // Select has syntax like a switch statement but each case involves + // a channel operation. It selects a case at random out of the cases + // that are ready to communicate. select { case i := <-c: // the value received can be assigned to a variable fmt.Println("it's a", i) @@ -375,37 +271,19 @@ func learnConcurrency() { learnWebProgramming() // Go does it. You want to do it too. } -// A simple web server can be created with a single function from the standard -// library. ListenAndServe, in package net/http, listens at the specified -// TCP address and uses an object that knows how to serve data. "Knows how" -// means "satisfies an interface." The second parameter is of type interface, -// specifically http.Handler. http.Handler has a single method, ServeHTTP. +// A single function from package http starts a web server. func learnWebProgramming() { + // ListenAndServe first parameter is TCP address to listen at. + // Second parameter is an interface, specifically http.Handler. err := http.ListenAndServe(":8080", pair{}) - // Error returns are ubiquitous in Go. Always check error returns and - // do something with them. Often it's enough to print it out as an - // indication of what failed. Of course there are better things to do - // in production code: log it, try something else, shut everything down, - // and so on. - fmt.Println(err) + fmt.Println(err) // don't ignore errors } -// You can make any type into an http.Hander by implementing ServeHTTP. -// Lets use the pair type we defined earlier, just because we have it -// sitting around. ServeHTTP has two parameters. The request parameter -// is a struct that we'll ignore here. http.ResponseWriter is yet another -// interface! Here it is an object supplied to us with the guarantee that -// it implements its interface, which includes a method Write. -// We call this Write method to serve data. +// Make pair an http.Handler by implementing its only method, ServeHTTP. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Serve data with a method of http.ResponseWriter w.Write([]byte("You learned Go in Y minutes!")) } - -// And that's it for a proof-of-concept web server! If you run this program -// it will print out all the lines from the earlier parts of the lesson, then -// start this web server. To hit the web server, just point a browser at -// localhost:8080 and you'll see the message. (Then you can probably press -// ctrl-C to kill it.) ``` ## Further Reading -- cgit v1.2.3 From ea853dfa674a1be2c6d5e54b1307bf80693cf01d Mon Sep 17 00:00:00 2001 From: Nick LaMuro Date: Tue, 13 Aug 2013 17:42:03 -0500 Subject: Fixes array typos --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 68c5b524..46bfbb7c 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -117,11 +117,11 @@ status == :approved #=> false # Arrays # This is an array -[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arrays can contain different types of items -array = [1, "hello", false] #=> => [1, "hello", false] +[1, "hello", false] #=> [1, "hello", false] # Arrays can be indexed # From the front -- cgit v1.2.3 From 7af884a9407c0b79aaede1edd3539e13a55552c8 Mon Sep 17 00:00:00 2001 From: Nick LaMuro Date: Tue, 13 Aug 2013 17:46:33 -0500 Subject: Fixes spacing issues --- ruby.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 46bfbb7c..963d1fc1 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -173,9 +173,9 @@ new_hash.keys #=> [:defcon, :action] if true "if statement" elsif false - "else if, optional" + "else if, optional" else - "else, also optional" + "else, also optional" end for counter in 1..5 @@ -190,7 +190,8 @@ end # HOWEVER, No-one uses for loops. # Instead you should use the "each" method and pass it a block. # A block is a bunch of code that you can pass to a method like "each". -# It is analogous to lambdas, anonymous functions or closures in other programming languages. +# It is analogous to lambdas, anonymous functions or closures in other +# programming languages. # # The "each" method of a range runs the block once for each element of the range. # The block is passed a counter as a parameter. -- cgit v1.2.3 From 9fd70ffbb12e92a4bd129cfbe28d91e07138c398 Mon Sep 17 00:00:00 2001 From: Nick LaMuro Date: Tue, 13 Aug 2013 17:47:52 -0500 Subject: Giving myself some credit... I guess --- ruby.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 963d1fc1..19f2ec86 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] --- ```ruby -- cgit v1.2.3 From c5a3e191405e6722239c951635a2205c93d55bde Mon Sep 17 00:00:00 2001 From: hbc Date: Wed, 14 Aug 2013 08:19:05 +0800 Subject: Improved some translations, made the code more PEP8 --- zh-cn/python-cn.html.markdown | 277 +++++++++++++++++++++--------------------- 1 file changed, 139 insertions(+), 138 deletions(-) diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown index 764eed54..51efaac3 100755 --- a/zh-cn/python-cn.html.markdown +++ b/zh-cn/python-cn.html.markdown @@ -17,6 +17,7 @@ Python 由 Guido Van Rossum 在90年代初创建。 它现在是最流行的语 如果是Python 3,请在网络上寻找其他教程 ```python + # 单行注释 """ 多行字符串可以用 三个引号包裹,不过这也可以被当做 @@ -28,84 +29,84 @@ Python 由 Guido Van Rossum 在90年代初创建。 它现在是最流行的语 #################################################### # 数字类型 -3 #=> 3 +3 # => 3 # 简单的算数 -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 # 整数的除法会自动取整 -5 / 2 #=> 2 +5 / 2 # => 2 # 要做精确的除法,我们需要引入浮点数 2.0 # 浮点数 -11.0 / 4.0 #=> 2.75 好多了 +11.0 / 4.0 # => 2.75 精确多了 # 括号具有最高优先级 -(1 + 3) * 2 #=> 8 +(1 + 3) * 2 # => 8 -# 布尔值也是原始数据类型 +# 布尔值也是基本的数据类型 True False -# 用not来取非 -not True #=> False -not False #=> True +# 用 not 来取非 +not True # => False +not False # => True # 相等 -1 == 1 #=> True -2 == 1 #=> False +1 == 1 # => True +2 == 1 # => False # 不等 -1 != 1 #=> False -2 != 1 #=> True +1 != 1 # => False +2 != 1 # => True # 更多的比较操作符 -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True # 比较运算可以连起来写! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False +1 < 2 < 3 # => True +2 < 3 < 2 # => False -# 字符串通过"或'括起来 +# 字符串通过 " 或 ' 括起来 "This is a string." 'This is also a string.' # 字符串通过加号拼接 -"Hello " + "world!" #=> "Hello world!" +"Hello " + "world!" # => "Hello world!" # 字符串可以被视为字符的列表 -"This is a string"[0] #=> 'T' +"This is a string"[0] # => 'T' # % 可以用来格式化字符串 "%s can be %s" % ("strings", "interpolated") -# 也可以用format方法来格式化字符串 +# 也可以用 format 方法来格式化字符串 # 推荐使用这个方法 "{0} can be {1}".format("strings", "formatted") # 也可以用变量名代替数字 "{name} wants to eat {food}".format(name="Bob", food="lasagna") # None 是对象 -None #=> None +None # => None # 不要用相等 `==` 符号来和None进行比较 -# 要用 `is` -"etc" is None #=> False -None is None #=> True +# 要用 `is` +"etc" is None # => False +None is None # => True # 'is' 可以用来比较对象的相等性 # 这个操作符在比较原始数据时没多少用,但是比较对象时必不可少 -# None, 0, 和空字符串都被算作False -# 其他的均为True -0 == False #=> True -"" == False #=> True +# None, 0, 和空字符串都被算作 False +# 其他的均为 True +0 == False # => True +"" == False # => True #################################################### @@ -116,16 +117,16 @@ None is None #=> True print "I'm Python. Nice to meet you!" -# 给变量赋值前不需要事先生命 -some_var = 5 # 规范用小写字母和下划线来做为变量名 -some_var #=> 5 +# 给变量赋值前不需要事先声明 +some_var = 5 # 一般建议使用小写字母和下划线组合来做为变量名 +some_var # => 5 -# 访问之前为赋值的变量会抛出异常 -# 查看控制流程一节来了解异常处理 -some_other_var # 抛出命名异常 +# 访问未赋值的变量会抛出异常 +# 可以查看控制流程一节来了解如何异常处理 +some_other_var # 抛出 NameError -# if语句可以作为表达式来使用 -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" +# if 语句可以作为表达式来使用 +"yahoo!" if 3 > 2 else 2 # => "yahoo!" # 列表用来保存序列 li = [] @@ -133,64 +134,64 @@ li = [] other_li = [4, 5, 6] # 在列表末尾添加元素 -li.append(1) #li 现在是 [1] -li.append(2) #li 现在是 [1, 2] -li.append(4) #li 现在是 [1, 2, 4] -li.append(3) #li 现在是 [1, 2, 4, 3] +li.append(1) # li 现在是 [1] +li.append(2) # li 现在是 [1, 2] +li.append(4) # li 现在是 [1, 2, 4] +li.append(3) # li 现在是 [1, 2, 4, 3] # 移除列表末尾元素 -li.pop() #=> 3 and li is now [1, 2, 4] -# 放回来 +li.pop() # => 3 li 现在是 [1, 2, 4] +# 重新加进去 li.append(3) # li is now [1, 2, 4, 3] again. # 像其他语言访问数组一样访问列表 -li[0] #=> 1 +li[0] # => 1 # 访问最后一个元素 -li[-1] #=> 3 +li[-1] # => 3 # 越界会抛出异常 -li[4] # 抛出越界异常 +li[4] # 抛出越界异常 # 切片语法需要用到列表的索引访问 # 可以看做数学之中左闭右开区间 -li[1:3] #=> [2, 4] +li[1:3] # => [2, 4] # 省略开头的元素 -li[2:] #=> [4, 3] +li[2:] # => [4, 3] # 省略末尾的元素 -li[:3] #=> [1, 2, 4] +li[:3] # => [1, 2, 4] # 删除特定元素 -del li[2] # li 现在是 [1, 2, 3] +del li[2] # li 现在是 [1, 2, 3] # 合并列表 -li + other_li #=> [1, 2, 3, 4, 5, 6] - 不改变这两个列表 +li + other_li # => [1, 2, 3, 4, 5, 6] - 并不会不改变这两个列表 -# 通过拼接合并列表 -li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6] +# 通过拼接来合并列表 +li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6] -# 用in来返回元素是否在列表中 -1 in li #=> True +# 用 in 来返回元素是否在列表中 +1 in li # => True # 返回列表长度 -len(li) #=> 6 +len(li) # => 6 -# 元组类似于列表,但是他是不可改变的 +# 元组类似于列表,但它是不可改变的 tup = (1, 2, 3) -tup[0] #=> 1 +tup[0] # => 1 tup[0] = 3 # 类型错误 # 对于大多数的列表操作,也适用于元组 -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True # 你可以将元组解包赋给多个变量 -a, b, c = (1, 2, 3) # a是1,b是2,c是3 -# 如果不加括号,那么会自动视为元组 +a, b, c = (1, 2, 3) # a 是 1,b 是 2,c 是 3 +# 如果不加括号,将会被自动视为元组 d, e, f = 4, 5, 6 # 现在我们可以看看交换两个数字是多么容易的事 -e, d = d, e # d是5,e是4 +e, d = d, e # d 是 5,e 是 4 # 字典用来储存映射关系 @@ -199,59 +200,59 @@ empty_dict = {} filled_dict = {"one": 1, "two": 2, "three": 3} # 字典也用中括号访问元素 -filled_dict["one"] #=> 1 +filled_dict["one"] # => 1 # 把所有的键保存在列表中 -filled_dict.keys() #=> ["three", "two", "one"] +filled_dict.keys() # => ["three", "two", "one"] # 键的顺序并不是唯一的,得到的不一定是这个顺序 # 把所有的值保存在列表中 -filled_dict.values() #=> [3, 2, 1] +filled_dict.values() # => [3, 2, 1] # 和键的顺序相同 # 判断一个键是否存在 -"one" in filled_dict #=> True -1 in filled_dict #=> False +"one" in filled_dict # => True +1 in filled_dict # => False -# 查询一个不存在的键会抛出键异常 -filled_dict["four"] # 键异常 +# 查询一个不存在的键会抛出 KeyError +filled_dict["four"] # KeyError -# 用get方法来避免键异常 -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# get方法支持在不存在的时候返回一个默认值 -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 +# 用 get 方法来避免 KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# get 方法支持在不存在的时候返回一个默认值 +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 -# Setdefault是一个更安全的添加字典元素的方法 -filled_dict.setdefault("five", 5) #filled_dict["five"] 的值为 5 -filled_dict.setdefault("five", 6) #filled_dict["five"] 的值仍然是 5 +# setdefault 是一个更安全的添加字典元素的方法 +filled_dict.setdefault("five", 5) # filled_dict["five"] 的值为 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] 的值仍然是 5 # 集合储存无顺序的元素 empty_set = set() -# 出事话一个集合 -some_set = set([1,2,2,3,4]) # filled_set 现在是 set([1, 2, 3, 4]) +# 初始化一个集合 +some_set = set([1, 2, 2, 3, 4]) # filled_set 现在是 set([1, 2, 3, 4]) # Python 2.7 之后,大括号可以用来表示集合 -filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} -# 为集合添加元素 -filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5} +# 向集合添加元素 +filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5} -# 用&来实现集合的交 +# 用 & 来计算集合的交 other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} +filled_set & other_set # => {3, 4, 5} -# 用|来实现集合的并 -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} +# 用 | 来计算集合的并 +filled_set | other_set # => {1, 2, 3, 4, 5, 6} -# 用-来实现集合的差 -{1,2,3,4} - {2,3,5} #=> {1, 4} +# 用 - 来计算集合的差 +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} -# 用in来判断元素是否存在于集合中 -2 in filled_set #=> True -10 in filled_set #=> False +# 用 in 来判断元素是否存在于集合中 +2 in filled_set # => True +10 in filled_set # => False #################################################### @@ -261,13 +262,13 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6} # 新建一个变量 some_var = 5 -# 这是个if语句,在python中缩进是很重要的。 -# 会输出 "some var is smaller than 10" +# 这是个 if 语句,在 python 中缩进是很重要的。 +# 下面的代码片段将会输出 "some var is smaller than 10" if some_var > 10: print "some_var is totally bigger than 10." elif some_var < 10: # 这个 elif 语句是不必须的 print "some_var is smaller than 10." -else: # 也不是必须的 +else: # 这个 else 也不是必须的 print "some_var is indeed 10." @@ -281,7 +282,7 @@ else: # 也不是必须的 for animal in ["dog", "cat", "mouse"]: # 你可以用 % 来格式化字符串 print "%s is a mammal" % animal - + """ `range(number)` 返回从0到给定数字的列表 输出: @@ -294,7 +295,7 @@ for i in range(4): print i """ -While循环 +while 循环 输出: 0 1 @@ -304,29 +305,29 @@ While循环 x = 0 while x < 4: print x - x += 1 # Shorthand for x = x + 1 + x += 1 # x = x + 1 的简写 -# 用 try/except块来处理异常 +# 用 try/except 块来处理异常 # Python 2.6 及以上适用: try: - # 用raise来抛出异常 + # 用 raise 来抛出异常 raise IndexError("This is an index error") except IndexError as e: - pass # Pass就是什么都不做,不过通常这里会做一些恢复工作 + pass # pass 就是什么都不做,不过通常这里会做一些恢复工作 #################################################### ## 4. 函数 #################################################### -# 用def来新建函数 +# 用 def 来新建函数 def add(x, y): print "x is %s and y is %s" % (x, y) - return x + y # Return values with a return statement + return x + y # 通过 return 来返回值 # 调用带参数的函数 -add(5, 6) #=> 输出 "x is 5 and y is 6" 返回 11 +add(5, 6) # => 输出 "x is 5 and y is 6" 返回 11 # 通过关键字赋值来调用函数 add(y=6, x=5) # 顺序是无所谓的 @@ -335,7 +336,7 @@ add(y=6, x=5) # 顺序是无所谓的 def varargs(*args): return args -varargs(1, 2, 3) #=> (1,2,3) +varargs(1, 2, 3) # => (1,2,3) # 我们也可以定义接受多个变量的函数,这些变量是按照关键字排列的 @@ -343,7 +344,7 @@ def keyword_args(**kwargs): return kwargs # 实际效果: -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} # 你也可以同时将一个函数定义成两种形式 def all_the_args(*args, **kwargs): @@ -355,38 +356,38 @@ all_the_args(1, 2, a=3, b=4) prints: {"a": 3, "b": 4} """ -# 当调用函数的时候,我们也可以和之前所做的相反,把元组和字典展开为参数 +# 当调用函数的时候,我们也可以进行相反的操作,把元组和字典展开为参数 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) +all_the_args(*args) # 等价于 foo(1, 2, 3, 4) +all_the_args(**kwargs) # 等价于 foo(a=3, b=4) +all_the_args(*args, **kwargs) # 等价于 foo(1, 2, 3, 4, a=3, b=4) -# Python 有一等函数: +# 函数在 python 中是一等公民 def create_adder(x): def adder(y): return x + y return adder add_10 = create_adder(10) -add_10(3) #=> 13 +add_10(3) # => 13 # 匿名函数 -(lambda x: x > 2)(3) #=> True +(lambda x: x > 2)(3) # => True # 内置高阶函数 -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # 可以用列表方法来对高阶函数进行更巧妙的引用 -[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] +[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. 类 #################################################### -# 我们新建的类是从object类中继承的 +# 我们新建的类是从 object 类中继承的 class Human(object): # 类属性,由所有类的对象共享 @@ -397,9 +398,9 @@ class Human(object): # 将参数赋给对象成员属性 self.name = name - # 成员方法,参数要有self + # 成员方法,参数要有 self def say(self, msg): - return "%s: %s" % (self.name, msg) + return "%s: %s" % (self.name, msg) # 类方法由所有类的对象共享 # 这类方法在调用时,会把类本身传给第一个参数 @@ -421,15 +422,15 @@ j = Human("Joel") print j.say("hello") # 输出 "Joel: hello" # 访问类的方法 -i.get_species() #=> "H. sapiens" +i.get_species() # => "H. sapiens" # 改变共享属性 Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" # 访问静态变量 -Human.grunt() #=> "*grunt*" +Human.grunt() # => "*grunt*" #################################################### @@ -438,12 +439,12 @@ Human.grunt() #=> "*grunt*" # 我们可以导入其他模块 import math -print math.sqrt(16) #=> 4 +print math.sqrt(16) # => 4 -# 我们也可以从一个模块中特定的函数 +# 我们也可以从一个模块中导入特定的函数 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 # 从模块中导入所有的函数 # 警告:不推荐使用 @@ -451,13 +452,13 @@ from math import * # 简写模块名 import math as m -math.sqrt(16) == m.sqrt(16) #=> True +math.sqrt(16) == m.sqrt(16) # => True # Python的模块其实只是普通的python文件 # 你也可以创建自己的模块,并且导入它们 # 模块的名字就和文件的名字相同 -# 以可以通过下面的信息找找要成为模块需要什么属性或方法 +# 也可以通过下面的方法查看模块中有什么属性和方法 import math dir(math) -- cgit v1.2.3 From f96fa02fe8985872c0f12256c02e54c752abee27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9C=84=ED=82=A4=EB=B6=81=EC=8A=A4?= Date: Wed, 14 Aug 2013 09:54:44 +0900 Subject: Update javascript-kr.html.markdown --- ko-kr/javascript-kr.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index 79f5d88b..e5517aa8 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -268,7 +268,7 @@ function sayHelloInFiveSeconds(name){ // 기다리지 않고 실행을 마칩니다. 하지만 5초가 지나면 inner에서도 // prompt의 값에 접근할 수 있습니다. } -sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s +sayHelloInFiveSeconds("Adam") // 5초 내로 "Hello, Adam!"이라고 적힌 팝업이 표시됨 /////////////////////////////////// // 5. 객체 심화; 생성자와 프로토타입 @@ -403,7 +403,7 @@ String.prototype.firstCharacter = function(){ // 예를 들어, Object.create가 모든 구현체에서 사용 가능한 것은 아니라고 // 했지만 아래의 폴리필을 이용해 Object.create를 여전히 사용할 수 있습니다. -if (Object.create === undefined){ // don't overwrite it if it exists +if (Object.create === undefined){ // 이미 존재하면 덮어쓰지 않음 Object.create = function(proto){ // 올바른 프로토타입을 가지고 임시 생성자를 만듬 var Constructor = function(){} @@ -432,4 +432,4 @@ MDN의 ['자바스크립트 재입문'](https://developer.mozilla.org/ko/docs/A_ 더불어 이 글에 직접적으로 기여한 분들로, 내용 중 일부는 이 사이트에 있는 루이 딘(Louie Dihn)의 파이썬 튜토리얼과 모질라 개발자 네트워크에 있는 -[자바스크립트 튜토리얼](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)을 참고했습니다. \ No newline at end of file +[자바스크립트 튜토리얼](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)을 참고했습니다. -- cgit v1.2.3 From e7eb0e1281d0f360ddca17a9b97be4c363c2c276 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9C=84=ED=82=A4=EB=B6=81=EC=8A=A4?= Date: Wed, 14 Aug 2013 10:13:10 +0900 Subject: Update lua-kr.html.markdown --- ko-kr/lua-kr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index 3f6223d6..7e8c2bc0 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -327,7 +327,7 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- 필요할 경우, 하위 클래스의 new()는 기반 클래스의 new()와 유사합니다. function LoudDog:new() newObj = {} - -- set up newObj + -- newObj를 구성 self.__index = self return setmetatable(newObj, self) end @@ -420,4 +420,4 @@ learn.lua로 저장한 후 "lua learn.lua"를 실행해 보세요! 이 글은 tylerneylon.com에 처음으로 써본 글이며, Github의 Gist에서도 확인할 수 있습니다. -루아로 즐거운 시간을 보내세요! \ No newline at end of file +루아로 즐거운 시간을 보내세요! -- cgit v1.2.3 From 4d705abd99dbe13fbdb50b5d5e74d6fe8c18f559 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 13 Aug 2013 19:59:19 -0700 Subject: Piddly things --- go.html.markdown | 354 +++++++++++++++++++++---------------------- pt-br/elisp-pt.html.markdown | 16 +- 2 files changed, 185 insertions(+), 185 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index e7b35926..4db76a49 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -18,7 +18,7 @@ help with large-scale programming. Go comes with a great standard library and an enthusiastic community. -```Go +```go // Single line comment /* Multi- line comment */ @@ -29,260 +29,260 @@ package main // Import declaration declares library packages referenced in this file. import ( - "fmt" // A package in the Go standard library - "net/http" // Yes, a web server! - "strconv" // String conversions + "fmt" // A package in the Go standard library + "net/http" // Yes, a web server! + "strconv" // String conversions ) // A function definition. Main is special. It is the entry point for the // executable program. Love it or hate it, Go uses brace brackets. func main() { - // Println outputs a line to stdout. - // Qualify it with the package name, fmt. - fmt.Println("Hello world!") + // Println outputs a line to stdout. + // Qualify it with the package name, fmt. + fmt.Println("Hello world!") - // Call another function within this package. - beyondHello() + // Call another function within this package. + beyondHello() } // Functions have parameters in parentheses. // If there are no parameters, empty parens are still required. func beyondHello() { - var x int // Variable declaration. Variables must be declared before use. - x = 3 // Variable assignment. - // "Short" declarations use := to infer the type, declare, and assign. - y := 4 - sum, prod := learnMultiple(x, y) // function returns two values - fmt.Println("sum:", sum, "prod:", prod) // simple output - learnTypes() // < y minutes, learn more! + var x int // Variable declaration. Variables must be declared before use. + x = 3 // Variable assignment. + // "Short" declarations use := to infer the type, declare, and assign. + y := 4 + sum, prod := learnMultiple(x, y) // function returns two values + fmt.Println("sum:", sum, "prod:", prod) // simple output + learnTypes() // < y minutes, learn more! } // Functions can have parameters and (multiple!) return values. func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // return two values + return x + y, x * y // return two values } // Some built-in types and literals. func learnTypes() { - // Short declaration usually gives you what you want. - s := "Learn Go!" // string type + // Short declaration usually gives you what you want. + s := "Learn Go!" // string type - s2 := `A "raw" string literal + s2 := `A "raw" string literal can include line breaks.` // same string type - // non-ASCII literal. Go source is UTF-8. - g := 'Σ' // rune type, an alias for uint32, holds a UTF-8 code point + // non-ASCII literal. Go source is UTF-8. + g := 'Σ' // rune type, an alias for uint32, holds a UTF-8 code point - f := 3.14195 // float64, an IEEE-754 64-bit floating point number - c := 3 + 4i // complex128, represented internally with two float64s + f := 3.14195 // float64, an IEEE-754 64-bit floating point number + c := 3 + 4i // complex128, represented internally with two float64s - // Var syntax with an initializers. - var u uint = 7 // unsigned, but implementation dependent size as with int - var pi float32 = 22. / 7 + // Var syntax with an initializers. + var u uint = 7 // unsigned, but implementation dependent size as with int + var pi float32 = 22. / 7 - // Conversion syntax with a short declaration. - n := byte('\n') // byte is an alias for uint8 + // Conversion syntax with a short declaration. + n := byte('\n') // byte is an alias for uint8 - // Arrays have size fixed at compile time. - var a4 [4]int // an array of 4 ints, initialized to all 0 - a3 := [...]int{3, 1, 5} // an array of 3 ints, initialized as shown + // Arrays have size fixed at compile time. + var a4 [4]int // an array of 4 ints, initialized to all 0 + a3 := [...]int{3, 1, 5} // an array of 3 ints, initialized as shown - // Slices have dynamic size. Arrays and slices each have advantages - // but use cases for slices are much more common. - s3 := []int{4, 5, 9} // compare to a3. no ellipsis here - s4 := make([]int, 4) // allocates slice of 4 ints, initialized to all 0 - var d2 [][]float64 // declaration only, nothing allocated here - bs := []byte("a slice") // type conversion syntax + // Slices have dynamic size. Arrays and slices each have advantages + // but use cases for slices are much more common. + s3 := []int{4, 5, 9} // compare to a3. no ellipsis here + s4 := make([]int, 4) // allocates slice of 4 ints, initialized to all 0 + var d2 [][]float64 // declaration only, nothing allocated here + bs := []byte("a slice") // type conversion syntax - p, q := learnMemory() // declares p, q to be type pointer to int. - fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + p, q := learnMemory() // declares p, q to be type pointer to int. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. - // Maps are a dynamically growable associative array type, like the - // hash or dictionary types of some other languages. - m := map[string]int{"three": 3, "four": 4} - m["one"] = 1 + // Maps are a dynamically growable associative array type, like the + // hash or dictionary types of some other languages. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 - // Unused variables are an error in Go. - // The underbar lets you "use" a variable but discard its value. - _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs - // Output of course counts as using a variable. - fmt.Println(s, c, a4, s3, d2, m) + // Unused variables are an error in Go. + // The underbar lets you "use" a variable but discard its value. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Output of course counts as using a variable. + fmt.Println(s, c, a4, s3, d2, m) - learnFlowControl() // back in the flow + learnFlowControl() // back in the flow } // Go is fully garbage collected. It has pointers but no pointer arithmetic. // You can make a mistake with a nil pointer, but not by incrementing a pointer. func learnMemory() (p, q *int) { - // Named return values p and q have type pointer to int. - p = new(int) // built-in function new allocates memory. - // The allocated int is initialized to 0, p is no longer nil. - s := make([]int, 20) // allocate 20 ints as a single block of memory - s[3] = 7 // assign one of them - r := -2 // declare another local variable - return &s[3], &r // & takes the address of an object. + // Named return values p and q have type pointer to int. + p = new(int) // built-in function new allocates memory. + // The allocated int is initialized to 0, p is no longer nil. + s := make([]int, 20) // allocate 20 ints as a single block of memory + s[3] = 7 // assign one of them + r := -2 // declare another local variable + return &s[3], &r // & takes the address of an object. } func expensiveComputation() int { - return 1e6 + return 1e6 } func learnFlowControl() { - // If statements require brace brackets, and do not require parens. - if true { - fmt.Println("told ya") - } - // Formatting is standardized by the command line command "go fmt." - if false { - // pout - } else { - // gloat - } - // Use switch in preference to chained if statements. - x := 1 - switch x { - case 0: - case 1: - // cases don't "fall through" - case 2: - // unreached - } - // Like if, for doesn't use parens either. - for x := 0; x < 3; x++ { // ++ is a statement - fmt.Println("iteration", x) - } - // x == 1 here. - - // For is the only loop statement in Go, but it has alternate forms. - for { // infinite loop - break // just kidding - continue // unreached - } - // As with for, := in an if statement means to declare and assign y first, - // then test y > x. - if y := expensiveComputation(); y > x { - x = y - } - // Function literals are closures. - xBig := func() bool { - return x > 100 // references x declared above switch statement. - } - fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x) - x /= 1e5 // this makes it == 10 - fmt.Println("xBig:", xBig()) // false now - - // When you need it, you'll love it. - goto love + // If statements require brace brackets, and do not require parens. + if true { + fmt.Println("told ya") + } + // Formatting is standardized by the command line command "go fmt." + if false { + // pout + } else { + // gloat + } + // Use switch in preference to chained if statements. + x := 1 + switch x { + case 0: + case 1: + // cases don't "fall through" + case 2: + // unreached + } + // Like if, for doesn't use parens either. + for x := 0; x < 3; x++ { // ++ is a statement + fmt.Println("iteration", x) + } + // x == 1 here. + + // For is the only loop statement in Go, but it has alternate forms. + for { // infinite loop + break // just kidding + continue // unreached + } + // As with for, := in an if statement means to declare and assign y first, + // then test y > x. + if y := expensiveComputation(); y > x { + x = y + } + // Function literals are closures. + xBig := func() bool { + return x > 100 // references x declared above switch statement. + } + fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x) + x /= 1e5 // this makes it == 10 + fmt.Println("xBig:", xBig()) // false now + + // When you need it, you'll love it. + goto love love: - learnInterfaces() // Good stuff coming up! + learnInterfaces() // Good stuff coming up! } // Define Stringer as an interface type with one method, String. type Stringer interface { - String() string + String() string } // Define pair as a struct with two fields, ints named x and y. type pair struct { - x, y int + x, y int } // Define a method on type pair. Pair now implements Stringer. func (p pair) String() string { // p is called the "receiver" - // Sprintf is another public function in package fmt. - // Dot syntax references fields of p. - return fmt.Sprintf("(%d, %d)", p.x, p.y) + // Sprintf is another public function in package fmt. + // Dot syntax references fields of p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { - // Brace syntax is a "struct literal." It evaluates to an initialized - // struct. The := syntax declares and initializes p to this struct. - p := pair{3, 4} - fmt.Println(p.String()) // call String method of p, of type pair. - var i Stringer // declare i of interface type Stringer. - i = p // valid because pair implements Stringer - // Call String method of i, of type Stringer. Output same as above. - fmt.Println(i.String()) - - // Functions in the fmt package call the String method to ask an object - // for a printable representation of itself. - fmt.Println(p) // output same as above. Println calls String method. - fmt.Println(i) // output same as above - - learnErrorHandling() + // Brace syntax is a "struct literal." It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. + p := pair{3, 4} + fmt.Println(p.String()) // call String method of p, of type pair. + var i Stringer // declare i of interface type Stringer. + i = p // valid because pair implements Stringer + // Call String method of i, of type Stringer. Output same as above. + fmt.Println(i.String()) + + // Functions in the fmt package call the String method to ask an object + // for a printable representation of itself. + fmt.Println(p) // output same as above. Println calls String method. + fmt.Println(i) // output same as above + + learnErrorHandling() } func learnErrorHandling() { - // ", ok" idiom used to tell if something worked or not. - m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. - fmt.Println("no one there") - } else { - fmt.Print(x) // x would be the value, if it were in the map. - } - // An error value communicates not just "ok" but more about the problem. - if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value - // prints "strconv.ParseInt: parsing "non-int": invalid syntax" - fmt.Println(err) - } - // We'll revisit interfaces a little later. Meanwhile, - learnConcurrency() + // ", ok" idiom used to tell if something worked or not. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. + fmt.Println("no one there") + } else { + fmt.Print(x) // x would be the value, if it were in the map. + } + // An error value communicates not just "ok" but more about the problem. + if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value + // prints "strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // We'll revisit interfaces a little later. Meanwhile, + learnConcurrency() } // c is a channel, a concurrency-safe communication object. func inc(i int, c chan int) { - c <- i + 1 // <- is the "send" operator when a channel appears on the left. + c <- i + 1 // <- is the "send" operator when a channel appears on the left. } // We'll use inc to increment some numbers concurrently. func learnConcurrency() { - // Same make function used earlier to make a slice. Make allocates and - // initializes slices, maps, and channels. - c := make(chan int) - // Start three concurrent goroutines. Numbers will be incremented - // concurrently, perhaps in parallel if the machine is capable and - // properly configured. All three send to the same channel. - go inc(0, c) // go is a statement that starts a new goroutine. - go inc(10, c) - go inc(-805, c) - // Read three results from the channel and print them out. - // There is no telling in what order the results will arrive! - fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. - - cs := make(chan string) // another channel, this one handles strings. - cc := make(chan chan string) // a channel of channels. - go func() { c <- 84 }() // start a new goroutine just to send a value - go func() { cs <- "wordy" }() // again, for cs this time - // Select has syntax like a switch statement but each case involves - // a channel operation. It selects a case at random out of the cases - // that are ready to communicate. - select { - case i := <-c: // the value received can be assigned to a variable - fmt.Println("it's a", i) - case <-cs: // or the value received can be discarded - fmt.Println("it's a string") - case <-cc: // empty channel, not ready for communication. - fmt.Println("didn't happen.") - } - // At this point a value was taken from either c or cs. One of the two - // goroutines started above has completed, the other will remain blocked. - - learnWebProgramming() // Go does it. You want to do it too. + // Same make function used earlier to make a slice. Make allocates and + // initializes slices, maps, and channels. + c := make(chan int) + // Start three concurrent goroutines. Numbers will be incremented + // concurrently, perhaps in parallel if the machine is capable and + // properly configured. All three send to the same channel. + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) + // Read three results from the channel and print them out. + // There is no telling in what order the results will arrive! + fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. + + cs := make(chan string) // another channel, this one handles strings. + cc := make(chan chan string) // a channel of channels. + go func() { c <- 84 }() // start a new goroutine just to send a value + go func() { cs <- "wordy" }() // again, for cs this time + // Select has syntax like a switch statement but each case involves + // a channel operation. It selects a case at random out of the cases + // that are ready to communicate. + select { + case i := <-c: // the value received can be assigned to a variable + fmt.Println("it's a", i) + case <-cs: // or the value received can be discarded + fmt.Println("it's a string") + case <-cc: // empty channel, not ready for communication. + fmt.Println("didn't happen.") + } + // At this point a value was taken from either c or cs. One of the two + // goroutines started above has completed, the other will remain blocked. + + learnWebProgramming() // Go does it. You want to do it too. } // A single function from package http starts a web server. func learnWebProgramming() { - // ListenAndServe first parameter is TCP address to listen at. - // Second parameter is an interface, specifically http.Handler. - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // don't ignore errors + // ListenAndServe first parameter is TCP address to listen at. + // Second parameter is an interface, specifically http.Handler. + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // don't ignore errors } // Make pair an http.Handler by implementing its only method, ServeHTTP. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Serve data with a method of http.ResponseWriter - w.Write([]byte("You learned Go in Y minutes!")) + // Serve data with a method of http.ResponseWriter + w.Write([]byte("You learned Go in Y minutes!")) } ``` diff --git a/pt-br/elisp-pt.html.markdown b/pt-br/elisp-pt.html.markdown index 9031cad9..fc2d1e40 100644 --- a/pt-br/elisp-pt.html.markdown +++ b/pt-br/elisp-pt.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Bastien Guerry", "http://bzg.fr"] translators: - ["Lucas Tadeu Teixeira", "http://ltt.me"] -lang: pt-br +lang: pt-br filename: learn-emacs-lisp-pt.el --- @@ -30,9 +30,9 @@ filename: learn-emacs-lisp-pt.el ;; Realizar este tutorial não danificará seu computador, a menos ;; que você fique tão irritado a ponto de jogá-lo no chão. Neste caso, ;; me abstenho de qualquer responsabilidade. Divirta-se! - + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; +;; ;; Abra o Emacs. ;; ;; Aperte a tecla `q' para ocultar a mensagem de boas vindas. @@ -45,11 +45,11 @@ filename: learn-emacs-lisp-pt.el ;; O buffer de rascunho (i.e., "scratch") é o buffer padrão quando ;; o Emacs é aberto. Você nunca está editando arquivos: você está ;; editando buffers que você pode salvar em um arquivo. -;; +;; ;; "Lisp interaction" refere-se a um conjunto de comandos disponíveis aqui. -;; -;; O Emacs possui um conjunto de comandos embutidos (disponíveis em -;; qualquer buffer) e vários subconjuntos de comandos disponíveis +;; +;; O Emacs possui um conjunto de comandos embutidos (disponíveis em +;; qualquer buffer) e vários subconjuntos de comandos disponíveis ;; quando você ativa um modo específico. Aqui nós utilizamos ;; `lisp-interaction-mode', que possui comandos para interpretar e navegar ;; em código Elisp. @@ -137,7 +137,7 @@ filename: learn-emacs-lisp-pt.el ;; => [a tela exibirá duas janelas e o cursor estará no buffer *test*] ;; Posicione o mouse sobre a janela superior e clique com o botão -;; esquerdo para voltar. Ou você pode utilizar `C-xo' (i.e. segure +;; esquerdo para voltar. Ou você pode utilizar `C-xo' (i.e. segure ;; ctrl-x e aperte o) para voltar para a outra janela, de forma interativa. ;; Você pode combinar várias "sexps" com `progn': -- cgit v1.2.3 From 69c4e4e509019740cab8eb2074826b5c5c9f6ec3 Mon Sep 17 00:00:00 2001 From: Kyle Simpson Date: Wed, 14 Aug 2013 00:12:15 -0500 Subject: Made some corrections and clarifications --- javascript.html.markdown | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index cc279b9a..865edc36 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -104,9 +104,10 @@ false // There's also null and undefined null // used to indicate a deliberate non-value -undefined // used to indicate a value that hasn't been set yet +undefined // used to indicate a value is not currently present (although undefined + // is actually a value itself) -// null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. +// false, null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. // Note that 0 is falsy and "0" is truthy, even though 0 == "0". /////////////////////////////////// @@ -142,7 +143,7 @@ myArray[1] // = 45 // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. -{key1: "Hello", key2: "World"} +var myObj = {key1: "Hello", key2: "World"} // Keys are strings, but quotes aren't required if they're a valid // JavaScript identifier. Values can be any type. @@ -211,9 +212,13 @@ function myFunction(thing){ myFunction("foo") // = "FOO" // Functions can also be defined "anonymously" - without a name: -function(thing){ +(function(thing){ return thing.toLowerCase() -} +}) +// Note: Stand-alone function declarations require an identifier name. +// Anonymous functions are values, not declarations, so they must be +// treated as a value. We wrap ours here in ( ) to do so, or you could assign +// it to a variable, or pass it as a parameter to another function. // (we can't call our function, since we don't have a name to refer to it with) // JavaScript functions are first class objects, so they can be reassigned to @@ -247,12 +252,15 @@ i // = 5 - not undefined as you'd expect in a block-scoped language // in a web browser is always 'window'. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10 - // Or, as previously mentioned, we can just leave the var keyword off. + // Or, as previously mentioned, if you leave the var keyword off, a + // global variable will be created when you assign it a value. However, + // this behavior is frowned upon, and in fact is disallowed in "strict + // mode". permanent2 = 15 })() temporary // raises ReferenceError permanent // = 10 -permanent2 // = 15 +permanent2 // = 15 <-- the accidental global variable // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the @@ -268,6 +276,12 @@ function sayHelloInFiveSeconds(name){ // access to the value of prompt. } sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s +// inner() has access to the variable "prompt" strictly because of lexical scope. +// A closure is being demonstrated because the inner() function is being executed +// at a later time, and in fact being executed "outside" the scope where it was +// declared (inside of the implementation of setTimeout()), but yet inner() STILL +// has access to the variable "prompt". It is said that inner() has a "closure" +// over the variables of sayHelloInFiveSeconds(). /////////////////////////////////// // 5. More about Objects; Constructors and Prototypes -- cgit v1.2.3 From 02ea95377d4963c60a96976b4092bdcc2b638594 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 14 Aug 2013 17:20:34 +0930 Subject: Avoid telling people about techniques that are discouraged anyway --- javascript.html.markdown | 6 ------ 1 file changed, 6 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 865edc36..1f188832 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -252,15 +252,9 @@ i // = 5 - not undefined as you'd expect in a block-scoped language // in a web browser is always 'window'. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10 - // Or, as previously mentioned, if you leave the var keyword off, a - // global variable will be created when you assign it a value. However, - // this behavior is frowned upon, and in fact is disallowed in "strict - // mode". - permanent2 = 15 })() temporary // raises ReferenceError permanent // = 10 -permanent2 // = 15 <-- the accidental global variable // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the -- cgit v1.2.3 From a82859f95bb235074d740530dfa60afca7025223 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 14 Aug 2013 17:21:29 +0930 Subject: Explain anonymous functions after first-class, and more concisely --- javascript.html.markdown | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 1f188832..bcaf9a29 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -211,16 +211,6 @@ function myFunction(thing){ } myFunction("foo") // = "FOO" -// Functions can also be defined "anonymously" - without a name: -(function(thing){ - return thing.toLowerCase() -}) -// Note: Stand-alone function declarations require an identifier name. -// Anonymous functions are values, not declarations, so they must be -// treated as a value. We wrap ours here in ( ) to do so, or you could assign -// it to a variable, or pass it as a parameter to another function. -// (we can't call our function, since we don't have a name to refer to it with) - // JavaScript functions are first class objects, so they can be reassigned to // different variable names and passed to other functions as arguments - for // example, when supplying an event handler: @@ -229,9 +219,16 @@ function myFunction(){ } setTimeout(myFunction, 5000) +// Functions can also be defined "anonymously" - without a name: +var lowerFunction = function(thing){ + return thing.toLowerCase() +} +lowerFunction("Foo") // = "foo" +// (note: we've assigned our anonymous function to a variable - if we didn't, we +// wouldn't be able to access it) + // You can even write the function statement directly in the call to the other // function. - setTimeout(function myFunction(){ // this code will be called in 5 seconds' time }, 5000) -- cgit v1.2.3 From 5f2928df6b19337426bed0a60650be79bda437a1 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 14 Aug 2013 17:21:44 +0930 Subject: More concise explanation of closures --- javascript.html.markdown | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index bcaf9a29..9b87b022 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -185,7 +185,7 @@ do { input = getInput() } while (!isValid(input)) -// the for loop is the same as C and Java: +// the for loop is the same as C and Java: // initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ // will run 5 times @@ -255,24 +255,19 @@ permanent // = 10 // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the -// outer function's variables. +// outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!" function inner(){ alert(prompt) } setTimeout(inner, 5000) - // setTimeout is asynchronous, so this function will finish without waiting - // 5 seconds. However, once the 5 seconds is up, inner will still have - // access to the value of prompt. + // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will + // exit immediately, and setTimeout will call inner afterwards. However, + // because inner is "closed over" sayHelloInFiveSeconds, inner still has + // access to the 'prompt' variable when it is finally called. } sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s -// inner() has access to the variable "prompt" strictly because of lexical scope. -// A closure is being demonstrated because the inner() function is being executed -// at a later time, and in fact being executed "outside" the scope where it was -// declared (inside of the implementation of setTimeout()), but yet inner() STILL -// has access to the variable "prompt". It is said that inner() has a "closure" -// over the variables of sayHelloInFiveSeconds(). /////////////////////////////////// // 5. More about Objects; Constructors and Prototypes -- cgit v1.2.3 From a40ae177d0088f7adfb7b0441678d076bba34ed4 Mon Sep 17 00:00:00 2001 From: wikibook Date: Wed, 14 Aug 2013 17:34:41 +0900 Subject: Korean version of python tutorial added --- ko-kr/python-kr.html.markdown | 484 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 484 insertions(+) create mode 100644 ko-kr/python-kr.html.markdown diff --git a/ko-kr/python-kr.html.markdown b/ko-kr/python-kr.html.markdown new file mode 100644 index 00000000..a131e9a2 --- /dev/null +++ b/ko-kr/python-kr.html.markdown @@ -0,0 +1,484 @@ +--- +language: python +category: language +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +filename: learnpython.py +translators: + - ["wikibook", "http://wikibook.co.kr"] +lang: ko-kr +--- + +파이썬은 귀도 반 로섬이 90년대에 만들었습니다. 파이썬은 현존하는 널리 사용되는 언어 중 하나입니다. +저는 문법적 명료함에 반해 파이썬을 사랑하게 됐습니다. 파이썬은 기본적으로 실행 가능한 의사코드입니다. + +피드백 주시면 정말 감사하겠습니다! [@louiedinh](http://twitter.com/louiedinh)나 +louiedinh [at] [구글의 이메일 서비스]를 통해 저에게 연락하시면 됩니다. + +참고: 이 글은 구체적으로 파이썬 2.7에 해당하는 내용을 담고 있습니다만 +파이썬 2.x에도 적용할 수 있을 것입니다. 파이썬 3을 다룬 튜토리얼도 곧 나올 테니 기대하세요! + +```python +# 한 줄짜리 주석은 해시로 시작합니다. +""" 여러 줄 문자열은 "를 세 개 써서 시작할 수 있고, + 주석으로 자주 사용됩니다. +""" + +#################################################### +## 1. 기본 자료형과 연산자 +#################################################### + +# 숫자 +3 #=> 3 + +# 수학 연산은 예상하신 대로입니다. +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# 나눗셈은 약간 까다롭습니다. 정수로 나눈 다음 결과값을 자동으로 내림합니다. +5 / 2 #=> 2 + +# 나눗셈 문제를 해결하려면 float에 대해 알아야 합니다. +2.0 # 이것이 float입니다. +11.0 / 4.0 #=> 2.75 훨씬 낫네요 + +# 괄호를 이용해 연산자 우선순위를 지정합니다. +(1 + 3) * 2 #=> 8 + +# 불린(Boolean) 값은 기본형입니다. +True +False + +# not을 이용해 부정합니다. +not True #=> False +not False #=> True + +# 동일성 연산자는 ==입니다. +1 == 1 #=> True +2 == 1 #=> False + +# 불일치 연산자는 !=입니다. +1 != 1 #=> False +2 != 1 #=> True + +# 그밖의 비교 연산자는 다음과 같습니다. +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# 비교 연산을 연결할 수도 있습니다! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# 문자열은 "나 '로 생성합니다. +"This is a string." +'This is also a string.' + +# 문자열도 연결할 수 있습니다! +"Hello " + "world!" #=> "Hello world!" + +# 문자열은 문자로 구성된 리스트로 간주할 수 있습니다. +"This is a string"[0] #=> 'T' + +# %는 다음과 같이 문자열을 형식화하는 데 사용할 수 있습니다: +"%s can be %s" % ("strings", "interpolated") + +# 문자열을 형식화하는 새로운 방법은 format 메서드를 이용하는 것입니다. +# 이 메서드를 이용하는 방법이 더 선호됩니다. +"{0} can be {1}".format("strings", "formatted") +# 자릿수를 세기 싫다면 키워드를 이용해도 됩니다. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# None은 객체입니다. +None #=> None + +# 객체와 None을 비교할 때는 동일성 연산자인 `==`를 사용해서는 안 됩니다. +# 대신 `is`를 사용하세요. +"etc" is None #=> False +None is None #=> True + +# 'is' 연산자는 객체의 식별자를 검사합니다. +# 기본형 값을 다룰 때는 이 연산자가 그다지 유용하지 않지만 +# 객체를 다룰 때는 매우 유용합니다. + +# None, 0, 빈 문자열/리스트는 모두 False로 평가됩니다. +# 그밖의 다른 값은 모두 True입니다 +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. 변수와 컬렉션 +#################################################### + +# 뭔가를 출력하는 것은 상당히 쉽습니다. +print "I'm Python. Nice to meet you!" + + +# 변수에 값을 할당하기 전에 변수를 반드시 선언하지 않아도 됩니다. +some_var = 5 # 명명관례는 '밑줄이_포함된_소문자'입니다. +some_var #=> 5 + +# 미할당된 변수에 접근하면 예외가 발생합니다. +# 예외 처리에 관해서는 '제어 흐름'을 참고하세요. +some_other_var # 이름 오류가 발생 + +# 표현식으로도 사용할 수 있습니다. +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# 리스트는 순차 항목을 저장합니다. +li = [] +# 미리 채워진 리스트로 시작할 수도 있습니다. +other_li = [4, 5, 6] + +# append를 이용해 리스트 끝에 항목을 추가합니다. +li.append(1) #li는 이제 [1]입니다. +li.append(2) #li는 이제 [1, 2]입니다. +li.append(4) #li는 이제 [1, 2, 4]입니다. +li.append(3) #li는 이제 [1, 2, 4, 3]입니다. +# pop을 이용해 끝에서부터 항목을 제거합니다. +li.pop() #=> 3이 반환되고 li는 이제 [1, 2, 4]입니다. +# 다시 넣어봅시다 +li.append(3) # li는 이제 다시 [1, 2, 4, 3]가 됩니다. + +# 배열에서 했던 것처럼 리스트에도 접근할 수 있습니다. +li[0] #=> 1 +# 마지막 요소를 봅시다. +li[-1] #=> 3 + +# 범위를 벗어나서 접근하면 IndexError가 발생합니다. +li[4] # IndexError가 발생 + +# 슬라이스 문법을 통해 범위를 지정해서 값을 조회할 수 있습니다. +# (이 문법을 통해 간편하게 범위를 지정할 수 있습니다.) +li[1:3] #=> [2, 4] +# 앞부분을 생략합니다. +li[2:] #=> [4, 3] +# 끝부분을 생략합니다. +li[:3] #=> [1, 2, 4] + +# del로 임의의 요소를 제거할 수 있습니다. +del li[2] # li is now [1, 2, 3] + +# 리스트를 추가할 수도 있습니다. +li + other_li #=> [1, 2, 3, 4, 5, 6] - 참고: li와 other_li는 그대로 유지됩니다. + +# extend로 리스트를 연결합니다. +li.extend(other_li) # 이제 li는 [1, 2, 3, 4, 5, 6]입니다. + +# in으로 리스트 안에서 특정 요소가 존재하는지 확인합니다. +1 in li #=> True + +# len으로 길이를 검사합니다. +len(li) #=> 6 + +# 튜플은 리스트와 비슷하지만 불변성을 띱니다. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # TypeError가 발생 + +# 튜플에 대해서도 리스트에서 할 수 있는 일들을 모두 할 수 있습니다. +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# 튜플(또는 리스트)을 변수로 풀 수 있습니다. +a, b, c = (1, 2, 3) # 이제 a는 1, b는 2, c는 3입니다 +# 괄호를 빼면 기본적으로 튜플이 만들어집니다. +d, e, f = 4, 5, 6 +# 이제 두 값을 바꾸는 게 얼마나 쉬운지 확인해 보세요. +e, d = d, e # 이제 d는 5이고 e는 4입니다. + +# 딕셔너리는 매핑을 저장합니다. +empty_dict = {} +# 다음은 값을 미리 채운 딕셔너리입니다. +filled_dict = {"one": 1, "two": 2, "three": 3} + +# []를 이용해 값을 조회합니다. +filled_dict["one"] #=> 1 + +# 모든 키를 리스트로 구합니다. +filled_dict.keys() #=> ["three", "two", "one"] +# 참고 - 딕셔너리 키의 순서는 보장되지 않습니다. +# 따라서 결과가 이와 정확히 일치하지 않을 수도 있습니다. + +# 모든 값을 리스트로 구합니다. +filled_dict.values() #=> [3, 2, 1] +# 참고 - 키 순서와 관련해서 위에서 설명한 내용과 같습니다. + +# in으로 딕셔너리 안에 특정 키가 존재하는지 확인합니다. +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# 존재하지 않는 키를 조회하면 KeyError가 발생합니다. +filled_dict["four"] # KeyError + +# get 메서드를 이용하면 KeyError가 발생하지 않습니다. +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# get 메서드는 값이 누락된 경우 기본 인자를 지원합니다. +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# setdefault 메서드는 딕셔너리에 새 키-값 쌍을 추가하는 안전한 방법입니다. +filled_dict.setdefault("five", 5) #filled_dict["five"]는 5로 설정됩니다. +filled_dict.setdefault("five", 6) #filled_dict["five"]는 여전히 5입니다. + + +# 세트는 집합을 저장합니다. +empty_set = set() +# 다수의 값으로 세트를 초기화합니다. +some_set = set([1,2,2,3,4]) # 이제 some_set는 set([1, 2, 3, 4])입니다. + +# 파이썬 2.7부터는 {}를 세트를 선언하는 데 사용할 수 있습니다. +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# 세트에 항목을 추가합니다. +filled_set.add(5) # 이제 filled_set는 {1, 2, 3, 4, 5}입니다. + +# &을 이용해 교집합을 만듭니다. +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# |를 이용해 합집합을 만듭니다. +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# -를 이용해 차집합을 만듭니다. +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# in으로 세트 안에 특정 요소가 존재하는지 검사합니다. +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. 제어 흐름 +#################################################### + +# 변수를 만들어 봅시다. +some_var = 5 + +# 다음은 if 문입니다. 파이썬에서는 들여쓰기가 대단히 중요합니다! +# 다음 코드를 실행하면 "some_var is smaller than 10"가 출력됩니다. +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # elif 절은 선택사항입니다. + print "some_var is smaller than 10." +else: # 이 부분 역시 선택사항입니다. + print "some_var is indeed 10." + + +""" +for 루프는 리스트를 순회합니다. +아래 코드는 다음과 같은 내용을 출력합니다: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # %로 형식화된 문자열에 값을 채워넣을 수 있습니다. + print "%s is a mammal" % animal + +""" +`range(number)`는 숫자 리스트를 반환합니다. +이때 숫자 리스트의 범위는 0에서 지정한 숫자까지입니다. +아래 코드는 다음과 같은 내용을 출력합니다: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +while 루프는 조건이 더는 충족되지 않을 때까지 진행됩니다. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # x = x + 1의 축약형 + +# try/except 블록을 이용한 예외 처리 + +# 파이썬 2.6 및 상위 버전에서 동작하는 코드 +try: + # raise를 이용해 오류를 발생시킵니다 + raise IndexError("This is an index error") +except IndexError as e: + pass # pass는 단순 no-op 연산입니다. 보통 이곳에 복구 코드를 작성합니다. + + +#################################################### +## 4. 함수 +#################################################### + +# 새 함수를 만들 때 def를 사용합니다. +def add(x, y): + print "x is %s and y is %s" % (x, y) + return x + y # return 문을 이용해 값을 반환합니다. + +# 매개변수를 전달하면서 함수를 호출 +add(5, 6) #=> "x is 5 and y is 6"가 출력되고 11이 반환됨 + +# 함수를 호출하는 또 다른 방법은 키워드 인자를 지정하는 방법입니다. +add(y=6, x=5) # 키워드 인자는 순서에 구애받지 않습니다. + +# 위치 기반 인자를 임의 개수만큼 받는 함수를 정의할 수 있습니다. +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# 키워드 인자를 임의 개수만큼 받는 함수 또한 정의할 수 있습니다. +def keyword_args(**kwargs): + return kwargs + +# 이 함수를 호출해서 어떤 일이 일어나는지 확인해 봅시다. +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# 원한다면 한 번에 두 가지 종류의 인자를 모두 받는 함수를 정의할 수도 있습니다. +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4)를 실행하면 다음과 같은 내용이 출력됩니다: + (1, 2) + {"a": 3, "b": 4} +""" + +# 함수를 호출할 때 varargs/kwargs와 반대되는 일을 할 수 있습니다! +# *를 이용해 튜플을 확장하고 **를 이용해 kwargs를 확장합니다. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # foo(1, 2, 3, 4)와 같음 +all_the_args(**kwargs) # foo(a=3, b=4)와 같음 +all_the_args(*args, **kwargs) # foo(1, 2, 3, 4, a=3, b=4)와 같음 + +# 파이썬에는 일급 함수가 있습니다 +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# 게다가 익명 함수도 있습니다. +(lambda x: x > 2)(3) #=> True + +# 내장된 고차 함수(high order function)도 있습니다. +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# 맵과 필터에 리스트 조건 제시법(list comprehensions)을 사용할 수 있습니다. +[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. 클래스 +#################################################### + +# 클래스를 하나 만들기 위해 특정 객체의 하위 클래스를 만들 수 있습니다. +class Human(object): + + # 클래스 속성은 이 클래스의 모든 인스턴스에서 공유합니다. + species = "H. sapiens" + + # 기본 초기화자 + def __init__(self, name): + # 인자를 인스턴스의 name 속성에 할당합니다. + self.name = name + + # 모든 인스턴스 메서드에서는 self를 첫 번째 인자로 받습니다. + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # 클래스 메서드는 모든 인스턴스에서 공유합니다. + # 클래스 메서드는 호출하는 클래스를 첫 번째 인자로 호출됩니다. + @classmethod + def get_species(cls): + return cls.species + + # 정적 메서드는 클래스나 인스턴스 참조 없이도 호출할 수 있습니다. + @staticmethod + def grunt(): + return "*grunt*" + + +# 클래스 인스턴스화 +i = Human(name="Ian") +print i.say("hi") # "Ian: hi"가 출력됨 + +j = Human("Joel") +print j.say("hello") # "Joel: hello"가 출력됨 + +# 클래스 메서드를 호출 +i.get_species() #=> "H. sapiens" + +# 공유 속성을 변경 +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# 정적 메서드를 호출 +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. 모듈 +#################################################### + +# 다음과 같이 모듈을 임포트할 수 있습니다. +import math +print math.sqrt(16) #=> 4 + +# 모듈의 특정 함수를 호출할 수 있습니다. +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# 모듈의 모든 함수를 임포트할 수 있습니다. +# Warning: this is not recommended +from math import * + +# 모듈 이름을 축약해서 쓸 수 있습니다. +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# 파이썬 모듈은 평범한 파이썬 파일에 불과합니다. +# 직접 모듈을 작성해서 그것들을 임포트할 수 있습니다. +# 모듈의 이름은 파일의 이름과 같습니다. + +# 다음과 같은 코드로 모듈을 구성하는 함수와 속성을 확인할 수 있습니다. +import math +dir(math) + + +``` + +## 더 배울 준비가 되셨습니까? + +### 무료 온라인 참고자료 + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### 파이썬 관련 도서 + +* [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) \ No newline at end of file -- cgit v1.2.3 From 7d015d8cee3a71fb54ed205a348428ab589ef1a6 Mon Sep 17 00:00:00 2001 From: Pablo Elices Date: Wed, 14 Aug 2013 13:12:27 +0200 Subject: Translate CoffeeScript file to spanish. --- es-es/coffeescript-es.html.markdown | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 es-es/coffeescript-es.html.markdown diff --git a/es-es/coffeescript-es.html.markdown b/es-es/coffeescript-es.html.markdown new file mode 100644 index 00000000..eb6825c0 --- /dev/null +++ b/es-es/coffeescript-es.html.markdown @@ -0,0 +1,56 @@ +--- +language: coffeescript +lang: es-es +contributors: + - ["Tenor Biel", "http://github.com/L8D"] +translators: + - ["Pablo Elices", "http://github.com/pabloelices"] +filename: coffeescript-es.coffee +--- + +``` coffeescript +# CoffeeScript es un lenguaje hipster. +# Tiene convenciones de muchos lenguajes modernos. +# Los comentarios son como en Ruby y Python, usan almohadilla. + +### +Los comentarios en bloque son como estos, y se traducen directamente a '/*' y '*/' para el código JavaScript resultante. + +Deberías entender la mayor parte de la semántica de JavaScript antes de continuar. +### + +# Asignación: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Condiciones: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Funciones: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +# Rangos: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objetos: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +#} + +# Símbolos: +race = (winner, runners...) -> + print winner, runners + +# Existencia: +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# Colecciones por comprensión: +cubes = (math.cube num for num in list) #=> ... +``` -- cgit v1.2.3 From f29098292c71a897efbcdbe702146831e5ca4831 Mon Sep 17 00:00:00 2001 From: Pablo Elices Date: Wed, 14 Aug 2013 13:13:56 +0200 Subject: Fix typo. --- es-es/coffeescript-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/coffeescript-es.html.markdown b/es-es/coffeescript-es.html.markdown index eb6825c0..a58c0d07 100644 --- a/es-es/coffeescript-es.html.markdown +++ b/es-es/coffeescript-es.html.markdown @@ -11,7 +11,7 @@ filename: coffeescript-es.coffee ``` coffeescript # CoffeeScript es un lenguaje hipster. # Tiene convenciones de muchos lenguajes modernos. -# Los comentarios son como en Ruby y Python, usan almohadilla. +# Los comentarios son como en Ruby y Python, usan almohadillas. ### Los comentarios en bloque son como estos, y se traducen directamente a '/*' y '*/' para el código JavaScript resultante. -- cgit v1.2.3 From 89821fd235560bdfddd61fb4ac52aafc4772ee14 Mon Sep 17 00:00:00 2001 From: Katyanna Moura Date: Wed, 14 Aug 2013 11:56:14 -0300 Subject: =?UTF-8?q?revis=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/ruby-pt.html.markdown | 79 +----- pt-br/ruby-pt.html.markdown~ | 598 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 607 insertions(+), 70 deletions(-) create mode 100644 pt-br/ruby-pt.html.markdown~ diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index cedd2db1..732d06a4 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -9,19 +9,13 @@ contributors: # Isso é um comentario =begin -This is a multiline comment -No-one uses them -You shouldn't either - -Isso é um comentario multilinha +Isso é um comentário multilinha Ninguém os usa - +Você não deve usar também =end -# First and foremost: Everything is an object. # Primeiro e principal: Tudo é um objeto. -# Numbers are objects # Números são objetos 3.class #=> Fixnum @@ -29,8 +23,7 @@ Ninguém os usa 3.to_s #=> "3" -# Some basic arithmetic -# Aritmética básica +# Um pouco de aritmética básica 1 + 1 #=> 2 8 - 1 #=> 7 @@ -44,7 +37,6 @@ Ninguém os usa 1.+(3) #=> 4 10.* 5 #=> 50 -# Special values are objects # Valores especiais são obejetos nil # Nothing to see here nil # Nada para ver aqui @@ -57,26 +49,22 @@ nil.class #=> NilClass true.class #=> TrueClass false.class #=> FalseClass -# Equality # Igualdade 1 == 1 #=> true 2 == 1 #=> false -# Inequality # Desigualdade 1 != 1 #=> false 2 != 1 #=> true !true #=> false !false #=> true -# apart from false itself, nil is the only other 'falsey' value # além de 'false', 'nil' é o único outro valor falso !nil #=> true !false #=> true !0 #=> false -# More comparisons # Mais comparações 1 < 10 #=> true 1 > 10 #=> false @@ -84,7 +72,6 @@ false.class #=> FalseClass 2 >= 2 #=> true # Strings are objects -# Strings são obejetos 'I am a string'.class #=> String 'Eu sou uma string'.class #=> String @@ -95,47 +82,35 @@ placeholder = "use string interpolation" placeholder = "usar interpolação de string" "I can #{placeholder} when using double quoted strings" "Eu posso #{placeholder} quando estiver usando aspas duplas" -#=> "I can use string interpolation when using double quoted strings" #=> "Eu posso usar insterpolação de string quando estiver usando aspas duplas" - -# print to the output -# imprime para output (saida) +# imprime para output (saída) puts "I'm printing!" puts "Estou imprimindo" -# Variables # Variáveis x = 25 #=> 25 x #=> 25 -# Note that assignment returns the value assigned # Note que uma atribuição retorna o valor atribuido -# This means you can do multiple assignment: -# Isso significa que você pode fazer multiplas atribuições: +# Isso significa que você pode fazer múltiplas atribuições: x = y = 10 #=> 10 x #=> 10 y #=> 10 -# By convention, use snake_case for variable names # Por convenção, use snake_case para nomes de variáveis snake_case = true -# Use descriptive variable names # Use nomes de variáveis descrivos path_to_project_root = '/good/name/' caminho_para_a_raiz_do_projeto = '/bom/nome/' path = '/bad/name/' caminho = '/nome/ruim/' -# Symbols (are objects) # Simbolos (são objetos) -# Symbols are immutable, reusable constants represented internally by an # Simbolos são imultáveis, são constantes reutilizáveis representadadas internamente por um -# integer value. They're often used instead of strings to efficiently convey # valor inteiro. Eles são frequentemente usados no lugar de strings para transmitir com eficiência os valores -# specific, meaningful values # específicos e significativos :pending.class #=> Symbol @@ -155,68 +130,52 @@ status == :aprovado #=> false # Arrays -# This is an array # Isso é um array [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] -# Arrays can contain different types of items # Arrays podem conter diferentes tipos de itens array = [1, "hello", false] #=> => [1, "hello", false] array = [1, "Oi", false] #=> => [1, "Oi", false] -# Arrays can be indexed # Arrays podem ser indexados -# From the front # a partir do começo array[0] #=> 1 array[12] #=> nil -# Like arithmetic, [var] access # Como aritimetica, o acesso via [var] -# is just syntactic sugar # é apenas açúcar sintático -# for calling a method [] on an object # para chamar o método [] de um objeto array.[] 0 #=> 1 array.[] 12 #=> nil -# From the end # a partir do final array[-1] #=> 5 -# With a start and end index # Com um índice de começo e fim array[2, 4] #=> [3, 4, 5] -# Or with a range # Ou com um intervalo de valores array[1..3] #=> [2, 3, 4] -# Add to an array like this # Adicionar a um array como este array << 6 #=> [1, 2, 3, 4, 5, 6] -# Hashes are Ruby's primary dictionary with keys/value pairs. -# Hashes são dicionário com um par de chave(key)/valor(value) -# Hashes are denoted with curly braces: +# Hashes são o principal dicionário de Ruby com pares de chaves(keys)/valor(value). # Hashes são simbolizados com chaves "{}" hash = {'color' => 'green', 'number' => 5} hash = {'cor' => 'verde', 'numero' => 5} hash.keys #=> ['cor', 'numero'] -# Hashes can be quickly looked up by key: # Hashes podem ser rapidamente pesquisado pela chave (key) hash['cor'] #=> 'verde' hash['numero'] #=> 5 -# Asking a hash for a key that doesn't exist returns nil: # Procurar em um hash por uma chave que não existe retorna nil: hash['nothing here'] #=> nil hash['nada aqui'] #=> nil -# Iterate over hashes with the #each method: # Interar sobre hashes com o método #each: hash.each do |k, v| puts "#{k} is #{v}" @@ -226,7 +185,6 @@ hash.each do |k, v| puts "#{k} é #{v}" end -# Since Ruby 1.9, there's a special syntax when using symbols as keys: # Desde o Ruby 1.9, temos uma sintaxe especial quando usamos simbolos como chaves (keys) new_hash = { defcon: 3, action: true} @@ -235,12 +193,9 @@ novo_hash = { defcon: 3, acao: true} new_hash.keys #=> [:defcon, :action] novo_hash.keys #=> [:defcon, :acao] -# Tip: Both Arrays and Hashes are Enumerable # Dica: Tanto Arrays quanto Hashes são Enumerable -# They share a lot of useful methods such as each, map, count, and more # Eles compartilham um monte de métodos úteis como each, map, count e mais -# Control structures # Estruturas de controle if true @@ -272,11 +227,8 @@ end #=> contador 4 #=> contador 5 -# HOWEVER # PORÉM -# No-one uses for loops # Ninguém usa para loops -# Use `each` instead, like this: # Use "each" em vez, dessa forma: (1..5).each do |counter| @@ -343,19 +295,16 @@ else puts "Alternative grading system, eh?" end -# Functions # Funções def dobrar(x) x * 2 end -# Functions (and all blocks) implcitly return the value of the last statement # Funções (e todos os blocos) retornam implicitamente o valor da última linha double(2) #=> 4 dobrar(2) #=> 4 -# Parentheses are optional where the result is unambiguous # Parênteses são opicionais onde o resultado é claro double 3 #=> 6 dobrar 3 #=> 6 @@ -371,7 +320,6 @@ def somar(x,y) x + y end -# Method arguments are separated by a comma # Argumentos de métodos são separados por uma virgula sum 3, 4 #=> 7 somar 3, 4 #=> 7 @@ -379,9 +327,7 @@ somar 3, 4 #=> 7 somar somar(3,4), 5 #=> 12 # yield -# All methods have an implicit, optional block parameter # Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco -# it can be called with the 'yield' keyword # ele pode ser chamado com a palavra chave 'yield' def surround @@ -406,7 +352,6 @@ ao_redor { puts 'Olá mundo' } # } -# Define a class with the class keyword # Define uma classe com a palavra chave 'class' class Human @@ -480,7 +425,6 @@ class Humano end -# Instantiate a class # Instaciando uma classe jim = Human.new("Jim Halpert") jim = Humano.new("Jim Halpert") @@ -488,7 +432,6 @@ jim = Humano.new("Jim Halpert") dwight = Human.new("Dwight K. Schrute") dwight = Humano.new("Dwight K. Schrute") -# Let's call a couple of methods # Vamos chamar um par de métodos jim.species #=> "H. sapiens" jim.especies #=> "H. sapiens" @@ -508,15 +451,12 @@ dwight.especies #=> "H. sapiens" dwight.name #=> "Dwight K. Schrute" dwight.nome #=> "Dwight K. Schrute" -# Call the class method # Chamar o método de classe Human.say("Hi") #=> "Hi" Humano.diz("Oi") #=> "Oi" -# Class also is object in ruby. So class can have instance variables. -# Uma classe também é objeto em Ruby. Então uma classe pode possuir um variavel de instancia -# Class variable is shared among the class and all of its descendants. -# Variavies de classe são compartilhadas entre a classe e todos os seus descendentes. +# Uma classe também é objeto em Ruby. Então uma classe pode possuir variável de instância +# Variáveis de classe são compartilhadas entre a classe e todos os seus descendentes. # base class class Human @@ -559,8 +499,7 @@ Humano.foo = 2 # 2 Worker.foo # 2 Trabalhador.foo # 2 -# Class instance variable is not shared by the class's descendants. -# Uma variavel de instancia não é compartilhada por suas classes decendentes. +# Uma variável de instância não é compartilhada por suas classes decendentes. class Human @bar = 0 diff --git a/pt-br/ruby-pt.html.markdown~ b/pt-br/ruby-pt.html.markdown~ new file mode 100644 index 00000000..cedd2db1 --- /dev/null +++ b/pt-br/ruby-pt.html.markdown~ @@ -0,0 +1,598 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["Bruno Henrique - Garu", "http://garulab.com"] +--- + +```ruby +# Isso é um comentario + +=begin +This is a multiline comment +No-one uses them +You shouldn't either + +Isso é um comentario multilinha +Ninguém os usa + +=end + +# First and foremost: Everything is an object. +# Primeiro e principal: Tudo é um objeto. + +# Numbers are objects +# Números são objetos + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Some basic arithmetic +# Aritmética básica + +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Arithmetic is just syntactic sugar +# for calling a method on an object +# Arithmetic é apenas açúcar semântico +# para chamar um métoddo de um objeto +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Special values are objects +# Valores especiais são obejetos +nil # Nothing to see here +nil # Nada para ver aqui +true # truth +true # verdadeiro +false # falsehood +false # falso + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Equality +# Igualdade +1 == 1 #=> true +2 == 1 #=> false + +# Inequality +# Desigualdade +1 != 1 #=> false +2 != 1 #=> true +!true #=> false +!false #=> true + +# apart from false itself, nil is the only other 'falsey' value +# além de 'false', 'nil' é o único outro valor falso + +!nil #=> true +!false #=> true +!0 #=> false + +# More comparisons +# Mais comparações +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Strings are objects +# Strings são obejetos + +'I am a string'.class #=> String +'Eu sou uma string'.class #=> String +"I am a string too".class #=> String +"Eu também sou uma string".class #=> String + +placeholder = "use string interpolation" +placeholder = "usar interpolação de string" +"I can #{placeholder} when using double quoted strings" +"Eu posso #{placeholder} quando estiver usando aspas duplas" +#=> "I can use string interpolation when using double quoted strings" +#=> "Eu posso usar insterpolação de string quando estiver usando aspas duplas" + + +# print to the output +# imprime para output (saida) +puts "I'm printing!" +puts "Estou imprimindo" + +# Variables +# Variáveis +x = 25 #=> 25 +x #=> 25 + +# Note that assignment returns the value assigned +# Note que uma atribuição retorna o valor atribuido +# This means you can do multiple assignment: +# Isso significa que você pode fazer multiplas atribuições: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# By convention, use snake_case for variable names +# Por convenção, use snake_case para nomes de variáveis +snake_case = true + +# Use descriptive variable names +# Use nomes de variáveis descrivos +path_to_project_root = '/good/name/' +caminho_para_a_raiz_do_projeto = '/bom/nome/' +path = '/bad/name/' +caminho = '/nome/ruim/' + +# Symbols (are objects) +# Simbolos (são objetos) +# Symbols are immutable, reusable constants represented internally by an +# Simbolos são imultáveis, são constantes reutilizáveis representadadas internamente por um +# integer value. They're often used instead of strings to efficiently convey +# valor inteiro. Eles são frequentemente usados no lugar de strings para transmitir com eficiência os valores +# specific, meaningful values +# específicos e significativos + +:pending.class #=> Symbol +:pendente.class #=> Symbol + +status = :pending +status = :pendente + +status == :pending #=> true +status == :pendente #=> true + +status == 'pending' #=> false +status == 'pendente' #=> false + +status == :approved #=> false +status == :aprovado #=> false + +# Arrays + +# This is an array +# Isso é um array +[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Arrays can contain different types of items +# Arrays podem conter diferentes tipos de itens + +array = [1, "hello", false] #=> => [1, "hello", false] +array = [1, "Oi", false] #=> => [1, "Oi", false] + +# Arrays can be indexed +# Arrays podem ser indexados +# From the front +# a partir do começo +array[0] #=> 1 +array[12] #=> nil + +# Like arithmetic, [var] access +# Como aritimetica, o acesso via [var] +# is just syntactic sugar +# é apenas açúcar sintático +# for calling a method [] on an object +# para chamar o método [] de um objeto +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# From the end +# a partir do final +array[-1] #=> 5 + +# With a start and end index +# Com um índice de começo e fim +array[2, 4] #=> [3, 4, 5] + +# Or with a range +# Ou com um intervalo de valores +array[1..3] #=> [2, 3, 4] + +# Add to an array like this +# Adicionar a um array como este +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# Hashes are Ruby's primary dictionary with keys/value pairs. +# Hashes são dicionário com um par de chave(key)/valor(value) +# Hashes are denoted with curly braces: +# Hashes são simbolizados com chaves "{}" +hash = {'color' => 'green', 'number' => 5} +hash = {'cor' => 'verde', 'numero' => 5} + +hash.keys #=> ['cor', 'numero'] + +# Hashes can be quickly looked up by key: +# Hashes podem ser rapidamente pesquisado pela chave (key) +hash['cor'] #=> 'verde' +hash['numero'] #=> 5 + +# Asking a hash for a key that doesn't exist returns nil: +# Procurar em um hash por uma chave que não existe retorna nil: +hash['nothing here'] #=> nil +hash['nada aqui'] #=> nil + +# Iterate over hashes with the #each method: +# Interar sobre hashes com o método #each: +hash.each do |k, v| + puts "#{k} is #{v}" +end + +hash.each do |k, v| + puts "#{k} é #{v}" +end + +# Since Ruby 1.9, there's a special syntax when using symbols as keys: +# Desde o Ruby 1.9, temos uma sintaxe especial quando usamos simbolos como chaves (keys) + +new_hash = { defcon: 3, action: true} +novo_hash = { defcon: 3, acao: true} + +new_hash.keys #=> [:defcon, :action] +novo_hash.keys #=> [:defcon, :acao] + +# Tip: Both Arrays and Hashes are Enumerable +# Dica: Tanto Arrays quanto Hashes são Enumerable +# They share a lot of useful methods such as each, map, count, and more +# Eles compartilham um monte de métodos úteis como each, map, count e mais + +# Control structures +# Estruturas de controle + +if true + "if statement" +elsif false + "else if, optional" +else + "else, also optional" +end + +if true + "Se verdadeiro" +elsif false + "else if, opicional" +else + "else, também é opicional" +end + +for counter in 1..5 + puts "iteration #{counter}" +end + +for contador in 1..5 + puts "interação #{contador}" +end +#=> contador 1 +#=> contador 2 +#=> contador 3 +#=> contador 4 +#=> contador 5 + +# HOWEVER +# PORÉM +# No-one uses for loops +# Ninguém usa para loops +# Use `each` instead, like this: +# Use "each" em vez, dessa forma: + +(1..5).each do |counter| + puts "iteration #{counter}" +end + +(1..5).each do |contador| + puts "interação #{contador}" +end +#=> contador 1 +#=> contador 2 +#=> contador 3 +#=> contador 4 +#=> contador 5 + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end + +contador = 1 +while contador <= 5 do + puts "interação #{contador}" + contador += 1 +end +#=> contador 1 +#=> contador 2 +#=> contador 3 +#=> contador 4 +#=> contador 5 + +grade = 'B' + +case grade +when 'A' + puts "Way to go kiddo" +when 'B' + puts "Better luck next time" +when 'C' + puts "You can do better" +when 'D' + puts "Scraping through" +when 'F' + puts "You failed!" +else + puts "Alternative grading system, eh?" +end + +grau = 'B' + +case grau +when 'A' + puts "Um longo caminho a percorrer pequeno gafanhoto" +when 'B' + puts "Melhor sorte da próxima vez" +when 'C' + puts "Você pode fazer melhor" +when 'D' + puts "Scraping through" +when 'F' + puts "Você falhou" +else + puts "Alternative grading system, eh?" +end + +# Functions +# Funções + +def dobrar(x) + x * 2 +end + +# Functions (and all blocks) implcitly return the value of the last statement +# Funções (e todos os blocos) retornam implicitamente o valor da última linha +double(2) #=> 4 +dobrar(2) #=> 4 + +# Parentheses are optional where the result is unambiguous +# Parênteses são opicionais onde o resultado é claro +double 3 #=> 6 +dobrar 3 #=> 6 + +double double 3 #=> 12 +dobrar dobrar 3 #=> 12 + +def sum(x,y) + x + y +end + +def somar(x,y) + x + y +end + +# Method arguments are separated by a comma +# Argumentos de métodos são separados por uma virgula +sum 3, 4 #=> 7 +somar 3, 4 #=> 7 + +somar somar(3,4), 5 #=> 12 + +# yield +# All methods have an implicit, optional block parameter +# Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco +# it can be called with the 'yield' keyword +# ele pode ser chamado com a palavra chave 'yield' + +def surround + puts "{" + yield + puts "}" +end + +surround { puts 'hello world' } + + +def ao_redor + puts "{" + yield + puts "}" +end + +ao_redor { puts 'Olá mundo' } + +# { +# Olá mundo +# } + + +# Define a class with the class keyword +# Define uma classe com a palavra chave 'class' +class Human + + # A class variable. It is shared by all instances of this class. + @@species = "H. sapiens" + + # Basic initializer + def initialize(name, age=0) + # Assign the argument to the "name" instance variable for the instance + @name = name + # If no age given, we will fall back to the default in the arguments list. + @age = age + end + + # Basic setter method + def name=(name) + @name = name + end + + # Basic getter method + def name + @name + end + + # A class method uses self to distinguish from instance methods. + # It can only be called on the class, not an instance. + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end + +end + + +class Humano + + # Uma variavel de classe. Ela é compartilhada por todas as instancias dessa classe + @@especies = "H. sapiens" + + # Inicialização básica (contructor) + def initialize(nome, idade=0) + # Atribui o argumento para a variavel de instacia "nome" do objeto + @nome = nome + # Se a idade não for passada, nós definimos um valor padrão na lista de argumentos + @idade = idade + end + + # Método básico para atribuir valor + def nome=(nome) + @nome = nome + end + + # Método básico de resgatar valor + def nome + @nome + end + + # Um método de classe usa a palavra chave self para se defenciar dos métodos de instancia. + # Ele só pode ser chamado na classe, não na instancia + def self.diz(msg) + puts "#{msg}" + end + + def especies + @@especies + end + +end + + +# Instantiate a class +# Instaciando uma classe +jim = Human.new("Jim Halpert") +jim = Humano.new("Jim Halpert") + +dwight = Human.new("Dwight K. Schrute") +dwight = Humano.new("Dwight K. Schrute") + +# Let's call a couple of methods +# Vamos chamar um par de métodos +jim.species #=> "H. sapiens" +jim.especies #=> "H. sapiens" + +jim.name #=> "Jim Halpert" +jim.nome #=> "Jim Halpert" + +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.nome = "Jim Halpert II" #=> "Jim Halpert II" + +jim.name #=> "Jim Halpert II" +jim.nome #=> "Jim Halpert II" + +dwight.species #=> "H. sapiens" +dwight.especies #=> "H. sapiens" + +dwight.name #=> "Dwight K. Schrute" +dwight.nome #=> "Dwight K. Schrute" + +# Call the class method +# Chamar o método de classe +Human.say("Hi") #=> "Hi" +Humano.diz("Oi") #=> "Oi" + +# Class also is object in ruby. So class can have instance variables. +# Uma classe também é objeto em Ruby. Então uma classe pode possuir um variavel de instancia +# Class variable is shared among the class and all of its descendants. +# Variavies de classe são compartilhadas entre a classe e todos os seus descendentes. + +# base class +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + + +# Classe base +class Humano + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# classe filha +class Trabalhador < Humano +end + +Human.foo # 0 +Humano.foo # 0 +Worker.foo # 0 +Trabalhador.foo # 0 + +Human.foo = 2 # 2 +Humano.foo = 2 # 2 +Worker.foo # 2 +Trabalhador.foo # 2 + +# Class instance variable is not shared by the class's descendants. +# Uma variavel de instancia não é compartilhada por suas classes decendentes. + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Humano + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +class Doutor < Humano +end + +Humano.bar # 0 +Doutor.bar # nil + +``` -- cgit v1.2.3 From 38c3c4d6a8571a4d48a46925f4feb717d7e9f164 Mon Sep 17 00:00:00 2001 From: Peter Mitchell Date: Wed, 14 Aug 2013 10:58:19 -0400 Subject: Update clojure.html.markdown Small typo fix --- clojure.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index 6baae0ce..a502a95c 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -365,7 +365,7 @@ my-atom ;=> Atom<#...> (Returns the Atom object) ### Further Reading -This is far from exhaustive, but hopefully it's enought o get you on your feet. +This is far from exhaustive, but hopefully it's enough to get you on your feet. Clojure.org has lots of articles: [http://clojure.org/](http://clojure.org/) -- cgit v1.2.3 From a2432ef31727c56fcfb2528523804da6ad21c4a0 Mon Sep 17 00:00:00 2001 From: Katyanna Moura Date: Wed, 14 Aug 2013 12:01:30 -0300 Subject: =?UTF-8?q?revis=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/ruby-pt.html.markdown~ | 598 ------------------------------------------- 1 file changed, 598 deletions(-) delete mode 100644 pt-br/ruby-pt.html.markdown~ diff --git a/pt-br/ruby-pt.html.markdown~ b/pt-br/ruby-pt.html.markdown~ deleted file mode 100644 index cedd2db1..00000000 --- a/pt-br/ruby-pt.html.markdown~ +++ /dev/null @@ -1,598 +0,0 @@ ---- -language: ruby -filename: learnruby.rb -contributors: - - ["Bruno Henrique - Garu", "http://garulab.com"] ---- - -```ruby -# Isso é um comentario - -=begin -This is a multiline comment -No-one uses them -You shouldn't either - -Isso é um comentario multilinha -Ninguém os usa - -=end - -# First and foremost: Everything is an object. -# Primeiro e principal: Tudo é um objeto. - -# Numbers are objects -# Números são objetos - -3.class #=> Fixnum - -3.to_s #=> "3" - - -# Some basic arithmetic -# Aritmética básica - -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# Arithmetic is just syntactic sugar -# for calling a method on an object -# Arithmetic é apenas açúcar semântico -# para chamar um métoddo de um objeto -1.+(3) #=> 4 -10.* 5 #=> 50 - -# Special values are objects -# Valores especiais são obejetos -nil # Nothing to see here -nil # Nada para ver aqui -true # truth -true # verdadeiro -false # falsehood -false # falso - -nil.class #=> NilClass -true.class #=> TrueClass -false.class #=> FalseClass - -# Equality -# Igualdade -1 == 1 #=> true -2 == 1 #=> false - -# Inequality -# Desigualdade -1 != 1 #=> false -2 != 1 #=> true -!true #=> false -!false #=> true - -# apart from false itself, nil is the only other 'falsey' value -# além de 'false', 'nil' é o único outro valor falso - -!nil #=> true -!false #=> true -!0 #=> false - -# More comparisons -# Mais comparações -1 < 10 #=> true -1 > 10 #=> false -2 <= 2 #=> true -2 >= 2 #=> true - -# Strings are objects -# Strings são obejetos - -'I am a string'.class #=> String -'Eu sou uma string'.class #=> String -"I am a string too".class #=> String -"Eu também sou uma string".class #=> String - -placeholder = "use string interpolation" -placeholder = "usar interpolação de string" -"I can #{placeholder} when using double quoted strings" -"Eu posso #{placeholder} quando estiver usando aspas duplas" -#=> "I can use string interpolation when using double quoted strings" -#=> "Eu posso usar insterpolação de string quando estiver usando aspas duplas" - - -# print to the output -# imprime para output (saida) -puts "I'm printing!" -puts "Estou imprimindo" - -# Variables -# Variáveis -x = 25 #=> 25 -x #=> 25 - -# Note that assignment returns the value assigned -# Note que uma atribuição retorna o valor atribuido -# This means you can do multiple assignment: -# Isso significa que você pode fazer multiplas atribuições: - -x = y = 10 #=> 10 -x #=> 10 -y #=> 10 - -# By convention, use snake_case for variable names -# Por convenção, use snake_case para nomes de variáveis -snake_case = true - -# Use descriptive variable names -# Use nomes de variáveis descrivos -path_to_project_root = '/good/name/' -caminho_para_a_raiz_do_projeto = '/bom/nome/' -path = '/bad/name/' -caminho = '/nome/ruim/' - -# Symbols (are objects) -# Simbolos (são objetos) -# Symbols are immutable, reusable constants represented internally by an -# Simbolos são imultáveis, são constantes reutilizáveis representadadas internamente por um -# integer value. They're often used instead of strings to efficiently convey -# valor inteiro. Eles são frequentemente usados no lugar de strings para transmitir com eficiência os valores -# specific, meaningful values -# específicos e significativos - -:pending.class #=> Symbol -:pendente.class #=> Symbol - -status = :pending -status = :pendente - -status == :pending #=> true -status == :pendente #=> true - -status == 'pending' #=> false -status == 'pendente' #=> false - -status == :approved #=> false -status == :aprovado #=> false - -# Arrays - -# This is an array -# Isso é um array -[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] - -# Arrays can contain different types of items -# Arrays podem conter diferentes tipos de itens - -array = [1, "hello", false] #=> => [1, "hello", false] -array = [1, "Oi", false] #=> => [1, "Oi", false] - -# Arrays can be indexed -# Arrays podem ser indexados -# From the front -# a partir do começo -array[0] #=> 1 -array[12] #=> nil - -# Like arithmetic, [var] access -# Como aritimetica, o acesso via [var] -# is just syntactic sugar -# é apenas açúcar sintático -# for calling a method [] on an object -# para chamar o método [] de um objeto -array.[] 0 #=> 1 -array.[] 12 #=> nil - -# From the end -# a partir do final -array[-1] #=> 5 - -# With a start and end index -# Com um índice de começo e fim -array[2, 4] #=> [3, 4, 5] - -# Or with a range -# Ou com um intervalo de valores -array[1..3] #=> [2, 3, 4] - -# Add to an array like this -# Adicionar a um array como este -array << 6 #=> [1, 2, 3, 4, 5, 6] - -# Hashes are Ruby's primary dictionary with keys/value pairs. -# Hashes são dicionário com um par de chave(key)/valor(value) -# Hashes are denoted with curly braces: -# Hashes são simbolizados com chaves "{}" -hash = {'color' => 'green', 'number' => 5} -hash = {'cor' => 'verde', 'numero' => 5} - -hash.keys #=> ['cor', 'numero'] - -# Hashes can be quickly looked up by key: -# Hashes podem ser rapidamente pesquisado pela chave (key) -hash['cor'] #=> 'verde' -hash['numero'] #=> 5 - -# Asking a hash for a key that doesn't exist returns nil: -# Procurar em um hash por uma chave que não existe retorna nil: -hash['nothing here'] #=> nil -hash['nada aqui'] #=> nil - -# Iterate over hashes with the #each method: -# Interar sobre hashes com o método #each: -hash.each do |k, v| - puts "#{k} is #{v}" -end - -hash.each do |k, v| - puts "#{k} é #{v}" -end - -# Since Ruby 1.9, there's a special syntax when using symbols as keys: -# Desde o Ruby 1.9, temos uma sintaxe especial quando usamos simbolos como chaves (keys) - -new_hash = { defcon: 3, action: true} -novo_hash = { defcon: 3, acao: true} - -new_hash.keys #=> [:defcon, :action] -novo_hash.keys #=> [:defcon, :acao] - -# Tip: Both Arrays and Hashes are Enumerable -# Dica: Tanto Arrays quanto Hashes são Enumerable -# They share a lot of useful methods such as each, map, count, and more -# Eles compartilham um monte de métodos úteis como each, map, count e mais - -# Control structures -# Estruturas de controle - -if true - "if statement" -elsif false - "else if, optional" -else - "else, also optional" -end - -if true - "Se verdadeiro" -elsif false - "else if, opicional" -else - "else, também é opicional" -end - -for counter in 1..5 - puts "iteration #{counter}" -end - -for contador in 1..5 - puts "interação #{contador}" -end -#=> contador 1 -#=> contador 2 -#=> contador 3 -#=> contador 4 -#=> contador 5 - -# HOWEVER -# PORÉM -# No-one uses for loops -# Ninguém usa para loops -# Use `each` instead, like this: -# Use "each" em vez, dessa forma: - -(1..5).each do |counter| - puts "iteration #{counter}" -end - -(1..5).each do |contador| - puts "interação #{contador}" -end -#=> contador 1 -#=> contador 2 -#=> contador 3 -#=> contador 4 -#=> contador 5 - -counter = 1 -while counter <= 5 do - puts "iteration #{counter}" - counter += 1 -end - -contador = 1 -while contador <= 5 do - puts "interação #{contador}" - contador += 1 -end -#=> contador 1 -#=> contador 2 -#=> contador 3 -#=> contador 4 -#=> contador 5 - -grade = 'B' - -case grade -when 'A' - puts "Way to go kiddo" -when 'B' - puts "Better luck next time" -when 'C' - puts "You can do better" -when 'D' - puts "Scraping through" -when 'F' - puts "You failed!" -else - puts "Alternative grading system, eh?" -end - -grau = 'B' - -case grau -when 'A' - puts "Um longo caminho a percorrer pequeno gafanhoto" -when 'B' - puts "Melhor sorte da próxima vez" -when 'C' - puts "Você pode fazer melhor" -when 'D' - puts "Scraping through" -when 'F' - puts "Você falhou" -else - puts "Alternative grading system, eh?" -end - -# Functions -# Funções - -def dobrar(x) - x * 2 -end - -# Functions (and all blocks) implcitly return the value of the last statement -# Funções (e todos os blocos) retornam implicitamente o valor da última linha -double(2) #=> 4 -dobrar(2) #=> 4 - -# Parentheses are optional where the result is unambiguous -# Parênteses são opicionais onde o resultado é claro -double 3 #=> 6 -dobrar 3 #=> 6 - -double double 3 #=> 12 -dobrar dobrar 3 #=> 12 - -def sum(x,y) - x + y -end - -def somar(x,y) - x + y -end - -# Method arguments are separated by a comma -# Argumentos de métodos são separados por uma virgula -sum 3, 4 #=> 7 -somar 3, 4 #=> 7 - -somar somar(3,4), 5 #=> 12 - -# yield -# All methods have an implicit, optional block parameter -# Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco -# it can be called with the 'yield' keyword -# ele pode ser chamado com a palavra chave 'yield' - -def surround - puts "{" - yield - puts "}" -end - -surround { puts 'hello world' } - - -def ao_redor - puts "{" - yield - puts "}" -end - -ao_redor { puts 'Olá mundo' } - -# { -# Olá mundo -# } - - -# Define a class with the class keyword -# Define uma classe com a palavra chave 'class' -class Human - - # A class variable. It is shared by all instances of this class. - @@species = "H. sapiens" - - # Basic initializer - def initialize(name, age=0) - # Assign the argument to the "name" instance variable for the instance - @name = name - # If no age given, we will fall back to the default in the arguments list. - @age = age - end - - # Basic setter method - def name=(name) - @name = name - end - - # Basic getter method - def name - @name - end - - # A class method uses self to distinguish from instance methods. - # It can only be called on the class, not an instance. - def self.say(msg) - puts "#{msg}" - end - - def species - @@species - end - -end - - -class Humano - - # Uma variavel de classe. Ela é compartilhada por todas as instancias dessa classe - @@especies = "H. sapiens" - - # Inicialização básica (contructor) - def initialize(nome, idade=0) - # Atribui o argumento para a variavel de instacia "nome" do objeto - @nome = nome - # Se a idade não for passada, nós definimos um valor padrão na lista de argumentos - @idade = idade - end - - # Método básico para atribuir valor - def nome=(nome) - @nome = nome - end - - # Método básico de resgatar valor - def nome - @nome - end - - # Um método de classe usa a palavra chave self para se defenciar dos métodos de instancia. - # Ele só pode ser chamado na classe, não na instancia - def self.diz(msg) - puts "#{msg}" - end - - def especies - @@especies - end - -end - - -# Instantiate a class -# Instaciando uma classe -jim = Human.new("Jim Halpert") -jim = Humano.new("Jim Halpert") - -dwight = Human.new("Dwight K. Schrute") -dwight = Humano.new("Dwight K. Schrute") - -# Let's call a couple of methods -# Vamos chamar um par de métodos -jim.species #=> "H. sapiens" -jim.especies #=> "H. sapiens" - -jim.name #=> "Jim Halpert" -jim.nome #=> "Jim Halpert" - -jim.name = "Jim Halpert II" #=> "Jim Halpert II" -jim.nome = "Jim Halpert II" #=> "Jim Halpert II" - -jim.name #=> "Jim Halpert II" -jim.nome #=> "Jim Halpert II" - -dwight.species #=> "H. sapiens" -dwight.especies #=> "H. sapiens" - -dwight.name #=> "Dwight K. Schrute" -dwight.nome #=> "Dwight K. Schrute" - -# Call the class method -# Chamar o método de classe -Human.say("Hi") #=> "Hi" -Humano.diz("Oi") #=> "Oi" - -# Class also is object in ruby. So class can have instance variables. -# Uma classe também é objeto em Ruby. Então uma classe pode possuir um variavel de instancia -# Class variable is shared among the class and all of its descendants. -# Variavies de classe são compartilhadas entre a classe e todos os seus descendentes. - -# base class -class Human - @@foo = 0 - - def self.foo - @@foo - end - - def self.foo=(value) - @@foo = value - end -end - - -# Classe base -class Humano - @@foo = 0 - - def self.foo - @@foo - end - - def self.foo=(value) - @@foo = value - end -end - -# classe filha -class Trabalhador < Humano -end - -Human.foo # 0 -Humano.foo # 0 -Worker.foo # 0 -Trabalhador.foo # 0 - -Human.foo = 2 # 2 -Humano.foo = 2 # 2 -Worker.foo # 2 -Trabalhador.foo # 2 - -# Class instance variable is not shared by the class's descendants. -# Uma variavel de instancia não é compartilhada por suas classes decendentes. - -class Human - @bar = 0 - - def self.bar - @bar - end - - def self.bar=(value) - @bar = value - end -end - -class Humano - @bar = 0 - - def self.bar - @bar - end - - def self.bar=(value) - @bar = value - end -end - -class Doctor < Human -end - -class Doutor < Humano -end - -Humano.bar # 0 -Doutor.bar # nil - -``` -- cgit v1.2.3 From d9a27d3aa497dd1bb360c24566130fa3b154cb34 Mon Sep 17 00:00:00 2001 From: Katyanna Moura Date: Wed, 14 Aug 2013 12:52:39 -0300 Subject: adding name and removing lines in English --- pt-br/ruby-pt.html.markdown | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 732d06a4..a3e60043 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -3,6 +3,7 @@ language: ruby filename: learnruby.rb contributors: - ["Bruno Henrique - Garu", "http://garulab.com"] + - ["Katyanna Moura"] --- ```ruby @@ -30,14 +31,12 @@ Você não deve usar também 10 * 2 #=> 20 35 / 5 #=> 7 -# Arithmetic is just syntactic sugar -# for calling a method on an object -# Arithmetic é apenas açúcar semântico -# para chamar um métoddo de um objeto +# Aritimética é apenas açúcar sintático +# para chamar um método de um objeto 1.+(3) #=> 4 10.* 5 #=> 50 -# Valores especiais são obejetos +# Valores especiais são objetos nil # Nothing to see here nil # Nada para ver aqui true # truth @@ -71,7 +70,7 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true -# Strings are objects +# Strings são objects 'I am a string'.class #=> String 'Eu sou uma string'.class #=> String @@ -102,14 +101,14 @@ y #=> 10 # Por convenção, use snake_case para nomes de variáveis snake_case = true -# Use nomes de variáveis descrivos +# Use nomes de variáveis descritivos path_to_project_root = '/good/name/' caminho_para_a_raiz_do_projeto = '/bom/nome/' path = '/bad/name/' caminho = '/nome/ruim/' -# Simbolos (são objetos) -# Simbolos são imultáveis, são constantes reutilizáveis representadadas internamente por um +# Símbolos (são objetos) +# Símbolos são imutáveis, são constantes reutilizáveis representadadas internamente por um # valor inteiro. Eles são frequentemente usados no lugar de strings para transmitir com eficiência os valores # específicos e significativos @@ -143,7 +142,7 @@ array = [1, "Oi", false] #=> => [1, "Oi", false] array[0] #=> 1 array[12] #=> nil -# Como aritimetica, o acesso via [var] +# Como aritimética, o acesso via [var] # é apenas açúcar sintático # para chamar o método [] de um objeto array.[] 0 #=> 1 @@ -168,7 +167,7 @@ hash = {'cor' => 'verde', 'numero' => 5} hash.keys #=> ['cor', 'numero'] -# Hashes podem ser rapidamente pesquisado pela chave (key) +# Hashes podem ser rapidamente pesquisados pela chave (key) hash['cor'] #=> 'verde' hash['numero'] #=> 5 @@ -185,7 +184,7 @@ hash.each do |k, v| puts "#{k} é #{v}" end -# Desde o Ruby 1.9, temos uma sintaxe especial quando usamos simbolos como chaves (keys) +# Desde o Ruby 1.9, temos uma sintaxe especial quando usamos símbolos como chaves (keys) new_hash = { defcon: 3, action: true} novo_hash = { defcon: 3, acao: true} @@ -193,7 +192,7 @@ novo_hash = { defcon: 3, acao: true} new_hash.keys #=> [:defcon, :action] novo_hash.keys #=> [:defcon, :acao] -# Dica: Tanto Arrays quanto Hashes são Enumerable +# Dica: Tanto Arrays quanto Hashes são Enumerable. # Eles compartilham um monte de métodos úteis como each, map, count e mais # Estruturas de controle @@ -320,7 +319,7 @@ def somar(x,y) x + y end -# Argumentos de métodos são separados por uma virgula +# Argumentos de métodos são separados por uma vírgula sum 3, 4 #=> 7 somar 3, 4 #=> 7 @@ -425,7 +424,7 @@ class Humano end -# Instaciando uma classe +# Instanciando uma classe jim = Human.new("Jim Halpert") jim = Humano.new("Jim Halpert") -- cgit v1.2.3 From e938d244fcd4095a6dc8be117fdabb4d2370ca2f Mon Sep 17 00:00:00 2001 From: Pablo Elices Date: Wed, 14 Aug 2013 17:56:15 +0200 Subject: Split long line. --- es-es/coffeescript-es.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/es-es/coffeescript-es.html.markdown b/es-es/coffeescript-es.html.markdown index a58c0d07..78bb9be5 100644 --- a/es-es/coffeescript-es.html.markdown +++ b/es-es/coffeescript-es.html.markdown @@ -14,7 +14,8 @@ filename: coffeescript-es.coffee # Los comentarios son como en Ruby y Python, usan almohadillas. ### -Los comentarios en bloque son como estos, y se traducen directamente a '/*' y '*/' para el código JavaScript resultante. +Los comentarios en bloque son como estos, y se traducen directamente a '/*' y '*/' +para el código JavaScript resultante. Deberías entender la mayor parte de la semántica de JavaScript antes de continuar. ### -- cgit v1.2.3 From c1b08624fb7b4fa36cb55ad7fcefe98e073ab32c Mon Sep 17 00:00:00 2001 From: Katyanna Moura Date: Wed, 14 Aug 2013 13:20:47 -0300 Subject: removing lines of code in english --- pt-br/ruby-pt.html.markdown | 162 ++------------------------------------------ 1 file changed, 5 insertions(+), 157 deletions(-) diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index a3e60043..a6021b06 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -7,7 +7,7 @@ contributors: --- ```ruby -# Isso é um comentario +# Isso é um comentário =begin Isso é um comentário multilinha @@ -37,11 +37,8 @@ Você não deve usar também 10.* 5 #=> 50 # Valores especiais são objetos -nil # Nothing to see here nil # Nada para ver aqui -true # truth true # verdadeiro -false # falsehood false # falso nil.class #=> NilClass @@ -72,19 +69,14 @@ false.class #=> FalseClass # Strings são objects -'I am a string'.class #=> String 'Eu sou uma string'.class #=> String -"I am a string too".class #=> String "Eu também sou uma string".class #=> String -placeholder = "use string interpolation" placeholder = "usar interpolação de string" -"I can #{placeholder} when using double quoted strings" "Eu posso #{placeholder} quando estiver usando aspas duplas" #=> "Eu posso usar insterpolação de string quando estiver usando aspas duplas" # imprime para output (saída) -puts "I'm printing!" puts "Estou imprimindo" # Variáveis @@ -102,9 +94,7 @@ y #=> 10 snake_case = true # Use nomes de variáveis descritivos -path_to_project_root = '/good/name/' caminho_para_a_raiz_do_projeto = '/bom/nome/' -path = '/bad/name/' caminho = '/nome/ruim/' # Símbolos (são objetos) @@ -112,19 +102,14 @@ caminho = '/nome/ruim/' # valor inteiro. Eles são frequentemente usados no lugar de strings para transmitir com eficiência os valores # específicos e significativos -:pending.class #=> Symbol :pendente.class #=> Symbol -status = :pending status = :pendente -status == :pending #=> true status == :pendente #=> true -status == 'pending' #=> false status == 'pendente' #=> false -status == :approved #=> false status == :aprovado #=> false # Arrays @@ -134,7 +119,6 @@ status == :aprovado #=> false # Arrays podem conter diferentes tipos de itens -array = [1, "hello", false] #=> => [1, "hello", false] array = [1, "Oi", false] #=> => [1, "Oi", false] # Arrays podem ser indexados @@ -162,7 +146,6 @@ array << 6 #=> [1, 2, 3, 4, 5, 6] # Hashes são o principal dicionário de Ruby com pares de chaves(keys)/valor(value). # Hashes são simbolizados com chaves "{}" -hash = {'color' => 'green', 'number' => 5} hash = {'cor' => 'verde', 'numero' => 5} hash.keys #=> ['cor', 'numero'] @@ -172,7 +155,6 @@ hash['cor'] #=> 'verde' hash['numero'] #=> 5 # Procurar em um hash por uma chave que não existe retorna nil: -hash['nothing here'] #=> nil hash['nada aqui'] #=> nil # Interar sobre hashes com o método #each: @@ -186,10 +168,8 @@ end # Desde o Ruby 1.9, temos uma sintaxe especial quando usamos símbolos como chaves (keys) -new_hash = { defcon: 3, action: true} novo_hash = { defcon: 3, acao: true} -new_hash.keys #=> [:defcon, :action] novo_hash.keys #=> [:defcon, :acao] # Dica: Tanto Arrays quanto Hashes são Enumerable. @@ -197,14 +177,6 @@ novo_hash.keys #=> [:defcon, :acao] # Estruturas de controle -if true - "if statement" -elsif false - "else if, optional" -else - "else, also optional" -end - if true "Se verdadeiro" elsif false @@ -213,10 +185,6 @@ else "else, também é opicional" end -for counter in 1..5 - puts "iteration #{counter}" -end - for contador in 1..5 puts "interação #{contador}" end @@ -230,10 +198,6 @@ end # Ninguém usa para loops # Use "each" em vez, dessa forma: -(1..5).each do |counter| - puts "iteration #{counter}" -end - (1..5).each do |contador| puts "interação #{contador}" end @@ -243,12 +207,6 @@ end #=> contador 4 #=> contador 5 -counter = 1 -while counter <= 5 do - puts "iteration #{counter}" - counter += 1 -end - contador = 1 while contador <= 5 do puts "interação #{contador}" @@ -260,28 +218,11 @@ end #=> contador 4 #=> contador 5 -grade = 'B' - -case grade -when 'A' - puts "Way to go kiddo" -when 'B' - puts "Better luck next time" -when 'C' - puts "You can do better" -when 'D' - puts "Scraping through" -when 'F' - puts "You failed!" -else - puts "Alternative grading system, eh?" -end - grau = 'B' case grau when 'A' - puts "Um longo caminho a percorrer pequeno gafanhoto" + puts "Um longo caminho a percorrer, pequeno gafanhoto" when 'B' puts "Melhor sorte da próxima vez" when 'C' @@ -301,26 +242,18 @@ def dobrar(x) end # Funções (e todos os blocos) retornam implicitamente o valor da última linha -double(2) #=> 4 dobrar(2) #=> 4 # Parênteses são opicionais onde o resultado é claro -double 3 #=> 6 dobrar 3 #=> 6 -double double 3 #=> 12 dobrar dobrar 3 #=> 12 -def sum(x,y) - x + y -end - def somar(x,y) x + y end # Argumentos de métodos são separados por uma vírgula -sum 3, 4 #=> 7 somar 3, 4 #=> 7 somar somar(3,4), 5 #=> 12 @@ -329,15 +262,6 @@ somar somar(3,4), 5 #=> 12 # Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco # ele pode ser chamado com a palavra chave 'yield' -def surround - puts "{" - yield - puts "}" -end - -surround { puts 'hello world' } - - def ao_redor puts "{" yield @@ -352,50 +276,15 @@ ao_redor { puts 'Olá mundo' } # Define uma classe com a palavra chave 'class' -class Human - - # A class variable. It is shared by all instances of this class. - @@species = "H. sapiens" - - # Basic initializer - def initialize(name, age=0) - # Assign the argument to the "name" instance variable for the instance - @name = name - # If no age given, we will fall back to the default in the arguments list. - @age = age - end - - # Basic setter method - def name=(name) - @name = name - end - - # Basic getter method - def name - @name - end - - # A class method uses self to distinguish from instance methods. - # It can only be called on the class, not an instance. - def self.say(msg) - puts "#{msg}" - end - - def species - @@species - end - -end - class Humano - # Uma variavel de classe. Ela é compartilhada por todas as instancias dessa classe + # Uma variável de classe. Ela é compartilhada por todas as instâncias dessa classe @@especies = "H. sapiens" # Inicialização básica (contructor) def initialize(nome, idade=0) - # Atribui o argumento para a variavel de instacia "nome" do objeto + # Atribui o argumento para a variável de instancia "nome" do objeto @nome = nome # Se a idade não for passada, nós definimos um valor padrão na lista de argumentos @idade = idade @@ -411,7 +300,7 @@ class Humano @nome end - # Um método de classe usa a palavra chave self para se defenciar dos métodos de instancia. + # Um método de classe usa a palavra chave self para se defenciar dos métodos de instância. # Ele só pode ser chamado na classe, não na instancia def self.diz(msg) puts "#{msg}" @@ -425,51 +314,29 @@ end # Instanciando uma classe -jim = Human.new("Jim Halpert") jim = Humano.new("Jim Halpert") -dwight = Human.new("Dwight K. Schrute") dwight = Humano.new("Dwight K. Schrute") # Vamos chamar um par de métodos -jim.species #=> "H. sapiens" jim.especies #=> "H. sapiens" -jim.name #=> "Jim Halpert" jim.nome #=> "Jim Halpert" -jim.name = "Jim Halpert II" #=> "Jim Halpert II" jim.nome = "Jim Halpert II" #=> "Jim Halpert II" -jim.name #=> "Jim Halpert II" jim.nome #=> "Jim Halpert II" -dwight.species #=> "H. sapiens" dwight.especies #=> "H. sapiens" -dwight.name #=> "Dwight K. Schrute" dwight.nome #=> "Dwight K. Schrute" # Chamar o método de classe -Human.say("Hi") #=> "Hi" Humano.diz("Oi") #=> "Oi" # Uma classe também é objeto em Ruby. Então uma classe pode possuir variável de instância # Variáveis de classe são compartilhadas entre a classe e todos os seus descendentes. -# base class -class Human - @@foo = 0 - - def self.foo - @@foo - end - - def self.foo=(value) - @@foo = value - end -end - # Classe base class Humano @@ -488,30 +355,14 @@ end class Trabalhador < Humano end -Human.foo # 0 Humano.foo # 0 -Worker.foo # 0 Trabalhador.foo # 0 -Human.foo = 2 # 2 Humano.foo = 2 # 2 -Worker.foo # 2 Trabalhador.foo # 2 # Uma variável de instância não é compartilhada por suas classes decendentes. -class Human - @bar = 0 - - def self.bar - @bar - end - - def self.bar=(value) - @bar = value - end -end - class Humano @bar = 0 @@ -524,9 +375,6 @@ class Humano end end -class Doctor < Human -end - class Doutor < Humano end -- cgit v1.2.3 From c0d84572021330c404fb689241369878cff200e4 Mon Sep 17 00:00:00 2001 From: Bruno Henrique - Garu Date: Wed, 14 Aug 2013 13:34:10 -0300 Subject: Add link to contributor --- pt-br/ruby-pt.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index a6021b06..8e8ce6a8 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -3,7 +3,7 @@ language: ruby filename: learnruby.rb contributors: - ["Bruno Henrique - Garu", "http://garulab.com"] - - ["Katyanna Moura"] + - ["Katyanna Moura", "https://twitter.com/amelie_kn"] --- ```ruby @@ -34,7 +34,7 @@ Você não deve usar também # Aritimética é apenas açúcar sintático # para chamar um método de um objeto 1.+(3) #=> 4 -10.* 5 #=> 50 +10.* 5 #=> 50 # Valores especiais são objetos nil # Nada para ver aqui @@ -135,7 +135,7 @@ array.[] 12 #=> nil # a partir do final array[-1] #=> 5 -# Com um índice de começo e fim +# Com um índice de começo e fim array[2, 4] #=> [3, 4, 5] # Ou com um intervalo de valores @@ -231,7 +231,7 @@ when 'D' puts "Scraping through" when 'F' puts "Você falhou" -else +else puts "Alternative grading system, eh?" end @@ -259,7 +259,7 @@ somar 3, 4 #=> 7 somar somar(3,4), 5 #=> 12 # yield -# Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco +# Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco # ele pode ser chamado com a palavra chave 'yield' def ao_redor -- cgit v1.2.3 From 6062618d358839e22f4bbe6348658253ad2e0209 Mon Sep 17 00:00:00 2001 From: Geoffrey Roguelon Date: Wed, 14 Aug 2013 19:11:13 +0200 Subject: Fix a missing character in the comment. remove useless whitespace at the end of the lines. --- ruby.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 19f2ec86..3a233d98 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -36,7 +36,7 @@ You shouldn't either # Arithmetic is just syntactic sugar # for calling a method on an object 1.+(3) #=> 4 -10.* 5 #=> 50 +10.* 5 #=> 50 # Special values are objects nil # Nothing to see here @@ -242,7 +242,7 @@ when 'D' puts "Scraping through" when 'F' puts "You failed!" -else +else puts "Alternative grading system, eh?" end @@ -252,7 +252,7 @@ def double(x) x * 2 end -# Functions (and all blocks) implcitly return the value of the last statement +# Functions (and all blocks) implicitly return the value of the last statement double(2) #=> 4 # Parentheses are optional where the result is unambiguous -- cgit v1.2.3 From ae73dd671f521527f6e58a877026c35d58173671 Mon Sep 17 00:00:00 2001 From: Geoffrey Roguelon Date: Wed, 14 Aug 2013 19:12:21 +0200 Subject: Add the French translation of the Ruby language. --- fr-fr/ruby-fr.html.markdown | 406 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 406 insertions(+) create mode 100644 fr-fr/ruby-fr.html.markdown diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown new file mode 100644 index 00000000..f6bfe42a --- /dev/null +++ b/fr-fr/ruby-fr.html.markdown @@ -0,0 +1,406 @@ +--- +language: ruby +filename: learnruby-fr.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] +translators: + - ["Geoffrey Roguelon", "https://github.com/GRoguelon"] +lang: fr-fr +--- + +```ruby +# Ceci est un commentaire + +=begin +Ceci est un commentaire multiligne +Personne ne les utilise +Vous devriez en faire de même +=end + +# Tout d'abord : Tout est un objet. + +# Les nombres sont des objets + +3.class #=> Fixnum + +3.to_s #=> "3" + +# Arithmétique de base +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# L'arithmétique est juste un raccourci +# pour appeler la méthode d'un objet +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Les valeurs spéciales sont des objets +nil # Nothing to see here +true # truth +false # falsehood + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Égalité +1 == 1 #=> true +2 == 1 #=> false + +# Inégalité +1 != 1 #=> false +2 != 1 #=> true +!true #=> false +!false #=> true + +# à part false lui-même, nil est la seule autre valeur 'false' + +!nil #=> true +!false #=> true +!0 #=> false + +# Plus de comparaisons +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Les chaînes de caractères sont des objets + +'Je suis une chaîne de caractères'.class #=> String +"Je suis également une chaîne de caractères".class #=> String + +placeholder = "utiliser l'interpolation de chaîne de caractères" +"Je peux #{placeholder} quand j'utilise les guillemets" +#=> "Je peux utiliser l'interpolation de chaîne de caractères quand j'utilise les guillemets" + +# Afficher sur la sortie standard +puts "J'affiche à l'écran!" + +# Variables +x = 25 #=> 25 +x #=> 25 + +# Notez que l'affectation retourne la valeur affectée. +# Cela signifie que vous pouvez affecter plusieurs fois de suite : + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Par convention, utiliser snake_case (à base d'underscore) +# comme nom de variable +snake_case = true + +# Utiliser des noms de variable explicites +path_to_project_root = '/nom/correct/' +path = '/mauvais/nom/' + +# Symboles (sont des objets) +# Les symboles sont immuables, constants, +# réutilisables et représentés en interne +# par une valeur entière. Ils sont souvent +# utilisés à la place des chaînes de caractères +# pour transmettre efficacement des valeurs +# spécifiques ou significatives + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# Tableaux + +# Ceci est un tableau +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Les tableaux contiennent différents types d'élément. + +[1, "hello", false] #=> [1, "hello", false] + +# Les tableaux peuvent être indéxés +# Du début +array[0] #=> 1 +array[12] #=> nil + +# Comme l'arithmétique, la syntaxe [var] est juste un raccourci +# pour appeler la méthode [] d'un objet +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# À la fin +array[-1] #=> 5 + +# Avec un index de début et de fin +array[2, 4] #=> [3, 4, 5] + +# Ou avec un interval +array[1..3] #=> [2, 3, 4] + +# Ajouter un élément au tableau comme ceci +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# Les Hashes sont des dictionnaires Ruby contenant des paires de clé/valeur. +# Les Hashes sont délimitées par des accolades : +hash = {'color' => 'green', 'number' => 5} + +hash.keys #=> ['color', 'number'] + +# Les Hashes peuvent retourner rapidement +# la valeur en utilisant la clé : +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# Rechercher une clé inexistante dans une Hash retourne nil: +hash['nothing here'] #=> nil + +# Depuis Ruby 1.9, Une syntaxe spécifique est apparue en utilisant les symboles comme clés : + +new_hash = { defcon: 3, action: true} + +new_hash.keys #=> [:defcon, :action] + +# Astuce : Les tableaux et les Hashes sont dénombrables +# Ils partagent un certain nombre de méthodes pratiques +# telle que each, map, count, etc... + +# Structures de contrôle + +if true + "si instruction" +elsif false + "autrement si, facultatif" +else + "autrement, également facultatif" +end + +for compteur in 1..5 + puts "itération #{compteur}" +end +#=> itération 1 +#=> itération 2 +#=> itération 3 +#=> itération 4 +#=> itération 5 + +# CEPENDANT, Personne n'utilise la boucle for. +# À la place, vous devrez utiliser la méthode "each" +# et lui passer un bloc de code. +# Un bloc de code est un ensemble d'instructions que vous pouvez passer à une methode comme "each". +# Les blocs sont similaires aux lambdas, les fonctions anonymes ou les closures dans d'autres langages. +# +# La méthode "each" exécute le bloc de code pour chaque élément de l'interval d'éléments. +# Le bloc de code passe un paramètre compteur. +# Appeler la méthode "each" avec un bloc de code comme ceci : + +(1..5).each do |compteur| + puts "itération #{compteur}" +end +#=> itération 1 +#=> itération 2 +#=> itération 3 +#=> itération 4 +#=> itération 5 + +# Vous pouvez également mettre un bloc de code entre accolades : +(1..5).each {|compteur| puts "itération #{compteur}"} + +# Le contenu des structures de données peut être parcouru +# en utilisant la méthode each. +array.each do |element| + puts "#{element} est une partie du tableau" +end +hash.each do |cle, valeur| + puts "#{cle} est #{valeur}" +end + +compteur = 1 +while compteur <= 5 do + puts "itération #{compteur}" + compteur += 1 +end +#=> itération 1 +#=> itération 2 +#=> itération 3 +#=> itération 4 +#=> itération 5 + +grade = 'B' + +case grade +when 'A' + puts "Excellence" +when 'B' + puts "Plus de chance la première fois" +when 'C' + puts "Vous pouvez faire mieux" +when 'D' + puts "C'est pas terrible" +when 'F' + puts "Vous avez échoué!" +else + puts "Sytème de notation alternatif" +end + +# Fonctions + +def double(x) + x * 2 +end + +# Les fonctions (et tous les blocs de code) retournent +# implicitement la valeur de la dernière instruction évaluée +double(2) #=> 4 + +# Les paranthèses sont facultative +# où il n'y a pas d'ambiguïté sur le résultat +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x,y) + x + y +end + +# Les paramètres de méthode sont séparés par des virgules +sum 3, 4 #=> 7 + +sum sum(3,4), 5 #=> 12 + +# yield +# Toutes les méthodes ont un argument de type bloc de code +# facultatif et implicite +# il peut être appelé avec le mot clé 'yield' + +def surround + puts "{" + yield + puts "}" +end + +surround { puts 'Bonjour tout le monde' } + +# { +# Bonjour tout le monde +# } + + +# Définir une classe avec le mot clé 'class' +class Humain + + # Une variable de classe, + # elle est partagée par toutes les instances de cette classe. + @@espece = "H. sapiens" + + # Constructeur de classe + def initialize(nom, age = 0) + # Affecter l'argument à la variable d'instance 'nom' + # pour la durée de vie de l'instance de cette classe + @nom = nom + # Si le paramètre 'age' est absent, + # la valeur par défaut définie dans la liste des arguments sera utilisée. + @age = age + end + + # Une simple méthode setter + def nom=(nom) + @nom = nom + end + + # Une simple méthode getter + def nom + @nom + end + + # Une méthode de classe utilise le mot clé 'self' + # pour se distinguer de la méthode d'instance. + # La méthode sera alors accessible à partir de la classe + # et non pas de l'instance. + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end + +end + + +# Instancier une classe +jim = Humain.new("Jim Halpert") + +dwight = Humain.new("Dwight K. Schrute") + +# Appelons quelques méthodes +jim.espece #=> "H. sapiens" +jim.nom #=> "Jim Halpert" +jim.nom = "Jim Halpert II" #=> "Jim Halpert II" +jim.nom #=> "Jim Halpert II" +dwight.espece #=> "H. sapiens" +dwight.nom #=> "Dwight K. Schrute" + +# Appelons la méthode de classe +Humain.say("Hi") #=> "Hi" + +# Les classes sont également des objets en Ruby. +# Par conséquent, les classes peuvent avoir des variables d'instance. +# Les variables de classe sont partagées parmi +# la classe et ses descendants. + +# Classe de base +class Humain + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(valeur) + @@foo = valeur + end +end + +# Héritage de classe +class Travailleur < Humain +end + +Humain.foo # 0 +Travailleur.foo # 0 + +Humain.foo = 2 # 2 +Travailleur.foo # 2 + +# Les variables d'instance de classe ne sont pas partagées +# avec les classes héritées. + +class Humain + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(valeur) + @bar = valeur + end +end + +class Docteur < Humain +end + +Humain.bar # 0 +Docteur.bar # nil + +``` -- cgit v1.2.3 From 162b5bb60dea93dac591005a73956be663313761 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Wed, 14 Aug 2013 23:15:17 +0300 Subject: Fix typo about how pointers are declared Of course it is completely valid that star can go right after type name, but it might be not that obvious that during declaration the star is associated to the variable, not with the type name. --- c.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index d243b19d..2b50efa0 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -230,10 +230,13 @@ printf("%p\n", &x); // Use & to retrieve the address of a variable // (%p formats a pointer) // => Prints some address in memory; -// Pointer types end with * in their declaration -int* px; // px is a pointer to an int + +// Pointers start with * in their declaration +int *px, not_a_pointer; // px is a pointer to an int px = &x; // Stores the address of x in px printf("%p\n", px); // => Prints some address in memory +printf("%d, %d\n", (int)sizeof(px), (int)sizeof(not_a_pointer)); +// => Prints "8, 4" on 64-bit system // To retreive the value at the address a pointer is pointing to, // put * in front to de-reference it. -- cgit v1.2.3 From c4f86cbf70a6c8d3b03be87df32aeff88183da63 Mon Sep 17 00:00:00 2001 From: Vyacheslav Redkin Date: Thu, 15 Aug 2013 09:26:41 +0400 Subject: Add russian translate for php language --- ru-ru/php-ru.html.markdown | 658 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 658 insertions(+) create mode 100644 ru-ru/php-ru.html.markdown diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown new file mode 100644 index 00000000..6c5720e3 --- /dev/null +++ b/ru-ru/php-ru.html.markdown @@ -0,0 +1,658 @@ +--- +language: php +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] + - ["SlaF", "https://github.com/SlaF"] +lang: ru-ru +filename: learnphp-ru.php +--- + +Этот документ описывает версию PHP 5 и выше. + +```php + + +// А так начинаются комментарии + +# Это тоже комментарий но // предпочтительнее + +/* + Окруженный /* и */ текст превращается + в многострочный комментарий +*/ + +// Используйте "echo" или "print" для вывода. +print('Hello '); // Напечатать "Hello " без перевода строки + +// () необязательно применять для print и echo +echo "World\n"; // Печатать "World" и перейти на новую строку. +// (все утверждения должны заканчиваться ;) + +// Любые символы за пределами закрывающегося тега выводятся автоматически: +?> +Hello World Again! + 12 +$int2 = -12; // => -12- +$int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число) +$int4 = 0x0F; // => 15 (ведущие символы 0x означает шестнадцатеричное число) + +// Дробные числа +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Арифметика +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// Арифметические сокращения +$number = 0; +$number += 1; // Увеличивает $number на 1 +echo $number++; // Печатает 1 (инкрементируется после вывода) +echo ++$number; // Печатает 3 (инкрементируется до вывода) +$number /= $float; // Делится и результат присваивается $number + +// Строки должны быть заключены в одинарные кавычки; +$sgl_quotes = '$String'; // => '$String' + +// Избегайте двойных кавычек за исключением случаев интерполирования переменной +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Специальные (escape) символы работают только в двойных кавычках +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// Заключайте переменные в фигурные скобки если это необходимо +$money = "I have $${number} in the bank."; + +// Начиная с PHP 5.3, синтаксис nowdocs может использоваться для неинтерполированного многострочного текста +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredocs поддерживает интерполяцию переменных +$heredoc = << 1, 'Two' => 2, 'Three' => 3); + +// В PHP 5.4 появился новый синтаксис +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // печатает 1 + +// Список тоже содержит целочисленные ключи +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + + +/******************************** + * Вывод + */ + +echo('Hello World!'); +// Печатает Hello World! на stdout. +// Stdout это веб-страница запущенная в браузере. + +print('Hello World!'); // Аналогично echo + +// echo - это конструкция языка, вы можете опустить скобки. +echo 'Hello World!'; +print 'Hello World!'; // Выводит Hello World! + +$paragraph = 'paragraph'; + +echo 100; // Печать скалярной переменной напрямую +echo $paragraph; // или печать переменной + +// Если короткие теги разрешены, или ваша версия PHP >= 5.4 +// вы можете использовать сокращенный синтаксис echo +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + + +/******************************** + * Логические выражения + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// Утверждение (assert) выдает предупреждение если аргумент не true + +// Эти сравнения всегда будут истинными, даже если типы будут различаться +assert($a == $b); // "равно" +assert($c != $a); // "не равно" +assert($c <> $a); // другое обозначение "не равно" +assert($a < $c); // меньше +assert($c > $b); // больше +assert($a <= $b); // меньше или равно +assert($c >= $d); // больше или равно + +// Следующие утверждения истинны если переменные имеют одинаковый тип. +assert($c === $d); +assert($a !== $d); +assert(1 == '1'); +assert(1 !== '1'); + +// Переменные могут изменять тип, в зависимости от их использования. +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (строка превращается в число) + +// Выводится 0 по той причине, что оператор + не может привести строку 'one' к числовому типу +$string = 'one'; +echo $string + $string; // => 0 + +// Приведение типов (type casting) может быть использовано для преобразование переменной в другой тип +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// Также существуют функции выполняющие приведение типов +$integer = 5; +$string = strval($integer); +$float = floatval($integer); + +$var = null; // Null + +// И похожая по действию функция +$integer = 10; +$boolen = settype($integer, "string") // теперь $integer имеет строковый тип + +// settype возвращает true - если преобразование удалось и false в противном случае + +/******************************** + * Управляющие структуры + */ + +if (true) { + print 'I get printed'; +} + +if (false) { + print 'I don\'t'; +} else { + print 'I get printed'; +} + +if (false) { + print 'Does not get printed'; +} elseif(true) { + print 'Does'; +} + +// Тернарный оператор +print (false ? 'Does not get printed' : 'Does'); + +$x = 0; +if ($x === '0') { + print 'Does not print'; +} elseif($x == '1') { + print 'Does not print'; +} else { + print 'Does print'; +} + +// Альтернативный синтаксис полезный для шаблонов +?> + + +This is displayed if the test is truthy. + +This is displayed otherwise. + + + 2, 'car' => 4]; + +// Циклы foreach могут обходить массивы +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Prints "24" + +echo "\n"; + +// Вы можете обходить как ключи, так и их значения +foreach ($wheels as $vehicle => $wheel_count) { + echo "A $vehicle has $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Exit out of the while loop + } + echo $i++; +} // Prints "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Skip this iteration of the loop + } + echo $i; +} // Prints "0124" + + +/******************************** + * Функции + */ + +// Определение функции: +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// Правильное имя функции начинается с буквы или символа подчеркивания +// и состоит из букв, цифр или знаков подчеркивания. + +function add ($x, $y = 1) { // $y по умолчанию равно 1 + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result недоступна за пределами функции +// print $result; // Выдает предупреждение + +// Начиная с PHP 5.3 вы можете объявлять анонимные функции: +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Функции могут возвращать функции +function bar ($x, $y) { + // Используйте 'use' для передачи внешних переменных + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Prints "A - B - C" + +// Вы можете вызывать именованные функции используя строки +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// Полезно для программного определения запущенной функции. +// Или используйте call_user_func(callable $callback [, $parameter [, ... ]]); + + +/******************************** + * Includes + */ + +instanceProp = $instanceProp; + } + + // Methods are declared as functions inside a class + public function myMethod() + { + print 'MyClass'; + } + + final function youCannotOverrideMe() + { + } + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +echo MyClass::MY_CONST; // Выведет 'value'; +echo MyClass::$staticVar; // Выведет 'static'; +MyClass::myStaticMethod(); // Выведет 'I am static'; + +// Новый экземпляр класса используя new +$my_class = new MyClass('An instance property'); + +// Если аргументы отсутствуют, можно не ставить круглые скобки + +// Доступ к членам класса используя -> +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + +// Наследование классов используя "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Выведет "protected" +$my_other_class->myMethod(); // Выведет "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// Вы можете использовать "магические методы" для создания геттеров и сеттеров +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Будет использован метод __get() +$x->property = 'Something'; // Будет использован метод __set() + +// Классы могут быть абстрактными (используя ключевое слово abstract) +// или реализовывать интерфейсы (используя ключевое слово implements). +// Интерфейсы определяются при помощи ключевого слова interface + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// Интерфейсы могут быть расширены +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + +// Классы могут реализовывать более одного интерфейса +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Трейты + */ + +// Трейты появились в PHP 5.4.0 и объявляются при помощи ключевого слова trait + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Пространства имен + */ + +// Это секция особая, ведь объявление пространства имен +// должно быть самым первым в файле. Позвольте сделать вид, что это не так + + Date: Thu, 15 Aug 2013 10:45:06 +0200 Subject: Fix the comments of French Ruby file from the Nami-Doc's comments (adambard/learnxinyminutes-docs#223). Thanks to him. --- fr-fr/ruby-fr.html.markdown | 81 +++++++++++++++++++++++---------------------- 1 file changed, 41 insertions(+), 40 deletions(-) diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown index f6bfe42a..f5212787 100644 --- a/fr-fr/ruby-fr.html.markdown +++ b/fr-fr/ruby-fr.html.markdown @@ -9,6 +9,7 @@ contributors: - ["Nick LaMuro", "https://github.com/NickLaMuro"] translators: - ["Geoffrey Roguelon", "https://github.com/GRoguelon"] + - ["Nami-Doc", "https://github.com/Nami-Doc"] lang: fr-fr --- @@ -29,21 +30,21 @@ Vous devriez en faire de même 3.to_s #=> "3" -# Arithmétique de base +# Les opérateurs de base 1 + 1 #=> 2 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 -# L'arithmétique est juste un raccourci -# pour appeler la méthode d'un objet +# Les opérateurs sont juste des raccourcis +# pour appeler une méthode sur un objet 1.+(3) #=> 4 10.* 5 #=> 50 # Les valeurs spéciales sont des objets -nil # Nothing to see here -true # truth -false # falsehood +nil # Nul +true # Vrai +false # Faux nil.class #=> NilClass true.class #=> TrueClass @@ -80,7 +81,7 @@ placeholder = "utiliser l'interpolation de chaîne de caractères" "Je peux #{placeholder} quand j'utilise les guillemets" #=> "Je peux utiliser l'interpolation de chaîne de caractères quand j'utilise les guillemets" -# Afficher sur la sortie standard +# Affichez un message puts "J'affiche à l'écran!" # Variables @@ -94,15 +95,15 @@ x = y = 10 #=> 10 x #=> 10 y #=> 10 -# Par convention, utiliser snake_case (à base d'underscore) -# comme nom de variable +# Par convention, utilisez la notation underscore +# pour nommer les variables snake_case = true -# Utiliser des noms de variable explicites +# Utilisez des noms de variable explicites path_to_project_root = '/nom/correct/' path = '/mauvais/nom/' -# Symboles (sont des objets) +# Symboles (aussi des objets) # Les symboles sont immuables, constants, # réutilisables et représentés en interne # par une valeur entière. Ils sont souvent @@ -129,40 +130,40 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] [1, "hello", false] #=> [1, "hello", false] -# Les tableaux peuvent être indéxés +# Les tableaux peuvent être indexés # Du début array[0] #=> 1 array[12] #=> nil -# Comme l'arithmétique, la syntaxe [var] est juste un raccourci +# Comme les opérateurs, la syntaxe [var] est juste un raccourci # pour appeler la méthode [] d'un objet array.[] 0 #=> 1 array.[] 12 #=> nil -# À la fin +# Depuis la fin array[-1] #=> 5 # Avec un index de début et de fin array[2, 4] #=> [3, 4, 5] -# Ou avec un interval +# Ou avec un intervalle array[1..3] #=> [2, 3, 4] -# Ajouter un élément au tableau comme ceci +# Ajoutez un élément au tableau comme ceci array << 6 #=> [1, 2, 3, 4, 5, 6] -# Les Hashes sont des dictionnaires Ruby contenant des paires de clé/valeur. -# Les Hashes sont délimitées par des accolades : +# Les Hash sont des dictionnaires Ruby contenant des paires de clé/valeur. +# Les Hash sont délimitées par des accolades : hash = {'color' => 'green', 'number' => 5} hash.keys #=> ['color', 'number'] -# Les Hashes peuvent retourner rapidement -# la valeur en utilisant la clé : +# Les Hash retournent la valeur +# en utilisant la clé associée à la valeur : hash['color'] #=> 'green' hash['number'] #=> 5 -# Rechercher une clé inexistante dans une Hash retourne nil: +# Recherchez une clé inexistante dans une Hash retourne nil : hash['nothing here'] #=> nil # Depuis Ruby 1.9, Une syntaxe spécifique est apparue en utilisant les symboles comme clés : @@ -171,7 +172,7 @@ new_hash = { defcon: 3, action: true} new_hash.keys #=> [:defcon, :action] -# Astuce : Les tableaux et les Hashes sont dénombrables +# Astuce : Les tableaux et les Hash sont dénombrables # Ils partagent un certain nombre de méthodes pratiques # telle que each, map, count, etc... @@ -194,15 +195,15 @@ end #=> itération 4 #=> itération 5 -# CEPENDANT, Personne n'utilise la boucle for. -# À la place, vous devrez utiliser la méthode "each" -# et lui passer un bloc de code. +# CEPENDANT, l'usage de la boucle for est très rare. +# À la place, utilisez la méthode "each" +# et passez lui un bloc de code. # Un bloc de code est un ensemble d'instructions que vous pouvez passer à une methode comme "each". # Les blocs sont similaires aux lambdas, les fonctions anonymes ou les closures dans d'autres langages. # -# La méthode "each" exécute le bloc de code pour chaque élément de l'interval d'éléments. +# La méthode "each" exécute le bloc de code pour chaque élément de l'intervalle d'éléments. # Le bloc de code passe un paramètre compteur. -# Appeler la méthode "each" avec un bloc de code comme ceci : +# Appelez la méthode "each" avec un bloc de code comme ceci : (1..5).each do |compteur| puts "itération #{compteur}" @@ -240,7 +241,7 @@ grade = 'B' case grade when 'A' - puts "Excellence" + puts "Excellent" when 'B' puts "Plus de chance la première fois" when 'C' @@ -264,7 +265,7 @@ end double(2) #=> 4 # Les paranthèses sont facultative -# où il n'y a pas d'ambiguïté sur le résultat +# lorsqu'il n'y a pas d'ambiguïté sur le résultat double 3 #=> 6 double double 3 #=> 12 @@ -279,8 +280,8 @@ sum 3, 4 #=> 7 sum sum(3,4), 5 #=> 12 # yield -# Toutes les méthodes ont un argument de type bloc de code -# facultatif et implicite +# Toutes les méthodes ont un argument facultatif et implicite +# de type bloc de code # il peut être appelé avec le mot clé 'yield' def surround @@ -296,16 +297,16 @@ surround { puts 'Bonjour tout le monde' } # } -# Définir une classe avec le mot clé 'class' +# Définissez une classe avec le mot clé 'class' class Humain - # Une variable de classe, - # elle est partagée par toutes les instances de cette classe. + # Une variable de classe + # est partagée par toutes les instances de cette classe. @@espece = "H. sapiens" # Constructeur de classe def initialize(nom, age = 0) - # Affecter l'argument à la variable d'instance 'nom' + # Affectez l'argument à la variable d'instance 'nom' # pour la durée de vie de l'instance de cette classe @nom = nom # Si le paramètre 'age' est absent, @@ -338,12 +339,12 @@ class Humain end -# Instancier une classe +# Instanciez une classe jim = Humain.new("Jim Halpert") dwight = Humain.new("Dwight K. Schrute") -# Appelons quelques méthodes +# Appelez quelques méthodes jim.espece #=> "H. sapiens" jim.nom #=> "Jim Halpert" jim.nom = "Jim Halpert II" #=> "Jim Halpert II" @@ -351,7 +352,7 @@ jim.nom #=> "Jim Halpert II" dwight.espece #=> "H. sapiens" dwight.nom #=> "Dwight K. Schrute" -# Appelons la méthode de classe +# Appelez la méthode de classe Humain.say("Hi") #=> "Hi" # Les classes sont également des objets en Ruby. @@ -359,7 +360,7 @@ Humain.say("Hi") #=> "Hi" # Les variables de classe sont partagées parmi # la classe et ses descendants. -# Classe de base +# Classe parente class Humain @@foo = 0 @@ -372,7 +373,7 @@ class Humain end end -# Héritage de classe +# Classe fille class Travailleur < Humain end -- cgit v1.2.3 From 7cb78e94d24d7c768868fa4bd575a7572126cbe5 Mon Sep 17 00:00:00 2001 From: dacechavez Date: Thu, 15 Aug 2013 12:12:19 +0200 Subject: Fixed 2 typos around function pointers --- c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 2b50efa0..e8a26056 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -373,7 +373,7 @@ int area(rect r){ /////////////////////////////////////// /* At runtime, functions are located at known memory addresses. Function pointers are -much likely any other pointer (they just store a memory address), but can be used +much like any other pointer (they just store a memory address), but can be used to invoke functions directly, and to pass handlers (or callback functions) around. However, definition syntax may be initially confusing. @@ -394,7 +394,7 @@ Function pointers are usually typedef'd for simplicity and readability, as follo typedef void (*my_fnp_type)(char *); -// The used when declaring the actual pointer variable: +// Then used when declaring the actual pointer variable: // ... // my_fnp_type f; -- cgit v1.2.3 From 7f8e5deba129c4b9fb34b89077a63829546b0bd3 Mon Sep 17 00:00:00 2001 From: Geoffrey Roguelon Date: Thu, 15 Aug 2013 12:22:36 +0200 Subject: Fix a word of French Ruby language. --- fr-fr/ruby-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown index f5212787..5efb2f3c 100644 --- a/fr-fr/ruby-fr.html.markdown +++ b/fr-fr/ruby-fr.html.markdown @@ -243,7 +243,7 @@ case grade when 'A' puts "Excellent" when 'B' - puts "Plus de chance la première fois" + puts "Plus de chance la prochaine fois" when 'C' puts "Vous pouvez faire mieux" when 'D' -- cgit v1.2.3 From 24fd870589d863618e6ba2571b6a0c8339d35edc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81rp=C3=A1d=20Goretity=20=EF=A3=BF?= Date: Thu, 15 Aug 2013 12:30:22 +0200 Subject: Update c.html.markdown --- c.html.markdown | 629 ++++++++++++++++++++++++++++++++------------------------ 1 file changed, 356 insertions(+), 273 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 2b50efa0..ac6c7ab4 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -5,19 +5,20 @@ language: c filename: learnc.c contributors: - ["Adam Bard", "http://adambard.com/"] + - ["Árpád Goretity", "http://twitter.com/h2co3_ios"] --- -Ah, C. Still the language of modern high-performance computing. +Ah, C. Still **the** language of modern high-performance computing. C is the lowest-level language most programmers will ever use, but it more than makes up for it with raw speed. Just be aware of its manual memory management and C will take you as far as you need to go. ```c -// Single-line comments start with // +// Single-line comments start with // - only available in C99 and later. /* -Multi-line comments look like this. +Multi-line comments look like this. They work in C89 as well. */ // Import headers with #include @@ -25,6 +26,11 @@ Multi-line comments look like this. #include #include +// file names between are headers from the C standard library. +// They are searched for by the preprocessor in the system include paths +// (usually /usr/lib on Unices, can be controlled with the -I option if you are using GCC or clang.) +// For your + // Declare function signatures in advance in a .h file, or at the top of // your .c file. void function_1(); @@ -33,264 +39,317 @@ void function_2(); // Your program's entry point is a function called // main with an integer return type. int main() { - -// print output using printf, for "print formatted" -// %d is an integer, \n is a newline -printf("%d\n", 0); // => Prints 0 -// All statements must end with a semicolon - -/////////////////////////////////////// -// Types -/////////////////////////////////////// - -// You have to declare variables before using them. A variable declaration -// requires you to specify its type; a variable's type determines its size -// in bytes. - -// ints are usually 4 bytes -int x_int = 0; - -// shorts are usually 2 bytes -short x_short = 0; - -// chars are guaranteed to be 1 byte -char x_char = 0; -char y_char = 'y'; // Char literals are quoted with '' - -// longs are often 4 to 8 bytes; long longs are guaranteed to be at least -// 64 bits -long x_long = 0; -long long x_long_long = 0; - -// floats are usually 32-bit floating point numbers -float x_float = 0.0; - -// doubles are usually 64-bit floating-point numbers -double x_double = 0.0; - -// Integral types may be unsigned. This means they can't be negative, but -// the maximum value of an unsigned variable is greater than the maximum -// signed value of the same size. -unsigned char ux_char; -unsigned short ux_short; -unsigned int ux_int; -unsigned long long ux_long_long; - -// Other than char, which is always 1 byte, these types vary in size depending -// on your machine. sizeof(T) gives you the size of a variable with type T in -// bytes so you can express the size of these types in a portable way. -// For example, -printf("%lu\n", sizeof(int)); // => 4 (on machines with 4-byte words) - -// Arrays must be initialized with a concrete size. -char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes -int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes - // (assuming 4-byte words) - - -// You can initialize an array to 0 thusly: -char my_array[20] = {0}; - -// Indexing an array is like other languages -- or, -// rather, other languages are like C -my_array[0]; // => 0 - -// Arrays are mutable; it's just memory! -my_array[1] = 2; -printf("%d\n", my_array[1]); // => 2 - -// Strings are just arrays of chars terminated by a NUL (0x00) byte, -// represented in strings as the special character '\0'. -// (We don't have to include the NUL byte in string literals; the compiler -// inserts it at the end of the array for us.) -char a_string[20] = "This is a string"; -printf("%s\n", a_string); // %s formats a string - -/* -You may have noticed that a_string is only 16 chars long. -Char #17 is the NUL byte. -Chars #18, 19 and 20 have undefined values. -*/ - -printf("%d\n", a_string[16]); // => 0 - -/////////////////////////////////////// -// Operators -/////////////////////////////////////// - -int i1 = 1, i2 = 2; // Shorthand for multiple declaration -float f1 = 1.0, f2 = 2.0; - -// Arithmetic is straightforward -i1 + i2; // => 3 -i2 - i1; // => 1 -i2 * i1; // => 2 -i1 / i2; // => 0 (0.5, but truncated towards 0) - -f1 / f2; // => 0.5, plus or minus epsilon - -// Modulo is there as well -11 % 3; // => 2 - -// Comparison operators are probably familiar, but -// there is no boolean type in c. We use ints instead. -// 0 is false, anything else is true. (The comparison -// operators always return 0 or 1.) -3 == 2; // => 0 (false) -3 != 2; // => 1 (true) -3 > 2; // => 1 -3 < 2; // => 0 -2 <= 2; // => 1 -2 >= 2; // => 1 - -// Logic works on ints -!3; // => 0 (Logical not) -!0; // => 1 -1 && 1; // => 1 (Logical and) -0 && 1; // => 0 -0 || 1; // => 1 (Logical or) -0 || 0; // => 0 - -// Bitwise operators! -~0x0F; // => 0xF0 (bitwise negation) -0x0F & 0xF0; // => 0x00 (bitwise AND) -0x0F | 0xF0; // => 0xFF (bitwise OR) -0x04 ^ 0x0F; // => 0x0B (bitwise XOR) -0x01 << 1; // => 0x02 (bitwise left shift (by 1)) -0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) - -/////////////////////////////////////// -// Control Structures -/////////////////////////////////////// - -if (0) { - printf("I am never run\n"); -} else if (0) { - printf("I am also never run\n"); -} else { - printf("I print\n"); -} - -// While loops exist -int ii = 0; -while (ii < 10) { - printf("%d, ", ii++); // ii++ increments ii in-place, after using its value. -} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - -printf("\n"); - -int kk = 0; -do { - printf("%d, ", kk); -} while (++kk < 10); // ++kk increments kk in-place, before using its value -// => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - -printf("\n"); - -// For loops too -int jj; -for (jj=0; jj < 10; jj++) { - printf("%d, ", jj); -} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - -printf("\n"); - -/////////////////////////////////////// -// Typecasting -/////////////////////////////////////// - -// Every value in C has a type, but you can cast one value into another type -// if you want. - -int x_hex = 0x01; // You can assign vars with hex literals - -// Casting between types will attempt to preserve their numeric values -printf("%d\n", x_hex); // => Prints 1 -printf("%d\n", (short) x_hex); // => Prints 1 -printf("%d\n", (char) x_hex); // => Prints 1 - -// Types will overflow without warning -printf("%d\n", (char) 257); // => 1 (Max char = 255) - -// Integral types can be cast to floating-point types, and vice-versa. -printf("%f\n", (float)100); // %f formats a float -printf("%lf\n", (double)100); // %lf formats a double -printf("%d\n", (char)100.0); - -/////////////////////////////////////// -// Pointers -/////////////////////////////////////// - -// A pointer is a variable declared to store a memory address. Its declaration will -// also tell you the type of data it points to. You can retrieve the memory address -// of your variables, then mess with them. - -int x = 0; -printf("%p\n", &x); // Use & to retrieve the address of a variable -// (%p formats a pointer) -// => Prints some address in memory; - - -// Pointers start with * in their declaration -int *px, not_a_pointer; // px is a pointer to an int -px = &x; // Stores the address of x in px -printf("%p\n", px); // => Prints some address in memory -printf("%d, %d\n", (int)sizeof(px), (int)sizeof(not_a_pointer)); -// => Prints "8, 4" on 64-bit system - -// To retreive the value at the address a pointer is pointing to, -// put * in front to de-reference it. -printf("%d\n", *px); // => Prints 0, the value of x, which is what px is pointing to the address of - -// You can also change the value the pointer is pointing to. -// We'll have to wrap the de-reference in parenthesis because -// ++ has a higher precedence than *. -(*px)++; // Increment the value px is pointing to by 1 -printf("%d\n", *px); // => Prints 1 -printf("%d\n", x); // => Prints 1 - -int x_array[20]; // Arrays are a good way to allocate a contiguous block of memory -int xx; -for (xx=0; xx<20; xx++) { - x_array[xx] = 20 - xx; -} // Initialize x_array to 20, 19, 18,... 2, 1 - -// Declare a pointer of type int and initialize it to point to x_array -int* x_ptr = x_array; -// x_ptr now points to the first element in the array (the integer 20). -// This works because arrays are actually just pointers to their first element. - -// Arrays are pointers to their first element -printf("%d\n", *(x_ptr)); // => Prints 20 -printf("%d\n", x_array[0]); // => Prints 20 - -// Pointers are incremented and decremented based on their type -printf("%d\n", *(x_ptr + 1)); // => Prints 19 -printf("%d\n", x_array[1]); // => Prints 19 - -// You can also dynamically allocate contiguous blocks of memory with the -// standard library function malloc, which takes one integer argument -// representing the number of bytes to allocate from the heap. -int* my_ptr = (int*) malloc(sizeof(int) * 20); -for (xx=0; xx<20; xx++) { - *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx would also work here -} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) - -// Dereferencing memory that you haven't allocated gives -// unpredictable results -printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? - -// When you're done with a malloc'd block of memory, you need to free it, -// or else no one else can use it until your program terminates -free(my_ptr); - -// Strings can be char arrays, but are usually represented as char -// pointers: -char* my_str = "This is my very own string"; - -printf("%c\n", *my_str); // => 'T' - -function_1(); + // print output using printf, for "print formatted" + // %d is an integer, \n is a newline + printf("%d\n", 0); // => Prints 0 + // All statements must end with a semicolon + + /////////////////////////////////////// + // Types + /////////////////////////////////////// + + // You have to declare variables before using them. A variable declaration + // requires you to specify its type; a variable's type determines its size + // in bytes. + + // ints are usually 4 bytes + int x_int = 0; + + // shorts are usually 2 bytes + short x_short = 0; + + // chars are guaranteed to be 1 byte + char x_char = 0; + char y_char = 'y'; // Char literals are quoted with '' + + // longs are often 4 to 8 bytes; long longs are guaranteed to be at least + // 64 bits + long x_long = 0; + long long x_long_long = 0; + + // floats are usually 32-bit floating point numbers + float x_float = 0.0; + + // doubles are usually 64-bit floating-point numbers + double x_double = 0.0; + + // Integral types may be unsigned. This means they can't be negative, but + // the maximum value of an unsigned variable is greater than the maximum + // signed value of the same size. + unsigned char ux_char; + unsigned short ux_short; + unsigned int ux_int; + unsigned long long ux_long_long; + + // Other than char, which is always 1 byte (but not necessarily 8 bits!), + // these types vary in size depending on your machine and compiler. + // sizeof(T) gives you the size of a variable with type T in + // bytes so you can express the size of these types in a portable way. + // sizeof(obj) yields the size of an actual expression (variable, literal, etc.). + // For example, + printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) + + + // It's worth noting that if the argument of the `sizeof` operator is not a type but an expression, + // then its argument is not evaluated except VLAs (see below). Also, `sizeof()` is an operator, not a function, + // furthermore, the value it yields is a compile-time constant (except when used on VLAs, again.) + int a = 1; + size_t size = sizeof(a++); // a++ is not evaluated + printf("sizeof(a++) = %zu where a = %d\n", size, a); + // the above code prints "sizeof(a++) = 4 where a = 1" (on a usual 32-bit architecture) + + // Arrays must be initialized with a concrete size. + char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes + int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes + // (assuming 4-byte words) + + + // You can initialize an array to 0 thusly: + char my_array[20] = {0}; + + // Indexing an array is like other languages -- or, + // rather, other languages are like C + my_array[0]; // => 0 + + // Arrays are mutable; it's just memory! + my_array[1] = 2; + printf("%d\n", my_array[1]); // => 2 + + // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) can be declared as well. + // The size of such an array need not be a compile time constant: + printf("Enter the array size: "); // ask the user for an array size + char buf[0x100]; + fgets(buf, sizeof buf, stdin); + size_t size = strtoul(buf, NULL, 10); // strtoul parses a string to an unsigned integer + int var_length_array[size]; // declare the VLA + printf("sizeof array = %zu\n", sizeof var_length_array); + + // A possible outcome of this program may be: + Enter the array size: 10 + sizeof array = 40 + + // Strings are just arrays of chars terminated by a NUL (0x00) byte, + // represented in strings as the special character '\0'. + // (We don't have to include the NUL byte in string literals; the compiler + // inserts it at the end of the array for us.) + char a_string[20] = "This is a string"; + printf("%s\n", a_string); // %s formats a string + + /* + You may have noticed that a_string is only 16 chars long. + Char #17 is the NUL byte. + Chars #18, 19 and 20 are 0 as well - if an initializer list (in this case, the string literal) + has less elements than the array it is initializing, then excess array elements are implicitly + initialized to zero. This is why int ar[10] = { 0 } works as expected intuitively. + */ + + printf("%d\n", a_string[16]); // => 0 + + // So string literals are strings enclosed within double quotes, but if we have characters + // between single quotes, that's a character literal. + // It's of type `int`, and *not* `char` (for hystorical reasons). + int cha = 'a'; // fine + char chb = 'a'; // fine too (implicit conversion from int to char - truncation) + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + + int i1 = 1, i2 = 2; // Shorthand for multiple declaration + float f1 = 1.0, f2 = 2.0; + + // Arithmetic is straightforward + i1 + i2; // => 3 + i2 - i1; // => 1 + i2 * i1; // => 2 + i1 / i2; // => 0 (0.5, but truncated towards 0) + + f1 / f2; // => 0.5, plus or minus epsilon - floating-point numbers and calculations are not exact + + // Modulo is there as well + 11 % 3; // => 2 + + // Comparison operators are probably familiar, but + // there is no boolean type in c. We use ints instead. + // 0 is false, anything else is true. (The comparison + // operators always yield 0 or 1.) + 3 == 2; // => 0 (false) + 3 != 2; // => 1 (true) + 3 > 2; // => 1 + 3 < 2; // => 0 + 2 <= 2; // => 1 + 2 >= 2; // => 1 + + // Logic works on ints + !3; // => 0 (Logical not) + !0; // => 1 + 1 && 1; // => 1 (Logical and) + 0 && 1; // => 0 + 0 || 1; // => 1 (Logical or) + 0 || 0; // => 0 + + // Bitwise operators! + ~0x0F; // => 0xF0 (bitwise negation, "1's complement") + 0x0F & 0xF0; // => 0x00 (bitwise AND) + 0x0F | 0xF0; // => 0xFF (bitwise OR) + 0x04 ^ 0x0F; // => 0x0B (bitwise XOR) + 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) + 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + + if (0) { + printf("I am never run\n"); + } else if (0) { + printf("I am also never run\n"); + } else { + printf("I print\n"); + } + + // While loops exist + int ii = 0; + while (ii < 10) { + printf("%d, ", ii++); // ii++ increments ii in-place, after yielding its value ("postincrement"). + } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + int kk = 0; + do { + printf("%d, ", kk); + } while (++kk < 10); // ++kk increments kk in-place, and yields the already incremented value ("preincrement") + // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + // For loops too + int jj; + for (jj=0; jj < 10; jj++) { + printf("%d, ", jj); + } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + /////////////////////////////////////// + // Typecasting + /////////////////////////////////////// + + // Every value in C has a type, but you can cast one value into another type + // if you want (with some constraints). + + int x_hex = 0x01; // You can assign vars with hex literals + + // Casting between types will attempt to preserve their numeric values + printf("%d\n", x_hex); // => Prints 1 + printf("%d\n", (short) x_hex); // => Prints 1 + printf("%d\n", (char) x_hex); // => Prints 1 + + // Types will overflow without warning + printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long) + // printf("%d\n", (unsigned char) 257); would be undefined behavior - `char' is usually signed + // on most modern systems, and signed integer overflow invokes UB. + // Also, for determining the maximal value of a `char`, a `signed char` and an `unisigned char`, + // respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from + + // Integral types can be cast to floating-point types, and vice-versa. + printf("%f\n", (float)100); // %f formats a float + printf("%lf\n", (double)100); // %lf formats a double + printf("%d\n", (char)100.0); + + /////////////////////////////////////// + // Pointers + /////////////////////////////////////// + + // A pointer is a variable declared to store a memory address. Its declaration will + // also tell you the type of data it points to. You can retrieve the memory address + // of your variables, then mess with them. + + int x = 0; + printf("%p\n", (void *)&x); // Use & to retrieve the address of a variable + // (%p formats an object pointer of type void *) + // => Prints some address in memory; + + + // Pointers start with * in their declaration + int *px, not_a_pointer; // px is a pointer to an int + px = &x; // Stores the address of x in px + printf("%p\n", (void *)px); // => Prints some address in memory + printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); + // => Prints "8, 4" on a typical 64-bit system + + // To retreive the value at the address a pointer is pointing to, + // put * in front to de-reference it. + // Note: yes, it may be confusing that '*' is used for _both_ declaring a pointer and dereferencing it. + printf("%d\n", *px); // => Prints 0, the value of x, which is what px is pointing to the address of + + // You can also change the value the pointer is pointing to. + // We'll have to wrap the de-reference in parenthesis because + // ++ has a higher precedence than *. + (*px)++; // Increment the value px is pointing to by 1 + printf("%d\n", *px); // => Prints 1 + printf("%d\n", x); // => Prints 1 + + int x_array[20]; // Arrays are a good way to allocate a contiguous block of memory + int xx; + for (xx = 0; xx < 20; xx++) { + x_array[xx] = 20 - xx; + } // Initialize x_array to 20, 19, 18,... 2, 1 + + // Declare a pointer of type int and initialize it to point to x_array + int* x_ptr = x_array; + // x_ptr now points to the first element in the array (the integer 20). + // This works because arrays often decay into pointers to their first element. + // For example, when an array is passed to a function or is assigned to a pointer, + // it decays into (implicitly converted to) a pointer. + // Exceptions: when the array is the argument of the `&` (address-od) operator: + int arr[10]; + int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`! It's of type "pointer to array" (of ten `int`s). + // or when the array is a string literal used for initializing a char array: + char arr[] = "foobarbazquirk"; + // or when it's the argument of the `sizeof` or `alignof` operator: + int arr[10]; + int *ptr = arr; // equivalent with int *ptr = &arr[0]; + printf("%zu %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8" + + + // Pointers are incremented and decremented based on their type + // (this is called pointer arithmetic) + printf("%d\n", *(x_ptr + 1)); // => Prints 19 + printf("%d\n", x_array[1]); // => Prints 19 + + // You can also dynamically allocate contiguous blocks of memory with the + // standard library function malloc, which takes one argument of type size_t + // representing the number of bytes to allocate (usually from the heap, although this + // may not be true on e. g. embedded systems - the C standard says nothing about it). + int *my_ptr = malloc(sizeof(*my_ptr) * 20); + for (xx = 0; xx < 20; xx++) { + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx would also work here, and it's also more readable + } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) + + // Dereferencing memory that you haven't allocated gives + // "unpredictable results" - the program is said to invoke "undefined behavior" + printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash. + + // When you're done with a malloc'd block of memory, you need to free it, + // or else no one else can use it until your program terminates + // (this is called a "memory leak"): + free(my_ptr); + + // Strings are arrays of char, but they are usually represented as a + // pointer-to-char (which is a pointer to the first element of the array). + // It's good practice to use `const char *' when referring to a string literal, + // since string literals shall not be modified (i. e. "foo"[0] = 'a' is ILLEGAL.) + const char *my_str = "This is my very own string literal"; + printf("%c\n", *my_str); // => 'T' + + // This is not the case if the string is an array (potentially initialized with a string literal) + // that resides in writable memory, as in: + char foo[] = "foo"; + foo[0] = 'a'; // this is legal, foo now contains "aoo" + + function_1(); } // end main function /////////////////////////////////////// @@ -300,7 +359,8 @@ function_1(); // Function declaration syntax: // () -int add_two_ints(int x1, int x2){ +int add_two_ints(int x1, int x2) +{ return x1 + x2; // Use return to return a value } @@ -312,10 +372,12 @@ Example: in-place string reversal */ // A void function returns no value -void str_reverse(char* str_in){ +void str_reverse(char *str_in) +{ char tmp; - int ii=0, len = strlen(str_in); // Strlen is part of the c standard library - for(ii=0; ii ".tset a si sihT" typedef int my_type; my_type my_type_var = 0; -// Structs are just collections of data +// Structs are just collections of data, the members are allocated sequentially, in the order they are written: struct rectangle { int width; int height; }; +// it's generally not true that sizeof(struct rectangle) == sizeof(int) + sizeof(int) due to +// potential padding between the structure members (this is for alignment reasons. Probably won't +// happen if all members are of the same type, but watch out! +// See http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member +// for further information. -void function_1(){ - +void function_1() +{ struct rectangle my_rec; // Access struct members with . @@ -352,22 +419,29 @@ void function_1(){ my_rec.height = 20; // You can declare pointers to structs - struct rectangle* my_rec_ptr = &my_rec; + struct rectangle *my_rec_ptr = &my_rec; // Use dereferencing to set struct pointer members... (*my_rec_ptr).width = 30; - // ... or use the -> shorthand + // ... or even better: prefer the -> shorthand for the sake of readability my_rec_ptr->height = 10; // Same as (*my_rec_ptr).height = 10; } // You can apply a typedef to a struct for convenience typedef struct rectangle rect; -int area(rect r){ +int area(rect r) +{ return r.width * r.height; } +// if you have large structs, you can pass them "by pointer" to avoid copying the whole struct: +int area(const rect *r) +{ + return r->width * r->height; +} + /////////////////////////////////////// // Function pointers /////////////////////////////////////// @@ -379,10 +453,11 @@ However, definition syntax may be initially confusing. Example: use str_reverse from a pointer */ -void str_reverse_through_pointer(char * str_in) { +void str_reverse_through_pointer(char *str_in) { // Define a function pointer variable, named f. void (*f)(char *); // Signature should exactly match the target function. f = &str_reverse; // Assign the address for the actual function (determined at runtime) + // f = str_reverse; would work as well - functions decay into pointers, similar to arrays (*f)(str_in); // Just calling the function through the pointer // f(str_in); // That's an alternative but equally valid syntax for calling it. } @@ -403,7 +478,15 @@ typedef void (*my_fnp_type)(char *); ## Further Reading Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) +It is *the* book about C, written by the creators of C. Be careful, though - it's ancient and it contains some +inaccuracies (well, ideas that are not considered good anymore) or now-changed practices. + +Another good resource is [Learn C the hard way](http://c.learncodethehardway.org/book/). + +If you have a question, read the [compl.lang.c Frequently Asked Questions](http://c-faq.com). -Another good resource is [Learn C the hard way](http://c.learncodethehardway.org/book/) +It's very important to use proper spacing, indentation and to be consistent with your coding style in general. +Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the +[Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle). Other than that, Google is your friend. -- cgit v1.2.3 From f2c41a8a9915606ed801a87f153d91fd347069a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81rp=C3=A1d=20Goretity=20=EF=A3=BF?= Date: Thu, 15 Aug 2013 12:36:29 +0200 Subject: whoops, fixed typos and added missing info --- c.html.markdown | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index ac6c7ab4..ec5c5e0d 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -5,7 +5,6 @@ language: c filename: learnc.c contributors: - ["Adam Bard", "http://adambard.com/"] - - ["Árpád Goretity", "http://twitter.com/h2co3_ios"] --- Ah, C. Still **the** language of modern high-performance computing. @@ -29,7 +28,13 @@ Multi-line comments look like this. They work in C89 as well. // file names between are headers from the C standard library. // They are searched for by the preprocessor in the system include paths // (usually /usr/lib on Unices, can be controlled with the -I option if you are using GCC or clang.) -// For your +// For your own headers, use double quotes instead of angle brackets: +#include "my_header.h" + +// The C preprocessor introduces an almost fully-featured macro language. It's useful, but +// it can be confusing (and what's even worse, it can be misused). Read the +// Wikipedia article on the C preprocessor for further information: +// http://en.wikipedia.org/wiki/C_preprocessor // Declare function signatures in advance in a .h file, or at the top of // your .c file. -- cgit v1.2.3 From 05c3ca90447e6f63fa02847468e8a95f250fbe50 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Thu, 15 Aug 2013 20:33:44 +0930 Subject: [javascript] Remove anonymous function assignment example. ref #215 --- javascript.html.markdown | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 9b87b022..25777578 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -219,17 +219,9 @@ function myFunction(){ } setTimeout(myFunction, 5000) -// Functions can also be defined "anonymously" - without a name: -var lowerFunction = function(thing){ - return thing.toLowerCase() -} -lowerFunction("Foo") // = "foo" -// (note: we've assigned our anonymous function to a variable - if we didn't, we -// wouldn't be able to access it) - -// You can even write the function statement directly in the call to the other -// function. -setTimeout(function myFunction(){ +// Function objects don't even have to be declared with a name - you can write +// an anonymous function definition directly into the arguments of another. +setTimeout(function(){ // this code will be called in 5 seconds' time }, 5000) -- cgit v1.2.3 From 273c08d1fe2ebe362826fd0707d55b728538c33d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81rp=C3=A1d=20Goretity=20=EF=A3=BF?= Date: Thu, 15 Aug 2013 13:08:52 +0200 Subject: fixed header, added switch statement --- c.html.markdown | 46 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index ec5c5e0d..8e16837c 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -1,10 +1,12 @@ --- -name: c -category: language -language: c -filename: learnc.c -contributors: - - ["Adam Bard", "http://adambard.com/"] +- name: c +- category: language +- language: c +- filename: learnc.c +- contributors: + - [Adam Bard](http://adambard.com/) + - [Árpád Goretity](http://twitter.com/H2CO3_iOS) + --- Ah, C. Still **the** language of modern high-performance computing. @@ -152,7 +154,7 @@ int main() { // So string literals are strings enclosed within double quotes, but if we have characters // between single quotes, that's a character literal. - // It's of type `int`, and *not* `char` (for hystorical reasons). + // It's of type `int`, and *not* `char` (for historical reasons). int cha = 'a'; // fine char chb = 'a'; // fine too (implicit conversion from int to char - truncation) @@ -176,6 +178,7 @@ int main() { // Comparison operators are probably familiar, but // there is no boolean type in c. We use ints instead. + // (Or _Bool or bool in C99.) // 0 is false, anything else is true. (The comparison // operators always yield 0 or 1.) 3 == 2; // => 0 (false) @@ -185,6 +188,13 @@ int main() { 2 <= 2; // => 1 2 >= 2; // => 1 + // C is not Python - comparisons don't chain. + int a = 1; + // WRONG: + int between_0_and_2 = 0 < a < 2; + // Correct: + int between_0_and_2 = 0 < a && a < 2; + // Logic works on ints !3; // => 0 (Logical not) !0; // => 1 @@ -201,6 +211,12 @@ int main() { 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) + // Be careful when shifting signed integers - the following are all undefined behavior: + // - shifting into the sign bit of a signed integer (int a = 1 << 32) + // - left-shifting a negative number (int a = -1 << 2) + // - shifting by an offset which is more than or equal to the width of the type of the LHS: + // int a = 1 << 32; // UB if int is 32 bits wide + /////////////////////////////////////// // Control Structures /////////////////////////////////////// @@ -237,6 +253,22 @@ int main() { printf("\n"); + // branching with multiple choices: switch() + switch (some_integral_expression) { + case 0: // labels need to be integral *constant* epxressions + do_stuff(); + break; // if you don't break, control flow falls over labels - you usually don't want that. + case 1: + do_something_else(); + break; + default: + // if `some_integral_expression` didn't match any of the labels + fputs("error!\n", stderr); + exit(-1); + break; + } + + /////////////////////////////////////// // Typecasting /////////////////////////////////////// -- cgit v1.2.3 From 80f97751a21b0c04ee077c23b715a8adc0063788 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Thu, 15 Aug 2013 21:05:27 +0930 Subject: [javascript] Add semicolons. Closes #214. --- javascript.html.markdown | 218 +++++++++++++++++++++++------------------------ 1 file changed, 109 insertions(+), 109 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 25777578..fb79949e 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -30,82 +30,82 @@ doStuff(); // wherever there's a newline, except in certain cases. doStuff() -// We'll leave semicolons off here; whether you do or not will depend on your -// personal preference or your project's style guide. +// So that we don't have to worry about those certain cases (for now), we'll +// leave them on. /////////////////////////////////// // 1. Numbers, Strings and Operators // Javascript has one number type (which is a 64-bit IEEE 754 double). -3 // = 3 -1.5 // = 1.5 +3; // = 3 +1.5; // = 1.5 // All the basic arithmetic works as you'd expect. -1 + 1 // = 2 -8 - 1 // = 7 -10 * 2 // = 20 -35 / 5 // = 7 +1 + 1; // = 2 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 // Including uneven division. -5 / 2 // = 2.5 +5 / 2; // = 2.5 // Bitwise operations also work; when you perform a bitwise operation your float // is converted to a signed int *up to* 32 bits. -1 << 2 // = 4 +1 << 2; // = 4 // Precedence is enforced with parentheses. -(1 + 3) * 2 // = 8 +(1 + 3) * 2; // = 8 // There are three special not-a-real-number values: -Infinity // result of e.g. 1/0 --Infinity // result of e.g. -1/0 -NaN // result of e.g. 0/0 +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0 // There's also a boolean type. -true -false +true; +false; // Strings are created with ' or ". -'abc' -"Hello, world" +'abc'; +"Hello, world"; // Negation uses the ! symbol -!true // = false -!false // = true +!true; // = false +!false; // = true // Equality is == -1 == 1 // = true -2 == 1 // = false +1 == 1; // = true +2 == 1; // = false // Inequality is != -1 != 1 // = false -2 != 1 // = true +1 != 1; // = false +2 != 1; // = true // More comparisons -1 < 10 // = true -1 > 10 // = false -2 <= 2 // = true -2 >= 2 // = true +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true // Strings are concatenated with + -"Hello " + "world!" // = "Hello world!" +"Hello " + "world!"; // = "Hello world!" // and are compared with < and > -"a" < "b" // = true +"a" < "b"; // = true // Type coercion is performed for comparisons... -"5" == 5 // = true +"5" == 5; // = true // ...unless you use === -"5" === 5 // = false +"5" === 5; // = false // You can access characters in a string with charAt -"This is a string".charAt(0) +"This is a string".charAt(0); // There's also null and undefined -null // used to indicate a deliberate non-value -undefined // used to indicate a value is not currently present (although undefined - // is actually a value itself) +null; // used to indicate a deliberate non-value +undefined; // used to indicate a value is not currently present (although undefined + // is actually a value itself) // false, null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. // Note that 0 is falsy and "0" is truthy, even though 0 == "0". @@ -115,57 +115,57 @@ undefined // used to indicate a value is not currently present (although undefin // Variables are declared with the var keyword. Javascript is dynamically typed, // so you don't need to specify type. Assignment uses a single = character. -var someVar = 5 +var someVar = 5; // if you leave the var keyword off, you won't get an error... -someOtherVar = 10 +someOtherVar = 10; // ...but your variable will be created in the global scope, not in the scope // you defined it in. // Variables declared without being assigned to are set to undefined. -var someThirdVar // = undefined +var someThirdVar; // = undefined // There's shorthand for performing math operations on variables: -someVar += 5 // equivalent to someVar = someVar + 5; someVar is 10 now -someVar *= 10 // now someVar is 100 +someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now +someVar *= 10; // now someVar is 100 // and an even-shorter-hand for adding or subtracting 1 -someVar++ // now someVar is 101 -someVar-- // back to 100 +someVar++; // now someVar is 101 +someVar--; // back to 100 // Arrays are ordered lists of values, of any type. -var myArray = ["Hello", 45, true] +var myArray = ["Hello", 45, true]; // Their members can be accessed using the square-brackets subscript syntax. // Array indices start at zero. -myArray[1] // = 45 +myArray[1]; // = 45 // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. -var myObj = {key1: "Hello", key2: "World"} +var myObj = {key1: "Hello", key2: "World"}; // Keys are strings, but quotes aren't required if they're a valid // JavaScript identifier. Values can be any type. -var myObj = {myKey: "myValue", "my other key": 4} +var myObj = {myKey: "myValue", "my other key": 4}; // Object attributes can also be accessed using the subscript syntax, -myObj["my other key"] // = 4 +myObj["my other key"]; // = 4 // ... or using the dot syntax, provided the key is a valid identifier. -myObj.myKey // = "myValue" +myObj.myKey; // = "myValue" // Objects are mutable; values can be changed and new keys added. -myObj.myThirdKey = true +myObj.myThirdKey = true; // If you try to access a value that's not yet set, you'll get undefined. -myObj.myFourthKey // = undefined +myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Logic and Control Structures // The if structure works as you'd expect. -var count = 1 +var count = 1; if (count == 3){ // evaluated if count is 3 } else if (count == 4) { @@ -182,7 +182,7 @@ while (true) { // Do-while loops are like while loops, except they always run at least once. var input do { - input = getInput() + input = getInput(); } while (!isValid(input)) // the for loop is the same as C and Java: @@ -193,23 +193,23 @@ for (var i = 0; i < 5; i++){ // && is logical and, || is logical or if (house.size == "big" && house.colour == "blue"){ - house.contains = "bear" + house.contains = "bear"; } if (colour == "red" || colour == "blue"){ // colour is either red or blue } // && and || "short circuit", which is useful for setting default values. -var name = otherName || "default" +var name = otherName || "default"; /////////////////////////////////// // 4. Functions, Scope and Closures // JavaScript functions are declared with the function keyword. function myFunction(thing){ - return thing.toUpperCase() + return thing.toUpperCase(); } -myFunction("foo") // = "FOO" +myFunction("foo"); // = "FOO" // JavaScript functions are first class objects, so they can be reassigned to // different variable names and passed to other functions as arguments - for @@ -217,49 +217,49 @@ myFunction("foo") // = "FOO" function myFunction(){ // this code will be called in 5 seconds' time } -setTimeout(myFunction, 5000) +setTimeout(myFunction, 5000); // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. setTimeout(function(){ // this code will be called in 5 seconds' time -}, 5000) +}, 5000); // JavaScript has function scope; functions get their own scope but other blocks // do not. if (true){ - var i = 5 + var i = 5; } -i // = 5 - not undefined as you'd expect in a block-scoped language +i; // = 5 - not undefined as you'd expect in a block-scoped language // This has led to a common pattern of "immediately-executing anonymous // functions", which prevent temporary variables from leaking into the global // scope. (function(){ - var temporary = 5 + var temporary = 5; // We can access the global scope by assiging to the 'global object', which // in a web browser is always 'window'. The global object may have a // different name in non-browser environments such as Node.js. - window.permanent = 10 -})() -temporary // raises ReferenceError -permanent // = 10 + window.permanent = 10; +})(); +temporary; // raises ReferenceError +permanent; // = 10 // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the // outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!" + var prompt = "Hello, " + name + "!"; function inner(){ - alert(prompt) + alert(prompt); } - setTimeout(inner, 5000) + setTimeout(inner, 5000); // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will // exit immediately, and setTimeout will call inner afterwards. However, // because inner is "closed over" sayHelloInFiveSeconds, inner still has // access to the 'prompt' variable when it is finally called. } -sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s +sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s /////////////////////////////////// // 5. More about Objects; Constructors and Prototypes @@ -267,44 +267,44 @@ sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s // Objects can contain functions. var myObj = { myFunc: function(){ - return "Hello world!" + return "Hello world!"; } -} -myObj.myFunc() // = "Hello world!" +}; +myObj.myFunc(); // = "Hello world!" // When functions attached to an object are called, they can access the object // they're attached to using the this keyword. myObj = { myString: "Hello world!", myFunc: function(){ - return this.myString + return this.myString; } -} -myObj.myFunc() // = "Hello world!" +}; +myObj.myFunc(); // = "Hello world!" // What this is set to has to do with how the function is called, not where // it's defined. So, our function doesn't work if it isn't called in the // context of the object. -var myFunc = myObj.myFunc -myFunc() // = undefined +var myFunc = myObj.myFunc; +myFunc(); // = undefined // Inversely, a function can be assigned to the object and gain access to it // through this, even if it wasn't attached when it was defined. var myOtherFunc = function(){ - return this.myString.toUpperCase() + return this.myString.toUpperCase(); } -myObj.myOtherFunc = myOtherFunc -myObj.myOtherFunc() // = "HELLO WORLD!" +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" // When you call a function with the new keyword, a new object is created, and // made available to the function via this. Functions designed to be called // like this are called constructors. var MyConstructor = function(){ - this.myNumber = 5 + this.myNumber = 5; } -myNewObj = new MyConstructor() // = {myNumber: 5} -myNewObj.myNumber // = 5 +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 // Every JavaScript object has a 'prototype'. When you go to access a property // on an object that doesn't exist on the actual object, the interpreter will @@ -315,31 +315,31 @@ myNewObj.myNumber // = 5 // part of the standard; we'll get to standard ways of using prototypes later. var myObj = { myString: "Hello world!", -} +}; var myPrototype = { meaningOfLife: 42, myFunc: function(){ return this.myString.toLowerCase() } -} -myObj.__proto__ = myPrototype -myObj.meaningOfLife // = 42 +}; +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 // This works for functions, too. -myObj.myFunc() // = "hello world!" +myObj.myFunc(); // = "hello world!" // Of course, if your property isn't on your prototype, the prototype's // prototype is searched, and so on. myPrototype.__proto__ = { myBoolean: true -} -myObj.myBoolean // = true +}; +myObj.myBoolean; // = true // There's no copying involved here; each object stores a reference to its // prototype. This means we can alter the prototype and our changes will be // reflected everywhere. -myPrototype.meaningOfLife = 43 -myObj.meaningOfLife // = 43 +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 // We mentioned that __proto__ was non-standard, and there's no standard way to // change the prototype of an existing object. However, there's two ways to @@ -347,8 +347,8 @@ myObj.meaningOfLife // = 43 // The first is Object.create, which is a recent addition to JS, and therefore // not available in all implementations yet. -var myObj = Object.create(myPrototype) -myObj.meaningOfLife // = 43 +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 // The second way, which works anywhere, has to do with constructors. // Constructors have a property called prototype. This is *not* the prototype of @@ -358,20 +358,20 @@ myConstructor.prototype = { getMyNumber: function(){ return this.myNumber } -} -var myNewObj2 = new myConstructor() -myNewObj2.getMyNumber() // = 5 +}; +var myNewObj2 = new myConstructor(); +myNewObj2.getMyNumber(); // = 5 // Built-in types like strings and numbers also have constructors that create // equivalent wrapper objects. -var myNumber = 12 -var myNumberObj = new Number(12) -myNumber == myNumberObj // = true +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true // Except, they aren't exactly equivalent. -typeof(myNumber) // = 'number' -typeof(myNumberObj) // = 'object' -myNumber === myNumberObj // = false +typeof(myNumber); // = 'number' +typeof(myNumberObj); // = 'object' +myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. } @@ -382,9 +382,9 @@ if (Number(0)){ // However, the wrapper objects and the regular builtins share a prototype, so // you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ - return this.charAt(0) + return this.charAt(0); } -"abc".firstCharacter() // = "a" +"abc".firstCharacter(); // = "a" // This fact is often used in "polyfilling", which is implementing newer // features of JavaScript in an older subset of JavaScript, so that they can be @@ -395,10 +395,10 @@ String.prototype.firstCharacter = function(){ if (Object.create === undefined){ // don't overwrite it if it exists Object.create = function(proto){ // make a temporary constructor with the right prototype - var Constructor = function(){} - Constructor.prototype = proto + var Constructor = function(){}; + Constructor.prototype = proto; // then use it to create a new, appropriately-prototyped object - return new Constructor() + return new Constructor(); } } ``` -- cgit v1.2.3 From 3497a0858a8aec1c0eab850b432f5a0c166df2a0 Mon Sep 17 00:00:00 2001 From: godtao Date: Thu, 15 Aug 2013 19:40:05 +0800 Subject: Add go-zh.html.markdown --- zh-cn/go-zh.html.markdown | 280 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 280 insertions(+) create mode 100644 zh-cn/go-zh.html.markdown diff --git a/zh-cn/go-zh.html.markdown b/zh-cn/go-zh.html.markdown new file mode 100644 index 00000000..6a4c09be --- /dev/null +++ b/zh-cn/go-zh.html.markdown @@ -0,0 +1,280 @@ +--- +名字:Go +分类:编程语言 +文件名:learngo.go +贡献者: + - ["Sonia Keys", "https://github.com/soniakeys"] +翻译者: + - ["pantaovay", "https://github.com/pantaovay"] +--- + +发明Go语言是出于更好地完成工作的需要。Go不是计算机科学的最新发展潮流,但它却提供了解决现实问题的最新最快的方法。 + +Go拥有命令式语言的静态类型,编译很快,执行也很快,同时加入了对于目前多核CPU的并发计算支持,也有相应的特性来大规模编程。 + +Go语言有非常棒的标准库,还有一个充满热情的社区。 + +```Go +// 单行注释 +/* 多行 + 注释 */ + +// 导入包的子句在每个源文件的开头。 +// Main比较特殊,它用来声明可执行文件,而不是一个库。 +package main + +// Import语句声明了当前文件引用的包。 +import ( + "fmt" // Go语言标准库中的包 + "net/http" // 一个web服务器包 + "strconv" // 字符串转换 +) + +//函数声明:Main是程序执行的入口。不管你喜欢还是不喜欢,反正G就用了花括号来包住函数体。 +func main() { + // 往标准输出打印一行。 + // 用包名fmt限制打印函数。 + fmt.Println("Hello world!") + + // 调用当前包的另一个函数。 + beyondHello() +} + +// 函数可以在括号里加参数。 +// 如果没有参数的话,也需要一个空括号。 +func beyondHello() { + var x int // 变量声明,变量必须在使用之前声明。 + x = 3 // 变量赋值。 + // 可以用:=来偷懒,它自动把变量类型、声明和赋值都搞定了。 + y := 4 + sum, prod := learnMultiple(x, y) // 多个返回变量的函数 + fmt.Println("sum:", sum, "prod:", prod) // 简单输出 + learnTypes() // 少于y分钟,学的更多! +} + +// 多变量和多返回值的函数 +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // 返回两个值 +} + +// 内置变量类型和关键词 +func learnTypes() { + // 短声明给你所想。 + s := "Learn Go!" // String类型 + + s2 := `A "raw" string literal +can include line breaks.` // 同样是String类型 + + // 非ascii字符。Go使用UTF-8编码。 + g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码 + + f := 3.14195 // float64类型,IEEE-754 64位浮点数 + c := 3 + 4i // complex128类型,内部使用两个float64表示 + + // Var变量可以直接初始化。 + var u uint = 7 // unsigned 无符号变量,但是实现依赖int型变量的长度 + var pi float32 = 22. / 7 + + // 字符转换 + n := byte('\n') // byte是uint8的别名 + + // 数组类型编译的时候大小固定。 + var a4 [4] int // 有4个int变量的数组,初始为0 + a3 := [...]int{3, 1, 5} // 有3个int变量的数组,同时进行了初始化 + + // Slice 有动态大小。Array和Slice各有千秋,但是使用slice的地方更多些。 + s3 := []int{4, 5, 9} // 和a3相比,这里没有省略号 + s4 := make([]int, 4) // 分配一个有4个int型变量的slice,全部被初始化为0 + + var d2 [][]float64 // 声明而已,什么都没有分配 + bs := []byte("a slice") // 类型转换的语法 + + p, q := learnMemory() // 声明p,q为int型变量的指针 + fmt.Println(*p, *q) // * 取值 + + // Map是动态可增长关联数组,和其他语言中的hash或者字典相似。 + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // 在Go语言中未使用的变量在编译的时候会报错,而不是warning。 + // 下划线 _ 可以使你“使用”一个变量,但是丢弃它的值。 + _,_,_,_,_,_,_,_,_ = s2, g, f, u, pi, n, a3, s4, bs + // 输出变量 + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // 回到流程控制 +} + +// Go全面支持垃圾回收。Go有指针,但是不支持指针运算。 +// 你会因为空指针而犯错,但是不会因为增加指针而犯错。 +func learnMemory() (p, q *int) { + // 返回int型变量指针p和q + p = new(int) // 内置函数new分配内存 + // 自动将分配的int赋值0,p不再是空的了。 + s := make([]int, 20) // 给20个int变量分配一块内存 + s[3] = 7 // 赋值 + r := -2 // 声明另一个局部变量 + return &s[3], &r // & 取址 +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // If需要花括号,括号就免了 + if true { + fmt.Println("told ya") + } + // 用go fmt 命令可以帮你格式化代码,所以不用怕被人吐槽代码风格了,也不用容忍被人的代码风格。 + if false { + // pout + } else { + // gloat + } + // 如果太多嵌套的if语句,推荐使用switch + x := 1 + switch x { + case 0: + case 1: + // 隐式调用break语句,匹配上一个即停止 + case 2: + // 不会运行 + } + // 和if一样,for也不用括号 + for x := 0; x < 3; x++ { // ++ 自增 + fmt.Println("iteration", x) + } + // x在这里还是1。为什么? + + // for 是go里唯一的循环关键字,不过它有很多变种 + for { // 无限循环 + break // 骗你的 + continue // 不会运行的 + } + // 和for一样,if中的:=先给y赋值,然后再和x作比较。 + if y := expensiveComputation(); y > x { + x = y + } + // 闭包函数 + xBig := func() bool { + return x > 100 // x是上面声明的变量引用 + } + fmt.Println("xBig:", xBig()) // true (上面把y赋给x了) + x /= 1e5 // x变成10 + fmt.Println("xBig:", xBig()) // 现在是false + + // 当你需要goto的时候,你会爱死它的! + goto love +love: + + learnInterfaces() // 好东西来了! +} + +// 定义Stringer为一个接口类型,有一个方法String +type Stringer interface { + String() string +} + +// 定义pair为一个结构体,有x和y两个int型变量。 +type pair struct { + x, y int +} + +// 定义pair类型的方法,实现Stringer接口。 +func (p pair) String() string { // p被叫做“接收器” + // Sprintf是fmt包中的另一个公有函数。 + // 用 . 调用p中的元素。 + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // 花括号用来定义结构体变量,:=在这里将一个结构体变量赋值给p。 + p := pair{3, 4} + fmt.Println(p.String()) // 调用pair类型p的String方法 + var i Stringer // 声明i为Stringer接口类型 + i = p // 有效!因为p实现了Stringer接口(类似java中的塑型) + // 调用i的String方法,输出和上面一样 + fmt.Println(i.String()) + + // fmt包中的Println函数向对象要它们的string输出,实现了String方法就可以这样使用了。(类似java中的序列化) + fmt.Println(p) // 输出和上面一样,自动调用String函数。 + fmt.Println(i) // 输出和上面一样。 + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok"用来判断有没有正常工作 + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok 为false,因为m中没有1 + fmt.Println("no one there") + } else { + fmt.Print(x) // 如果x在map中的话,x就是那个值喽。 + } + // 错误可不只是ok,它还可以给出关于问题的更多细节。 + if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value + // 输出"strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // 待会再说接口吧。同时, + learnConcurrency() +} + +// c是channel类型,一个并发安全的通信对象。 +func inc(i int, c chan int) { + c <- i + 1 // <-把右边的发送到左边的channel。 +} + +// 我们将用inc函数来并发地增加一些数字。 +func learnConcurrency() { + // 用make来声明一个slice,make会分配和初始化slice,map和channel。 + c := make(chan int) + // 用go关键字开始三个并发的goroutine,如果机器支持的话,还可能是并行执行。三个都被发送到同一个channel。 + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) + // 从channel中独处结果并打印。 + // 打印出什么东西是不可预知的。 + fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是接收操作。 + + cs := make(chan string) // 操作string的channel + cc := make(chan chan string) // 操作channel的channel + go func() { c <- 84 }() // 开始一个goroutine来发送一个新的数字 + go func() { cs <- "wordy" }() // 发送给cs + // Select类似于switch,但是每个case包括一个channel操作。它随机选择一个准备好通讯的case。 + select { + case i := <-c: // 从channel接收的值可以赋给其他变量 + fmt.Println("it's a", i) + case <-cs: // 或者直接丢弃 + fmt.Println("it's a string") + case <-cc: // 空的,还没作好通讯的准备 + fmt.Println("didn't happen.") + } + // 上面c或者cs的值被取到,其中一个goroutine结束,另外一个保持阻塞。 + + learnWebProgramming() // Go很适合web编程,我知道你也想学! +} + +// http包中的一个简单的函数就可以开启web服务器。 +func learnWebProgramming() { + // ListenAndServe第一个参数指定了监听端口,第二个参数是一个接口,特定是http.Handler。 + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // 不要无视错误。 +} + +// 使pair实现http.Handler接口的ServeHTTP方法。 +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // 使用http.ResponseWriter返回数据 + w.Write([]byte("You learned Go in Y minutes!")) +} +``` + +## 更进一步 + +Go的根源在[Go官方网站](http://golang.org/)。 +在那里你可以学习入门教程,通过浏览器交互式地学习,而且可以读到很多东西。 + +强烈推荐阅读语言定义部分,很简单而且很简洁!(as language definitions go these days.) + +学习Go还要阅读Go标准库的源代码,全部文档化了,可读性非常好,可以学到go,go style和go idioms。在文档中点击函数名,源代码就出来了! -- cgit v1.2.3 From dffa1b4f7426b61af77b0a13954c0fe49eb4a578 Mon Sep 17 00:00:00 2001 From: Tao Pan Date: Thu, 15 Aug 2013 19:44:39 +0800 Subject: =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zh-cn/go-zh.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/zh-cn/go-zh.html.markdown b/zh-cn/go-zh.html.markdown index 6a4c09be..25fd1f03 100644 --- a/zh-cn/go-zh.html.markdown +++ b/zh-cn/go-zh.html.markdown @@ -4,13 +4,12 @@ 文件名:learngo.go 贡献者: - ["Sonia Keys", "https://github.com/soniakeys"] -翻译者: - ["pantaovay", "https://github.com/pantaovay"] --- 发明Go语言是出于更好地完成工作的需要。Go不是计算机科学的最新发展潮流,但它却提供了解决现实问题的最新最快的方法。 -Go拥有命令式语言的静态类型,编译很快,执行也很快,同时加入了对于目前多核CPU的并发计算支持,也有相应的特性来大规模编程。 +Go拥有命令式语言的静态类型,编译很快,执行也很快,同时加入了对于目前多核CPU的并发计算支持,也有相应的特性来实现大规模编程。 Go语言有非常棒的标准库,还有一个充满热情的社区。 -- cgit v1.2.3 From e0b44e5aad796fe6c08cfee22f8fcfe84703250d Mon Sep 17 00:00:00 2001 From: Yury Date: Thu, 15 Aug 2013 23:47:46 +0400 Subject: Russian translate for python --- ru-ru/python-ru.html.markdown | 486 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 486 insertions(+) create mode 100644 ru-ru/python-ru.html.markdown diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown new file mode 100644 index 00000000..58b0adcc --- /dev/null +++ b/ru-ru/python-ru.html.markdown @@ -0,0 +1,486 @@ +--- +language: python +contributors: + - ["Yury Timofeev", "http://twitter.com/gagar1n"] +filename: learnpython-ru.py +--- + +Язык Python был создан Гвидо ван Россумом в ранние 90-е. Сегодня это один из самых популярных +языков. Я влюбился в него благодаря его понятному и доходчивому синтаксису - это почти что исполняемый псевдокод. + +Обратная связь будет высоко оценена! Вы можете связаться со мной: [@louiedinh](http://twitter.com/louiedinh) или louiedinh [at] [google's email service] + +Замечание: Эта статья относится к Python 2.7, но должна быть применима к Python 2.x. Скоро ожидается версия и для Python 3! + +```python +# Однострочные комментарии начинаются с hash-символа. +""" Многострочный текст может быть + записан, используя 3 знака " и обычно используется + в качестве комментария +""" + +#################################################### +## 1. Примитивные типы данных и операторв +#################################################### + +# У вас есть числа +3 #=> 3 + +# Математика работает так, как вы и думаете +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Деление немного сложнее. Это деление целых чисел и результат +# автоматически округляется в меньшую сторону. +5 / 2 #=> 2 + +# Чтобы научиться делить, сначала нужно немного узнать о дробных числах. +2.0 # Это дробное число. +11.0 / 4.0 #=> 2.75 вооот... гораздо лучше + +# Приоритет операций указывается скобками +(1 + 3) * 2 #=> 8 + +# Логические значения являются примитивами +True +False + +# Для отрицания используется ключевое слово not +not True #=> False +not False #=> True + +# Равенство это == +1 == 1 #=> True +2 == 1 #=> False + +# Неравенство это != +1 != 1 #=> False +2 != 1 #=> True + +# Больше сравнений +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Сравнения могут быть соединены в цепь! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Строки создаются при символом " или ' +"Это строка." +'Это тоже строка.' + +# Строки тоже могут складываться! +"Привет " + "мир!" #=> "Привет мир!" + +# Со строкой можно работать как со списком символов +"Это строка"[0] #=> 'Э' + +# % используется для форматирования строк, например: +"%s могут быть %s" % ("строки", "интерполированы") + +# Новый метод форматирования строк - использование метода format. +# Это предпочитаемый способ. +"{0} могут быть {1}".format("строки", "форматированы") +# Вы можете использовать ключевые слова, если не хотите считать. +"{name} хочет есть {food}".format(name="Боб", food="лазанью") + +# None является объектом +None #=> None + +# Не используйте оператор равенства `==` для сравнения +# объектов с None. Используйте для этого `is` +"etc" is None #=> False +None is None #=> True + +# Оператор 'is' проверяет идентичность объектов. Он не +# очень полезен при работе с примитивными типами, но +# очень полезен при работе с объектами. + +# None, 0, и пустые строки/списки равны False. +# Все остальные значения равны True +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Переменные и коллекции +#################################################### + +# Печать довольно проста +print "Я Python. Приятно познакомиться!" + + +# Необязательно объявлять переменные перед присваиванием им значения. +some_var = 5 # По соглашению используется нижний_регистр_с_подчеркиваниями +some_var #=> 5 + +# При попытке доступа к переменной, которой не было ранее присвоено значение, +# выбрасывается исключение. +# См. раздел "Поток управления" для информации об исключениях. +some_other_var # Выбрасывает ошибку именования + +# if может быть использован как выражение +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Списки хранят последовательности +li = [] +# Можно сразу начать с заполненным списком +other_li = [4, 5, 6] + +# Объекты добавляются в конец списка методом append +li.append(1) #li содержит [1] +li.append(2) #li содержит [1, 2] +li.append(4) #li содержит [1, 2, 4] +li.append(3) #li содержит [1, 2, 4, 3] +# Удаляются с конца методом pop +li.pop() #=> 3 и li содержит [1, 2, 4] +# Положим его обратно +li.append(3) # li содержит [1, 2, 4, 3] опять. + +# Обращайтесь со списком, как с обычным массивом +li[0] #=> 1 +# Посмотрим на последний элемент +li[-1] #=> 3 + +# Попытка выйти за границы массива приводит к IndexError +li[4] # Выдает IndexError + +# Можно обращаться к диапазону, используя "кусочный синтаксис" (slice syntax) +# (Для тех из вас, кто любит математику, это замкнуто/открытый интервал.) +li[1:3] #=> [2, 4] +# Опускаем начало +li[2:] #=> [4, 3] +# Опускаем конец +li[:3] #=> [1, 2, 4] + +# Удаляем произвольные элементы из списка оператором del +del li[2] # li содержит [1, 2, 3] + +# Вы можете складывать списки +li + other_li #=> [1, 2, 3, 4, 5, 6] - ЗАмечание: li и other_li остаются нетронутыми + +# Конкатенировать списки можно методом extend +li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6] + +# Проверять элемент на вхождение на список оператором in +1 in li #=> True + +# Длина списка вычисляется при помощи len +len(li) #=> 6 + + +# Кортежи - это как списки, только неизменяемые +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Выдает TypeError + +# Все те же штуки можно делать и с кортежами +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Вы можете распаковывать кортежи (или списки) в переменные +a, b, c = (1, 2, 3) # a теперь равно 1, b равно 2 и c равно 3 +# Кортежи создаются по умолчанию, если опущены скобки +d, e, f = 4, 5, 6 +# Обратите внимание, как легко поменять местами значения двух переменных +e, d = d, e # d теперь равно 5 and e равно 4 + + +# Словари содержат ассоциативные массивы +empty_dict = {} +# Вот так описывается предзаполненный словарь +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Значения ищутся по ключу с помощью оператора [] +filled_dict["one"] #=> 1 + +# Можно получить все ключи в виде списка +filled_dict.keys() #=> ["three", "two", "one"] +# Замечание - сохранение порядка ключей в словаре не гарантируется +# Ваши результаты могут не совпадать с этими. + +# Можно получить и все значения в виде списка +filled_dict.values() #=> [3, 2, 1] +# Замечание - то же самое, что и выше, насчет порядка ключей + +# При помощи оператора in можно проверять ключи на вхождение в словарь +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Попытка получить значение по несуществующему ключу выбросит KeyError +filled_dict["four"] # KeyError + +# Чтобы избежать этого, используйте метод get +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Метод get также принимает аргумент default, значение которого будет возвращено при отсутствии указанного ключа +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Метод setdefault - это безопасный способ добавить новую пару ключ-значение в словарь +filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] по прежнему возвращает 5 + + +# Множества содержат... ну, в общем, множества +empty_set = set() +# Инициализация множества набором значений +some_set = set([1,2,2,3,4]) # some_set теперь равно set([1, 2, 3, 4]) + +# Начиная с Python 2.7, вы можете использовать {} чтобы обьявить множество +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Добавление новых элементов в множество +filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5} + +# Пересечение множеств: & +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Объединение множеств: | +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Разность множеств: - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Проверка на вхождение во множество: in +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Поток управления +#################################################### + +# Давайте заведем переменную +some_var = 5 + +# Так выглядит выражение if. Отступы в python очень важны! +# результат: "some_var меньше, чем 10" +if some_var > 10: + print "some_var намного больше, чем 10." +elif some_var < 10: # Выражение elif необязательно. + print "some_var меньше, чем 10." +else: # Это тоже необязательно. + print "some_var равно 10." + + +""" +Циклы For проходят по циклам +результат: + собака это млекопитающее + кошка это млекопитающее + мышь это млекопитающее +""" +for animal in ["собака", "кошка", "мышь"]: + # Можете использовать оператор % для интерполяции форматированных строк + print "%s это млекопитающее" % animal + +""" +`range(number)` возвращает список чисел +от нуля до заданного числа +результат: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +Циклы while продолжаются до тех пор, пока указанное условие не станет ложным. +результат: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # То же самое, что x = x + 1 + +# Обрабывайте исключения блоками try/except + +# Работает в Python 2.6 и выше: +try: + # Для выбора ошибки используется raise + raise IndexError("Это IndexError") +except IndexError as e: + pass # pass это просто отсутствие оператора. Обычно здесь происходит восстановление от ошибки. + + +#################################################### +## 4. Функции +#################################################### + +# Используйте def для создания новых функций +def add(x, y): + print "x равен %s, а y равен %s" % (x, y) + return x + y # Возвращайте результат выражением return + +# Вызов функции с аргументами +add(5, 6) #=> prints out "x равен 5, а y равен 6" и возвращает 11 + +# Другой способ вызова функции с аргументами +add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке. + +# Вы можете определить функцию, принимающую неизвестное количество аргументов +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# А также можете определить функцию, принимающую изменяющееся количество +# именованных аргументов +def keyword_args(**kwargs): + return kwargs + +# Вызовем эту функцию и посмотрим, что из этого получится +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Если хотите, можете использовать оба способа одновременно +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) выводит: + (1, 2) + {"a": 3, "b": 4} +""" + +# Вызывая функции, можете сделать наоборот! +# Используйте символ * для передачи кортежей и ** для передачи словарей +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # эквивалент foo(1, 2, 3, 4) +all_the_args(**kwargs) # эквивалент foo(a=3, b=4) +all_the_args(*args, **kwargs) # эквивалент foo(1, 2, 3, 4, a=3, b=4) + +# Python имеет функции первого класса +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Также есть и анонимные функции +(lambda x: x > 2)(3) #=> True + +# Есть встроенные функции высшего порядка +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Мы можем использовать списки для удобного отображения и фильтрации +[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. Классы +#################################################### + +# Чтобы получить класс, мы наследуемся от object. +class Human(object): + + # Атрибут класса. Он разделяется всеми экземплярами этого класса + species = "H. sapiens" + + # Обычный конструктор + def __init__(self, name): + # Присваивание значения аргумента атрибуту класса name + self.name = name + + # Метод экземпляра. Все методы принимают self в качестве первого аргумента + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Метод класса разделяется между всеми экземплярами + # Они вызываются с указыванием вызывающего класса в качестве первого аргумента + @classmethod + def get_species(cls): + return cls.species + + # Статический метод вызывается без ссылки на класс или экземпляр + @staticmethod + def grunt(): + return "*grunt*" + + +# Инстанцирование класса +i = Human(name="Иван") +print i.say("привет") # выводит "Иван: привет" + +j = Human("Петр") +print j.say("Привет") #выводит "Петр: привет" + +# Вызов метода класса +i.get_species() #=> "H. sapiens" + +# Присвоение разделяемому атрибуту +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Вызов статического метода +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Модули +#################################################### + +# Вы можете импортировать модули +import math +print math.sqrt(16) #=> 4 + +# Вы можете импортировать отдельные функции модуля +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Можете импортировать все функции модуля. +# Предупреждение: не рекомендуется +from math import * + +# Можете сокращать имена модулей +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Модули в Python это обычные файлы с кодом python. Вы +# можете писать свои модули и импортировать их. Название +# модуля совпадает с названием файла. + +# Вы можете узнать, какие функции и атрибуты определены +# в модуле +import math +dir(math) + + +``` + +## Хочется большего? + +### Бесплатные онлайн-материалы + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Готовьте деньги + +* [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 cf5730cebc5756e5b5cb18e93fe53092c3d6a036 Mon Sep 17 00:00:00 2001 From: Yury Date: Fri, 16 Aug 2013 00:21:28 +0400 Subject: fixed typo in C spanish version adressed in #230 --- es-es/c-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown index b109f761..5d3aae0c 100644 --- a/es-es/c-es.html.markdown +++ b/es-es/c-es.html.markdown @@ -284,7 +284,7 @@ for (xx=0; xx<20; xx++) { // impredecibles printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? -// Cuando hallas acabado con el bloque de memoría malloc, necesitas +// Cuando hayas acabado con el bloque de memoría malloc, necesitas // liberarlo o sino nadie más podrá usarlo hasta que tu programa se cierre free(my_ptr); -- cgit v1.2.3 From 50ac50f05f82c3b3069329634f373c1ba55263c0 Mon Sep 17 00:00:00 2001 From: Seva Baskin Date: Thu, 15 Aug 2013 23:25:51 +0100 Subject: Update objective-c.html.markdown Fixed a few typos --- objective-c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 2b1b3c67..b92e3218 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -160,7 +160,7 @@ int main (int argc, const char * argv[]) int jj; for (jj=0; jj < 4; jj++) { - NSLog(@"%d,", ii++); + NSLog(@"%d,", jj++); } // => prints "0," // "1," // "2," @@ -256,7 +256,7 @@ int main (int argc, const char * argv[]) } // Constructors are a way of creating classes -// This is a default constructor which is call when the object is creating +// This is a default constructor which is called when the object is creating - (id)init { if ((self = [super init])) -- cgit v1.2.3 From 91db568e0dec9f062bab03d4643f59356ed5d574 Mon Sep 17 00:00:00 2001 From: sergiokas Date: Thu, 15 Aug 2013 19:29:27 -0300 Subject: Fixed typo Fixed a typo. Nice tutorial, by the way. --- ruby-ecosystem.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index cae55cd3..54c1d178 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -81,7 +81,7 @@ development. Less mature/compatible: * Topaz - Written in RPython (using the PyPy toolchain), Topaz is fairly young - and not yet compatable. It shows promise to be a high-performance ruby + and not yet compatible. It shows promise to be a high-performance ruby implementation. * IronRuby - Written in C# targeting the .NET platform, work on IronRuby seems to have stopped since Microsoft pulled their support. -- cgit v1.2.3 From f840436ea22836a0f09af795593ee47b909e047f Mon Sep 17 00:00:00 2001 From: wikibook Date: Fri, 16 Aug 2013 14:42:26 +0900 Subject: added Korean version of Java tutorial --- ko-kr/java-kr.html.markdown | 406 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 406 insertions(+) create mode 100644 ko-kr/java-kr.html.markdown diff --git a/ko-kr/java-kr.html.markdown b/ko-kr/java-kr.html.markdown new file mode 100644 index 00000000..dcca9b2e --- /dev/null +++ b/ko-kr/java-kr.html.markdown @@ -0,0 +1,406 @@ +--- +language: java +category: language +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: + - ["wikibook", "http://wikibook.co.kr"] +lang: ko-kr +--- + +자바는 일반 목적으로 사용할 수 있고 동시성을 지원하며, 클래스 기반의 객체지향 컴퓨터 프로그래밍 언어입니다. +[더 자세한 사항](http://docs.oracle.com/javase/tutorial/java/index.html) + +```java +// 한 줄짜리 주석은 //로 시작합니다. +/* +여러 줄 주석은 다음과 같은 형태입니다. +*/ +/** +자바독(JavaDoc) 주석은 이렇게 생겼습니다. 자바독 주석은 클래스나 클래스의 +다양한 속성을 기술하는 데 사용됩니다. +*/ + +// java.util 패키지 안에 있는 ArrayList 클래스를 임포트합니다. +import java.util.ArrayList; +// java.security 패키지 안에 있는 모든 클래스를 임포트합니다. +import java.security.*; + +// 각 .java 파일에는 공용(public) 클래스가 들어 있으며, 클래스의 이름은 파일명과 동일합니다. +public class LearnJava { + + // 프로그램에는 반드시 진입점 역할을 하는 main 메서드가 하나 있어야 합니다. + public static void main (String[] args) { + + // System.out.println을 이용해 한 줄을 출력합니다. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // 줄바꿈 없이 뭔가를 출력하려면 System.out.print를 사용합니다. + System.out.print("Hello "); + System.out.print("World"); + + + /////////////////////////////////////// + // 타입 & 변수 + /////////////////////////////////////// + + // <타입> <이름>과 같은 형태로 변수를 선언합니다. + // Byte - 부호가 있는 8비트 2의 보수 정수 + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 부호가 있는 16비트 2의 보수 정수 + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 부호가 있는 32비트 2의 보수 정수 + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 부호가 있는 64비트 2의 보수 정수 + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L은 이 변수의 값이 Long 타입임을 나타내는 데 사용됩니다. + // L이 없는 것들은 기본적으로 정수로 간주됩니다. + + // 참고: 자바에는 부호 없는(unsigned) 타입이 없습니다. + + // Float - 단정도 32비트 IEEE 754 부동 소수점 수 + float fooFloat = 234.5f; + // f는 이 변수의 값이 float 타입임을 나타내는 데 사용됩니다. + // f를 지정하지 않으면 double로 간주됩니다. + + // Double - 배정도 64비트 IEEE 754 부동 소수점 수 + double fooDouble = 123.4; + + // Boolean - 참(true) & 거짓(false) + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - 단일 16비트 유니코드 문자 + char fooChar = 'A'; + + // 변수를 변경할 수 없게 만들려면 final을 지정합니다. + final int HOURS_I_WORK_PER_WEEK = 9001; + + // 문자열 + String fooString = "My String Is Here!"; + + // \n은 새로운 줄을 시작하는 이스케이프 문자입니다. + String barString = "Printing on a new line?\nNo Problem!"; + // \t는 탭 문자를 추가하는 이스케이프 문자입니다. + String bazString = "Do you want to add a tab?\tNo Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // 배열 + // 배열의 크기는 반드시 선언할 때 결정해야 합니다. + // 배열을 선언하는 형식은 다음과 같습니다. + //<자료형> [] <변수명> = new <자료형>[<배열 크기>]; + int [] intArray = new int[10]; + String [] stringArray = new String[1]; + boolean [] booleanArray = new boolean[100]; + + // 배열을 선언하고 초기화하는 또 다른 방법 + int [] y = {9000, 1000, 1337}; + + // 배열 인덱스 - 요소에 접근 + System.out.println("intArray @ 0: " + intArray[0]); + + // 배열의 인덱스는 0에서부터 시작하며 변경 가능합니다. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // 기타 참고할 만한 자료구조 + // ArrayLists - 좀 더 많은 기능을 제공하고 크기를 변경 가능하다는 점을 + // 제외하면 배열과 비슷합니다. + // LinkedLists + // Maps + // HashMaps + + /////////////////////////////////////// + // 연산자 + /////////////////////////////////////// + System.out.println("\n->Operators"); + + int i1 = 1, i2 = 2; // 다중 선언의 축약형 + + // 산술 연산은 이해하기 어렵지 않습니다. + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5를 잘라 버립니다) + + // 나눗셈 + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // 비교 연산자 + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // 비트 연산자! + /* + ~ 단항 보수 연산 + << 산술적 왼쪽 시프트 + >> 산술적 오른쪽 시프트 + >>> 논리적 오른쪽 시프트 + & 비트 단위 논리곱(AND) + ^ 비트 단위 배타적 논리합(OR) + | 비트 단위 논리합(OR) + */ + + // 증감 연산자 + int i = 0; + System.out.println("\n->Inc/Dec-rementation"); + System.out.println(i++); //i = 1. 후치 증가 연산 + System.out.println(++i); //i = 2. 전치 증가 연산 + System.out.println(i--); //i = 1. 후치 감소 연산 + System.out.println(--i); //i = 0. 전치 감소 연산 + + /////////////////////////////////////// + // 에저 구조 + /////////////////////////////////////// + System.out.println("\n->Control Structures"); + + // if 문은 C 언어와 비슷합니다. + int j = 10; + if (j == 10){ + System.out.println("I get printed"); + } else if (j > 10) { + System.out.println("I don't"); + } else { + System.out.println("I also don't"); + } + + // while 루프 + int fooWhile = 0; + while(fooWhile < 100) + { + // System.out.println(fooWhile); + // 카운터를 증가 + // 99번 반복, fooWhile 0->99 + fooWhile++; + } + System.out.println("fooWhile Value: " + fooWhile); + + // do-while 루프 + int fooDoWhile = 0; + do + { + // System.out.println(fooDoWhile); + // 카운터를 증가 + // 99번 반복, fooDoWhile 0->99 + fooDoWhile++; + }while(fooDoWhile < 100); + System.out.println("fooDoWhile Value: " + fooDoWhile); + + // for 루프 + int fooFor; + // for 루프 구조 => for(<초기식>; <조건식>; <증감식>) + for(fooFor=0; fooFor<10; fooFor++){ + // System.out.println(fooFor); + // 10번 반복, fooFor 0->9 + } + System.out.println("fooFor Value: " + fooFor); + + // switch-case 문 + // switch는 byte, short, char, int 자료형을 대상으로 동작합니다. + // 아울러 열거형을 비롯해 String 클래스 및 원시 타입을 감싼 Character, + // Byte, Short, Integer와 같은 몇 가지 특별한 클래스에 대해서도 동작합니다. + int month = 3; + String monthString; + switch (month){ + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + default: + monthString = "Some other month"; + break; + } + System.out.println("Switch Case Result: " + monthString); + + + /////////////////////////////////////// + // 자료형 변환과 형변환 + /////////////////////////////////////// + + // 데이터 변환 + + // 문자열에서 정수로 변환 + Integer.parseInt("123");// 정수 버전의 "123"을 반환 + + // 정수를 문자열로 변환 + Integer.toString(123);// 문자열 버전의 123을 반환 + + // 다른 변환에 대해서는 아래 클래스를 확인해 보세요. + // Double + // Long + // String + + // 형변환 + // 자바 객채 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이 많을뿐더러 + // 다소 중급 수준에 해당하는 개념들도 다뤄야 합니다. + // 이와 관련된 사항은 아래 링크를 참고하세요. + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // 클래스와 함수 + /////////////////////////////////////// + + System.out.println("\n->Classes & Functions"); + + // (Bicycle 클래스의 정의) + + // 클래스를 인스턴스화하려면 new를 사용합니다. + Bicycle trek = new Bicycle(); + + // 객체의 메서드를 호출합니다. + trek.speedUp(3); // 항상 설정자 메서드와 접근자 메서드를 사용해야 합니다. + trek.setCadence(100); + + // 현재 객체의 값을 표시할 때는 관례적으로 toString을 사용합니다. + System.out.println("trek info: " + trek.toString()); + + } // main 메서드 끝 +} // LearnJava 클래스 끝 + + +// .java 파일 안에 다른 비공개 클래스를 포함할 수 있습니다. + + +// 클래스 선언 문법: +// class <클래스명>{ +// // 데이터 필드, 생성자, 함수가 모두 이곳에 들어갑니다. +// // 자바에서는 함수를 메서드라고 부릅니다. +// } + +class Bicycle { + + // Bicycle의 필드와 변수 + public int cadence; // Public: 어느 곳에서도 접근할 수 있습니다. + private int speed; // Private: 클래스 안에서만 접근할 수 있습니다. + protected int gear; // Protected: 현재 클래스와 하위 클래스에서 접근할 수 있습니다. + String name; // default: 현재 패키지 안에서만 접근할 수 있습니다. + + // 생성자는 클래스를 생성하는 방법 중 하나입니다. + // 다음은 기본 생성자입니다. + public Bicycle() { + gear = 1; + cadence = 50; + speed = 5; + name = "Bontrager"; + } + + // 다음은 구체화된 생성자입니다(인자를 담고 있습니다) + public Bicycle(int startCadence, int startSpeed, int startGear, String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // 함수 문법: + // <반환형> <함수명>(<인자>) + + // 자바 클래스는 필드에 대해 접근자 메서드와 설정자 메서드를 구현할 때가 많습니다. + + // 메서드 선언 문법: + // <유효범위> <반환형> <메서드명>(<인자>) + public int getCadence() { + return cadence; + } + + // void 메서드는 반환형이 필요하지 않습니다. + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + // 현재 객체의 속성값을 표시하는 메서드 + @Override + public String toString() { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + speed + + " name: " + name; + } +} // Bicycle 클래스의 끝 + +// PennyFarthing은 Bicycle의 하위 클래스입니다. +class PennyFarthing extends Bicycle { + // (페니 파딩은 앞바퀴가 굉장히 큰 자전거입니다. 기어가 없죠.) + + public PennyFarthing(int startCadence, int startSpeed){ + // super를 이용해 부모 생성자를 호출합니다. + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // @annotation을 이용해 재정의하는 메서드를 표시해야 합니다. + // 애노테이션과 애노테이션의 용도에 관한 자세한 내용은 아래 링크를 참고하세요. + // 애노테이션: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + gear = 0; + } + +} + +``` + +## 기타 참고자료 + +다음 링크를 통해 다양한 주제를 이해하고 구글을 통해 구체적인 예제들을 찾아보세요. + +공부할 만한 기타 주제: + +* [썬/오라클의 자바 자습서](http://docs.oracle.com/javase/tutorial/index.html) + +* [자바 접근 제한자](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [객체 지향 프로그래밍 개념](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [상속(Inheritance)](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [다형성(Polymorphism)](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [추상화(Abstraction)](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [예외(Exceptions)](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [인터페이스(Interfaces)](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [제네릭(Generics)](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [자바 코딩 관례(Java Code Conventions)](http://www.oracle.com/technetwork/java/codeconv-138413.html) \ No newline at end of file -- cgit v1.2.3 From 43d602b0c0ca473421cda2c43fd87f76cf1620e7 Mon Sep 17 00:00:00 2001 From: rduerig Date: Fri, 16 Aug 2013 12:37:40 +0200 Subject: Update java.html.markdown added a reference to a book --- java.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index b4531635..cdcf620c 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -405,3 +405,7 @@ Other Topics To Research: * [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) * [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + +Books: + +* [Head First Java] (http://www.headfirstlabs.com/books/hfjava/) -- cgit v1.2.3 From 41be9b284306ea70d44061fcbca1c71b8f201a97 Mon Sep 17 00:00:00 2001 From: Astynax84 Date: Fri, 16 Aug 2013 15:25:10 +0400 Subject: Russian translation of clojure.html.markdown --- ru-ru/clojure-ru.html.markdown | 425 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 425 insertions(+) create mode 100644 ru-ru/clojure-ru.html.markdown diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown new file mode 100644 index 00000000..9bc32856 --- /dev/null +++ b/ru-ru/clojure-ru.html.markdown @@ -0,0 +1,425 @@ +--- +language: clojure +filename: learnclojure-ru.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] + - ["Alexey Pirogov", "http://twitter.com/alex_pir"] +--- + +Clojure, это представитель семейства Lisp-подобных языков, разработанный +для Java Virtual Machine. Язык идейно гораздо ближе к чистому +[функциональному программированию](https://ru.wikipedia.org/wiki/%D0%A4%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%BE%D0%BD%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B5_%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) чем его прародитель Common Lisp, но в то же время обладает набором инструментов для работы с состоянием, +таких как [STM](https://ru.wikipedia.org/wiki/Software_transactional_memory). + +Благодаря такому сочетанию технологий в одном языке, разработка программ, +предполагающих конкурентное выполнение, значительно упрощается +и даже может быть автоматизирована. + +(Последующие примеры кода предполагают выполнение в Clojure версии 1.2 и выше) + + +```clojure +; Комментарии начинаются символом ";". + +; Код на языке Clojure записывается в виде "форм", +; которые представляют собой обычные списки элементов, разделенных пробелами, +; заключённые в круглые скобки +; +; Clojure Reader (инструмент языка, отвечающий за чтение исходного кода), +; анализируя форму, предполагает, что первым элементом формы (т.е. списка) +; является функция или макрос, который следует вызвать, передав ему +; в качестве аргументов остальные элементы списка-формы. + +; Первым вызовом в файле должен быть вызов функции ns, +; которая отвечает за выбор текущего пространства имен (namespace) +(ns learnclojure-ru) + +; Несколько простых примеров: + +; str объединяет в единую строку все свои аргументы +(str "Hello" " " "World") ; => "Hello World" + +; Арифметика тоже выглядит несложно +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 + +; Проверка на равенство (Equality) +(= 1 1) ; => true +(= 2 1) ; => false + +; Для булевой логики вам может понадобиться not +(not true) ; => false + +; Вложенные формы, конечно же, допустимы и работают вполне предсказуемо +(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 + +; Типы +;;;;;;;;;;;;; + +; Clojure использует типы Java для представления булевых значений, +; строк и чисел +; Узнать тип мы можем, использую функцию `class +(class 1) ; Целочисленные литералы типа по-умолчанию являются java.lang.Long +(class 1.) ; Числа с плавающей точкой, это java.lang.Double +(class "") ; Строки всегда заключаются в двойные кавычки + ; и представляют собой java.lang.String +(class false) ; Булевы значения, это экземпляры java.lang.Boolean +(class nil) ; "Пустое" значение называется "nil" + +; Если Вы захотите создать список из чисел, вы можете просто +; предварить форму списка символом "'", который подскажет Reader`у, +; что эта форма не требует вычисления +'(+ 1 2) ; => (+ 1 2) +; ("'", это краткая запись формы (quote (+ 1 2)) + +; "Квотированный" список можно вычислить, передав его функции eval +(eval '(+ 1 2)) ; => 3 + +; Коллекции и Последовательности +;;;;;;;;;;;;;;;;;;; + +; Списки (Lists) в clojure структурно представляют собой "связанные списки", +; тогда как Векторы (Vectors), устроены как массивы. +; Векторы и Списки тоже являются классами Java! +(class [1 2 3]); => clojure.lang.PersistentVector +(class '(1 2 3)); => clojure.lang.PersistentList + +; Список может быть записан, как (1 2 3), но в этом случае +; он будет воспринят reader`ом, как вызов функции. +; Есть два способа этого избежать: +; '(1 2 3) - квотирование, +; (list 1 2 3) - явное конструирование списка с помощью функции list. + +; "Коллекции", это некие наборы данных +; И списки, и векторы являются коллекциями: +(coll? '(1 2 3)) ; => true +(coll? [1 2 3]) ; => true + +; "Последовательности" (seqs), это абстракция над наборами данных, +; элементы которых "упакованы" последовательно. +; Списки - последовательности, а вектора - нет. +(seq? '(1 2 3)) ; => true +(seq? [1 2 3]) ; => false + +; Любая seq предоставляет доступ только к началу последовательности данных, +; не предоставляя информацию о её длине. +; При этом последовательности могут быть и бесконечными, +; т.к. являются ленивыми и предоставляют данные только по требованию! +(range 4) ; => (0 1 2 3) +(range) ; => (0 1 2 3 4 ...) (бесконечная последовательность!) +(take 4 (range)) ; (0 1 2 3) + +; Добавить элемент в начало списка или вектора можно с помощью функции cons +(cons 4 [1 2 3]) ; => (4 1 2 3) +(cons 4 '(1 2 3)) ; => (4 1 2 3) + +; Функция conj добавляет элемент в коллекцию +; максимально эффективным для неё способом. +; Для списков эффективно добавление в начло, а для векторов - в конец. +(conj [1 2 3] 4) ; => [1 2 3 4] +(conj '(1 2 3) 4) ; => (4 1 2 3) + +; Функция concat объединяет несколько списков и векторов в единый список +(concat [1 2] '(3 4)) ; => (1 2 3 4) + +; Работать с коллекциями удобно с помощью функций filter и map +(map inc [1 2 3]) ; => (2 3 4) +(filter even? [1 2 3]) ; => (2) + +; reduce поможет "свернуть" коллекцию +(reduce + [1 2 3 4]) +; = (+ (+ (+ 1 2) 3) 4) +; => 10 + +; Вызывая reduce, мы можем указать начальное значение +(reduce conj [] '(3 2 1)) +; = (conj (conj (conj [] 3) 2) 1) +; => [3 2 1] + +; Функции +;;;;;;;;;;;;;;;;;;;;; + +; Функция создается специальной формой fn. +; "Тело"" функции может состоять из нескольких форм, +; но результатом вызова функции всегда будет результат вычисления +; последней из них. +(fn [] "Hello World") ; => fn + +; (Вызов функции требует "оборачивания" fn-формы в форму вызова) +((fn [] "Hello World")) ; => "Hello World" + +; Назначить значению имя можно специальной формой def +(def x 1) +x ; => 1 + +; Назначить имя можно любому значению, в т.ч. и функции: +(def hello-world (fn [] "Hello World")) +(hello-world) ; => "Hello World" + +; Поскольку именование функций - очень частая операция, +; clojure позволяет, сделать это проще: +(defn hello-world [] "Hello World") + +; Вектор [] в форме описания функции, следующий сразу за именем, +; описывает параметры функции: +(defn hello [name] + (str "Hello " name)) +(hello "Steve") ; => "Hello Steve" + +; Одна функция может иметь сразу несколько наборов аргументов: +(defn hello3 + ([] "Hello World") + ([name] (str "Hello " name))) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" + +; Также функция может иметь набор аргументов переменной длины +(defn count-args [& args] ; args будет содержать seq аргументов + (str "You passed " (count args) " args: " args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" + +; Можно комбинировать оба подхода задания аргументов +(defn hello-count [name & args] + (str "Hello " name ", you passed " (count args) " extra args")) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" + +; Для создания анонимных функций есть специальный синтаксис: +; функциональные литералы +(def hello2 #(str "Hello " %1)) +(hello2 "Fanny") ; => "Hello Fanny" + +; такие функциональные литералы удобно использовать с map, filter и reduce +(map #(* 10 %1) [1 2 3 5]) ; => (10 20 30 50) +(filter #(> %1 3) [1 2 3 4 5 6 7]) ; => (4 5 6 7) +(reduce #(str %1 "," %2) [1 2 3 4]) ; => "1,2,3,4" + +; Отображения (Maps) +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +; Hash maps и array maps имеют одинаковый интерфейс. +; Hash maps производят поиск по ключу быстрее, но не сохраняют порядок ключей +(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap +(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap + +; Array maps автоматически преобразуются в hash maps, +; как только разрастутся до определенного размера + +; Отображения могут использовать в качестве ключей любые хэшируемые значения, +; однако предпочтительными являются ключи, +; являющиеся "ключевыми словами" (keywords) +(class :a) ; => clojure.lang.Keyword + +(def stringmap {"a" 1, "b" 2, "c" 3}) +stringmap ; => {"a" 1, "b" 2, "c" 3} + +(def keymap {:a 1, :b 2, :c 3}) +keymap ; => {:a 1, :c 3, :b 2} + +; Предыдущий пример содержит запятые в коде, однако reader не использует их, +; при обработке литералов - запятые просто воспринимаются, +; как "пробельные символы" (whitespaces) + +; Отображение может выступать в роли функции, возвращающей значение по ключу +(stringmap "a") ; => 1 +(keymap :a) ; => 1 + +; При попытке получить отсутствующее значение, будет возвращён nil +(stringmap "d") ; => nil + +; Иногда бывает удобно указать конкретное значение по-умолчанию: +({:a 1 :b 2} :c "Oops!") ; => "Oops!" + +; Keywords тоже могут использоваться в роли функций! +(:b keymap) ; => 2 + +; Однако этот фокус не пройдёт со строками. +;("a" stringmap) +; => Exception: java.lang.String cannot be cast to clojure.lang.IFn + +; Добавить пару ключ-значение в отображение можно функцией assoc +(def newkeymap (assoc keymap :d 4)) +newkeymap ; => {:a 1, :b 2, :c 3, :d 4} + +; Но всегда следует помнить, что значения в Clojure - неизменяемые! +keymap ; => {:a 1, :b 2, :c 3} - оригинал не был затронут + +; dissoc позволяет исключить значение по ключу +(dissoc keymap :a :b) ; => {:c 3} + +; Множества (Sets) +;;;;;;;;;;;;;;;;;; + +(class #{1 2 3}) ; => clojure.lang.PersistentHashSet +(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} + +; Добавляются элементы посредством conj +(conj #{1 2 3} 4) ; => #{1 2 3 4} + +; Исключаются - посредством disj +(disj #{1 2 3} 1) ; => #{2 3} + +; Вызов множества, как функции, позволяет проверить +; принадлежность элемента этому множеству: +(#{1 2 3} 1) ; => 1 +(#{1 2 3} 4) ; => nil + +; В пространстве имен clojure.sets +; содержится множество функций для работы с множествами + +; Полезные формы +;;;;;;;;;;;;;;;;; + +; Конструкции ветвления в clojure, это обычные макросы +; и подобны их собратьям в других языках: +(if false "a" "b") ; => "b" +(if false "a") ; => nil + +; Специальная форма let позволяет присвоить имена значениям локально. +; При этом все изменения будут видны только вложенным формам: +(def a 10) +(let [a 1 b 2] + (> a b)) ; => false + +; Несколько форм можно объединить в одну форму посредством do +; Значением do-формы будет значение последней формы из списка вложенных в неё: +(do + (print "Hello") + "World") ; => "World" (prints "Hello") + +; Множество макросов содержит внутри себя неявную do-форму. +; Пример - макрос определения функции: +(defn print-and-say-hello [name] + (print "Saying hello to " name) + (str "Hello " name)) +(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") + +; Ещё один пример - let: +(let [name "Urkel"] + (print "Saying hello to " name) + (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Модули +;;;;;;;;; + +; Форма "use" позволяет добавить в текущее пространство имен +; все имена (вместе со значениями) из указанного модуля: +(use 'clojure.set) + +; Теперь нам доступны операции над множествами: +(intersection #{1 2 3} #{2 3 4}) ; => #{2 3} +(difference #{1 2 3} #{2 3 4}) ; => #{1} + +; use позволяет указать, какие конкретно имена +; должны быть импортированы из модуля: +(use '[clojure.set :only [intersection]]) + +; Также модуль может быть импортирован формой require +(require 'clojure.string) + +; После этого модуль становится доступе в текущем пространстве имен, +; а вызов его функций может быть осуществлен указанием полного имени функции: +(clojure.string/blank? "") ; => true + +; Импортируемому модулю можно назначить короткое имя: +(require '[clojure.string :as str]) +(str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." +; (Литерал вида #"" обозначает регулярное выражение) + +; Вместо отдельной формы require (и use, хотя это и не приветствуется) можно +; указать необходимые модули прямо в форме ns: +(ns test + (:require + [clojure.string :as str] ; Внимание: при указании внутри формы ns + [clojure.set :as set])) ; имена пакетов не квотируются! + +; Java +;;;;;;; + +; Стандартная библиотека Java очень богата, +; и всё это богатство доступно и для Clojure! + +; import позволяет импортировать модули Java +(import java.util.Date) + +; В том числе и из ns +(ns test + (:import java.util.Date + java.util.Calendar)) + +; Имя класса, сопровождаемое символом "." позволяет +; инстанцировать объекты Java-классов: +(Date.) ; + +; форма . позволяет вызывать методы: +(. (Date.) getTime) ; +(.getTime (Date.)) ; а можно и так + +; Статические методы вызываются как функции модуля: +(System/currentTimeMillis) ; (Модуль system всегда доступен!) + +; doto позволяет удобно работать с объектами, изменяющими свое состояние +(import java.util.Calendar) +(doto (Calendar/getInstance) + (.set 2000 1 1 0 0 0) + .getTime) ; => A Date. set to 2000-01-01 00:00:00 + +; Работа с изменяемым сотоянием +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +; Clojure предоставляет набор инструментов +; для работы с изменяемым состоянием: Software Transactional Memory. +; Структуры STM представлены тремя типами: +; - атомы (atoms) +; - агенты (agents) +: - ссылки (references) + +; Самые простые хранители состояния - атомы: +(def my-atom (atom {})) ; {} - начальное состояние атома + +; Обновляется атом посредством swap!. +; swap! применяет функцию аргумент к текущему значению +; атома и помещает в атом результат +(swap! my-atom assoc :a 1) ; Обновляет my-atom, помещая в него (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Обновляет my-atom, помещая в него (assoc {:a 1} :b 2) + +; Получить значение атома можно посредством '@' +; (провести так называемую операцию dereference) +my-atom ;=> Atom<#...> (Возвращает объект типа Atom) +@my-atom ; => {:a 1 :b 2} + +; Пример реализации счётчика на атоме +(def counter (atom 0)) +(defn inc-counter [] + (swap! counter inc)) + +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) + +@counter ; => 5 + +; С другими STM-конструкциями - refs и agents - можно ознакомиться тут: +; Refs: http://clojure.org/refs +; Agents: http://clojure.org/agents +``` + +### Для будущего чтения + +Это руководство не претендует на полноту, но мы смеем надеяться, способно вызвать интерес к дальнейшему изучению языка. + +Clojure.org - сайт содержит большое количество статей по языку: +[http://clojure.org/](http://clojure.org/) + +Clojuredocs.org - сайт документации языка с примерами использования функций: +[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) + +4Clojure - отличный способ закрепить навыки программирования на clojure, решая задачи вместе с коллегами со всего мира: +[http://www.4clojure.com/](http://www.4clojure.com/) + +Clojure-doc.org (да, именно) неплохой перечень статей для начинающих: +[http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From 0746979b8f1cf801cb22b6a5fff66b4caf6ca6d4 Mon Sep 17 00:00:00 2001 From: Astynax84 Date: Fri, 16 Aug 2013 15:28:16 +0400 Subject: fixed typos in russian translation of clojure.html.markdown --- ru-ru/clojure-ru.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown index 9bc32856..48c16192 100644 --- a/ru-ru/clojure-ru.html.markdown +++ b/ru-ru/clojure-ru.html.markdown @@ -4,6 +4,7 @@ filename: learnclojure-ru.clj contributors: - ["Adam Bard", "http://adambard.com/"] - ["Alexey Pirogov", "http://twitter.com/alex_pir"] + --- Clojure, это представитель семейства Lisp-подобных языков, разработанный @@ -374,7 +375,7 @@ keymap ; => {:a 1, :b 2, :c 3} - оригинал не был затронут ; Структуры STM представлены тремя типами: ; - атомы (atoms) ; - агенты (agents) -: - ссылки (references) +; - ссылки (references) ; Самые простые хранители состояния - атомы: (def my-atom (atom {})) ; {} - начальное состояние атома -- cgit v1.2.3 From 8aa0ab6068a13491ec9cba59bce32911ab9f8061 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 16 Aug 2013 09:44:22 -0700 Subject: Edits --- c.html.markdown | 250 +++++++++++++++++++---------------------- ko-kr/java-kr.html.markdown | 10 +- pt-br/ruby-pt.html.markdown | 8 +- ru-ru/clojure-ru.html.markdown | 2 +- ru-ru/php-ru.html.markdown | 18 +-- ru-ru/python-ru.html.markdown | 8 +- zh-cn/go-zh.html.markdown | 183 +++++++++++++++--------------- 7 files changed, 240 insertions(+), 239 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 00b13cb0..24a96463 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -1,11 +1,9 @@ --- -- name: c -- category: language -- language: c -- filename: learnc.c -- contributors: - - [Adam Bard](http://adambard.com/) - - [Árpád Goretity](http://twitter.com/H2CO3_iOS) +language: c +filename: learnc.c +contributors: + - ["Adam Bard", "http://adambard.com/"] + - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] --- @@ -27,17 +25,10 @@ Multi-line comments look like this. They work in C89 as well. #include #include -// file names between are headers from the C standard library. -// They are searched for by the preprocessor in the system include paths -// (usually /usr/lib on Unices, can be controlled with the -I option if you are using GCC or clang.) +// (File names between are headers from the C standard library.) // For your own headers, use double quotes instead of angle brackets: #include "my_header.h" -// The C preprocessor introduces an almost fully-featured macro language. It's useful, but -// it can be confusing (and what's even worse, it can be misused). Read the -// Wikipedia article on the C preprocessor for further information: -// http://en.wikipedia.org/wiki/C_preprocessor - // Declare function signatures in advance in a .h file, or at the top of // your .c file. void function_1(); @@ -50,132 +41,117 @@ int main() { // %d is an integer, \n is a newline printf("%d\n", 0); // => Prints 0 // All statements must end with a semicolon - + /////////////////////////////////////// // Types /////////////////////////////////////// - - // You have to declare variables before using them. A variable declaration - // requires you to specify its type; a variable's type determines its size - // in bytes. - + // ints are usually 4 bytes int x_int = 0; - + // shorts are usually 2 bytes short x_short = 0; - + // chars are guaranteed to be 1 byte char x_char = 0; char y_char = 'y'; // Char literals are quoted with '' - + // longs are often 4 to 8 bytes; long longs are guaranteed to be at least // 64 bits long x_long = 0; long long x_long_long = 0; - + // floats are usually 32-bit floating point numbers float x_float = 0.0; - + // doubles are usually 64-bit floating-point numbers double x_double = 0.0; - - // Integral types may be unsigned. This means they can't be negative, but - // the maximum value of an unsigned variable is greater than the maximum - // signed value of the same size. - unsigned char ux_char; + + // Integral types may be unsigned. unsigned short ux_short; unsigned int ux_int; unsigned long long ux_long_long; - - // Other than char, which is always 1 byte (but not necessarily 8 bits!), - // these types vary in size depending on your machine and compiler. - // sizeof(T) gives you the size of a variable with type T in - // bytes so you can express the size of these types in a portable way. - // sizeof(obj) yields the size of an actual expression (variable, literal, etc.). - // For example, + + // sizeof(T) gives you the size of a variable with type T in bytes + // sizeof(obj) yields the size of the expression (variable, literal, etc.). printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) - - - // It's worth noting that if the argument of the `sizeof` operator is not a type but an expression, - // then its argument is not evaluated except VLAs (see below). Also, `sizeof()` is an operator, not a function, - // furthermore, the value it yields is a compile-time constant (except when used on VLAs, again.) + + + // If the argument of the `sizeof` operator an expression, then its argument + // is not evaluated (except VLAs (see below)). + // The value it yields in this case is a compile-time constant. int a = 1; size_t size = sizeof(a++); // a++ is not evaluated printf("sizeof(a++) = %zu where a = %d\n", size, a); - // the above code prints "sizeof(a++) = 4 where a = 1" (on a usual 32-bit architecture) - + // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) + // Arrays must be initialized with a concrete size. char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes // (assuming 4-byte words) - - + + // You can initialize an array to 0 thusly: char my_array[20] = {0}; - + // Indexing an array is like other languages -- or, // rather, other languages are like C my_array[0]; // => 0 - + // Arrays are mutable; it's just memory! my_array[1] = 2; printf("%d\n", my_array[1]); // => 2 - - // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) can be declared as well. - // The size of such an array need not be a compile time constant: + + // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) + // can be declared as well. The size of such an array need not be a compile + // time constant: printf("Enter the array size: "); // ask the user for an array size char buf[0x100]; fgets(buf, sizeof buf, stdin); - size_t size = strtoul(buf, NULL, 10); // strtoul parses a string to an unsigned integer + + // strtoul parses a string to an unsigned integer + size_t size = strtoul(buf, NULL, 10); int var_length_array[size]; // declare the VLA printf("sizeof array = %zu\n", sizeof var_length_array); - + // A possible outcome of this program may be: - Enter the array size: 10 - sizeof array = 40 - + // > Enter the array size: 10 + // > sizeof array = 40 + // Strings are just arrays of chars terminated by a NUL (0x00) byte, // represented in strings as the special character '\0'. // (We don't have to include the NUL byte in string literals; the compiler // inserts it at the end of the array for us.) char a_string[20] = "This is a string"; printf("%s\n", a_string); // %s formats a string - - /* - You may have noticed that a_string is only 16 chars long. - Char #17 is the NUL byte. - Chars #18, 19 and 20 are 0 as well - if an initializer list (in this case, the string literal) - has less elements than the array it is initializing, then excess array elements are implicitly - initialized to zero. This is why int ar[10] = { 0 } works as expected intuitively. - */ - + printf("%d\n", a_string[16]); // => 0 - - // So string literals are strings enclosed within double quotes, but if we have characters - // between single quotes, that's a character literal. + // i.e., byte #17 is 0 (as are 18, 19, and 20) + + // If we have characters between single quotes, that's a character literal. // It's of type `int`, and *not* `char` (for historical reasons). int cha = 'a'; // fine - char chb = 'a'; // fine too (implicit conversion from int to char - truncation) - + char chb = 'a'; // fine too (implicit conversion from int to char) + /////////////////////////////////////// // Operators /////////////////////////////////////// - + int i1 = 1, i2 = 2; // Shorthand for multiple declaration float f1 = 1.0, f2 = 2.0; - + // Arithmetic is straightforward i1 + i2; // => 3 i2 - i1; // => 1 i2 * i1; // => 2 i1 / i2; // => 0 (0.5, but truncated towards 0) - - f1 / f2; // => 0.5, plus or minus epsilon - floating-point numbers and calculations are not exact - + + f1 / f2; // => 0.5, plus or minus epsilon + // Floating-point numbers and calculations are not exact + // Modulo is there as well 11 % 3; // => 2 - + // Comparison operators are probably familiar, but // there is no boolean type in c. We use ints instead. // (Or _Bool or bool in C99.) @@ -187,14 +163,14 @@ int main() { 3 < 2; // => 0 2 <= 2; // => 1 2 >= 2; // => 1 - + // C is not Python - comparisons don't chain. int a = 1; // WRONG: int between_0_and_2 = 0 < a < 2; // Correct: int between_0_and_2 = 0 < a && a < 2; - + // Logic works on ints !3; // => 0 (Logical not) !0; // => 1 @@ -202,7 +178,7 @@ int main() { 0 && 1; // => 0 0 || 1; // => 1 (Logical or) 0 || 0; // => 0 - + // Bitwise operators! ~0x0F; // => 0xF0 (bitwise negation, "1's complement") 0x0F & 0xF0; // => 0x00 (bitwise AND) @@ -210,17 +186,17 @@ int main() { 0x04 ^ 0x0F; // => 0x0B (bitwise XOR) 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) - - // Be careful when shifting signed integers - the following are all undefined behavior: + + // Be careful when shifting signed integers - the following are undefined: // - shifting into the sign bit of a signed integer (int a = 1 << 32) // - left-shifting a negative number (int a = -1 << 2) - // - shifting by an offset which is more than or equal to the width of the type of the LHS: + // - 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 - + /////////////////////////////////////// // Control Structures /////////////////////////////////////// - + if (0) { printf("I am never run\n"); } else if (0) { @@ -228,36 +204,38 @@ int main() { } else { printf("I print\n"); } - + // While loops exist int ii = 0; while (ii < 10) { - printf("%d, ", ii++); // ii++ increments ii in-place, after yielding its value ("postincrement"). + printf("%d, ", ii++); // ii++ increments ii in-place + // after yielding its value ("postincrement"). } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - + printf("\n"); - + int kk = 0; do { printf("%d, ", kk); - } while (++kk < 10); // ++kk increments kk in-place, and yields the already incremented value ("preincrement") + } while (++kk < 10); // ++kk increments kk in-place, and yields + // the already incremented value ("preincrement") // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - + printf("\n"); - + // For loops too int jj; for (jj=0; jj < 10; jj++) { printf("%d, ", jj); } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - + printf("\n"); - + // branching with multiple choices: switch() switch (some_integral_expression) { case 0: // labels need to be integral *constant* epxressions do_stuff(); - break; // if you don't break, control flow falls over labels - you usually don't want that. + break; // if you don't break, control flow falls over labels case 1: do_something_else(); break; @@ -267,73 +245,74 @@ int main() { exit(-1); break; } - + /////////////////////////////////////// // Typecasting /////////////////////////////////////// - + // Every value in C has a type, but you can cast one value into another type // if you want (with some constraints). - + int x_hex = 0x01; // You can assign vars with hex literals - + // Casting between types will attempt to preserve their numeric values printf("%d\n", x_hex); // => Prints 1 printf("%d\n", (short) x_hex); // => Prints 1 printf("%d\n", (char) x_hex); // => Prints 1 - + // Types will overflow without warning printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long) - // printf("%d\n", (unsigned char) 257); would be undefined behavior - `char' is usually signed - // on most modern systems, and signed integer overflow invokes UB. - // Also, for determining the maximal value of a `char`, a `signed char` and an `unisigned char`, + + // For determining the max value of a `char`, a `signed char` and an `unisigned char`, // respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from - + // Integral types can be cast to floating-point types, and vice-versa. printf("%f\n", (float)100); // %f formats a float printf("%lf\n", (double)100); // %lf formats a double printf("%d\n", (char)100.0); - + /////////////////////////////////////// // Pointers /////////////////////////////////////// - + // A pointer is a variable declared to store a memory address. Its declaration will // also tell you the type of data it points to. You can retrieve the memory address // of your variables, then mess with them. - + int x = 0; printf("%p\n", (void *)&x); // Use & to retrieve the address of a variable // (%p formats an object pointer of type void *) // => Prints some address in memory; - - + + // Pointers start with * in their declaration int *px, not_a_pointer; // px is a pointer to an int px = &x; // Stores the address of x in px printf("%p\n", (void *)px); // => Prints some address in memory printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); // => Prints "8, 4" on a typical 64-bit system - + // To retreive the value at the address a pointer is pointing to, // put * in front to de-reference it. - // Note: yes, it may be confusing that '*' is used for _both_ declaring a pointer and dereferencing it. - printf("%d\n", *px); // => Prints 0, the value of x, which is what px is pointing to the address of - + // Note: yes, it may be confusing that '*' is used for _both_ declaring a + // pointer and dereferencing it. + printf("%d\n", *px); // => Prints 0, the value of x + // You can also change the value the pointer is pointing to. // We'll have to wrap the de-reference in parenthesis because // ++ has a higher precedence than *. (*px)++; // Increment the value px is pointing to by 1 printf("%d\n", *px); // => Prints 1 printf("%d\n", x); // => Prints 1 - - int x_array[20]; // Arrays are a good way to allocate a contiguous block of memory + + // Arrays are a good way to allocate a contiguous block of memory + int x_array[20]; int xx; for (xx = 0; xx < 20; xx++) { x_array[xx] = 20 - xx; } // Initialize x_array to 20, 19, 18,... 2, 1 - + // Declare a pointer of type int and initialize it to point to x_array int* x_ptr = x_array; // x_ptr now points to the first element in the array (the integer 20). @@ -342,50 +321,52 @@ int main() { // it decays into (implicitly converted to) a pointer. // Exceptions: when the array is the argument of the `&` (address-od) operator: int arr[10]; - int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`! It's of type "pointer to array" (of ten `int`s). + int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`! + // It's of type "pointer to array" (of ten `int`s). // or when the array is a string literal used for initializing a char array: char arr[] = "foobarbazquirk"; // or when it's the argument of the `sizeof` or `alignof` operator: int arr[10]; int *ptr = arr; // equivalent with int *ptr = &arr[0]; printf("%zu %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8" - + // Pointers are incremented and decremented based on their type // (this is called pointer arithmetic) printf("%d\n", *(x_ptr + 1)); // => Prints 19 printf("%d\n", x_array[1]); // => Prints 19 - + // You can also dynamically allocate contiguous blocks of memory with the // standard library function malloc, which takes one argument of type size_t // representing the number of bytes to allocate (usually from the heap, although this // may not be true on e. g. embedded systems - the C standard says nothing about it). int *my_ptr = malloc(sizeof(*my_ptr) * 20); for (xx = 0; xx < 20; xx++) { - *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx would also work here, and it's also more readable + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) - + // Dereferencing memory that you haven't allocated gives // "unpredictable results" - the program is said to invoke "undefined behavior" printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash. - + // When you're done with a malloc'd block of memory, you need to free it, // or else no one else can use it until your program terminates // (this is called a "memory leak"): free(my_ptr); - + // Strings are arrays of char, but they are usually represented as a // pointer-to-char (which is a pointer to the first element of the array). // It's good practice to use `const char *' when referring to a string literal, // since string literals shall not be modified (i. e. "foo"[0] = 'a' is ILLEGAL.) const char *my_str = "This is my very own string literal"; printf("%c\n", *my_str); // => 'T' - - // This is not the case if the string is an array (potentially initialized with a string literal) + + // This is not the case if the string is an array + // (potentially initialized with a string literal) // that resides in writable memory, as in: char foo[] = "foo"; foo[0] = 'a'; // this is legal, foo now contains "aoo" - + function_1(); } // end main function @@ -435,17 +416,17 @@ printf("%s\n", c); // => ".tset a si sihT" typedef int my_type; my_type my_type_var = 0; -// Structs are just collections of data, the members are allocated sequentially, in the order they are written: +// Structs are just collections of data, the members are allocated sequentially, +// in the order they are written: struct rectangle { int width; int height; }; -// it's generally not true that sizeof(struct rectangle) == sizeof(int) + sizeof(int) due to -// potential padding between the structure members (this is for alignment reasons. Probably won't -// happen if all members are of the same type, but watch out! -// See http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member -// for further information. +// It's not generally true that +// sizeof(struct rectangle) == sizeof(int) + sizeof(int) +// due to potential padding between the structure members (this is for alignment +// reasons). [1] void function_1() { @@ -473,7 +454,8 @@ int area(rect r) return r.width * r.height; } -// if you have large structs, you can pass them "by pointer" to avoid copying the whole struct: +// if you have large structs, you can pass them "by pointer" to avoid copying +// the whole struct: int area(const rect *r) { return r->width * r->height; @@ -527,3 +509,5 @@ Readable code is better than clever code and fast code. For a good, sane coding [Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle). Other than that, Google is your friend. + +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member diff --git a/ko-kr/java-kr.html.markdown b/ko-kr/java-kr.html.markdown index dcca9b2e..371b4665 100644 --- a/ko-kr/java-kr.html.markdown +++ b/ko-kr/java-kr.html.markdown @@ -1,5 +1,6 @@ --- language: java +filename: java-kr.java category: language contributors: - ["Jake Prather", "http://github.com/JakeHP"] @@ -26,7 +27,8 @@ import java.util.ArrayList; // java.security 패키지 안에 있는 모든 클래스를 임포트합니다. import java.security.*; -// 각 .java 파일에는 공용(public) 클래스가 들어 있으며, 클래스의 이름은 파일명과 동일합니다. +// 각 .java 파일에는 공용(public) 클래스가 들어 있으며, 클래스의 이름은 +// 파일명과 동일합니다. public class LearnJava { // 프로그램에는 반드시 진입점 역할을 하는 main 메서드가 하나 있어야 합니다. @@ -253,8 +255,8 @@ public class LearnJava { // String // 형변환 - // 자바 객채 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이 많을뿐더러 - // 다소 중급 수준에 해당하는 개념들도 다뤄야 합니다. + // 자바 객채 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이 + // 많을뿐더러 다소 중급 수준에 해당하는 개념들도 다뤄야 합니다. // 이와 관련된 사항은 아래 링크를 참고하세요. // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html @@ -403,4 +405,4 @@ class PennyFarthing extends Bicycle { * [제네릭(Generics)](http://docs.oracle.com/javase/tutorial/java/generics/index.html) -* [자바 코딩 관례(Java Code Conventions)](http://www.oracle.com/technetwork/java/codeconv-138413.html) \ No newline at end of file +* [자바 코딩 관례(Java Code Conventions)](http://www.oracle.com/technetwork/java/codeconv-138413.html) diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 8e8ce6a8..484bb0dd 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -1,5 +1,6 @@ --- language: ruby +lang: br-pt filename: learnruby.rb contributors: - ["Bruno Henrique - Garu", "http://garulab.com"] @@ -98,9 +99,10 @@ caminho_para_a_raiz_do_projeto = '/bom/nome/' caminho = '/nome/ruim/' # Símbolos (são objetos) -# Símbolos são imutáveis, são constantes reutilizáveis representadadas internamente por um -# valor inteiro. Eles são frequentemente usados no lugar de strings para transmitir com eficiência os valores -# específicos e significativos +# Símbolos são imutáveis, são constantes reutilizáveis representadadas +# internamente por um valor inteiro. Eles são frequentemente usados no +# lugar de strings para transmitir com eficiência os valores específicos +# e significativos :pendente.class #=> Symbol diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown index 48c16192..e1d68e5a 100644 --- a/ru-ru/clojure-ru.html.markdown +++ b/ru-ru/clojure-ru.html.markdown @@ -4,7 +4,7 @@ filename: learnclojure-ru.clj contributors: - ["Adam Bard", "http://adambard.com/"] - ["Alexey Pirogov", "http://twitter.com/alex_pir"] - +lang: ru-ru --- Clojure, это представитель семейства Lisp-подобных языков, разработанный diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index 6c5720e3..9133ecca 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -88,7 +88,8 @@ $unescaped = 'This just contains a slash and a t: \t'; // Заключайте переменные в фигурные скобки если это необходимо $money = "I have $${number} in the bank."; -// Начиная с PHP 5.3, синтаксис nowdocs может использоваться для неинтерполированного многострочного текста +// Начиная с PHP 5.3, синтаксис nowdocs может использоваться для +// неинтерполированного многострочного текста $nowdoc = <<<'END' Multi line string @@ -210,11 +211,13 @@ echo $integer + $integer; // => 2 $string = '1'; echo $string + $string; // => 2 (строка превращается в число) -// Выводится 0 по той причине, что оператор + не может привести строку 'one' к числовому типу +// Выводится 0 по той причине, что оператор + не может привести строку 'one' к +// числовому типу $string = 'one'; echo $string + $string; // => 0 -// Приведение типов (type casting) может быть использовано для преобразование переменной в другой тип +// Приведение типов (type casting) может быть использовано для преобразование +// переменной в другой тип $boolean = (boolean) 1; // => true $zero = 0; @@ -429,10 +432,11 @@ return 'Anything you like.'; // Эти функции могут также возвращать значения. $value = include 'my-include.php'; -// Имена файлов содержат их путь в файловой системе, или если передано просто имя файла, -// PHP обращается к директиве include_path. Если файл не найден в include_path, предпринимается -// попытка поиска в папке, где выполняется скрипт или в текущей рабочей директории. -// Если не в одном из этих мест файл не найден - выдается ошибка +// Имена файлов содержат их путь в файловой системе, или если передано просто +// имя файла, PHP обращается к директиве include_path. Если файл не найден в +// include_path, предпринимается попытка поиска в папке, где выполняется скрипт +// или в текущей рабочей директории. Если не в одном из этих мест файл не +// найден - выдается ошибка /* */ /******************************** diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index 58b0adcc..9163c8aa 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -1,5 +1,6 @@ --- language: python +lang: ru-ru contributors: - ["Yury Timofeev", "http://twitter.com/gagar1n"] filename: learnpython-ru.py @@ -219,7 +220,8 @@ filled_dict["four"] # KeyError # Чтобы избежать этого, используйте метод get filled_dict.get("one") #=> 1 filled_dict.get("four") #=> None -# Метод get также принимает аргумент default, значение которого будет возвращено при отсутствии указанного ключа +# Метод get также принимает аргумент default, значение которого будет +# возвращено при отсутствии указанного ключа filled_dict.get("one", 4) #=> 1 filled_dict.get("four", 4) #=> 4 @@ -314,7 +316,9 @@ try: # Для выбора ошибки используется raise raise IndexError("Это IndexError") except IndexError as e: - pass # pass это просто отсутствие оператора. Обычно здесь происходит восстановление от ошибки. + # pass это просто отсутствие оператора. Обычно здесь происходит + # восстановление от ошибки. + pass #################################################### diff --git a/zh-cn/go-zh.html.markdown b/zh-cn/go-zh.html.markdown index 25fd1f03..8f7cb2af 100644 --- a/zh-cn/go-zh.html.markdown +++ b/zh-cn/go-zh.html.markdown @@ -29,7 +29,8 @@ import ( "strconv" // 字符串转换 ) -//函数声明:Main是程序执行的入口。不管你喜欢还是不喜欢,反正G就用了花括号来包住函数体。 +// 函数声明:Main是程序执行的入口。 +// 不管你喜欢还是不喜欢,反正G就用了花括号来包住函数体。 func main() { // 往标准输出打印一行。 // 用包名fmt限制打印函数。 @@ -65,10 +66,10 @@ func learnTypes() { can include line breaks.` // 同样是String类型 // 非ascii字符。Go使用UTF-8编码。 - g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码 + g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码 - f := 3.14195 // float64类型,IEEE-754 64位浮点数 - c := 3 + 4i // complex128类型,内部使用两个float64表示 + f := 3.14195 // float64类型,IEEE-754 64位浮点数 + c := 3 + 4i // complex128类型,内部使用两个float64表示 // Var变量可以直接初始化。 var u uint = 7 // unsigned 无符号变量,但是实现依赖int型变量的长度 @@ -99,9 +100,9 @@ can include line breaks.` // 同样是String类型 // 下划线 _ 可以使你“使用”一个变量,但是丢弃它的值。 _,_,_,_,_,_,_,_,_ = s2, g, f, u, pi, n, a3, s4, bs // 输出变量 - fmt.Println(s, c, a4, s3, d2, m) + fmt.Println(s, c, a4, s3, d2, m) - learnFlowControl() // 回到流程控制 + learnFlowControl() // 回到流程控制 } // Go全面支持垃圾回收。Go有指针,但是不支持指针运算。 @@ -117,155 +118,159 @@ func learnMemory() (p, q *int) { } func expensiveComputation() int { - return 1e6 + return 1e6 } func learnFlowControl() { // If需要花括号,括号就免了 - if true { - fmt.Println("told ya") - } - // 用go fmt 命令可以帮你格式化代码,所以不用怕被人吐槽代码风格了,也不用容忍被人的代码风格。 - if false { - // pout - } else { - // gloat - } + if true { + fmt.Println("told ya") + } + // 用go fmt 命令可以帮你格式化代码,所以不用怕被人吐槽代码风格了, + // 也不用容忍被人的代码风格。 + if false { + // pout + } else { + // gloat + } // 如果太多嵌套的if语句,推荐使用switch - x := 1 - switch x { - case 0: - case 1: + x := 1 + switch x { + case 0: + case 1: // 隐式调用break语句,匹配上一个即停止 - case 2: + case 2: // 不会运行 - } + } // 和if一样,for也不用括号 - for x := 0; x < 3; x++ { // ++ 自增 - fmt.Println("iteration", x) - } + for x := 0; x < 3; x++ { // ++ 自增 + fmt.Println("iteration", x) + } // x在这里还是1。为什么? // for 是go里唯一的循环关键字,不过它有很多变种 - for { // 无限循环 - break // 骗你的 - continue // 不会运行的 - } + for { // 无限循环 + break // 骗你的 + continue // 不会运行的 + } // 和for一样,if中的:=先给y赋值,然后再和x作比较。 - if y := expensiveComputation(); y > x { - x = y - } + if y := expensiveComputation(); y > x { + x = y + } // 闭包函数 - xBig := func() bool { - return x > 100 // x是上面声明的变量引用 - } - fmt.Println("xBig:", xBig()) // true (上面把y赋给x了) - x /= 1e5 // x变成10 - fmt.Println("xBig:", xBig()) // 现在是false + xBig := func() bool { + return x > 100 // x是上面声明的变量引用 + } + fmt.Println("xBig:", xBig()) // true (上面把y赋给x了) + x /= 1e5 // x变成10 + fmt.Println("xBig:", xBig()) // 现在是false // 当你需要goto的时候,你会爱死它的! - goto love + goto love love: - learnInterfaces() // 好东西来了! + learnInterfaces() // 好东西来了! } // 定义Stringer为一个接口类型,有一个方法String type Stringer interface { - String() string + String() string } // 定义pair为一个结构体,有x和y两个int型变量。 type pair struct { - x, y int + x, y int } // 定义pair类型的方法,实现Stringer接口。 func (p pair) String() string { // p被叫做“接收器” // Sprintf是fmt包中的另一个公有函数。 // 用 . 调用p中的元素。 - return fmt.Sprintf("(%d, %d)", p.x, p.y) + return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { // 花括号用来定义结构体变量,:=在这里将一个结构体变量赋值给p。 - p := pair{3, 4} - fmt.Println(p.String()) // 调用pair类型p的String方法 - var i Stringer // 声明i为Stringer接口类型 - i = p // 有效!因为p实现了Stringer接口(类似java中的塑型) + p := pair{3, 4} + fmt.Println(p.String()) // 调用pair类型p的String方法 + var i Stringer // 声明i为Stringer接口类型 + i = p // 有效!因为p实现了Stringer接口(类似java中的塑型) // 调用i的String方法,输出和上面一样 - fmt.Println(i.String()) + fmt.Println(i.String()) - // fmt包中的Println函数向对象要它们的string输出,实现了String方法就可以这样使用了。(类似java中的序列化) - fmt.Println(p) // 输出和上面一样,自动调用String函数。 - fmt.Println(i) // 输出和上面一样。 + // fmt包中的Println函数向对象要它们的string输出,实现了String方法就可以这样使用了。 + // (类似java中的序列化) + fmt.Println(p) // 输出和上面一样,自动调用String函数。 + fmt.Println(i) // 输出和上面一样。 - learnErrorHandling() + learnErrorHandling() } func learnErrorHandling() { - // ", ok"用来判断有没有正常工作 - m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok 为false,因为m中没有1 - fmt.Println("no one there") - } else { - fmt.Print(x) // 如果x在map中的话,x就是那个值喽。 - } + // ", ok"用来判断有没有正常工作 + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok 为false,因为m中没有1 + fmt.Println("no one there") + } else { + fmt.Print(x) // 如果x在map中的话,x就是那个值喽。 + } // 错误可不只是ok,它还可以给出关于问题的更多细节。 - if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value - // 输出"strconv.ParseInt: parsing "non-int": invalid syntax" - fmt.Println(err) - } + if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value + // 输出"strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } // 待会再说接口吧。同时, - learnConcurrency() + learnConcurrency() } // c是channel类型,一个并发安全的通信对象。 func inc(i int, c chan int) { - c <- i + 1 // <-把右边的发送到左边的channel。 + c <- i + 1 // <-把右边的发送到左边的channel。 } // 我们将用inc函数来并发地增加一些数字。 func learnConcurrency() { // 用make来声明一个slice,make会分配和初始化slice,map和channel。 - c := make(chan int) - // 用go关键字开始三个并发的goroutine,如果机器支持的话,还可能是并行执行。三个都被发送到同一个channel。 - go inc(0, c) // go is a statement that starts a new goroutine. - go inc(10, c) - go inc(-805, c) + c := make(chan int) + // 用go关键字开始三个并发的goroutine,如果机器支持的话,还可能是并行执行。 + // 三个都被发送到同一个channel。 + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) // 从channel中独处结果并打印。 // 打印出什么东西是不可预知的。 - fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是接收操作。 - - cs := make(chan string) // 操作string的channel - cc := make(chan chan string) // 操作channel的channel - go func() { c <- 84 }() // 开始一个goroutine来发送一个新的数字 - go func() { cs <- "wordy" }() // 发送给cs - // Select类似于switch,但是每个case包括一个channel操作。它随机选择一个准备好通讯的case。 - select { - case i := <-c: // 从channel接收的值可以赋给其他变量 - fmt.Println("it's a", i) - case <-cs: // 或者直接丢弃 - fmt.Println("it's a string") - case <-cc: // 空的,还没作好通讯的准备 - fmt.Println("didn't happen.") - } + fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是接收操作。 + + cs := make(chan string) // 操作string的channel + cc := make(chan chan string) // 操作channel的channel + go func() { c <- 84 }() // 开始一个goroutine来发送一个新的数字 + go func() { cs <- "wordy" }() // 发送给cs + // Select类似于switch,但是每个case包括一个channel操作。 + // 它随机选择一个准备好通讯的case。 + select { + case i := <-c: // 从channel接收的值可以赋给其他变量 + fmt.Println("it's a", i) + case <-cs: // 或者直接丢弃 + fmt.Println("it's a string") + case <-cc: // 空的,还没作好通讯的准备 + fmt.Println("didn't happen.") + } // 上面c或者cs的值被取到,其中一个goroutine结束,另外一个保持阻塞。 - learnWebProgramming() // Go很适合web编程,我知道你也想学! + learnWebProgramming() // Go很适合web编程,我知道你也想学! } // http包中的一个简单的函数就可以开启web服务器。 func learnWebProgramming() { // ListenAndServe第一个参数指定了监听端口,第二个参数是一个接口,特定是http.Handler。 - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // 不要无视错误。 + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // 不要无视错误。 } // 使pair实现http.Handler接口的ServeHTTP方法。 func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // 使用http.ResponseWriter返回数据 - w.Write([]byte("You learned Go in Y minutes!")) + w.Write([]byte("You learned Go in Y minutes!")) } ``` -- cgit v1.2.3 From ed2884ca3c60571169bb93f853d307808f319522 Mon Sep 17 00:00:00 2001 From: Geoffrey Roguelon Date: Sat, 17 Aug 2013 10:29:45 +0200 Subject: Split the comment lines to avoid the exceeding of the block of code. --- fr-fr/ruby-fr.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown index 5efb2f3c..ab3ce0ac 100644 --- a/fr-fr/ruby-fr.html.markdown +++ b/fr-fr/ruby-fr.html.markdown @@ -166,7 +166,8 @@ hash['number'] #=> 5 # Recherchez une clé inexistante dans une Hash retourne nil : hash['nothing here'] #=> nil -# Depuis Ruby 1.9, Une syntaxe spécifique est apparue en utilisant les symboles comme clés : +# Depuis Ruby 1.9, Une syntaxe spécifique est apparue +# en utilisant les symboles comme clés : new_hash = { defcon: 3, action: true} @@ -198,10 +199,13 @@ end # CEPENDANT, l'usage de la boucle for est très rare. # À la place, utilisez la méthode "each" # et passez lui un bloc de code. -# Un bloc de code est un ensemble d'instructions que vous pouvez passer à une methode comme "each". -# Les blocs sont similaires aux lambdas, les fonctions anonymes ou les closures dans d'autres langages. +# Un bloc de code est un ensemble d'instructions +# que vous pouvez passer à une methode comme "each". +# Les blocs sont similaires aux lambdas, les fonctions anonymes +# ou les closures dans d'autres langages. # -# La méthode "each" exécute le bloc de code pour chaque élément de l'intervalle d'éléments. +# La méthode "each" exécute le bloc de code +# pour chaque élément de l'intervalle d'éléments. # Le bloc de code passe un paramètre compteur. # Appelez la méthode "each" avec un bloc de code comme ceci : -- cgit v1.2.3 From 6280f879b1395d61f07f223a9e4a4f0973414fdd Mon Sep 17 00:00:00 2001 From: Geoffrey Roguelon Date: Sat, 17 Aug 2013 10:31:54 +0200 Subject: Fix French syntax. --- fr-fr/ruby-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown index ab3ce0ac..3060bd75 100644 --- a/fr-fr/ruby-fr.html.markdown +++ b/fr-fr/ruby-fr.html.markdown @@ -201,8 +201,8 @@ end # et passez lui un bloc de code. # Un bloc de code est un ensemble d'instructions # que vous pouvez passer à une methode comme "each". -# Les blocs sont similaires aux lambdas, les fonctions anonymes -# ou les closures dans d'autres langages. +# Les blocs sont similaires aux lambdas, aux fonctions anonymes +# ou encore aux closures dans d'autres langages. # # La méthode "each" exécute le bloc de code # pour chaque élément de l'intervalle d'éléments. -- cgit v1.2.3 From e875c3fff10ace21756e22e77ebe1ed1131719f4 Mon Sep 17 00:00:00 2001 From: kultprok Date: Sat, 17 Aug 2013 12:40:17 +0200 Subject: added first draft of german translation for python --- de-de/python-de.html.markdown | 484 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 484 insertions(+) create mode 100644 de-de/python-de.html.markdown diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown new file mode 100644 index 00000000..0882d5e6 --- /dev/null +++ b/de-de/python-de.html.markdown @@ -0,0 +1,484 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["kultprok", "http:/www.kulturproktologie.de"] +filename: learnpython.py +--- + +Anmerkungen des ursprnglichen Autors: +Python wurde in den frhen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen bersichtlichkeit verliebt. Eigentlich ist es ausfhrbarer Pseudocode. + +Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service] + +Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber auf Python 2.x anwendbar sein. Haltet Ausschau nach einem Rundgang durch Python 3, der bald erscheinen soll. + +```python +# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) +""" Mehrzeilige Strings werden mit + drei '-Zeichen geschrieben und werden + oft als Kommentare genutzt. +""" + +#################################################### +## 1. Primitive Datentypen und Operatoren +#################################################### + +# Die Zahlen +3 #=> 3 + +# Mathematik ist das, was man erwartet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Division ist ein wenig kniffliger. Es ist ganzzahlige Division +# und rundet automatisch ab. +5 / 2 #=> 2 + +# Um das zu ndern, mssen wir Gleitkommazahlen kennenlernen. +2.0 # Das ist eine Gleitkommazahl +11.0 / 4.0 #=> 2.75 Ahhh...schon besser + +# Rangfolge wird mit Klammern erzwungen +(1 + 3) * 2 #=> 8 + +# Boolesche Ausdrcke sind primitive Datentypen +True +False + +# Mit not wird negiert +not True #=> False +not False #=> True + +# Gleichheit ist == +1 == 1 #=> True +2 == 1 #=> False + +# Ungleichheit is != +1 != 1 #=> False +2 != 1 #=> True + +# Ein paar weitere Vergleiche +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Vergleiche knnen verknpft werden! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings werden mit " oder ' gebildet +"Das ist ein String." +'Das ist auch ein String.' + +# Strings knnen addiert werden! +"Hello " + "world!" #=> "Hello world!" + +# Ein String kann wie eine Liste von Zeichen verwendet werden +"Das ist ein String"[0] #=> 'D' + +# Mit % knnen Strings formatiert werden, etwa so: +"%s knnen %s werden" % ("Strings", "interpoliert") + +# Ein neuerer Weg, um Strings zu formatieren, ist die format-Methode. +# Diese Methode wird bevorzugt +"{0} knnen {1} werden".format("Strings", "formatiert") +# Wir knnen Schlsselwrter verwenden, wenn wir nicht abzhlen wollen. +"{name} will {food} essen".format(name="Bob", food="Lasagne") + +# None ist ein Objekt +None #=> None + +# Verwendet nicht das Symbol fr Gleichheit `==`, um Objekte mit None zu vergleichen +# Benutzt stattdessen `is` +"etc" is None #=> False +None is None #=> True + +# Der 'is'-Operator testet Objektidentitt. Das ist nicht +# sehr ntzlich, wenn wir mit primitiven Datentypen arbeiten, aber +# sehr ntzlich bei Objekten. + +# None, 0, und leere Strings/Listen werden alle als False bewertet. +# Alle anderen Werte sind True +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Variablen und Collections +#################################################### + +# Ausgabe ist sehr einfach +print "Ich bin Python. Schn, dich kennenzulernen!" + + +# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. +some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm +some_var #=> 5 + +# Eine noch nicht deklarierte Variable anzusprechen, lst eine Exception aus. +# Siehe Kontrollstruktur, um mehr ber Ausnahmebehandlung zu lernen. +some_other_var # Lst einen NameError aus + +# if kann als Ausdruck verwendet werden +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listen speichern Sequenzen +li = [] +# Wir knnen mit einer bereits gefllten Liste anfangen +other_li = [4, 5, 6] + +# append fgt Daten am Ende der Liste ein +li.append(1) #li ist jetzt [1] +li.append(2) #li ist jetzt [1, 2] +li.append(4) #li ist jetzt [1, 2, 4] +li.append(3) #li ist jetzt [1, 2, 4, 3] +# Vom Ende der Liste mit pop entfernen +li.pop() #=> 3 und li ist jetzt [1, 2, 4] +# Fgen wir es wieder hinzu +li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. + +# Greife auf Listen wie auf Arrays zu +li[0] #=> 1 +# Das letzte Element ansehen +li[-1] #=> 3 + +# Auerhalb der Liste ist es ein IndexError +li[4] # Raises an IndexError + +# Wir knnen uns Ranges mit Slice-Syntax ansehen +li[1:3] #=> [2, 4] +# Den Anfang auslassen +li[2:] #=> [4, 3] +# Das Ende auslassen +li[:3] #=> [1, 2, 4] + +# Ein bestimmtes Element mit del aus der Liste entfernen +del li[2] # li ist jetzt [1, 2, 3] + +# Listen knnen addiert werden +li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen + +# Listen mit extend verknpfen +li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] + +# Mit in auf Existenz eines Elements prfen +1 in li #=> True + +# Die Lnge der Liste mit len ermitteln +len(li) #=> 6 + + +# Tupel sind wie Listen, nur unvernderlich. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Lst einen TypeError aus + +# Wir knnen all diese Listen-Dinge auch mit Tupeln anstellen +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Wir knnen 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 standardmig 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 + + +# Dictionarys (Wrterbucher) speichern Key-Value-Paare +empty_dict = {} +# Hier ein geflltes Wrterbuch +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Wir knnen Eintrge mit [] nachschlagen +filled_dict["one"] #=> 1 + +# So holen wir alle Keys (Schlssel) als Liste +filled_dict.keys() #=> ["three", "two", "one"] +# Hinweis - Die Reihenfolge von Schlsseln in der Liste ist nicht garantiert. +# Einzelne Resultate knnen anders angeordnet sein. + +# Alle Values (Werte) als Liste +filled_dict.values() #=> [3, 2, 1] +# Hinweis - Hier gelten dieselben Einschrnkungen fr die Reihenfolge wie bei Schlsseln. + +# Das Vorhandensein eines Schlssels im Wrterbuch mit in prfen +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Einen nicht vorhandenenen Schlssel zu suchen, lst einen KeyError aus +filled_dict["four"] # KeyError + +# Mit der get-Methode verhindern wir das +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Die get-Methode untersttzt auch ein Standardargument, falls der Wert fehlt +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlssel-Wert-Paar anzulegen +filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt +filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 + + +# Sets speichern Mengen +empty_set = set() +# Initialisieren wir ein Set mit ein paar Werten +some_set = set([1,2,2,3,4]) # some_set ist jetzt set([1, 2, 3, 4]) + +# Seit Python 2.7 kann {} benutzt werden, um ein Set zu erstellen +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Mehr Elemente hinzufgen +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Schnittmengen werden mit & gebildet +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Mengen werden mit | vereinigt +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Die Differenz einer Menge mit - bilden +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Auf Vorhandensein mit in prfen +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Kontrollstruktur +#################################################### + +# Erstellen wir mal eine Variable +some_var = 5 + +# Hier eine if-Anweisung. Die Einrckung ist in Python wichtig! +# gibt "some_var ist kleiner als 10" aus +if some_var > 10: + print "some_var ist viel grer als 10." +elif some_var < 10: # Dieser elif-Absatz ist optional. + print "some_var ist kleiner als 10." +else: # Das hier ist auch optional. + print "some_var ist tatschlich 10." + + +""" +For-Schleifen iterieren ber Listen +Ausgabe: + hund ist ein Sugetier + katze ist ein Sugetier + maus ist ein Sugetier +""" +for animal in ["hund", "katze", "maus"]: + # Wir knnen Strings mit % formatieren + print "%s ist ein Sugetier" % animal + +""" +`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder +Ausgabe: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While-Schleifen laufen, bis eine Bedingung erfllt ist. +Ausgabe: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Kurzform fr x = x + 1 + +# Ausnahmebehandlung mit einem try/except-Block + +# Funktioniert in Python 2.6 und hher: +try: + # Mit raise wird ein Fehler ausgegeben + raise IndexError("Das hier ist ein Index-Fehler") +except IndexError as e: + pass # Pass ist nur eine no-op. Normalerweise wrden wir hier den Fehler klren. + + +#################################################### +## 4. Funktionen +#################################################### + +# Mit def neue Funktionen erstellen +def add(x, y): + print "x ist %s und y ist %s" % (x, y) + return x + y # Werte werden mit return zurckgegeben + +# Funktionen mit Parametern aufrufen +add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurck + +# Ein anderer Weg des Funktionsaufrufs sind Schlsselwort-Argumente +add(y=6, x=5) # Schlsselwrter knnen in beliebiger Reihenfolge bergeben werden. + +# Wir knnen Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Wir knnen auch Funktionen mit beliebiger Anzahl +# Schlsselwort-Argumenten definieren +def keyword_args(**kwargs): + return kwargs + +# Rufen wir es mal auf, um zu sehen, was passiert +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Wir knnen beides gleichzeitig machem, wenn wir wollen +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) Ausgabe: + (1, 2) + {"a": 3, "b": 4} +""" + +# Beim Aufruf von Funktionen knnen wir das Gegenteil von varargs/kwargs machen! +# Wir benutzen dann *, um Tupel auszuweiten, und ** fr kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # quivalent zu foo(1, 2, 3, 4) +all_the_args(**kwargs) # quivalent zu foo(a=3, b=4) +all_the_args(*args, **kwargs) # quivalent zu foo(1, 2, 3, 4, a=3, b=4) + +# Python hat First-Class-Funktionen +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Es gibt auch anonyme Funktionen +(lambda x: x > 2)(3) #=> True + +# Es gibt auch Funktionen hherer Ordnung als Built-Ins +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Wir knnen bei map- und filter-Funktionen auch List Comprehensions einsetzen +[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. Klassen +#################################################### + +# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten. +class Human(object): + + # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt + species = "H. sapiens" + + # Ein simpler Konstruktor + def __init__(self, name): + # Wir weisen das Argument name dem name-Attribut der Instanz zu + self.name = name + + # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument. + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Eine Klassenmethode wird von allen Instanzen geteilt. + # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen + @classmethod + def get_species(cls): + return cls.species + + # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen + @staticmethod + def grunt(): + return "*grunt*" + + +# Eine Instanz einer Klasse erstellen +i = Human(name="Ian") +print i.say("hi") # gitbt "Ian: hi" aus + +j = Human("Joel") +print j.say("hello") #gibt "Joel: hello" aus + +# Rufen wir mal unsere Klassenmethode auf +i.get_species() #=> "H. sapiens" + +# ndern wir mal das gemeinsame Attribut +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Aufruf der statischen Methode +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Module +#################################################### + +# Wir knnen Module importieren +import math +print math.sqrt(16) #=> 4 + +# Wir knnen auch nur spezielle Funktionen eines Moduls importieren +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Wir knnen auch alle Funktionen eines Moduls importieren +# Warnung: Dies wird nicht empfohlen +from math import * + +# Wir knnen Modulnamen abkrzen +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Module sind in Python nur gewhnliche Dateien. Wir +# knnen unsere eigenen schreiben und importieren. Der Name des +# Moduls ist der Dateiname. + +# Wir knnen auch die Funktionen und Attribute eines +# Moduls herausfinden. +import math +dir(math) + + +``` + +## Lust auf mehr? + +### Kostenlos online (Englisch) + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Totholz (Englisch) + +* [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 4997a2af3333dd74074d88943a36569a038175ad Mon Sep 17 00:00:00 2001 From: marcuse Date: Sat, 17 Aug 2013 13:17:21 +0200 Subject: Spelling, capatability -> compatibility And added a link to the RubySpec section. --- ruby-ecosystem.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 54c1d178..c2a2087b 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -63,7 +63,7 @@ Very mature/compatible: * MRI - Written in C, this is the reference implementation of ruby. By definition it is 100% compatible (with itself). All other rubies -maintain capatability with MRI (see RubySpec below). +maintain compatibility with MRI (see [RubySpec](#rubyspec) below). * JRuby - Written in Java and ruby, this robust implementation is quite fast. Most importantly, JRuby's strength is JVM/Java interop, leveraging existing JVM tools, projects, and languages. -- cgit v1.2.3 From 2173dd419a1daa06efee295e3fe2cdbc40224433 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 15:57:52 +0200 Subject: Accessing nullable's value in C# --- csharp.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index c254b5a9..c9df6db9 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -144,6 +144,10 @@ namespace Learning 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 ); + // ?? is syntactic sugar for specifying default value // in case variable is null int notNullable = nullable ?? 0; -- cgit v1.2.3 From 541fd3fb06bf6e97974123934ad89cb07a7ef289 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 16:01:08 +0200 Subject: C# Coding style: property names start with capitals --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index c9df6db9..490c34bb 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -474,7 +474,7 @@ namespace Learning // when only data needs to be accessed, consider using properties. // properties may have either get or set, or both private bool _hasTassles; // private variable - public bool hasTassles // public accessor + public bool HasTassles // public accessor { get { return _hasTassles; } set { _hasTassles = value; } -- cgit v1.2.3 From 4295e85d6097e2d331ff75a958a3a5a064795410 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 16:03:35 +0200 Subject: C#: Auto-implemented properties --- csharp.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 490c34bb..951958b6 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -480,13 +480,13 @@ namespace Learning set { _hasTassles = value; } } - private int _frameSize; + // Properties can be auto-implemented public int FrameSize { - get { return _frameSize; } + get; // you are able to specify access modifiers for either get or set // this means only Bicycle class can call set on Framesize - private set { _frameSize = value; } + private set; } //Method to display the attribute values of this Object. -- cgit v1.2.3 From c3df13db567b82fc0802e46c23e4e4486618b207 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 16:06:04 +0200 Subject: C#: comments about "this" keyword --- csharp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 951958b6..0cef8f05 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -422,10 +422,10 @@ namespace Learning public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes) { - this.gear = startGear; + this.gear = startGear; // "this" keyword denotes the current object this.cadence = startCadence; this._speed = startSpeed; - this.name = name; + this.name = name; // it can be useful when there's a name conflict this.hasCardsInSpokes = hasCardsInSpokes; } -- cgit v1.2.3 From c903f5a73dc0b0eb5fe84e20182767dc310bd30a Mon Sep 17 00:00:00 2001 From: Roberto Perez Date: Sat, 17 Aug 2013 10:12:25 -0500 Subject: created groovy markdown --- groovy.html.markdown | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 groovy.html.markdown diff --git a/groovy.html.markdown b/groovy.html.markdown new file mode 100644 index 00000000..d015e5d2 --- /dev/null +++ b/groovy.html.markdown @@ -0,0 +1,9 @@ +--- +language: Groovy +filename: learngroovy.groovy +contributors: + - ["Roberto Perez Alcolea", "http://github.com/rpalcolea"] +filename: learngroovy.groovy +--- + +Groovy - A dynamic language for the Java platform -- cgit v1.2.3 From 767fb174f8e5981dec603c2ed6782cef5574c7b4 Mon Sep 17 00:00:00 2001 From: Roberto Perez Date: Sat, 17 Aug 2013 10:19:47 -0500 Subject: Groovy: Added references --- groovy.html.markdown | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index d015e5d2..94906ffc 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -6,4 +6,30 @@ contributors: filename: learngroovy.groovy --- -Groovy - A dynamic language for the Java platform +Groovy - A dynamic language for the Java platform [Read more here.](http://groovy.codehaus.org) + +```cpp + + +``` + +## Further resources + +[Groovy documentation](http://groovy.codehaus.org/Documentation) + +[Groovy web console](http://groovyconsole.appspot.com/) + +Join a [Groovy user group](http://groovy.codehaus.org/User+Groups) + +## Books + +* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) + +* [Groovy in Action] (http://manning.com/koenig2/) + +* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) + + + + + -- cgit v1.2.3 From 12b39c739f0f39a753ef30c70f1d57c6876c0902 Mon Sep 17 00:00:00 2001 From: Roberto Perez Date: Sat, 17 Aug 2013 11:23:36 -0500 Subject: Groovy: added installation, colletions, maps, beans, logical branching and loops --- groovy.html.markdown | 171 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) diff --git a/groovy.html.markdown b/groovy.html.markdown index 94906ffc..3a928787 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -10,6 +10,177 @@ Groovy - A dynamic language for the Java platform [Read more here.](http://groov ```cpp +/* + Set yourself up: + + 1) Install GVM - http://gvmtool.net/ + 2) Install Groovy: gvm install groovy + 3) Start the groovy console by typing: groovyConsole + +*/ + +// Single line comments start with two forward slashes +/* +Multi line comments look like this. +*/ + +// Hello World +println "Hello world!" + +/* + Variables: + + You can assign values to variables for later use +*/ + +def x = 1 +println x + +x = new java.util.Date() +println x + +x = -3.1499392 +println x + +x = false +println x + +x = "Groovy!" +println x + +/* + Collections and maps +*/ +//Creating an empty list +def technologies = [] + +//Add an element to the list +technologies << "Groovy" +technologies.add("Grails") +technologies.addAll(["Gradle","Griffon"]) + +//Remove an element from the list +technologies.remove("Griffon") + +//Iterate over elements of a list +technologies.each { println "Technology: $it"} +technologies.eachWithIndex { it, i -> println "$i: $it"} + +//Evaluate if a list contains element(s) (boolean) +technologies.contains('Groovy') +technologies.containsAll(['Groovy','Grails']) + +//Sort a list +technologies.sort() + +//Replace all elements in the list +Collections.replaceAll(technologies, 'Gradle', 'gradle') + +//Shuffle a list +Collections.shuffle(technologies, new Random()) + +//Clear a list +technologies.clear() + +//Creating an empty map +def devMap = [:] + +//Add values +devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +devMap.put('lastName','Perez') + +//Iterate over elements of a map +devMap.each { println "$it.key: $it.value" } +devMap.eachWithIndex { it, i -> println "$i: $it"} + +//Evaluate if a map contains a key +assert devMap.containsKey('name') + +//Evaluate if a map contains a value +assert devMap.containsValue('Roberto') + +//Get the keys of a map +println devMap.keySet() + +//Get the values of a map +println devMap.values() + +/* + Groovy Beans + + GroovyBeans are JavaBeans but using a much simpler syntax + + When Groovy is compiled to bytecode, the following rules are used. + + * If the name is declared with an access modifier (public, private or protected) then a field is generated. + * A name declared with no access modifier generates a private field with public getter and setter (i.e. a property). + * If a property is declared final the private field is created final and no setter is generated. + * You can declare a property and also declare your own getter or setter. + * You can declare a property and a field of the same name, the property will use that field then. + * If you want a private or protected property you have to provide your own getter and setter which must be declared private or protected. + * If you access a property from within the class the property is defined in at compile time with implicit or explicit this (for example this.foo, or simply foo), Groovy will access the field directly instead of going though the getter and setter. + * If you access a property that does not exist using the explicit or implicit foo, then Groovy will access the property through the meta class, which may fail at runtime. + +*/ + +class Foo { + // read only property + final String name = "Roberto" + + // read only property with public getter and protected setter + String language + protected void setLanguage(String language) { this.language = language } + + // dynamically typed property + def lastName +} + +/* + Logical Branching and Looping +*/ + +//Groovy supports the usual if - else syntax +def x = 3 + +if(x==1) { + println "One" +} else if(x==2) { + println "Two" +} else { + println "X greater than Two" +} + +//Groovy also supports the ternary operator: +def y = 10 +def x = (y > 1) ? "worked" : "failed" +assert x == "worked" + +//For loop +//Iterate over a range +def x = 0 +for (i in 0 .. 30) { + x += i +} + +//Iterate over a list +x = 0 +for( i in [5,3,2,1] ) { + x += i +} + +//Iterate over an array +array = (0..20).toArray() +x = 0 +for (i in array) { + x += i +} + +//Iterate over a map +def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +x = 0 +for ( e in map ) { + x += e.value +} ``` -- cgit v1.2.3 From f07376a26830eb9c2ade7933ca45191776e965da Mon Sep 17 00:00:00 2001 From: Geoffrey Roguelon Date: Sat, 17 Aug 2013 18:33:18 +0200 Subject: Add french coffeescript translation. --- fr-fr/coffeescript-fr.html.markdown | 58 +++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 fr-fr/coffeescript-fr.html.markdown diff --git a/fr-fr/coffeescript-fr.html.markdown b/fr-fr/coffeescript-fr.html.markdown new file mode 100644 index 00000000..c66b7be0 --- /dev/null +++ b/fr-fr/coffeescript-fr.html.markdown @@ -0,0 +1,58 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] +translators: + - ["Geoffrey Roguelon", "https://github.com/GRoguelon"] +lang: fr-fr +filename: coffeescript-fr.coffee +--- + +``` coffeescript +# CoffeeScript est un langage préprocesseur, il permet de générer du Javascript. +# Il suit les tendances de certains langages récents. +# Par exemple, les commentaires se définissent comme en Ruby ou en Python. + +### +Ceci est un bloc de commentaires +il est converti directement avec '/ *' et '* /' +pour correspondre aux commentaires Javascript + +Vous devez comprendre la syntaxe du langage JavaScript pour continuer. +### + +# Affectation : +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Structures de contrôle : +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Fonctions : +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +# Intervals : +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objets : +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +#} + +# Liste d'arguments variables : +race = (winner, runners...) -> + print winner, runners + +# Existance : +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# Lecture d'un tableau : +cubes = (math.cube num for num in list) #=> ... +``` -- cgit v1.2.3 From abf527143adf98564206f9253270e52d08045a49 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 17 Aug 2013 09:44:05 -0700 Subject: Changed python-de to utf-8 --- de-de/python-de.html.markdown | 162 +++++++++++++++++++++--------------------- 1 file changed, 81 insertions(+), 81 deletions(-) diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 0882d5e6..7298c62c 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -6,8 +6,8 @@ contributors: filename: learnpython.py --- -Anmerkungen des ursprnglichen Autors: -Python wurde in den frhen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen bersichtlichkeit verliebt. Eigentlich ist es ausfhrbarer Pseudocode. +Anmerkungen des ursprünglichen Autors: +Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode. Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service] @@ -37,14 +37,14 @@ Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber au # und rundet automatisch ab. 5 / 2 #=> 2 -# Um das zu ndern, mssen wir Gleitkommazahlen kennenlernen. +# Um das zu ändern, müssen wir Gleitkommazahlen kennenlernen. 2.0 # Das ist eine Gleitkommazahl 11.0 / 4.0 #=> 2.75 Ahhh...schon besser # Rangfolge wird mit Klammern erzwungen (1 + 3) * 2 #=> 8 -# Boolesche Ausdrcke sind primitive Datentypen +# Boolesche Ausdrücke sind primitive Datentypen True False @@ -66,7 +66,7 @@ not False #=> True 2 <= 2 #=> True 2 >= 2 #=> True -# Vergleiche knnen verknpft werden! +# Vergleiche können verknüpft werden! 1 < 2 < 3 #=> True 2 < 3 < 2 #=> False @@ -74,32 +74,32 @@ not False #=> True "Das ist ein String." 'Das ist auch ein String.' -# Strings knnen addiert werden! +# Strings können addiert werden! "Hello " + "world!" #=> "Hello world!" # Ein String kann wie eine Liste von Zeichen verwendet werden "Das ist ein String"[0] #=> 'D' -# Mit % knnen Strings formatiert werden, etwa so: -"%s knnen %s werden" % ("Strings", "interpoliert") +# Mit % können Strings formatiert werden, etwa so: +"%s können %s werden" % ("Strings", "interpoliert") # Ein neuerer Weg, um Strings zu formatieren, ist die format-Methode. # Diese Methode wird bevorzugt -"{0} knnen {1} werden".format("Strings", "formatiert") -# Wir knnen Schlsselwrter verwenden, wenn wir nicht abzhlen wollen. +"{0} können {1} werden".format("Strings", "formatiert") +# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. "{name} will {food} essen".format(name="Bob", food="Lasagne") # None ist ein Objekt None #=> None -# Verwendet nicht das Symbol fr Gleichheit `==`, um Objekte mit None zu vergleichen +# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen # Benutzt stattdessen `is` "etc" is None #=> False None is None #=> True -# Der 'is'-Operator testet Objektidentitt. Das ist nicht -# sehr ntzlich, wenn wir mit primitiven Datentypen arbeiten, aber -# sehr ntzlich bei Objekten. +# Der 'is'-Operator testet Objektidentität. Das ist nicht +# sehr nützlich, wenn wir mit primitiven Datentypen arbeiten, aber +# sehr nützlich bei Objekten. # None, 0, und leere Strings/Listen werden alle als False bewertet. # Alle anderen Werte sind True @@ -112,33 +112,33 @@ None is None #=> True #################################################### # Ausgabe ist sehr einfach -print "Ich bin Python. Schn, dich kennenzulernen!" +print "Ich bin Python. Schön, dich kennenzulernen!" # Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm some_var #=> 5 -# Eine noch nicht deklarierte Variable anzusprechen, lst eine Exception aus. -# Siehe Kontrollstruktur, um mehr ber Ausnahmebehandlung zu lernen. -some_other_var # Lst einen NameError aus +# Eine noch nicht deklarierte Variable anzusprechen, löst eine Exception aus. +# Siehe Kontrollstruktur, um mehr über Ausnahmebehandlung zu lernen. +some_other_var # Löst einen NameError aus # if kann als Ausdruck verwendet werden "yahoo!" if 3 > 2 else 2 #=> "yahoo!" # Listen speichern Sequenzen li = [] -# Wir knnen mit einer bereits gefllten Liste anfangen +# Wir können mit einer bereits gefüllten Liste anfangen other_li = [4, 5, 6] -# append fgt Daten am Ende der Liste ein +# append fügt Daten am Ende der Liste ein li.append(1) #li ist jetzt [1] li.append(2) #li ist jetzt [1, 2] li.append(4) #li ist jetzt [1, 2, 4] li.append(3) #li ist jetzt [1, 2, 4, 3] # Vom Ende der Liste mit pop entfernen li.pop() #=> 3 und li ist jetzt [1, 2, 4] -# Fgen wir es wieder hinzu +# Fügen wir es wieder hinzu li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. # Greife auf Listen wie auf Arrays zu @@ -146,10 +146,10 @@ li[0] #=> 1 # Das letzte Element ansehen li[-1] #=> 3 -# Auerhalb der Liste ist es ein IndexError +# Außerhalb der Liste ist es ein IndexError li[4] # Raises an IndexError -# Wir knnen uns Ranges mit Slice-Syntax ansehen +# Wir können uns Ranges mit Slice-Syntax ansehen li[1:3] #=> [2, 4] # Den Anfang auslassen li[2:] #=> [4, 3] @@ -159,70 +159,70 @@ li[:3] #=> [1, 2, 4] # Ein bestimmtes Element mit del aus der Liste entfernen del li[2] # li ist jetzt [1, 2, 3] -# Listen knnen addiert werden +# Listen können addiert werden li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen -# Listen mit extend verknpfen +# Listen mit extend verknüpfen li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] -# Mit in auf Existenz eines Elements prfen +# Mit in auf Existenz eines Elements prüfen 1 in li #=> True -# Die Lnge der Liste mit len ermitteln +# Die Länge der Liste mit len ermitteln len(li) #=> 6 -# Tupel sind wie Listen, nur unvernderlich. +# Tupel sind wie Listen, nur unveränderlich. tup = (1, 2, 3) tup[0] #=> 1 -tup[0] = 3 # Lst einen TypeError aus +tup[0] = 3 # Löst einen TypeError aus -# Wir knnen all diese Listen-Dinge auch mit Tupeln anstellen +# Wir können all diese Listen-Dinge auch mit Tupeln anstellen len(tup) #=> 3 tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) tup[:2] #=> (1, 2) 2 in tup #=> True -# Wir knnen Tupel (oder Listen) in Variablen entpacken +# 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 standardmig erstellt, wenn wir uns die Klammern sparen +# Tuple 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 -# Dictionarys (Wrterbucher) speichern Key-Value-Paare +# Dictionarys (Wörterbucher) speichern Key-Value-Paare empty_dict = {} -# Hier ein geflltes Wrterbuch +# Hier ein gefülltes Wörterbuch filled_dict = {"one": 1, "two": 2, "three": 3} -# Wir knnen Eintrge mit [] nachschlagen +# Wir können Einträge mit [] nachschlagen filled_dict["one"] #=> 1 -# So holen wir alle Keys (Schlssel) als Liste +# So holen wir alle Keys (Schlüssel) als Liste filled_dict.keys() #=> ["three", "two", "one"] -# Hinweis - Die Reihenfolge von Schlsseln in der Liste ist nicht garantiert. -# Einzelne Resultate knnen anders angeordnet sein. +# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert. +# Einzelne Resultate können anders angeordnet sein. # Alle Values (Werte) als Liste filled_dict.values() #=> [3, 2, 1] -# Hinweis - Hier gelten dieselben Einschrnkungen fr die Reihenfolge wie bei Schlsseln. +# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln. -# Das Vorhandensein eines Schlssels im Wrterbuch mit in prfen +# Das Vorhandensein eines Schlüssels im Wörterbuch mit in prüfen "one" in filled_dict #=> True 1 in filled_dict #=> False -# Einen nicht vorhandenenen Schlssel zu suchen, lst einen KeyError aus +# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus filled_dict["four"] # KeyError # Mit der get-Methode verhindern wir das filled_dict.get("one") #=> 1 filled_dict.get("four") #=> None -# Die get-Methode untersttzt auch ein Standardargument, falls der Wert fehlt +# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt filled_dict.get("one", 4) #=> 1 filled_dict.get("four", 4) #=> 4 -# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlssel-Wert-Paar anzulegen +# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 @@ -235,7 +235,7 @@ some_set = set([1,2,2,3,4]) # some_set ist jetzt set([1, 2, 3, 4]) # Seit Python 2.7 kann {} benutzt werden, um ein Set zu erstellen filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} -# Mehr Elemente hinzufgen +# Mehr Elemente hinzufügen filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Schnittmengen werden mit & gebildet @@ -248,7 +248,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6} # Die Differenz einer Menge mit - bilden {1,2,3,4} - {2,3,5} #=> {1, 4} -# Auf Vorhandensein mit in prfen +# Auf Vorhandensein mit in prüfen 2 in filled_set #=> True 10 in filled_set #=> False @@ -260,26 +260,26 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6} # Erstellen wir mal eine Variable some_var = 5 -# Hier eine if-Anweisung. Die Einrckung ist in Python wichtig! +# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig! # gibt "some_var ist kleiner als 10" aus if some_var > 10: - print "some_var ist viel grer als 10." + print "some_var ist viel größer als 10." elif some_var < 10: # Dieser elif-Absatz ist optional. print "some_var ist kleiner als 10." else: # Das hier ist auch optional. - print "some_var ist tatschlich 10." + print "some_var ist tatsächlich 10." """ -For-Schleifen iterieren ber Listen +For-Schleifen iterieren über Listen Ausgabe: - hund ist ein Sugetier - katze ist ein Sugetier - maus ist ein Sugetier + hund ist ein Säugetier + katze ist ein Säugetier + maus ist ein Säugetier """ for animal in ["hund", "katze", "maus"]: - # Wir knnen Strings mit % formatieren - print "%s ist ein Sugetier" % animal + # Wir können Strings mit % formatieren + print "%s ist ein Säugetier" % animal """ `range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder @@ -293,7 +293,7 @@ for i in range(4): print i """ -While-Schleifen laufen, bis eine Bedingung erfllt ist. +While-Schleifen laufen, bis eine Bedingung erfüllt ist. Ausgabe: 0 1 @@ -303,16 +303,16 @@ Ausgabe: x = 0 while x < 4: print x - x += 1 # Kurzform fr x = x + 1 + x += 1 # Kurzform für x = x + 1 # Ausnahmebehandlung mit einem try/except-Block -# Funktioniert in Python 2.6 und hher: +# Funktioniert in Python 2.6 und höher: try: # Mit raise wird ein Fehler ausgegeben raise IndexError("Das hier ist ein Index-Fehler") except IndexError as e: - pass # Pass ist nur eine no-op. Normalerweise wrden wir hier den Fehler klren. + pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären. #################################################### @@ -322,30 +322,30 @@ except IndexError as e: # Mit def neue Funktionen erstellen def add(x, y): print "x ist %s und y ist %s" % (x, y) - return x + y # Werte werden mit return zurckgegeben + return x + y # Werte werden mit return zurückgegeben # Funktionen mit Parametern aufrufen -add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurck +add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück -# Ein anderer Weg des Funktionsaufrufs sind Schlsselwort-Argumente -add(y=6, x=5) # Schlsselwrter knnen in beliebiger Reihenfolge bergeben werden. +# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente +add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden. -# Wir knnen Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren +# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren def varargs(*args): return args varargs(1, 2, 3) #=> (1,2,3) -# Wir knnen auch Funktionen mit beliebiger Anzahl -# Schlsselwort-Argumenten definieren +# Wir können auch Funktionen mit beliebiger Anzahl +# Schlüsselwort-Argumenten definieren def keyword_args(**kwargs): return kwargs # Rufen wir es mal auf, um zu sehen, was passiert keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} -# Wir knnen beides gleichzeitig machem, wenn wir wollen +# Wir können beides gleichzeitig machem, wenn wir wollen def all_the_args(*args, **kwargs): print args print kwargs @@ -355,13 +355,13 @@ all_the_args(1, 2, a=3, b=4) Ausgabe: {"a": 3, "b": 4} """ -# Beim Aufruf von Funktionen knnen wir das Gegenteil von varargs/kwargs machen! -# Wir benutzen dann *, um Tupel auszuweiten, und ** fr kwargs. +# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen! +# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -all_the_args(*args) # quivalent zu foo(1, 2, 3, 4) -all_the_args(**kwargs) # quivalent zu foo(a=3, b=4) -all_the_args(*args, **kwargs) # quivalent zu foo(1, 2, 3, 4, a=3, b=4) +all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4) +all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4) +all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4) # Python hat First-Class-Funktionen def create_adder(x): @@ -375,11 +375,11 @@ add_10(3) #=> 13 # Es gibt auch anonyme Funktionen (lambda x: x > 2)(3) #=> True -# Es gibt auch Funktionen hherer Ordnung als Built-Ins +# Es gibt auch Funktionen höherer Ordnung als Built-Ins map(add_10, [1,2,3]) #=> [11, 12, 13] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] -# Wir knnen bei map- und filter-Funktionen auch List Comprehensions einsetzen +# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen [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] @@ -424,7 +424,7 @@ print j.say("hello") #gibt "Joel: hello" aus # Rufen wir mal unsere Klassenmethode auf i.get_species() #=> "H. sapiens" -# ndern wir mal das gemeinsame Attribut +# Ändern wir mal das gemeinsame Attribut Human.species = "H. neanderthalensis" i.get_species() #=> "H. neanderthalensis" j.get_species() #=> "H. neanderthalensis" @@ -437,28 +437,28 @@ Human.grunt() #=> "*grunt*" ## 6. Module #################################################### -# Wir knnen Module importieren +# Wir können Module importieren import math print math.sqrt(16) #=> 4 -# Wir knnen auch nur spezielle Funktionen eines Moduls importieren +# Wir können auch nur spezielle Funktionen eines Moduls importieren from math import ceil, floor print ceil(3.7) #=> 4.0 print floor(3.7) #=> 3.0 -# Wir knnen auch alle Funktionen eines Moduls importieren +# Wir können auch alle Funktionen eines Moduls importieren # Warnung: Dies wird nicht empfohlen from math import * -# Wir knnen Modulnamen abkrzen +# Wir können Modulnamen abkürzen import math as m math.sqrt(16) == m.sqrt(16) #=> True -# Module sind in Python nur gewhnliche Dateien. Wir -# knnen unsere eigenen schreiben und importieren. Der Name des +# Module sind in Python nur gewöhnliche Dateien. Wir +# können unsere eigenen schreiben und importieren. Der Name des # Moduls ist der Dateiname. -# Wir knnen auch die Funktionen und Attribute eines +# Wir können auch die Funktionen und Attribute eines # Moduls herausfinden. import math dir(math) -- cgit v1.2.3 From f1692b1576e7f5a8193b1973020fce05c7b0f531 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 17 Aug 2013 09:44:28 -0700 Subject: Updated header matter in python-de --- de-de/python-de.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 7298c62c..6803f98b 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -2,8 +2,9 @@ language: python contributors: - ["Louie Dinh", "http://ldinh.ca"] - - ["kultprok", "http:/www.kulturproktologie.de"] -filename: learnpython.py + - ["kultprok", "http:/www.kulturproktologie.de"] +filename: learnpython-de.py +lang: de-de --- Anmerkungen des ursprünglichen Autors: -- cgit v1.2.3 From 655ef1d66fc564e394cdb2a370f5a8dad723c3c4 Mon Sep 17 00:00:00 2001 From: Roberto Perez Date: Sat, 17 Aug 2013 12:44:19 -0500 Subject: Groovy: v 1.0 --- groovy.html.markdown | 175 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 174 insertions(+), 1 deletion(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index 3a928787..5333935c 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -2,7 +2,7 @@ language: Groovy filename: learngroovy.groovy contributors: - - ["Roberto Perez Alcolea", "http://github.com/rpalcolea"] + - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"] filename: learngroovy.groovy --- @@ -182,6 +182,179 @@ for ( e in map ) { x += e.value } +/* + Operators + + Operator Overloading for a list of the common operators that Groovy supports: http://groovy.codehaus.org/Operator+Overloading + + Helpful groovy operators +*/ +//Spread operator: invoke an action on all items of an aggregate object. +def technologies = ['Groovy','Grails','Gradle'] +technologies*.toUpperCase() //equivalent to: technologies.collect { it?.toUpperCase() } + +//Safe navigation operator: used to avoid a NullPointerException. +def user = User.get(1) +def username = user?.username + + +/* + Closures + A Groovy Closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point. + + More info at: http://groovy.codehaus.org/Closures+-+Formal+Definition +*/ +//Example: +def clos = { println "Hello World!" } + +println "Executing the Closure:" +clos() + +//Passing parameters to a closure +def sum = { a, b -> println a+b } +sum(2,4) + +//Closures may refer to variables not listed in their parameter list. +def x = 5 +def multiplyBy = { num -> num * x } +println multiplyBy(10) + +//If you have a Closure that takes a single argument, you may omit the parameter definition of the Closure +def clos = { print it } +clos( "hi" ) + +/* + Groovy can memorize closure results: + More info at: + http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ + http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize + http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html +/* +def cl = {a, b -> + sleep(3000) // simulate some time consuming processing + a + b +} + +mem = cl.memoize() + +def callClosure(a, b) { + def start = System.currentTimeMillis() + mem(a, b) + println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs." +} + +callClosure(1, 2) +callClosure(1, 2) +callClosure(2, 3) +callClosure(2, 3) +callClosure(3, 4) +callClosure(3, 4) +callClosure(1, 2) +callClosure(2, 3) +callClosure(3, 4) + +/* + Expando + + The Expando class is a dynamic bean so we can add properties and we can add closures as methods to an instance of this class + + Reference: http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html +*/ + def user = new Expando(name:"Roberto") + assert 'Roberto' == user.name + + user.lastName = 'Pérez' + assert 'Pérez' == user.lastName + + user.showInfo = { out -> + out << "Name: $name" + out << ", Last name: $lastName" + } + + def sw = new StringWriter() + println user.showInfo(sw) + + +/* + Metaprogramming (MOP) +*/ + +//Using ExpandoMetaClass to add behaviour +String.metaClass.testAdd = { + println "we added this" +} + +String x = "test" +x?.testAdd() + +//Intercepting method calls +class Test implements GroovyInterceptable { + def sum(Integer x, Integer y) { x + y } + + def invokeMethod(String name, args) { + System.out.println "Invoke method $name with args: $args" + } +} + +def test = new Test() +test?.sum(2,3) +test?.multiply(2,3) + +//Groovy supports propertyMissing for dealing with property resolution attempts. +class Foo { + def propertyMissing(String name) { name } +} +def f = new Foo() + +assertEquals "boo", f.boo + +/* + TypeChecked and CompileStatic + Groovy, by nature, is and will always be a dynamic language but it supports typechecked and compilestatic + + More info: http://www.infoq.com/articles/new-groovy-20 +*/ +//TypeChecked +import groovy.transform.TypeChecked + +void testMethod() {} + +@TypeChecked +void test() { + testMeethod() + + def name = "Roberto" + + println naameee + +} + +//Another example: +import groovy.transform.TypeChecked + +@TypeChecked +Integer test() { + Integer num = "1" + + Integer[] numbers = [1,2,3,4] + + Date date = numbers[1] + + return "Test" + +} + +//CompileStatic example: +import groovy.transform.CompileStatic + +@CompileStatic +int sum(int x, int y) { + x + y +} + +assert sum(2,5) == 7 + + ``` ## Further resources -- cgit v1.2.3 From 77cb25bf9b35b5a8bae6bf5e3a3ff1a4fa9ec438 Mon Sep 17 00:00:00 2001 From: Roberto Perez Date: Sat, 17 Aug 2013 12:45:13 -0500 Subject: Groovy: v 1.0 --- groovy.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index 5333935c..e4c2180b 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -229,7 +229,7 @@ clos( "hi" ) http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html -/* +*/ def cl = {a, b -> sleep(3000) // simulate some time consuming processing a + b -- cgit v1.2.3 From 0312c061b292985a5d849253480b0a8e5eafb332 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 22:35:59 +0200 Subject: C#: Added myself to contributors list --- csharp.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 0cef8f05..b113b6d3 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"] filename: LearnCSharp.cs --- -- cgit v1.2.3 From b488745fc646b16df4ef87ddb746af596ea6588f Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 22:45:01 +0200 Subject: Static field --- csharp.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index b113b6d3..3de1eb66 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -403,7 +403,12 @@ namespace Learning private int _speed; // Private: Only accessible from within the class protected int gear; // Protected: Accessible from the class and subclasses internal int wheels; // Internal: Accessible from within the assembly - string name; // default: Only accessible from within this class + string name; // Everything is private by default: Only accessible from within this class + + // Static members belong to the type itself rather then specific object. + static public int bicyclesCreated = 0; + // You can access them without a reference to any object: + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); // readonly values are set at run time // they can only be assigned upon declaration or in a constructor @@ -417,6 +422,7 @@ namespace Learning cadence = 50; _speed = 5; name = "Bontrager"; + bicyclesCreated++; } // This is a specified constructor (it contains arguments) -- cgit v1.2.3 From 964476a6e859959a3c1ae6a005ba82ba0d6b234e Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 22:45:58 +0200 Subject: C#: Lacking static members --- csharp.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 3de1eb66..584d40fd 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -535,6 +535,7 @@ namespace Learning * Enums, Flags * Attributes * Generics (T), Delegates, Func, Actions, lambda expressions + * Static properties, methods and classes * Exceptions, Interfaces, Abstraction * LINQ * ASP.NET (Web Forms/MVC/WebMatrix) -- cgit v1.2.3 From bb1f4eb93a70882f959acf6e849a9663ad74deca Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 22:49:36 +0200 Subject: C#: edited example code according to Microsoft's naming conventions --- csharp.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 584d40fd..0740c3ed 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -450,29 +450,29 @@ namespace Learning // Method declaration syntax: // () - public int getCadence() + public int GetCadence() { return cadence; } // void methods require no return statement - public void setCadence(int newValue) + public void SetCadence(int newValue) { cadence = newValue; } // virtual keyword indicates this method can be overridden - public virtual void setGear(int newValue) + public virtual void SetGear(int newValue) { gear = newValue; } - public void speedUp(int increment) + public void SpeedUp(int increment) { _speed += increment; } - public void slowDown(int decrement) + public void SlowDown(int decrement) { _speed -= decrement; } @@ -521,7 +521,7 @@ namespace Learning { } - public override void setGear(int gear) + public override void SetGear(int gear) { gear = 0; } -- cgit v1.2.3 From ccdc21900d090a88ca02e25007f4e3c197b8f50e Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 23:08:24 +0200 Subject: C#: enums --- csharp.html.markdown | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 0740c3ed..fefcb0bb 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -405,6 +405,19 @@ namespace Learning internal int wheels; // Internal: Accessible from within the assembly 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 + public enum Brand + { + AIST, + BMC, + Electra, + 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 + // Static members belong to the type itself rather then specific object. static public int bicyclesCreated = 0; // You can access them without a reference to any object: @@ -416,28 +429,30 @@ namespace Learning // Constructors are a way of creating classes // This is a default constructor - public Bicycle() + private Bicycle() { gear = 1; cadence = 50; _speed = 5; name = "Bontrager"; + brand = Brand.AIST; bicyclesCreated++; } // This is a specified constructor (it contains arguments) public Bicycle(int startCadence, int startSpeed, int startGear, - string name, bool hasCardsInSpokes) + string name, bool hasCardsInSpokes, Brand brand) { this.gear = startGear; // "this" keyword denotes the current object this.cadence = startCadence; this._speed = startSpeed; this.name = name; // it can be useful when there's a name conflict this.hasCardsInSpokes = hasCardsInSpokes; + this.brand = brand; } // Constructors can be chained - public Bicycle(int startCadence, int startSpeed) : + public Bicycle(int startCadence, int startSpeed, Brand brand) : this(startCadence, startSpeed, 0, "big wheels", true) { } @@ -532,7 +547,7 @@ namespace Learning ## Topics Not Covered - * Enums, Flags + * Flags * Attributes * Generics (T), Delegates, Func, Actions, lambda expressions * Static properties, methods and classes -- cgit v1.2.3 From dd1a6193605909f3d6abf7795cd18261b27696b9 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 23:09:07 +0200 Subject: C#: default parameter values --- csharp.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index fefcb0bb..599aaca3 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -482,12 +482,13 @@ namespace Learning gear = newValue; } - public void SpeedUp(int increment) + // Method parameters can have defaut values. In this case, methods can be called with these parameters omitted + public void SpeedUp(int increment = 1) { _speed += increment; } - public void SlowDown(int decrement) + public void SlowDown(int decrement = 1) { _speed -= decrement; } -- cgit v1.2.3 From 41ec7af8e5ac7e4a7ab8b8fc008466be98b0cdc4 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 23:09:21 +0200 Subject: Static methods --- csharp.html.markdown | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 599aaca3..22fb58e1 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -523,6 +523,14 @@ namespace Learning "\n------------------------------\n" ; } + + // 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 + return bicyclesCreated > 9000; + } // If your class only needs static members, consider marking the class itself as static. + } // end class Bicycle // PennyFarthing is a subclass of Bicycle @@ -551,7 +559,7 @@ namespace Learning * Flags * Attributes * Generics (T), Delegates, Func, Actions, lambda expressions - * Static properties, methods and classes + * Static properties * Exceptions, Interfaces, Abstraction * LINQ * ASP.NET (Web Forms/MVC/WebMatrix) -- cgit v1.2.3 From cae70d430e40478e2c916489e53ffcb24f8fe024 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 23:28:21 +0200 Subject: C#: calling base method --- csharp.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 22fb58e1..0012fcb3 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -549,6 +549,13 @@ namespace Learning { gear = 0; } + + public override string ToString() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Calling the base version of the method + return reuslt; + } } } // End Namespace -- cgit v1.2.3 From a225349acb165084a9da95f2da631a7525c513d3 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 23:28:55 +0200 Subject: C#: interfaces --- csharp.html.markdown | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 0012fcb3..55de415d 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -557,6 +557,36 @@ namespace Learning return reuslt; } } + + // Interfaces only contain signatures of the members, without the implementation. + interface IJumpable + { + void Jump(int meters); // all interface members are implicitly public + } + + interface IBreakable + { + bool Broken { get; } // interfaces can contain properties as well as methods, fields & events + } + + // Class can inherit only one other class, but can implement any amount of interfaces + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public void Broken + { + get + { + return damage > 100; + } + } + } } // End Namespace ``` @@ -567,7 +597,7 @@ namespace Learning * Attributes * Generics (T), Delegates, Func, Actions, lambda expressions * Static properties - * Exceptions, Interfaces, Abstraction + * Exceptions, Abstraction * LINQ * ASP.NET (Web Forms/MVC/WebMatrix) * Winforms -- cgit v1.2.3 From dcdfd9114f3d606ede2a3d4967e7699579427e46 Mon Sep 17 00:00:00 2001 From: JakeHurlbut Date: Sat, 17 Aug 2013 18:06:23 -0400 Subject: Corrected Array Object NSLog Call --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index b92e3218..9e9f43e7 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -90,7 +90,7 @@ int main (int argc, const char * argv[]) // Array object NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; - NSLog(@"Third number = %@", thirdObject); // Print "Third number = 3" + NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" // Dictionary object NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; -- cgit v1.2.3 From 17733c473c700b0ecd9ecce481c985caf1ddffba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kriszti=C3=A1n=20Szab=C3=B3?= Date: Sun, 18 Aug 2013 09:44:10 +0200 Subject: Added hungarian translation of Golang --- hu-hu/go.html.markdown | 305 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 305 insertions(+) create mode 100644 hu-hu/go.html.markdown diff --git a/hu-hu/go.html.markdown b/hu-hu/go.html.markdown new file mode 100644 index 00000000..b3e8c1ca --- /dev/null +++ b/hu-hu/go.html.markdown @@ -0,0 +1,305 @@ +--- +name: Go +category: language +language: Go +filename: learngo.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] +translators: + - ["Szabó Krisztián", "https://github.com/thenonameguy/"] +--- + +A Go programozási nyelv az életszerű feladatok könnyebb elvégzése miatt született. +A mai legújabb programozási trendeket elkerülve, +praktikus megoldást nyújt a valós, üzleti problémákra. + +C-szerű szintaktikával és statikus típuskezeléssel rendelkezik. +A fordító szempillantás alatt végez és egy gyorsan futó,statikus futtatható állományt hoz létre. +A nyelv könnyen érthető, üzenet-alapú konkurenciát tesz lehetővé, így könnyen ki lehet használni +a mai számítógépek több magos processzorait, ez nagy rendszerek építéséhez ideális. + +A Go alap könyvtára mindenre területre kiterjed, ennek köszönhetően a nyelvnek egyre növekvő tábora van. + +```Go +// Egy soros komment +/* Több + soros komment */ + +// Minden forrás fájl egy csomag-definícióval kezdődik, ez hasonlít a Python csomagkezelésére +// A main egy különleges csomagnév, ennek a fordítása futtatható állományt hoz létre egy könyvtár helyett. +package main + +// Az import rész meghatározza melyik csomagokat kívánjuk használni ebben a forrásfájlban +import ( + "fmt" // A Go alap könyvtárának része + "net/http" // Beépített webszerver! + "strconv" // Stringek átalakítására szolgáló csomag +) + +// Funkció deklarás, a main nevű funkció a program kezdőpontja. +func main() { + // Println kiírja a beadott paramétereket a standard kimenetre. + // Ha más csomagot funkcióját akarjuk használni, akkor azt jelezni kell a csomag nevével + fmt.Println("Hello world!") + + // Meghívunk egy másik funkciót ebből a csomagból + beyondHello() +} + +// A függvények paraméterei zárójelek között vannak. +// Ha nincsenek paraméterek, akkor is kötelező a zárójel-pár. +func beyondHello() { + var x int // Változó deklaráció, használat előtt muszáj ezt megtenni. + x = 3 // Változó értékadás + // "Rövid" deklaráció is létezik, ez az érték alapján deklarálja, definiálja és értéket is ad a változónak + y := 4 + sum, prod := learnMultiple(x, y) // a függvényeknek több visszatérési értéke is lehet + fmt.Println("sum:", sum, "prod:", prod) // egyszerű kiíratás + learnTypes() +} + +// A funkcióknak elnevezett visszatérési értékük is lehet +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // visszatérünk két értékkel + /* + sum = x + y + prod = x * y + return + Ez ugyanezzel az eredménnyel járt volna, mint a fenti sor. + Üres return esetén, az elnevezett visszatérési változók + aktuális értékeikkel térnek vissza. */ +} + +// Beépített típusok +func learnTypes() { + // Rövid deklarás az esetek többségében elég lesz a változókhoz + s := "Tanulj Go-t!" // string típus + + s2 := `A "nyers" stringekben lehetnek + újsorok is!` // de ettől még ez is ugyanolyan string mint az s, nincs külön típusa + + // nem ASCII karakterek. Minden Go forrás UTF-8 és a stringek is azok. + g := 'Σ' // rúna(rune) típus, megegyezik az uint32-vel, egy UTF-8 karaktert tárol + + f := 3.14195 // float64, az IEEE-754 szabványnak megfelelő 64-bites lebegőpontos szám + c := 3 + 4i // complex128, belsőleg két float64-el tárolva + + // Var szintaxis változó típus definiálással + var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az int-nél + var pi float32 = 22. / 7 + + // Rövid deklarásnál átalakítás is lehetséges + n := byte('\n') // byte típus, ami megegyezik az uint8-al + + // A tömböknek fordítás-időben fixált méretük van + var a4 [4]int // egy tömb 4 int-tel, mind 0-ra inicializálva + a3 := [...]int{3, 1, 5} // egy tömb 3 int-tel, láthatóan inicalizálva egyedi értékekre + + // Szeleteknek dinamikus a méretük. A szeleteknek és a tömböknek is meg vannak az előnyeik + // de a szeleteket sokkal gyakrabban használjuk. + s3 := []int{4, 5, 9} // vesd össze a3-al, nincsenek pontok. + s4 := make([]int, 4) // allokál 4 int-et, mind 0-ra inicializálva + var d2 [][]float64 // ez csak deklaráció, semmi sincs még allokálva + bs := []byte("a slice") // típus konverzió szintaxisa + + p, q := learnMemory() // deklarál két mutatót (p,q), két int-re + fmt.Println(*p, *q) // * követi a mutatót. Ez a sor kiírja a két int értékét. + + // A map a dinamikusan növelhető asszociatív tömb része a nyelvnek, hasonlít + // a hash és dictionary típusokra más nyelvekben. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // A felhasználatlan változók fordítás-idejű hibát okoznak a Go-ban. + // Az aláhúzással "használod" a változókat, de eldobod az értéküket. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Kiíratás is természetesen használatnak minősül + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() +} + +// A Go nyelv teljesen szemétgyűjtött (garbage-collected). Megtalálhatók benne mutatók, de nincs mutató aritmetika. +// Ez azt jelenti, hogy üres mutatóval még mindig hibázhatsz, de hozzáadni/műveleteket végezni már nem lehet. +func learnMemory() (p, q *int) { + // Elnevezett visszatérési változóknak int-re mutató a típusa + p = new(int) // a beépített "new" funkció, egy típusnak elegendő memóriát allokál, és visszaad rá egy mutatót. + // Az allokált int nullázva van, p többé nem üres mutató. + s := make([]int, 20) // allokáljunk 20 int változót egy memóriaterületen. + s[3] = 7 // adjunk értéket az egyiknek + r := -2 // hozzánk létre egy lokális változót + return &s[3], &r // A & megadja a memóriacímét a változónak +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // Az elágazásoknak kötelező a kapcsos zárójel, a zárójel nem szükséges. + if true { + fmt.Println("megmondtam") + } + // A kód formátumát a nyelvvel járó "go" parancssori program "go fmt" parancsa szabványosítja + if false { + // így lehet + } else { + // if/else-t csinálni + } + // Használjunk switchet a hosszabb elágazások alkalmazása helyett. + x := 1 + switch x { + case 0: + case 1: + // Az "esetek" nem "esnek át", tehát + case 2: + // ez nem fog lefutni, nincs szükség break-ekre. + } + // A for ciklus sem használ zárójeleket + for x := 0; x < 3; x++ { + fmt.Println("iteráció", x) + } + // itt az x == 1. + + // A for az egyetlen ciklus fajta a Go-ban, de több formája van. + for { // végtelen ciklus + break // csak vicceltem + continue // soha nem fut le + } + // Akárcsak a for-nál, az if-ben is lehet rövid deklarással egy lokális változót létrehozni + // ami az blokk összes if/else-n keresztül érvényes marad. + if y := expensiveComputation(); y > x { + x = y + } + // Függvényeket használhatjuk closure-ként is. + xBig := func() bool { + return x > 100 // a switch felett deklarált x-et használjuk itt + } + fmt.Println("xBig:", xBig()) // igaz (utoljára 1e6 lett az értéke az x-nek) + x /= 1e5 // így most már x == 10 + fmt.Println("xBig:", xBig()) // 10 pedig kisebb mint 100, tehát hamis + + // Ha nagyon-nagyon szükséges, akkor használhatjuk a jó öreg goto-t. + goto love +love: + + learnInterfaces() // Itt kezdődnek az érdekes dolgok! +} + +// Definiáljuk a Stringert egy olyan interfésznek, amelynek egy metódusa van, a String, ami visszatér egy stringgel. +type Stringer interface { + String() string +} + +// Definiáljuk a pair-t egy olyan struktúrának amelynek két int változója van, x és y. +type pair struct { + x, y int +} + +// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer interf +func (p pair) String() string { // p lesz a "vevő" + // Sprintf az fmt csomag egy publikus függvénye, műkődése megegyezik a C-s megfelelőjével. + // A pontokkal érjük el a mindenkori p struktúra elemeit + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // A kapcsos zárójellel jelezzük, hogy egyből inicializálni + // szeretnénk a struktúra változóit a sorrendnek megfelelően. + p := pair{3, 4} + fmt.Println(p.String()) // meghívjuk a p String metódusát. + var i Stringer // deklaráljuk i-t Stringer típusú interfésznek + i = p // lehetséges, mert a pair struktúra eleget tesz a Stringer interfésznek + // Meghívjuk i String metódusát, az eredmény ugyanaz, mint az előbb. + fmt.Println(i.String()) + + // Az fmt csomag funckciói automatikusan meghívják a String funkciót + // hogy megtudják egy objektum szöveges reprezentációját. + fmt.Println(p) // ugyan az az eredmény mint az előbb, a Println meghívja a String metódust. + fmt.Println(i) // dettó + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" szokásos megoldás arra, hogy jól működött-e a függvény. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok hamis lesz, mert az 1 nincs benne a map-ban. + fmt.Println("nincs meg") + } else { + fmt.Print(x) // x lenne az érték, ha benne lenne a map-ban. + } + // A hiba érték többet is elmond a függvény kimeneteléről, mint hogy minden "ok" volt-e + if _, err := strconv.Atoi("non-int"); err != nil { // _ eldobja az értéket, úgy se lesz jó jelen esetben + // kiírja, hogy "strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // Az interfészekre még visszatérünk, addig is jöjjön a konkurens programozás! + learnConcurrency() +} + +// c egy csatorna, egy konkurens-biztos kommunikációs objektum. +func inc(i int, c chan int) { + c <- i + 1 // <- a "küldés" operátor, ha a bal oldalán csatorna van, így i+1-et küld be a csatornába +} + +// Az inc-et fogjuk arra használni, hogy konkurensen megnöveljünk számokat +func learnConcurrency() { + // Ugyan az a make funkció amivel korábban szeleteket hoztunk létre. + // Make allokál mapokat, szeleteket és csatornákat. + c := make(chan int) + // Indítsunk három konkurens goroutine-t. A számok konkurensen lesznek + // megnövelve, ha a számítógép képes rá és jól be van állítva, akkor pedig paralellizálva/egymás mellett. + // Mind a 3 ugyanabba a csatornába küldi az eredményeket. + go inc(0, c) // A go utasítás indít el goroutine-okat. + go inc(10, c) + go inc(-805, c) + // Beolvassuk 3x a csatornából az eredményeket és kiírjuk őket a kimenetre. + // Nem lehet tudni milyen sorrendben fognak érkezni az eredmények! + fmt.Println(<-c, <-c, <-c) // hogyha a jobb oldalon csatorna van, akkor a "<-" a beolvasó/kapó operátor + + cs := make(chan string) // még egy csatorna, ez stringekkel kommunikál + cc := make(chan chan string) // egy csatorna csatornával + go func() { c <- 84 }() // indítsunk egy új goroutine-t, csak azért hogy küldjünk egy számot + go func() { cs <- "wordy" }() // ugyanez, csak a cs csatornába stringet küldünk + // A select olyan mint a switch, csak feltételek helyett csatorna műveletek vannak. + // Véletlenszerűen kiválasztja az első olyan esetet, ahol létrejöhet kommunikáció. + select { + case i := <-c: // a megkapott értéket el lehet tárolni egy változóban + fmt.Println("ez egy", i) + case <-cs: // vagy el lehet dobni az értékét + fmt.Println("ez egy string volt") + case <-cc: // üres csatorna, soha nem fog rajta semmi se érkezni + fmt.Println("sose futok le :'( ") + } + // Ezen a ponton vagy c vagy a cs goroutineja lefutott. + // Amelyik hamarabb végzett, annak a megfelelő case-e lefutott, a másik blokkolva vár. + + learnWebProgramming() // Go képes rá. Te is képes akarsz rá lenni. +} + +// Egy funkció a http csomagból elindít egy webszervert. +func learnWebProgramming() { + // A ListenAndServe első paramétre egy TCP port, amin kiszolgálunk majd. + // Második paramétere egy interfész, pontosabban a http.Handler interfész. + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // nem felejtük el kiírni az esetleges hibákat! +} + +// Csináljunk a pair-ból egy http.Handler-t úgy, hogy implementáljuk az egyetlen metódusát a ServeHTTP-t. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Minden kapcsolatra elküldjük ezt a http.ResponseWriter-el + w.Write([]byte("Megtanultad a Go-t Y perc alatt!")) +} +``` + +## További olvasmányok + +Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](http://golang.org/). +Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten és sok érdekességet olvashatsz. + +A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és sokat tanul belőle az ember. + +Ha pedig jobban bele akarod vetni magad a Go-ba, akkor a standard könyvtárban a legjobb praktikákat kilesheted. +TIPP: a dokumentációban kattints egy funkció nevére és rögtön megmutatja a hozzá tartozó kódot! + -- cgit v1.2.3 From 2e465d0e7cce9cfb3d54d2a76a023610e29c2755 Mon Sep 17 00:00:00 2001 From: Alexey Date: Sun, 18 Aug 2013 15:44:31 +0700 Subject: Added Russian Translation of Ruby --- ru-ru/ruby-ru.html.markdown | 390 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 390 insertions(+) create mode 100644 ru-ru/ruby-ru.html.markdown diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown new file mode 100644 index 00000000..7d48d0e3 --- /dev/null +++ b/ru-ru/ruby-ru.html.markdown @@ -0,0 +1,390 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["Alexey Makarov", "https://github.com/Anakros"] +--- + +```ruby +# Это комментарий + +=begin +Это многострочный комментарий +Никто их не использует +И они не рекомендуются к использованию +=end + +# Первое и самое главное: Всё является объектом. + +# Числа это объекты + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Немного простой арифметики +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Арифметика -- это синтаксический сахар +# над вызовом метода для объекта +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Логические величины -- это объекты +nil # Здесь ничего нет +true # правда +false # ложь + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Операция равенства +1 == 1 #=> true +2 == 1 #=> false + +# Операция неравенства +1 != 1 #=> false +2 != 1 #=> true +!true #=> false +!false #=> true + +# nil -- имеет такое же логическое значение, как и false + +!nil #=> true +!false #=> true +!0 #=> false + +# Больше операций сравнения +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Строки -- это объекты + +'Я строка'.class #=> String +"Я тоже строка".class #=> String + +placeholder = "использовать интерполяцию строк" +"Я могу #{placeholder}, когда создаю строку с двойными кавычками" +#=> "Я могу использовать интерполяцию строк, когда создаю строку с двойными кавычками" + + +# печатать в стандартный вывод +puts "Я печатаюсь!" + +# Переменные +x = 25 #=> 25 +x #=> 25 + +# Присваивание значения возвращает присвоенное значение +# Это позволяет делать множественные присваивания: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# По соглашению, используйте snake_case для имён переменных +snake_case = true + +# Используйте подробные имена для переменных +# Но не переборщите! +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Идентификаторы (тоже объекты) + +# Идентификаторы -- это неизменяемые, многоразовые константы. +# Для каждого идентификатора (кроме текста) сохраняется цифровой хэш. При последующем +# использовании идентификатора, заместо создания нового объекта, будет найден уже +# существующий по цифровому хэшу. Они часто используются вместо строк +# для ускорения работы приложений + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# Массивы + +# Это массив +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Массив может содержать различные типы значений + +[1, "hello", false] #=> [1, "hello", false] + +# Значение в массиве можно получить по индексу с левой границы +array[0] #=> 1 +array[12] #=> nil + +# Как и арифметика, доступ к значению в массиве +# это синтаксический сахар над вызовом метода для объекта +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Также, можно получить по индексу с правой границы +array[-1] #=> 5 + +# С заданными левой и правой границами индексов +array[2, 4] #=> [3, 4, 5] + +# Или с использованием диапазона значений +array[1..3] #=> [2, 3, 4] + +# Вот так можно добавить значение в массив +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# Хэши -- это массив пар ключ => значение. +# Хэши объявляются с использованием фигурных скобок: +hash = {'color' => 'green', 'number' => 5} + +hash.keys #=> ['color', 'number'] + +# Значение в хэше легко может быть найдено по ключу: +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# Поиск по ключу, которого в хэше нет, вернёт nil: +hash['nothing here'] #=> nil + +# начиная с Ruby 1.9, существует специальный синтаксис +# при использовании идентификаторов как ключей хэша: + +new_hash = { defcon: 3, action: true} + +new_hash.keys #=> [:defcon, :action] + +# Массивы и Хэши -- перечисляемые типы данных +# У них есть много полезных методов, например: each, map, count и другие + +# Управление ходом выполнения (Управляющие структуры) + +if true + "if условие" +elsif false + "else if, условие" +else + "else, условие" +end + +for counter in 1..5 + puts "#итерация {counter}" +end +#=> итерация 1 +#=> итерация 2 +#=> итерация 3 +#=> итерация 4 +#=> итерация 5 + +# Однако, никто не использует "for" для циклов. +# Вместо него Вы должны использовать метод "each" вместе с блоком кода. +# +# Блок кода -- это один из вариантов создания замыканий (лямбды, анонимные функции). +# Блок может только передаваться методу, сам по себе он существовать не может. +# "for" не имеет своей области видимости и все переменные, объявленные в нём +# будут доступны отовсюду. "each" вместе с блоком создаёт свою область видимости. + +# Метод "each" для диапазона значений запускает блок кода один раз для каждого из значений диапазона +# Блок передаёт счётчик (counter) в качестве параметра. +# Вызов метода "each" с блоком выглядит следующим образом: + +(1..5).each do |counter| + puts "итерация #{counter}" +end +#=> итерация 1 +#=> итерация 2 +#=> итерация 3 +#=> итерация 4 +#=> итерация 5 + +# Вы также можете ограничивать блоки фигурными скобками: +(1..5).each {|counter| puts "итерация #{counter}"} + +# Содержимое управляющих структур также можно перебирать используя "each": +array.each do |element| + puts "#{element} -- часть массива" +end +hash.each do |key, value| + puts "#{key} -- это #{value}" +end + +counter = 1 +while counter <= 5 do + puts "итерация #{counter}" + counter += 1 +end +#=> итерация 1 +#=> итерация 2 +#=> итерация 3 +#=> итерация 4 +#=> итерация 5 + +grade = 'B' + +case grade +when 'A' + puts "Так держать, детка!" +when 'B' + puts "Тебе повезёт в следующий раз" +when 'C' + puts "Ты можешь сделать лучше" +when 'D' + puts "Выскоблил последнее" +when 'F' + puts "Ты провалился!" +else + puts "Альтернативная система оценок, да?" +end + +# Функции + +def double(x) + x * 2 +end + +# Функции (и все блоки) неявно возвращают значение последней операции +double(2) #=> 4 + +# Скобки необязательны, если возвращаемый результат однозначен +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x,y) + x + y +end + +# Аргументы метода разделены запятой +sum 3, 4 #=> 7 + +sum sum(3,4), 5 #=> 12 + +# yield +# Все методы имеют неявный, опциональный параметр, +# который может быть вызван с помощью инструкции "yield" + +def surround + puts "{" + yield + puts "}" +end + +surround { puts 'hello world' } + +# { +# hello world +# } + + +# Определение класса с помощью ключевого слова "class" +class Human + + # Переменная класса, она является общей для всех экземпляров класса + @@species = "H. sapiens" + + # Базовый метод-конструктор + def initialize(name, age=0) + # Присвоить аргумент "name" переменной "name" экземпляра класса + @name = name + # Если аргумент "age" не задан, мы используем значение по умолчанию из списка аргументов + @age = age + end + + # Базовый метод установки значения для переменной (setter) + def name=(name) + @name = name + end + + # Базовый метод получения значения переменной (getter) + def name + @name + end + + # Метод класса определяется с ключевым словом "self", + # чтобы можно было отличить его от метода экземпляра класса. + # Он может быть вызван только на уровне класса, не экземпляра. + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end + +end + + +# Создание экземпляра класса +jim = Human.new("Jim Halpert") + +dwight = Human.new("Dwight K. Schrute") + +# Давайте вызовем несколько методов этого класса +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# Вызов метода класса +Human.say("Hi") #=> "Hi" + +# Класс тоже объект в Ruby. Потому класс может иметь переменные экземпляра. +# Переменная класса доступна в классе, его экземплярах и его потомках. + +# Базовый класс +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Производный класс (класс-потомок) +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# Переменная экземпляра класса недоступна в потомках этого класса. + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +Human.bar # 0 +Doctor.bar # nil + +``` -- cgit v1.2.3 From 27a73fe1759dc049646b2a3e5feedf47d541b6e2 Mon Sep 17 00:00:00 2001 From: Alexey Date: Sun, 18 Aug 2013 15:52:30 +0700 Subject: Fixed filename, added previous contributors --- ru-ru/ruby-ru.html.markdown | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown index 7d48d0e3..baa5e8b5 100644 --- a/ru-ru/ruby-ru.html.markdown +++ b/ru-ru/ruby-ru.html.markdown @@ -1,8 +1,13 @@ --- language: ruby -filename: learnruby.rb +filename: learnruby-ru.rb contributors: - - ["Alexey Makarov", "https://github.com/Anakros"] + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Alexey Makarov", "https://github.com/Anakros"] --- ```ruby -- cgit v1.2.3 From e5f626f7c4acb6a1a87b1cb3f766de87b7bdc4ae Mon Sep 17 00:00:00 2001 From: Alexey Date: Sun, 18 Aug 2013 17:59:29 +0700 Subject: - added russian "lang" in description - removed tabs - minor changes in the text --- ru-ru/ruby-ru.html.markdown | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown index baa5e8b5..0a8fbb09 100644 --- a/ru-ru/ruby-ru.html.markdown +++ b/ru-ru/ruby-ru.html.markdown @@ -1,13 +1,14 @@ --- language: ruby +lang: ru-ru filename: learnruby-ru.rb contributors: - - ["David Underwood", "http://theflyingdeveloper.com"] - - ["Joel Walden", "http://joelwalden.net"] - - ["Luke Holder", "http://twitter.com/lukeholder"] - - ["Tristan Hume", "http://thume.ca/"] - - ["Nick LaMuro", "https://github.com/NickLaMuro"] - - ["Alexey Makarov", "https://github.com/Anakros"] + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Alexey Makarov", "https://github.com/Anakros"] --- ```ruby @@ -87,7 +88,7 @@ puts "Я печатаюсь!" x = 25 #=> 25 x #=> 25 -# Присваивание значения возвращает присвоенное значение +# Присваивание значения возвращает то самое присвоенное значение. # Это позволяет делать множественные присваивания: x = y = 10 #=> 10 @@ -150,7 +151,7 @@ array[1..3] #=> [2, 3, 4] # Вот так можно добавить значение в массив array << 6 #=> [1, 2, 3, 4, 5, 6] -# Хэши -- это массив пар ключ => значение. +# Хэши -- это массив пар "ключ => значение". # Хэши объявляются с использованием фигурных скобок: hash = {'color' => 'green', 'number' => 5} @@ -160,7 +161,7 @@ hash.keys #=> ['color', 'number'] hash['color'] #=> 'green' hash['number'] #=> 5 -# Поиск по ключу, которого в хэше нет, вернёт nil: +# Поиск по ключу, которого в хэше нет вернёт nil: hash['nothing here'] #=> nil # начиная с Ruby 1.9, существует специальный синтаксис @@ -200,7 +201,8 @@ end # "for" не имеет своей области видимости и все переменные, объявленные в нём # будут доступны отовсюду. "each" вместе с блоком создаёт свою область видимости. -# Метод "each" для диапазона значений запускает блок кода один раз для каждого из значений диапазона +# Метод "each" для диапазона значений запускает блок кода один раз +# для каждого из значений диапазона # Блок передаёт счётчик (counter) в качестве параметра. # Вызов метода "each" с блоком выглядит следующим образом: @@ -295,18 +297,19 @@ surround { puts 'hello world' } # Определение класса с помощью ключевого слова "class" class Human - # Переменная класса, она является общей для всех экземпляров класса + # Переменная класса, она является общей для всех экземпляров класса @@species = "H. sapiens" # Базовый метод-конструктор def initialize(name, age=0) - # Присвоить аргумент "name" переменной "name" экземпляра класса + # Присвоить аргумент "name" переменной "name" экземпляра класса @name = name - # Если аргумент "age" не задан, мы используем значение по умолчанию из списка аргументов + # Если аргумент "age" не задан, + # мы используем значение по умолчанию из списка аргументов @age = age end - # Базовый метод установки значения для переменной (setter) + # Базовый метод установки значения для переменной (setter) def name=(name) @name = name end @@ -316,9 +319,9 @@ class Human @name end - # Метод класса определяется с ключевым словом "self", - # чтобы можно было отличить его от метода экземпляра класса. - # Он может быть вызван только на уровне класса, не экземпляра. + # Метод класса определяется с ключевым словом "self", + # чтобы можно было отличить его от метода экземпляра класса. + # Он может быть вызван только на уровне класса, но не экземпляра. def self.say(msg) puts "#{msg}" end @@ -335,7 +338,7 @@ jim = Human.new("Jim Halpert") dwight = Human.new("Dwight K. Schrute") -# Давайте вызовем несколько методов этого класса +# Давайте вызовем несколько методов jim.species #=> "H. sapiens" jim.name #=> "Jim Halpert" jim.name = "Jim Halpert II" #=> "Jim Halpert II" -- cgit v1.2.3 From 0a7d50c097f36336adf92fd79144f370fd66caa2 Mon Sep 17 00:00:00 2001 From: kultprok Date: Sun, 18 Aug 2013 14:04:10 +0200 Subject: Added german translation for git. --- de-de/git-de.html.markdown | 374 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 374 insertions(+) create mode 100644 de-de/git-de.html.markdown diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown new file mode 100644 index 00000000..471c7641 --- /dev/null +++ b/de-de/git-de.html.markdown @@ -0,0 +1,374 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http:#github.com/JakeHP"] + - ["kultprok", "http://www.kulturproktologie.de"] +filename: LearnGit.txt +lang: de-de +--- + +Git ist eine verteilte Versions- und Quellcodeverwaltung. + +Es nimmt Schnappschüsse der Projekte, um mit diesen Schnappschüssen verschiedene Versionen unterscheiden und den Quellcode verwalten zu können. + +Anmerkung des Übersetzers: Einige englische Begriffe wie *Repository*, *Commit* oder *Head* sind idiomatische Bestandteile im Umgang mit Git. Sie wurden nicht übersetzt. + +## Konzepte der Versionsverwaltung + +### Was ist Versionsverwaltung? + +Eine Versionskontrolle erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit. + +### Zentrale im Vergleich mit verteilter Versionverwaltung + +* Zentrale Versionskontrolle konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien. +* Verteilte Versionskontrolle konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID. +* Verteilte Systeme haben keine vorbestimmte Struktur. Ein SVN-ähnliches, zentrales System wäre mit Git ebenso umsetzbar. + +[Weiterführende Informationen](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### Warum Git? + +* Ist offline einsetzbar. +* Einfache Kollaboration! +* Branching ist einfach! +* Merging ist einfach! +* Git ist schnell. +* Git ist flexibel. + +## Die Architektur von Git + + +### Repository (Repo) + +Ein Satz von Dateien, Verzeichnisen, Historieneinträgen, Commits und Heads. Stell es dir wie eine Quellcode-Datenstruktur vor, unter anderem mit der Eigenschaft, dass alle *Elemente* dir Zugriff auf die Revisionshistorie geben. + +Ein Repository besteht in Git aus dem .git-Verzeichnis und dem Arbeitsverzeichnis. + +### .git-Verzeichnis (Teil des Repositorys) + +Das .git-Verzeichnis enth? alle Einstellung, Logs, Branches, den HEAD und mehr. +[Ausführliche Übersicht](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Arbeitsverzeichnis (Teil des Repositorys) + +Dies sind die Verzeichnisse und Dateien in deinem Repository. + +### Index (Teil des .git-Verzeichnisses) + +Der Index ist die die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arbeitsverzeichnis vom Repository trennt. Sie gibt Entwicklern mehr Einfluss darüber, was ins Git-Repository eingeht. + +### Commit + +Ein Commit ist ein Schnappschuss von Uderungen in deinem Arbeitsverzeichnis. Wenn du zum Beispiel 5 Dateien hinzugefügt und 2 andere entfernt hast, werden diese Änderungen im Commit (Schnappschuss) enthalten sein. Dieser Commit kann dann in andere Repositorys gepusht werden. Oder nicht! + +### Branch + +Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den letzten Commit, den du gemacht hast. Während des Commits wird der Pointer automatisch auf Stand gebracht und zeigt dann auf den neuen letzten Commit. + +### HEAD und head (Teil des .git-Verzeichnisses) + +HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD. Ein head ist ein Pointer, der auf ein beliebige Zahl von heads zeigt. + +### Konzeptionelle Hintergründe + +* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) +* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) + + +## Befehle + + +### init + +Erstelle ein leeres Git-Repository. Die Einstellungen, gespeicherte Informationen und mehr zu diesem Git-Repository werden in einem Verzeichnis namens *.git* angelegt. + +```bash +$ git init +``` + +### config + +Hiermit werden Einstellungen vorgenommen. Dies kann das Repository, das System selbst oder globale Einstellungen betreffen. + +```bash +# Grundlegende Config-Variablen ausgeben und setzen +$ git config --global user.email +$ git config --global user.name + +$ git config --global user.email "MyEmail@Zoho.com" +$ git config --global user.name "My Name" +``` + +[Mehr über git config](http://git-scm.com/docs/git-config) + +### help + +Schnellzugriff auf extrem detaillierte Anleitungen zu allen Befehlen. Oder als Erinnerung zu semantischen Eigenheiten. + +```bash +# Übersicht gängiger Befehle +$ git help + +# Übersicht aller verfügbaren Befehle +$ git help -a + +# Befehlspezifische Hilfe - Bedienungsanleitung +# git help +$ git help add +$ git help commit +$ git help init +``` + +### status + +Zeigt die Unterschiede zwischen Index (im Grunde dein Arbeitsverzeichnis/-repository) und dem aktuellen HEAD an. + + +```bash +# Zeigt den Branch, nicht-verfolgte Dateien, Uderungen und andere Unterschiede an +$ git status + +# Anderes Wissenswertes über git status anzeigen +$ git help status +``` + +### add + +Hinzufügen von Dateien zum Arbeitsverzeichnis/-repository. Wenn du neue Dateien nicht mit *git add* zum Arbeitsverzeichnis hinzufügst, werden sie nicht in den Commit aufgenommen! + +```bash +# Fügt eine Datei deinem aktuellen Arbeitsverzeichnis hinzu +$ git add HelloWorld.java + +# Fügt eine Datei aus einem verschachtelten Verzeichnis hinzu +$ git add /path/to/file/HelloWorld.c + +# Reguläre Ausdrücke werden unterstützt! +$ git add ./*.java +``` + +### branch + +Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erschaffen oder löschen. + +```bash +# Liste alle bestehenden Branches und Remotes auf +$ git branch -a + +# Erstelle einen neuen Branch +$ git branch myNewBranch + +# Lösche einen Branch +$ git branch -d myBranch + +# Benenne einen Branch um +# git branch -m +$ git branch -m myBranchName myNewBranchName + +# Ändere die Beschreibung eines Branchs +$ git branch myBranchName --edit-description +``` + +### checkout + +Bringt alle Dateien im Arbeitsverzeichnis auf den Stand des Index oder des angegebenen Branches. + +```bash +# Ein Repo auschecken - wenn nicht anders angegeben ist das der master +$ git checkout +# Einen bestimmten Branch auschecken +$ git checkout branchName +# Erstelle einen neuen Branch und wechsle zu ihm. Wie: "git branch ; git checkout " +$ git checkout -b newBranch +``` + +### clone + +Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für hedes geklonte Repo remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen. + +```bash +# Klone learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +``` + +### commit + +Speichert die aktuellen Inhalte des Index in einen neuen *Commit*. Dieser Commit enthält alle Änderungen und eine vom Benutzer erstellte Beschreibung der Änderungen. + +```bash +# Commit mit Beschreibung erstellen. +$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" +``` + +### diff + +Zeigt die Unterschiede zwischen Dateien von Arbeitsverzeichnisse, dem Index und Commits an. + +```bash +# Unterschiede zwischen deinem Arbeitsverzeichnis und dem Index anzeigen +$ git diff + +# Unterschiede zwischen dem Index und dem aktuellsten Commit anzeigen +$ git diff --cached + +# Unterschiede zwischen deinem Arbeitsverzeichnis und dem aktuellsten Commit anzeigen +$ git diff HEAD +``` + +### grep + +Schnell ein Repository durchsuchen. + +Optionale Einstellungen: + +```bash +# Vielen Dank an Travis Jeffery für die Hinweise. +# Zeilennummerierung in grep-Suchergebnissen +$ git config --global grep.lineNumber true + +# Suchergebnisse lesbarer gestalten, auch Gruppierungen sind möglich +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Suche nach "variableName" in allen java-Dateien +$ git grep 'variableName' -- '*.java' + +# Suche nach eine Zeile, die "arrayListName" und "add" oder "remove" enthält +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Google ist dein Freund; für mehr Beispiele: +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Zeige Commits für das Repository an. + +```bash +# Zeige alle Commits +$ git log + +# Zeige die Anzahl n an Commits +$ git log -n 10 + +# Zeige nur Merges an +$ git log --merges +``` + +### merge + +*Merge*, also verschmelze, alle Änderungen von externen Commits in den aktuellen Branch. + +```bash +# Merge den angegebenen Branch in den aktuellen. +$ git merge branchName + +# Erstelle immer einen Merge-Commit. +$ git merge --no-ff branchName +``` + +### mv + +Eine Datei umbenennen oder verschieben. + +```bash +# Umbenennen +$ git mv HelloWorld.c HelloNewWorld.c + +# Verschieben +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Umbenennung oder Verschieben erzwingen +# "existingFile" besteht schon im Verzeichnis, wird überschrieben mit "myFile" +$ git mv -f myFile existingFile +``` + +### pull + +Führe einen Pull, zieht alle Daten, eines Repositorys und f?? einen Merge mit einem anderen Branch durch. + +```bash +# Update deines lokalen Repos, indem ein Merge der neuen Uderungen +# von den remote-liegenden "origin"- und "master"-Branches durchgef?? wird. +# git pull +# git pull => impliziter Verweis auf origin und master +$ git pull origin master + +# F?? einen Merge von Uderungen eines remote-Branch und ein Rebase +# des Branch-Commits im lokalen Repo durch. Wie: pull , git rebase " +$ git pull origin master --rebase +``` + +### push + +Führe einen Push, ein Hochladen, und einen Merge von Änderungen eines remote-Branch mit einem Branch aus. + +```bash +# Führe Push und Merge von Änderungen des lokalen Repo zu einem +# remote-Branch namens "origin" und dem "master"-Branch aus. +# git push +# git push => impliziter Verweis auf => git push origin master +$ git push origin master +``` + +### rebase (mit Vorsicht einsetzen) + +Nimm alle Änderungen, die in einem Branch durch Commits vorgenommen wurden, und übertrage sie auf einen anderen Branch. Achtung: Führe keinen Rebase von Commits durch, die auf ein öffentliches Repo gepusht wurden. + +```bash +# Rebase "experimentBranch" in den "master"-Branch +# git rebase +$ git rebase master experimentBranch +``` + +[Weiterführende Informationen](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (mit Vorsicht einsetzen) + +Setze den aktuellen HEAD auf den angegebenen Zustand zurück. So können Merges, Pulls, Commits, Hinzufügungen und andere Änderungen rückgängig gemacht werden. Es ist ein hervorragender Befehl, aber auch sehr gefährlich, wenn du nicht weißt, was du tust. + +```bash +# Setze die Staging-Area zurück, um dem letzten Commit zu entsprechen (das Verzeichnis bleibt unberührt) +$ git reset + +# Setze die Staging-Area zurück, um dem letzten Commit zu entsprechen und überschreibe das Arbeitsverzeichnis +$ git reset --hard + +# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unber??) +# Alle Uderungen bleiben im Verzeichnis erhalten +$ git reset 31f2bb1 + +# Bewegt die Spitze des Branches zurück zu dem angegebenen Commit +# und gleicht die Arbeitsverzeichnisse ab (löscht nicht vom Commit erfasste Änderungen und alle Commits, +# die dem angegebenen Commit folgen). +$ git reset --hard 31f2bb1 +``` + +### rm + +Das Gegenteil von *git add*. *git rm* löscht Dateien vom Arbeitsverzeichnis. + +```bash +# Entferne HelloWorld.c +$ git rm HelloWorld.c + +# Entferne eine Datei aus einem verschachtelten Verzeichnis +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## Weiterführende Informationen + +* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) + +* [git-scm - Video Tutorials](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) -- cgit v1.2.3 From 3a88d4f2443c91dba5a968e38ede2b4f145f152a Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sun, 18 Aug 2013 00:59:35 +0200 Subject: Stub bash file --- bash.html.markdown | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 bash.html.markdown diff --git a/bash.html.markdown b/bash.html.markdown new file mode 100644 index 00000000..ea0a28da --- /dev/null +++ b/bash.html.markdown @@ -0,0 +1,44 @@ +--- + +language: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] +filename: LearnBash.sh + +--- + +Bash is a name of the unix shell, which was also distributed as the shell for the GNU operating system and as default shell on Linux and Mac OS X. +Nearly all examples below can be a part of a shell script or executed directly in the shell. + +[Read more here.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/sh +# First line of the script is shebang which tells the system how to execute the script: http://en.wikipedia.org/wiki/Shebang_(Unix) +# As you already figured, comments start with #. Shebang is also a comment. + +# Simple hello world example: +echo 'Hello, world!' + +# Each command starts on a new line, or after semicolon: +echo 'This is the first line'; echo 'This is the second line' + +# Declaring a variable looks like this: +VARIABLE="Some string" + +# But not like this: +VARIABLE = "Some string" # Bash will decide that VARIABLE is a command he must execute and give an error because it couldn't be found. + +# Using the variable: +echo $VARIABLE +echo "$VARIABLE" + +# We have the usual if structure: +if true +then + echo "This is expected" +else + echo "And is was not" +fi + +``` \ No newline at end of file -- cgit v1.2.3 From 01f1419dd7d0fba8735cbafb4cff871e52604b07 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sun, 18 Aug 2013 01:14:00 +0200 Subject: Bash: user input and expressions --- bash.html.markdown | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index ea0a28da..1ddacc33 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -18,7 +18,7 @@ Nearly all examples below can be a part of a shell script or executed directly i # As you already figured, comments start with #. Shebang is also a comment. # Simple hello world example: -echo 'Hello, world!' +echo Hello, world! # Each command starts on a new line, or after semicolon: echo 'This is the first line'; echo 'This is the second line' @@ -32,6 +32,12 @@ VARIABLE = "Some string" # Bash will decide that VARIABLE is a command he must e # Using the variable: echo $VARIABLE echo "$VARIABLE" +# When you use the variable itself — assign it, export it, or else — you write it's name without $. If you want to use variable's value, you should use $. + +# Reading a value from input: +echo "What's your name?" +read NAME # Note that we didn't need to declare new variable +echo Hello, $NAME! # We have the usual if structure: if true @@ -41,4 +47,7 @@ else echo "And is was not" fi +# Expressions are denoted with the following format: +echo $(( 10 + 5 )) + ``` \ No newline at end of file -- cgit v1.2.3 From a538c52fb444fc14782ceb8353f69da04d232e60 Mon Sep 17 00:00:00 2001 From: Darren Lin Date: Sat, 17 Aug 2013 17:33:32 -0700 Subject: expanded the bash tutorial --- bash.html.markdown | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 1ddacc33..4e1eff9e 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -2,7 +2,7 @@ language: bash contributors: - - ["Max Yankov", "https://github.com/golergka"] + - ["Max Yankov", "https://github.com/golergka" - "Darren Lin", "https://github.com/CogBear"] filename: LearnBash.sh --- @@ -50,4 +50,24 @@ fi # Expressions are denoted with the following format: echo $(( 10 + 5 )) -``` \ No newline at end of file +# Commands can be substitued within other commands using $( ): +# The following command displays the number of files and directories in the current directory. +echo "There are $(ls | wc -l) items here." + +#Bash uses a case statement that works similarily to switch in Java and C++: +case "$VARIABLE" +in + #List patterns for the conditions you want to meet + 0) echo "There is a zero." + 1) echo "There is a one." + *) 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 +do + echo "$VARIABLE" +done + +``` -- cgit v1.2.3 From 3e8c292a10eabd9816f7b0ccb9249661fbb4c3be Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sun, 18 Aug 2013 14:25:20 +0200 Subject: Bash: commands, attributes, ls, grep & pipe --- bash.html.markdown | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index 4e1eff9e..8cf7be18 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -44,12 +44,23 @@ if true then echo "This is expected" else - echo "And is was not" + echo "And this is not" fi # Expressions are denoted with the following format: echo $(( 10 + 5 )) +# Unlike other programming languages, bash is a shell — so it works in a context of current directory. +# You can list files and directories in the current directories with ls command: +ls + +# These commands have options that control their execution: +ls -l # Lists every file and directory on a separate line + +# Results of the previous command can be passed to the next command as input. +# grep command filters the input with provided patterns. That's how we can list txt files in the current directory: +ls -l | grep "\.txt" + # Commands can be substitued within other commands using $( ): # The following command displays the number of files and directories in the current directory. echo "There are $(ls | wc -l) items here." -- cgit v1.2.3 From 0ff5090a5d60a91bbd8612ca4db186732bf4da72 Mon Sep 17 00:00:00 2001 From: Tenor Biel Date: Sun, 18 Aug 2013 10:10:40 -0500 Subject: Updated documentation for new language behaivour --- whip.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/whip.html.markdown b/whip.html.markdown index b8852ecb..3429ec24 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -109,18 +109,18 @@ undefined ; user to indicate a value that hasn't been set ; Dictionaries are Whip's equivalent to JavaScript 'objects' or Python 'dicts' ; or Ruby 'hashes': an unordered collection of key-value pairs. -{"key1":"value1" "key2":2 3:3} +{"key1" "value1" "key2" 2 3 3} ; Keys are just values, either identifier, number, or string. -(def my_dict {my_key:"my_value" "my other key":4}) -; But in Whip, dictionaries get parsed like: value, colon, value; -; with whitespace between each. So that means -{"key": "value" +(def my_dict {my_key "my_value" "my other key" 4}) +; But in Whip, dictionaries get parsed like: value, whitespace, value; +; with more whitespace between each. So that means +{"key" "value" "another key" -: 1234 +1234 } ; is evaluated to the same as -{"key":"value" "another key":1234} +{"key" "value" "another key" 1234} ; Dictionary definitions can be accessed used the `at` function ; (like strings and lists.) @@ -220,8 +220,8 @@ undefined ; user to indicate a value that hasn't been set (max (1 2 3 4)) ; 4 ; If value is in list or object (elem 1 (1 2 3)) ; true -(elem "foo" {"foo":"bar"}) ; true -(elem "bar" {"foo":"bar"}) ; false +(elem "foo" {"foo" "bar"}) ; true +(elem "bar" {"foo" "bar"}) ; false ; Reverse list order (reverse (1 2 3 4)) ; => (4 3 2 1) ; If value is even or odd -- cgit v1.2.3 From 081564a08af8b048e0b6f61e92d14b19d0918b0c Mon Sep 17 00:00:00 2001 From: rduerig Date: Sun, 18 Aug 2013 23:39:09 +0200 Subject: improved python german a little bit --- de-de/python-de.html.markdown | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 6803f98b..7462d5f6 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -28,17 +28,17 @@ Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber au # Die Zahlen 3 #=> 3 -# Mathematik ist das, was man erwartet +# Mathematik funktioniert so, wie man das erwartet 1 + 1 #=> 2 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 -# Division ist ein wenig kniffliger. Es ist ganzzahlige Division -# und rundet automatisch ab. +# Division ist ein wenig kniffliger. Ganze Zahlen werden ohne Rest dividiert +# und das Ergebnis wird automatisch abgerundet. 5 / 2 #=> 2 -# Um das zu ändern, müssen wir Gleitkommazahlen kennenlernen. +# Um das zu ändern, müssen wir Gleitkommazahlen einführen und benutzen 2.0 # Das ist eine Gleitkommazahl 11.0 / 4.0 #=> 2.75 Ahhh...schon besser @@ -57,7 +57,7 @@ not False #=> True 1 == 1 #=> True 2 == 1 #=> False -# Ungleichheit is != +# Ungleichheit ist != 1 != 1 #=> False 2 != 1 #=> True @@ -84,7 +84,7 @@ not False #=> True # Mit % können Strings formatiert werden, etwa so: "%s können %s werden" % ("Strings", "interpoliert") -# Ein neuerer Weg, um Strings zu formatieren, ist die format-Methode. +# Ein modernerer Weg, um Strings zu formatieren, ist die format-Methode. # Diese Methode wird bevorzugt "{0} können {1} werden".format("Strings", "formatiert") # Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. @@ -112,7 +112,7 @@ None is None #=> True ## 2. Variablen und Collections #################################################### -# Ausgabe ist sehr einfach +# Textausgabe ist sehr einfach print "Ich bin Python. Schön, dich kennenzulernen!" @@ -120,8 +120,9 @@ print "Ich bin Python. Schön, dich kennenzulernen!" some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm some_var #=> 5 -# Eine noch nicht deklarierte Variable anzusprechen, löst eine Exception aus. -# Siehe Kontrollstruktur, um mehr über Ausnahmebehandlung zu lernen. +# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus. +# Unter "Kontrollstruktur" kann noch mehr über +# Ausnahmebehandlung erfahren werden. some_other_var # Löst einen NameError aus # if kann als Ausdruck verwendet werden @@ -139,7 +140,7 @@ li.append(4) #li ist jetzt [1, 2, 4] li.append(3) #li ist jetzt [1, 2, 4, 3] # Vom Ende der Liste mit pop entfernen li.pop() #=> 3 und li ist jetzt [1, 2, 4] -# Fügen wir es wieder hinzu +# und dann wieder hinzufügen li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. # Greife auf Listen wie auf Arrays zu @@ -147,7 +148,7 @@ li[0] #=> 1 # Das letzte Element ansehen li[-1] #=> 3 -# Außerhalb der Liste ist es ein IndexError +# Bei Zugriffen außerhal der Liste kommt es jedoch zu einem IndexError li[4] # Raises an IndexError # Wir können uns Ranges mit Slice-Syntax ansehen @@ -249,7 +250,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6} # Die Differenz einer Menge mit - bilden {1,2,3,4} - {2,3,5} #=> {1, 4} -# Auf Vorhandensein mit in prüfen +# Auf Vorhandensein von Elementen mit in prüfen 2 in filled_set #=> True 10 in filled_set #=> False @@ -417,7 +418,7 @@ class Human(object): # Eine Instanz einer Klasse erstellen i = Human(name="Ian") -print i.say("hi") # gitbt "Ian: hi" aus +print i.say("hi") # gibt "Ian: hi" aus j = Human("Joel") print j.say("hello") #gibt "Joel: hello" aus -- cgit v1.2.3 From d7dba39dd6a210507f7fccd4dfe2eb1d435f3dbf Mon Sep 17 00:00:00 2001 From: wikibook Date: Mon, 19 Aug 2013 10:53:22 +0900 Subject: correct errata of Java tutorial --- ko-kr/java-kr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ko-kr/java-kr.html.markdown b/ko-kr/java-kr.html.markdown index dcca9b2e..d00775ae 100644 --- a/ko-kr/java-kr.html.markdown +++ b/ko-kr/java-kr.html.markdown @@ -253,7 +253,7 @@ public class LearnJava { // String // 형변환 - // 자바 객채 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이 많을뿐더러 + // 자바 객체 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이 많을뿐더러 // 다소 중급 수준에 해당하는 개념들도 다뤄야 합니다. // 이와 관련된 사항은 아래 링크를 참고하세요. // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html -- cgit v1.2.3 From 4e7f0ce330914cded8be937b8e5f1700350623d2 Mon Sep 17 00:00:00 2001 From: wikibook Date: Mon, 19 Aug 2013 17:24:12 +0900 Subject: added korean version of coffeescript and php tutorials --- ko-kr/coffeescript-kr.html.markdown | 58 ++++ ko-kr/php-kr.html.markdown | 662 ++++++++++++++++++++++++++++++++++++ 2 files changed, 720 insertions(+) create mode 100644 ko-kr/coffeescript-kr.html.markdown create mode 100644 ko-kr/php-kr.html.markdown diff --git a/ko-kr/coffeescript-kr.html.markdown b/ko-kr/coffeescript-kr.html.markdown new file mode 100644 index 00000000..7d00a0fe --- /dev/null +++ b/ko-kr/coffeescript-kr.html.markdown @@ -0,0 +1,58 @@ +--- +language: coffeescript +category: language +contributors: + - ["Tenor Biel", "http://github.com/L8D"] +filename: coffeescript.coffee +translators: + - ["wikibook", "http://wikibook.co.kr"] +lang: ko-kr +--- + +``` coffeescript +# 커피스크립트(CoffeeScript)는 최신 유행을 따르는 언어입니다. +# 커피스크립트는 여러 현대 언어의 트렌드를 따르는데, +# 그래서 주석을 작성할 때는 루비나 파이썬과 같이 해시를 씁니다. + +### +블록 주석은 이처럼 작성하며, 자바스크립트 코드로 만들어지도록 +'/ *'와 '* /'로 직접적으로 변환됩니다. + +계속하기에 앞서 자바스크립트 시맨틱을 대부분 이해하고 있어야 합니다. +### + +# 할당: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# 조건문: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# 함수: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +# 범위: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# 객체: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +#} + +# 가변 인자(splat): +race = (winner, runners...) -> + print winner, runners + +# 존재 여부 확인: +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# 배열 조건 제시법(comprehensions): +cubes = (math.cube num for num in list) #=> ... +``` diff --git a/ko-kr/php-kr.html.markdown b/ko-kr/php-kr.html.markdown new file mode 100644 index 00000000..2382a8fb --- /dev/null +++ b/ko-kr/php-kr.html.markdown @@ -0,0 +1,662 @@ +--- +language: php +category: language +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +filename: learnphp.php +translators: + - ["wikibook", "http://wikibook.co.kr"] +lang: ko-kr +--- + +이 문서에서는 PHP 5+를 설명합니다. + + +```php + +Hello World Again! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (a leading 0 denotes an octal number) +$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) + +// Float (doubles로도 알려짐) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// 산술 연산 +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// 축약형 산술 연산 +$number = 0; +$number += 1; // $number를 1만큼 증가 +echo $number++; // 1을 출력(평가 후 증가) +echo ++$number; // 3 (평가 전 증가) +$number /= $float; // 나눗셈 후 몫을 $number에 할당 + +// 문자열은 작은따옴표로 감싸야 합니다. +$sgl_quotes = '$String'; // => '$String' + +// 다른 변수를 포함할 때를 제외하면 큰따옴표 사용을 자제합니다. +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// 특수 문자는 큰따옴표에서만 이스케이프됩니다. +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// 필요할 경우 변수를 중괄호로 감쌉니다. +$money = "I have $${number} in the bank."; + +// PHP 5.3부터는 여러 줄 문자열을 생성하는 데 나우닥(nowdoc)을 사용할 수 있습니다. +$nowdoc = <<<'END' +Multi line +string +END; + +// 히어닥(heredoc)에서는 문자열 치환을 지원합니다. +$heredoc = << 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4에서는 새로운 문법이 도입됐습니다. +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // 1을 출력 + +// 리스트 리터럴은 암시적으로 정수형 키를 할당합니다. +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + + +/******************************** + * 출력 + */ + +echo('Hello World!'); +// 표준출력(stdout)에 Hello World!를 출력합니다. +// 브라우저에서 실행할 경우 표준출력은 웹 페이지입니다. + +print('Hello World!'); // echo과 동일 + +// echo는 실제로 언어 구성물에 해당하므로, 괄호를 생략할 수 있습니다. +echo 'Hello World!'; +print 'Hello World!'; // 똑같이 출력됩니다. + +$paragraph = 'paragraph'; + +echo 100; // 스칼라 변수는 곧바로 출력합니다. +echo $paragraph; // 또는 변수의 값을 출력합니다. + +// 축약형 여는 태그를 설정하거나 PHP 버전이 5.4.0 이상이면 +// 축약된 echo 문법을 사용할 수 있습니다. +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + + +/******************************** + * 로직 + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert는 인자가 참이 아닌 경우 경고를 출력합니다. + +// 다음과 같은 비교는 항상 참이며, 타입이 같지 않더라도 마찬가지입니다. +assert($a == $b); // 동일성 검사 +assert($c != $a); // 불일치성 검사 +assert($c <> $a); // 또 다른 불일치성 검사 +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// 다음과 같은 코드는 값과 타입이 모두 일치하는 경우에만 참입니다. +assert($c === $d); +assert($a !== $d); +assert(1 == '1'); +assert(1 !== '1'); + +// 변수는 어떻게 사용하느냐 따라 다른 타입으로 변환될 수 있습니다. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (문자열이 강제로 정수로 변환됩니다) + +$string = 'one'; +echo $string + $string; // => 0 +// + 연산자는 'one'이라는 문자열을 숫자로 형변환할 수 없기 때문에 0이 출력됩니다. + +// 한 변수를 다른 타입으로 처리하는 데 형변환을 사용할 수 있습니다. + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// 대다수의 타입을 형변환하는 데 사용하는 전용 함수도 있습니다. +$integer = 5; +$string = strval($integer); + +$var = null; // 널 타입 + + +/******************************** + * 제어 구조 + */ + +if (true) { + print 'I get printed'; +} + +if (false) { + print 'I don\'t'; +} else { + print 'I get printed'; +} + +if (false) { + print 'Does not get printed'; +} elseif(true) { + print 'Does'; +} + +// 사항 연산자 +print (false ? 'Does not get printed' : 'Does'); + +$x = 0; +if ($x === '0') { + print 'Does not print'; +} elseif($x == '1') { + print 'Does not print'; +} else { + print 'Does print'; +} + + + +// 다음과 같은 문법은 템플릿에 유용합니다. +?> + + +This is displayed if the test is truthy. + +This is displayed otherwise. + + + 2, 'car' => 4]; + +// foreach 문은 배영를 순회할 수 있습니다. +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // "24"를 출력 + +echo "\n"; + +// 키와 값을 동시에 순회할 수 있습니다. +foreach ($wheels as $vehicle => $wheel_count) { + echo "A $vehicle has $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // while 문을 빠져나옴 + } + echo $i++; +} // "012"를 출력 + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // 이번 순회를 생략 + } + echo $i; +} // "0124"를 출력 + + +/******************************** + * 함수 + */ + +// "function"으로 함수를 정의합니다. +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// 유효한 함수명은 문자나 밑줄로 시작하고, 이어서 +// 임의 개수의 문자나 숫자, 밑줄이 옵니다. + +function add ($x, $y = 1) { // $y는 선택사항이고 기본값은 1입니다. + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// 함수 밖에서는 $result에 접근할 수 없습니다. +// print $result; // 이 코드를 실행하면 경고가 출력됩니다. + +// PHP 5.3부터는 익명 함수를 선언할 수 있습니다. +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// 함수에서는 함수를 반환할 수 있습니다. +function bar ($x, $y) { + // 'use'를 이용해 바깥 함수의 변수를 전달합니다. + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // "A - B - C"를 출력 + +// 문자열을 이용해 이름이 지정된 함수를 호출할 수 있습니다. +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// 프로그램 방식으로 어느 함수를 실행할지 결정할 때 유용합니다. +// 아니면 call_user_func(callable $callback [, $parameter [, ... ]]);를 사용해도 됩니다. + +/******************************** + * 인클루드 + */ + +instanceProp = $instanceProp; + } + + // 메서드는 클래스 안의 함수로서 선언됩니다. + public function myMethod() + { + print 'MyClass'; + } + + final function youCannotOverrideMe() + { + } + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +echo MyClass::MY_CONST; // 'value' 출력 +echo MyClass::$staticVar; // 'static' 출력 +MyClass::myStaticMethod(); // 'I am static' 출력 + +// new를 사용해 클래스를 인스턴스화합니다. +$my_class = new MyClass('An instance property'); +// 인자를 전달하지 않을 경우 괄호를 생략할 수 있습니다. + +// ->를 이용해 클래스 멤버에 접근합니다 +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// "extends"를 이용해 클래스를 확장합니다. +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // 메서드 재정의 + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => "protected" 출력 +$my_other_class->myMethod(); // "MyClass > MyOtherClass" 출력 + +final class YouCannotExtendMe +{ +} + +// "마법 메서드(magic method)"로 설정자 메서드와 접근자 메서드를 만들 수 있습니다. +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // __get() 메서드를 사용 +$x->property = 'Something'; // __set() 메서드를 사용 + +// 클래스는 추상화하거나(abstract 키워드를 사용해) +// 인터페이스를 구현할 수 있습니다(implments 키워드를 사용해). +// 인터페이스는 interface 키워드로 선언합니다. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// 인터페이스는 확장할 수 있습니다. +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// 클래스에서는 하나 이상의 인터페이스를 구현할 수 있습니다. +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * 특성 + */ + +// 특성(trait)은 PHP 5.4.0부터 사용 가능하며, "trait"으로 선언합니다. + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // "I have MyTrait"을 출력 + + +/******************************** + * 네임스페이스 + */ + +// 이 부분은 별도의 영역인데, 파일에서 처음으로 나타나는 문장은 +// 네임스페이스 선언이어야 하기 때문입니다. 여기서는 그런 경우가 아니라고 가정합니다. + + Date: Mon, 19 Aug 2013 14:14:05 +0300 Subject: turkish translation for c language --- tr-tr/c-tr.html.markdown | 417 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 417 insertions(+) create mode 100644 tr-tr/c-tr.html.markdown diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown new file mode 100644 index 00000000..1f9db274 --- /dev/null +++ b/tr-tr/c-tr.html.markdown @@ -0,0 +1,417 @@ +--- +name: c +category: language +language: c +filename: learnc-tr.c +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Haydar KULEKCI", "http://scanf.info/"] +lang: tr-tr + +--- +/* +C halen modern yüksek performans bilgisayarların dili. + +C bir çok programcının kullandığı en düşük seviye dillerdendir, ama +salt hız ile daha fazlasını karşılar. C'nin bellek yönetiminden iyi +anlarsanız sizi isteğiniz yere götürecektir. + +```c +// Tek satır yorum // karakterleri ile başlar + +/* +Çoklu satırlı yorumlar bu şekilde görünür. +*/ + +// #include ile header dosyalarınız dahil edin. +#include +#include +#include + +// Fonksiyonlarınızı bir .h dosyasında ya da c dosyanızın üst tarafta +// tanımlayın. + +void function_1(); +void function_2(); + +// Programınızın giriş noktası main isimli bir fonksiyondur ve +// integer değer döner +int main() { + +// çıktıları yazdırmak için printf kullanılır, "print formatted" +// %d bir sayı tipidir, \n yeni satır karakteridir +printf("%d\n", 0); // => 0 karakteri yazdırılır. +// Tüm ifadeler noktalı virgül ile bitmelidir. + +/////////////////////////////////////// +// Tipler +/////////////////////////////////////// + +// Değişkenleri kullanmadan önce tanımlamalısınız. Bir değişken tanımlarken +// tipini belirtmelisiniz; bu tip onun byte olarak boyutunu belirler. + +// int değişken tipi 4 byte boyutundadır. +int x_int = 0; + +// short değişken tipi genellikle 2 byte boyutundadır. +short x_short = 0; + +// char tipi 1 byte boyutunu garanti eder. +char x_char = 0; +char y_char = 'y'; // Karakterler '' işaretleri arasına yazılır. + +// long tipi 4-8 byte olur; long long tipi en azından 64 bit garantiler. +long x_long = 0; +long long x_long_long = 0; + +// float tipi 32-bit kayan noktalı sayı boyutundadır. +float x_float = 0.0; + +// double değişken tipi 64-bit kayan noktalı yazı tipindedir. +double x_double = 0.0; + +// Integral türleri işaretsiz olabilir. Bunun anlamı, onlar eksi değer +// olamaz demektir, ama aynı boyuttaki işaretsiz bir sayının maksimum +// değeri işaretli bir sayının maksimum değeriden büyük olur. +unsigned char ux_char; +unsigned short ux_short; +unsigned int ux_int; +unsigned long long ux_long_long; + +// Diğer taraftan char, ki her zaman bir byte boyutundadır, bu tipler +// makinenize göre boyut değiştirir. sizeof(T) size bir değişkenin byte +// cinsinden boyutunu verir öyle ki bu tipin boyutunu taşınabilir bir +// şekilde ifade edilebilir +// Örneğin, +printf("%lu\n", sizeof(int)); // => 4 (on machines with 4-byte words) + +// Diziler somut bir boyut ile oluşturulmalıdır. +char my_char_array[20]; // Bu dizi 1 * 20 = 20 byte alan kaplar +int my_int_array[20]; // Bu dizi 4 * 20 = 80 byte alan kaplar + // (4-byte bir word varsayılır) + +// Şu şekilde bir diziyi 0 ile oluşturabilirsiniz: +char my_array[20] = {0}; + +// Dizinin elemanlarını indexlemek diğer diller gibidir, veya +// diğer diller C gibi. +my_array[0]; // => 0 + +// Diziler değişebilirdir (mutable); O sadece memory! +my_array[1] = 2; +printf("%d\n", my_array[1]); // => 2 + +// String'ler bir NUL (0x00) byte ile sonlandırılmış karakter dizileridir, +// bu string içerisinde özel bir karakter olan '\0' ile gösterilir. +// (Biz Nul byte'i string karakterleri arasında bulundurmamıza gerek +// yoktur; derleyici onu bizim için dizinin sonuna ekler.) +char a_string[20] = "This is a string"; +printf("%s\n", a_string); // %s bir string formatıdır. + +/* +a_string 16 karakter uzunluğundadır. +17. karakter NUL karakteridir. +18., 19. ve 20. karakterler tanımsızdır.(undefined) +*/ + +printf("%d\n", a_string[16]); // => 0 + +/////////////////////////////////////// +// Operatörler +/////////////////////////////////////// + +int i1 = 1, i2 = 2; // Çoklu tanımlama için kısayol. +float f1 = 1.0, f2 = 2.0; + +// Aritmatik basittir. +i1 + i2; // => 3 +i2 - i1; // => 1 +i2 * i1; // => 2 +i1 / i2; // => 0 (0.5'dir ama 0 a yuvarlanmıştır.) + +f1 / f2; // => 0.5, artı veya eksi epsilon + +// Modüler aritmetikte vardır. +11 % 3; // => 2 + +// Karşılaştırma operatörleri muhtemelen tanıdıktır, ama +// C'de boolean tipi yoktur. Bunun yerine sayı(int) kullanırız. +// 0 false yerine ve diğer herşey true yerine geçmektedir. +// (Karşılaştırma operatörleri her zaman 0 veya 1 dönmektedir.) +3 == 2; // => 0 (false) +3 != 2; // => 1 (true) +3 > 2; // => 1 +3 < 2; // => 0 +2 <= 2; // => 1 +2 >= 2; // => 1 + +// Sayılar üzerinde mantık işlemleri +!3; // => 0 (Logical not) +!0; // => 1 +1 && 1; // => 1 (Logical and) +0 && 1; // => 0 +0 || 1; // => 1 (Logical or) +0 || 0; // => 0 + +// Bit boyutunda işlem yapmak için operatörler +~0x0F; // => 0xF0 (bitwise negation) +0x0F & 0xF0; // => 0x00 (bitwise AND) +0x0F | 0xF0; // => 0xFF (bitwise OR) +0x04 ^ 0x0F; // => 0x0B (bitwise XOR) +0x01 << 1; // => 0x02 (bitwise left shift (by 1)) +0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) + +/////////////////////////////////////// +// Kontrol Yapıları +/////////////////////////////////////// + +if (0) { + printf("I am never run\n"); +} else if (0) { + printf("I am also never run\n"); +} else { + printf("I print\n"); +} + +// While Döngüsü +int ii = 0; +while (ii < 10) { + printf("%d, ", ii++); // ii++, ii değişkenini değerini kullandıktan sonra artırır. +} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + +printf("\n"); + +int kk = 0; +do { + printf("%d, ", kk); +} while (++kk < 10); // ++kk, kk değişkeninin değerini kullanmadan önce artırır. +// => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + +printf("\n"); + +// For Döngüsü +int jj; +for (jj=0; jj < 10; jj++) { + printf("%d, ", jj); +} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + +printf("\n"); + +/////////////////////////////////////// +// Tip Dönüşümleri +/////////////////////////////////////// + +// C'de her değer bir tipe sahiptir, ama siz bir değeri bir başka tipe +// dönüştürebilirsiniz. + +int x_hex = 0x01; // Hex literatüründe değer atayabilirsiniz. + +// Türler arasındaki dönüşümde kendi değerini korumak için çalışacaktır. +printf("%d\n", x_hex); // => Prints 1 +printf("%d\n", (short) x_hex); // => Prints 1 +printf("%d\n", (char) x_hex); // => Prints 1 + +// Tip hiçbir hata vermeden taşacaktır(overflow). +printf("%d\n", (char) 257); // => 1 (Max char = 255) + +// Integral tipi kayan noktalı yazı tipine dönüştürülecektir ve tam tersi. +printf("%f\n", (float)100); // %f formats a float +printf("%lf\n", (double)100); // %lf formats a double +printf("%d\n", (char)100.0); + +/////////////////////////////////////// +// İşaretçiler (Pointers) +/////////////////////////////////////// + +// Bir işaretci bellek adresini barındıran bir değişkendir. Tanımlaması ile işaret +// edeceği verinin tipi de belirtilecektir. Değişkenlerininzi bellek adreslerini +// getirerek bellek ile ilgili karışıklığı ortadan kaldırabilirsiniz. + +int x = 0; +printf("%p\n", &x); // & işareti bir değişkenin bellek adresini getirmek için kullanılır. +// (%p işaretçilerin formatıdır) +// => Bazı bellek adresleri yazdırılacaktır. + + +// İşaretçiler tanımlanırken * ile başlar +int *px, not_a_pointer; // px sayı tipinde bir işaretçidir. +px = &x; // X değişkeninin bellek adresi px değişkeninde tutulmaktadır. +printf("%p\n", px); // => x değişkeninin bellek adresi yazdırılacaktır. +printf("%d, %d\n", (int)sizeof(px), (int)sizeof(not_a_pointer)); +// => 64-bit sistemde "8, 4" yazdırılacaktır. + +// İşaretçinin adres olarak gösterdiği yerdeki değeri almak için +// değişkenin önüne * işareti ekleyiniz. +printf("%d\n", *px); // => 0 bastıracaktır, x in değeridir, + // çünkü px değişkeni x in adresini göstermektedir. + +// Ayrıca siz işaretçinin gösterdiği yerin değerini +// değiştirebilirsiniz. Burada referansı parantez içerisinde göstereceğiz +// çünkü ++ işleminin önceliği * işleminden yüksektir. +(*px)++; // px'in işaret ettiği değeri 1 artır. +printf("%d\n", *px); // => 1 yazdırılır. +printf("%d\n", x); // => 1 yazdırılır. + +int x_array[20]; // Diziler(arrays) bellekten yan yana bellek bloklarını + // tahsis etmek için iyi bir yöntemdir. +int xx; +for (xx=0; xx<20; xx++) { + x_array[xx] = 20 - xx; +} // x_array dizisi 20, 19, 18,... 2, 1 değerleri ile oluşturuluyor. + +// Bir sayı tipinde işaretçi tanımlanıyor ve x_array'i işaret ediyor. +int* x_ptr = x_array; +// x_ptr artık dizinin ilk elemanını işaret etmektedir (the integer 20). +// Bu çalışacaktır çünkü diziler(arrays) aslında sadece onların ilk +// elemanlarını gösteren birer işaretçidir. + +// Diziler ilk elemanlarını gösteren birer işaretçidirler. +printf("%d\n", *(x_ptr)); // => 20 yazılacaktır. +printf("%d\n", x_array[0]); // => 20 yazılacaktır. + +// İşaretçiler kendi tiplerinde artırılır ve azaltılır. +printf("%d\n", *(x_ptr + 1)); // => 19 yazılacaktır. +printf("%d\n", x_array[1]); // => 19 yazılacaktır. + +// Ayrıca dinamik olarak bir bellek bloğunu standart kütüphanede bulunan +// malloc fonksiyonu ile uygulamanız için ayırabilirsiniz. Bu fonksiyon +// byte türünden ayırmak istediğiniz bloğun boyutunu parametre olarak alır. +int* my_ptr = (int*) malloc(sizeof(int) * 20); +for (xx=0; xx<20; xx++) { + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx 'de aynı zamanda çalışabilir +} // Bellekte 20, 19, 18, 17... 2, 1 (as ints) şeklinde oluşturulmuş olacaktır. + +// Eğer ayrımadığınız bir bellek adresini çağırırsanız +// öngörülmeyen bir değer dönecektir. +printf("%d\n", *(my_ptr + 21)); // => kim-bilir-ne-yazacak? + +// Malloc fonksiyonu ile ayrıdığınız bellek kısmı ile işiniz bittiğinde +// onu free fonksiyonu ile boşaltmalısınız, aksi durumda uygulamanız +// kapatılana kadar belleğin o kısmını kimse kullanamaz. +free(my_ptr); + +// Metin Dizileri(String) birer karakter dizisidir(char array), ama +// genelde karakter işaretçisi olarak kullanılır. +char* my_str = "This is my very own string"; + +printf("%c\n", *my_str); // => 'T' + +function_1(); +} // main fonksiyon sonu + +/////////////////////////////////////// +// Fonksiyonlar +/////////////////////////////////////// + +// Fonksiyon tanımlama sözdizimi: +// () + +int add_two_ints(int x1, int x2){ + return x1 + x2; // bir değer geri döndürmek için return kullanılır. +} + +/* +Fonksiyonlar pass-by-value'dür, ama isterseniz işaretçi referanslarını +kullanarak fonksiyona gönderilen parametrenin değerini değiştirebilirsiniz. + +Example: Bir metni tersine çevirme +*/ + +// Bir void konksiyonu hiç bir değer dönmez +void str_reverse(char* str_in){ + char tmp; + int ii=0, len = strlen(str_in); // Strlen C'nin standart kütüphanesinin bir fonksiyonu + for(ii=0; ii ".tset a si sihT" +*/ + +/////////////////////////////////////// +// Kullanıcı Tanımlı Tipler ve Yapılar +/////////////////////////////////////// + +// Typedef'ler bir tip takma adı oluşturur. +typedef int my_type; +my_type my_type_var = 0; + +// Struct'lar bir veri koleksiyonudur. +struct rectangle { + int width; + int height; +}; + + +void function_1(){ + + struct rectangle my_rec; + + // "." ile yapı üyelerine ulaşılabilir. + my_rec.width = 10; + my_rec.height = 20; + + // Bir yapının adresini işaretçiye atayabilirsiniz. + struct rectangle* my_rec_ptr = &my_rec; + + // İşaretçi üzerinden bir yapıya ulaşabilirsiniz. + (*my_rec_ptr).width = 30; + + // ya da -> işareti ile yapının elemanlarına ulaşabilirsiniz. + my_rec_ptr->height = 10; // (*my_rec_ptr).height = 10; ile aynıdır. +} + +// Kolaylık sağlamak için bir yapıya typedef tanımlayabilirsiniz. +typedef struct rectangle rect; + +int area(rect r){ + return r.width * r.height; +} + +/////////////////////////////////////// +// Fonksiyon İşaretçiler +/////////////////////////////////////// + +/* +Çalışma zamanında, fonksiyonların bilinen bir bellek adresleri vardır. Fonksiyon +işaretçileri fonksiyonları direk olarak çağırmayı sağlayan veya geri bildirim(callback) +için parametre gönderirken kullanılan başka birer işaretçidirler. Ama, syntax tanımı +başlangıçta biraz karışık gelebilir. + +Örnek: bir işaretçiden str_reverse kullanımı +*/ +void str_reverse_through_pointer(char * str_in) { + // f adında bir fonksiyon işaretçisi tanımlanır. + void (*f)(char *); // Signature should exactly match the target function. + f = &str_reverse; // Assign the address for the actual function (determined at runtime) + (*f)(str_in); // Just calling the function through the pointer + // f(str_in); // That's an alternative but equally valid syntax for calling it. +} + +/* +As long as function signatures match, you can assign any function to the same pointer. +Function pointers are usually typedef'd for simplicity and readability, as follows: +*/ + +typedef void (*my_fnp_type)(char *); + +// Gerçek bir işaretçi tanımlandığı zaman ki kullanımı: +// ... +// my_fnp_type f; + +``` + +## Daha Fazla Okuma Listesi + +[K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)'in bir kopyasını bulundurmak mükemmel olabilir + +Diğer bir iyi kaynak ise [Learn C the hard way](http://c.learncodethehardway.org/book/) + +Diğer taraftan google sizin için bir arkadaş olabilir. -- cgit v1.2.3 From f6b7d0b2c02de143df5992fa10e5284bf72132d3 Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Mon, 19 Aug 2013 14:41:44 +0300 Subject: some updates turkish translation for latest updates of forked repo --- tr-tr/c-tr.html.markdown | 585 ++++++++++++++++++++++++++--------------------- 1 file changed, 326 insertions(+), 259 deletions(-) diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 1f9db274..50bca246 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -24,11 +24,16 @@ anlarsanız sizi isteğiniz yere götürecektir. Çoklu satırlı yorumlar bu şekilde görünür. */ -// #include ile header dosyalarınız dahil edin. +// C Standart kütüphanelerini uygulamanıza #include ile +// dahil edebilirsiniz. #include #include #include +// Kendi başlık(header) dosyalarınız dahil etmek için "çift tırnak" +// kullanmalısınız. +#include "my_header.h" + // Fonksiyonlarınızı bir .h dosyasında ya da c dosyanızın üst tarafta // tanımlayın. @@ -39,265 +44,317 @@ void function_2(); // integer değer döner int main() { -// çıktıları yazdırmak için printf kullanılır, "print formatted" -// %d bir sayı tipidir, \n yeni satır karakteridir -printf("%d\n", 0); // => 0 karakteri yazdırılır. -// Tüm ifadeler noktalı virgül ile bitmelidir. - -/////////////////////////////////////// -// Tipler -/////////////////////////////////////// - -// Değişkenleri kullanmadan önce tanımlamalısınız. Bir değişken tanımlarken -// tipini belirtmelisiniz; bu tip onun byte olarak boyutunu belirler. - -// int değişken tipi 4 byte boyutundadır. -int x_int = 0; - -// short değişken tipi genellikle 2 byte boyutundadır. -short x_short = 0; - -// char tipi 1 byte boyutunu garanti eder. -char x_char = 0; -char y_char = 'y'; // Karakterler '' işaretleri arasına yazılır. - -// long tipi 4-8 byte olur; long long tipi en azından 64 bit garantiler. -long x_long = 0; -long long x_long_long = 0; - -// float tipi 32-bit kayan noktalı sayı boyutundadır. -float x_float = 0.0; - -// double değişken tipi 64-bit kayan noktalı yazı tipindedir. -double x_double = 0.0; - -// Integral türleri işaretsiz olabilir. Bunun anlamı, onlar eksi değer -// olamaz demektir, ama aynı boyuttaki işaretsiz bir sayının maksimum -// değeri işaretli bir sayının maksimum değeriden büyük olur. -unsigned char ux_char; -unsigned short ux_short; -unsigned int ux_int; -unsigned long long ux_long_long; - -// Diğer taraftan char, ki her zaman bir byte boyutundadır, bu tipler -// makinenize göre boyut değiştirir. sizeof(T) size bir değişkenin byte -// cinsinden boyutunu verir öyle ki bu tipin boyutunu taşınabilir bir -// şekilde ifade edilebilir -// Örneğin, -printf("%lu\n", sizeof(int)); // => 4 (on machines with 4-byte words) - -// Diziler somut bir boyut ile oluşturulmalıdır. -char my_char_array[20]; // Bu dizi 1 * 20 = 20 byte alan kaplar -int my_int_array[20]; // Bu dizi 4 * 20 = 80 byte alan kaplar - // (4-byte bir word varsayılır) - -// Şu şekilde bir diziyi 0 ile oluşturabilirsiniz: -char my_array[20] = {0}; - -// Dizinin elemanlarını indexlemek diğer diller gibidir, veya -// diğer diller C gibi. -my_array[0]; // => 0 - -// Diziler değişebilirdir (mutable); O sadece memory! -my_array[1] = 2; -printf("%d\n", my_array[1]); // => 2 - -// String'ler bir NUL (0x00) byte ile sonlandırılmış karakter dizileridir, -// bu string içerisinde özel bir karakter olan '\0' ile gösterilir. -// (Biz Nul byte'i string karakterleri arasında bulundurmamıza gerek -// yoktur; derleyici onu bizim için dizinin sonuna ekler.) -char a_string[20] = "This is a string"; -printf("%s\n", a_string); // %s bir string formatıdır. - -/* -a_string 16 karakter uzunluğundadır. -17. karakter NUL karakteridir. -18., 19. ve 20. karakterler tanımsızdır.(undefined) -*/ - -printf("%d\n", a_string[16]); // => 0 - -/////////////////////////////////////// -// Operatörler -/////////////////////////////////////// - -int i1 = 1, i2 = 2; // Çoklu tanımlama için kısayol. -float f1 = 1.0, f2 = 2.0; - -// Aritmatik basittir. -i1 + i2; // => 3 -i2 - i1; // => 1 -i2 * i1; // => 2 -i1 / i2; // => 0 (0.5'dir ama 0 a yuvarlanmıştır.) - -f1 / f2; // => 0.5, artı veya eksi epsilon - -// Modüler aritmetikte vardır. -11 % 3; // => 2 - -// Karşılaştırma operatörleri muhtemelen tanıdıktır, ama -// C'de boolean tipi yoktur. Bunun yerine sayı(int) kullanırız. -// 0 false yerine ve diğer herşey true yerine geçmektedir. -// (Karşılaştırma operatörleri her zaman 0 veya 1 dönmektedir.) -3 == 2; // => 0 (false) -3 != 2; // => 1 (true) -3 > 2; // => 1 -3 < 2; // => 0 -2 <= 2; // => 1 -2 >= 2; // => 1 - -// Sayılar üzerinde mantık işlemleri -!3; // => 0 (Logical not) -!0; // => 1 -1 && 1; // => 1 (Logical and) -0 && 1; // => 0 -0 || 1; // => 1 (Logical or) -0 || 0; // => 0 - -// Bit boyutunda işlem yapmak için operatörler -~0x0F; // => 0xF0 (bitwise negation) -0x0F & 0xF0; // => 0x00 (bitwise AND) -0x0F | 0xF0; // => 0xFF (bitwise OR) -0x04 ^ 0x0F; // => 0x0B (bitwise XOR) -0x01 << 1; // => 0x02 (bitwise left shift (by 1)) -0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) - -/////////////////////////////////////// -// Kontrol Yapıları -/////////////////////////////////////// - -if (0) { - printf("I am never run\n"); -} else if (0) { - printf("I am also never run\n"); -} else { - printf("I print\n"); -} - -// While Döngüsü -int ii = 0; -while (ii < 10) { - printf("%d, ", ii++); // ii++, ii değişkenini değerini kullandıktan sonra artırır. -} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - -printf("\n"); - -int kk = 0; -do { - printf("%d, ", kk); -} while (++kk < 10); // ++kk, kk değişkeninin değerini kullanmadan önce artırır. -// => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - -printf("\n"); - -// For Döngüsü -int jj; -for (jj=0; jj < 10; jj++) { - printf("%d, ", jj); -} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - -printf("\n"); - -/////////////////////////////////////// -// Tip Dönüşümleri -/////////////////////////////////////// - -// C'de her değer bir tipe sahiptir, ama siz bir değeri bir başka tipe -// dönüştürebilirsiniz. - -int x_hex = 0x01; // Hex literatüründe değer atayabilirsiniz. - -// Türler arasındaki dönüşümde kendi değerini korumak için çalışacaktır. -printf("%d\n", x_hex); // => Prints 1 -printf("%d\n", (short) x_hex); // => Prints 1 -printf("%d\n", (char) x_hex); // => Prints 1 - -// Tip hiçbir hata vermeden taşacaktır(overflow). -printf("%d\n", (char) 257); // => 1 (Max char = 255) - -// Integral tipi kayan noktalı yazı tipine dönüştürülecektir ve tam tersi. -printf("%f\n", (float)100); // %f formats a float -printf("%lf\n", (double)100); // %lf formats a double -printf("%d\n", (char)100.0); - -/////////////////////////////////////// -// İşaretçiler (Pointers) -/////////////////////////////////////// + // çıktıları yazdırmak için printf kullanılır, "print formatted" + // %d bir sayı tipidir, \n yeni satır karakteridir + printf("%d\n", 0); // => 0 karakteri yazdırılır. + // Tüm ifadeler noktalı virgül ile bitmelidir. + + /////////////////////////////////////// + // Tipler + /////////////////////////////////////// + + // Değişkenleri kullanmadan önce tanımlamalısınız. Bir değişken tanımlarken + // tipini belirtmelisiniz; bu tip onun byte olarak boyutunu belirler. + + // int değişken tipi 4 byte boyutundadır. + int x_int = 0; + + // short değişken tipi genellikle 2 byte boyutundadır. + short x_short = 0; + + // char tipi 1 byte boyutunu garanti eder. + char x_char = 0; + char y_char = 'y'; // Karakterler '' işaretleri arasına yazılır. + + // long tipi 4-8 byte olur; long long tipi en azından 64 bit garantiler. + long x_long = 0; + long long x_long_long = 0; + + // float tipi 32-bit kayan noktalı sayı boyutundadır. + float x_float = 0.0; + + // double değişken tipi 64-bit kayan noktalı yazı tipindedir. + double x_double = 0.0; + + // Integral türleri işaretsiz olabilir. Bunun anlamı, onlar eksi değer + // olamaz demektir, ama aynı boyuttaki işaretsiz bir sayının maksimum + // değeri işaretli bir sayının maksimum değeriden büyük olur. + unsigned char ux_char; + unsigned short ux_short; + unsigned int ux_int; + unsigned long long ux_long_long; + + // Diğer taraftan char, ki her zaman bir byte boyutundadır, bu tipler + // makinenize göre boyut değiştirir. sizeof(T) size bir değişkenin byte + // cinsinden boyutunu verir öyle ki bu tipin boyutunu taşınabilir bir + // şekilde ifade edilebilir + // Örneğin, + printf("%lu\n", sizeof(int)); // => 4 (bir çok makinede 4-byte words) + + // If the argument of the `sizeof` operator an expression, then its argument + // is not evaluated (except VLAs (see below)). + // The value it yields in this case is a compile-time constant. + int a = 1; + size_t size = sizeof(a++); // a++ is not evaluated + printf("sizeof(a++) = %zu where a = %d\n", size, a); + // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) + + // Diziler somut bir boyut ile oluşturulmalıdır. + char my_char_array[20]; // Bu dizi 1 * 20 = 20 byte alan kaplar + int my_int_array[20]; // Bu dizi 4 * 20 = 80 byte alan kaplar + // (4-byte bir word varsayılır) + + // Şu şekilde bir diziyi 0 ile oluşturabilirsiniz: + char my_array[20] = {0}; + + // Dizinin elemanlarını indexlemek diğer diller gibidir, veya + // diğer diller C gibi. + my_array[0]; // => 0 + + // Diziler değişebilirdir (mutable); O sadece memory! + my_array[1] = 2; + printf("%d\n", my_array[1]); // => 2 + + // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) + // can be declared as well. The size of such an array need not be a compile + // time constant: + printf("Enter the array size: "); // ask the user for an array size + char buf[0x100]; + fgets(buf, sizeof buf, stdin); + + // strtoul parses a string to an unsigned integer + size_t size = strtoul(buf, NULL, 10); + int var_length_array[size]; // declare the VLA + printf("sizeof array = %zu\n", sizeof var_length_array); + + // A possible outcome of this program may be: + // > Enter the array size: 10 + // > sizeof array = 40 + + // String'ler bir NUL (0x00) byte ile sonlandırılmış karakter dizileridir, + // bu string içerisinde özel bir karakter olan '\0' ile gösterilir. + // (Biz Nul byte'i string karakterleri arasında bulundurmamıza gerek + // yoktur; derleyici onu bizim için dizinin sonuna ekler.) + char a_string[20] = "This is a string"; + printf("%s\n", a_string); // %s bir string formatıdır. + + /* + a_string 16 karakter uzunluğundadır. + 17. karakter NUL karakteridir. + 18., 19. ve 20. karakterler tanımsızdır.(undefined) + */ + + printf("%d\n", a_string[16]); // => 0 + // i.e., byte #17 is 0 (as are 18, 19, and 20) + + // If we have characters between single quotes, that's a character literal. + // It's of type `int`, and *not* `char` (for historical reasons). + int cha = 'a'; // fine + char chb = 'a'; // fine too (implicit conversion from int to char) + + /////////////////////////////////////// + // Operatörler + /////////////////////////////////////// + + int i1 = 1, i2 = 2; // Çoklu tanımlama için kısayol. + float f1 = 1.0, f2 = 2.0; + + // Aritmatik basittir. + i1 + i2; // => 3 + i2 - i1; // => 1 + i2 * i1; // => 2 + i1 / i2; // => 0 (0.5'dir ama 0 a yuvarlanmıştır.) + + f1 / f2; // => 0.5, artı veya eksi epsilon + + // Modüler aritmetikte vardır. + 11 % 3; // => 2 + + // Karşılaştırma operatörleri muhtemelen tanıdıktır, ama + // C'de boolean tipi yoktur. Bunun yerine sayı(int) kullanırız. + // 0 false yerine ve diğer herşey true yerine geçmektedir. + // (Karşılaştırma operatörleri her zaman 0 veya 1 dönmektedir.) + 3 == 2; // => 0 (false) + 3 != 2; // => 1 (true) + 3 > 2; // => 1 + 3 < 2; // => 0 + 2 <= 2; // => 1 + 2 >= 2; // => 1 + + // Sayılar üzerinde mantık işlemleri + !3; // => 0 (Logical not) + !0; // => 1 + 1 && 1; // => 1 (Logical and) + 0 && 1; // => 0 + 0 || 1; // => 1 (Logical or) + 0 || 0; // => 0 + + // Bit boyutunda işlem yapmak için operatörler + ~0x0F; // => 0xF0 (bitwise negation) + 0x0F & 0xF0; // => 0x00 (bitwise AND) + 0x0F | 0xF0; // => 0xFF (bitwise OR) + 0x04 ^ 0x0F; // => 0x0B (bitwise XOR) + 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) + 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) + // - 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 + + /////////////////////////////////////// + // Kontrol Yapıları + /////////////////////////////////////// + + if (0) { + printf("I am never run\n"); + } else if (0) { + printf("I am also never run\n"); + } else { + printf("I print\n"); + } -// Bir işaretci bellek adresini barındıran bir değişkendir. Tanımlaması ile işaret -// edeceği verinin tipi de belirtilecektir. Değişkenlerininzi bellek adreslerini -// getirerek bellek ile ilgili karışıklığı ortadan kaldırabilirsiniz. - -int x = 0; -printf("%p\n", &x); // & işareti bir değişkenin bellek adresini getirmek için kullanılır. -// (%p işaretçilerin formatıdır) -// => Bazı bellek adresleri yazdırılacaktır. - - -// İşaretçiler tanımlanırken * ile başlar -int *px, not_a_pointer; // px sayı tipinde bir işaretçidir. -px = &x; // X değişkeninin bellek adresi px değişkeninde tutulmaktadır. -printf("%p\n", px); // => x değişkeninin bellek adresi yazdırılacaktır. -printf("%d, %d\n", (int)sizeof(px), (int)sizeof(not_a_pointer)); -// => 64-bit sistemde "8, 4" yazdırılacaktır. - -// İşaretçinin adres olarak gösterdiği yerdeki değeri almak için -// değişkenin önüne * işareti ekleyiniz. -printf("%d\n", *px); // => 0 bastıracaktır, x in değeridir, - // çünkü px değişkeni x in adresini göstermektedir. - -// Ayrıca siz işaretçinin gösterdiği yerin değerini -// değiştirebilirsiniz. Burada referansı parantez içerisinde göstereceğiz -// çünkü ++ işleminin önceliği * işleminden yüksektir. -(*px)++; // px'in işaret ettiği değeri 1 artır. -printf("%d\n", *px); // => 1 yazdırılır. -printf("%d\n", x); // => 1 yazdırılır. - -int x_array[20]; // Diziler(arrays) bellekten yan yana bellek bloklarını - // tahsis etmek için iyi bir yöntemdir. -int xx; -for (xx=0; xx<20; xx++) { - x_array[xx] = 20 - xx; -} // x_array dizisi 20, 19, 18,... 2, 1 değerleri ile oluşturuluyor. - -// Bir sayı tipinde işaretçi tanımlanıyor ve x_array'i işaret ediyor. -int* x_ptr = x_array; -// x_ptr artık dizinin ilk elemanını işaret etmektedir (the integer 20). -// Bu çalışacaktır çünkü diziler(arrays) aslında sadece onların ilk -// elemanlarını gösteren birer işaretçidir. - -// Diziler ilk elemanlarını gösteren birer işaretçidirler. -printf("%d\n", *(x_ptr)); // => 20 yazılacaktır. -printf("%d\n", x_array[0]); // => 20 yazılacaktır. - -// İşaretçiler kendi tiplerinde artırılır ve azaltılır. -printf("%d\n", *(x_ptr + 1)); // => 19 yazılacaktır. -printf("%d\n", x_array[1]); // => 19 yazılacaktır. - -// Ayrıca dinamik olarak bir bellek bloğunu standart kütüphanede bulunan -// malloc fonksiyonu ile uygulamanız için ayırabilirsiniz. Bu fonksiyon -// byte türünden ayırmak istediğiniz bloğun boyutunu parametre olarak alır. -int* my_ptr = (int*) malloc(sizeof(int) * 20); -for (xx=0; xx<20; xx++) { - *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx 'de aynı zamanda çalışabilir -} // Bellekte 20, 19, 18, 17... 2, 1 (as ints) şeklinde oluşturulmuş olacaktır. - -// Eğer ayrımadığınız bir bellek adresini çağırırsanız -// öngörülmeyen bir değer dönecektir. -printf("%d\n", *(my_ptr + 21)); // => kim-bilir-ne-yazacak? - -// Malloc fonksiyonu ile ayrıdığınız bellek kısmı ile işiniz bittiğinde -// onu free fonksiyonu ile boşaltmalısınız, aksi durumda uygulamanız -// kapatılana kadar belleğin o kısmını kimse kullanamaz. -free(my_ptr); - -// Metin Dizileri(String) birer karakter dizisidir(char array), ama -// genelde karakter işaretçisi olarak kullanılır. -char* my_str = "This is my very own string"; - -printf("%c\n", *my_str); // => 'T' - -function_1(); + // While Döngüsü + int ii = 0; + while (ii < 10) { + printf("%d, ", ii++); // ii++, ii değişkenini değerini kullandıktan sonra artırır. + } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + int kk = 0; + do { + printf("%d, ", kk); + } while (++kk < 10); // ++kk, kk değişkeninin değerini kullanmadan önce artırır. + // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + // For Döngüsü + int jj; + for (jj=0; jj < 10; jj++) { + printf("%d, ", jj); + } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + /////////////////////////////////////// + // Tip Dönüşümleri + /////////////////////////////////////// + + // C'de her değer bir tipe sahiptir, ama siz bir değeri bir başka tipe + // dönüştürebilirsiniz. + + int x_hex = 0x01; // Hex literatüründe değer atayabilirsiniz. + + // Türler arasındaki dönüşümde kendi değerini korumak için çalışacaktır. + printf("%d\n", x_hex); // => Prints 1 + printf("%d\n", (short) x_hex); // => Prints 1 + printf("%d\n", (char) x_hex); // => Prints 1 + + // Tip hiçbir hata vermeden taşacaktır(overflow). + printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 eğer karakter 8 bit uzunluğunda ise) + + // `char`, `signed char` ve `unsigned char` karakter tiplerinin maksimum uzunluğunu + // belirlemek için kütüphanesindeki CHAR_MAX, SCHAR_MAX ve UCHAR_MAX + // macrolarını kullanınız. + + // Integral tipi kayan noktalı yazı tipine dönüştürülecektir ve tam tersi. + printf("%f\n", (float)100); // %f formats a float + printf("%lf\n", (double)100); // %lf formats a double + printf("%d\n", (char)100.0); + + /////////////////////////////////////// + // İşaretçiler (Pointers) + /////////////////////////////////////// + + // Bir işaretci bellek adresini barındıran bir değişkendir. Tanımlaması ile işaret + // edeceği verinin tipi de belirtilecektir. Değişkenlerininzi bellek adreslerini + // getirerek bellek ile ilgili karışıklığı ortadan kaldırabilirsiniz. + + int x = 0; + printf("%p\n", &x); // & işareti bir değişkenin bellek adresini getirmek için kullanılır. + // (%p işaretçilerin formatıdır) + // => Bazı bellek adresleri yazdırılacaktır. + + + // İşaretçiler tanımlanırken * ile başlar + int *px, not_a_pointer; // px sayı tipinde bir işaretçidir. + px = &x; // X değişkeninin bellek adresi px değişkeninde tutulmaktadır. + printf("%p\n", px); // => x değişkeninin bellek adresi yazdırılacaktır. + printf("%d, %d\n", (int)sizeof(px), (int)sizeof(not_a_pointer)); + // => 64-bit sistemde "8, 4" yazdırılacaktır. + + // İşaretçinin adres olarak gösterdiği yerdeki değeri almak için + // değişkenin önüne * işareti ekleyiniz. + printf("%d\n", *px); // => 0 bastıracaktır, x in değeridir, + // çünkü px değişkeni x in adresini göstermektedir. + + // Ayrıca siz işaretçinin gösterdiği yerin değerini + // değiştirebilirsiniz. Burada referansı parantez içerisinde göstereceğiz + // çünkü ++ işleminin önceliği * işleminden yüksektir. + (*px)++; // px'in işaret ettiği değeri 1 artır. + printf("%d\n", *px); // => 1 yazdırılır. + printf("%d\n", x); // => 1 yazdırılır. + + int x_array[20]; // Diziler(arrays) bellekten yan yana bellek bloklarını + // tahsis etmek için iyi bir yöntemdir. + int xx; + for (xx=0; xx<20; xx++) { + x_array[xx] = 20 - xx; + } // x_array dizisi 20, 19, 18,... 2, 1 değerleri ile oluşturuluyor. + + // Bir sayı tipinde işaretçi tanımlanıyor ve x_array'i işaret ediyor. + int* x_ptr = x_array; + // x_ptr artık dizinin ilk elemanını işaret etmektedir (the integer 20). + // Bu çalışacaktır çünkü diziler(arrays) aslında sadece onların ilk + // elemanlarını gösteren birer işaretçidir. + // For example, when an array is passed to a function or is assigned to a pointer, + // it decays into (implicitly converted to) a pointer. + // Exceptions: when the array is the argument of the `&` (address-od) operator: + int arr[10]; + int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`! + // It's of type "pointer to array" (of ten `int`s). + // or when the array is a string literal used for initializing a char array: + char arr[] = "foobarbazquirk"; + // or when it's the argument of the `sizeof` or `alignof` operator: + int arr[10]; + int *ptr = arr; // equivalent with int *ptr = &arr[0]; + printf("%zu %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8" + + // Diziler ilk elemanlarını gösteren birer işaretçidirler. + printf("%d\n", *(x_ptr)); // => 20 yazılacaktır. + printf("%d\n", x_array[0]); // => 20 yazılacaktır. + + // İşaretçiler kendi tiplerinde artırılır ve azaltılır. + printf("%d\n", *(x_ptr + 1)); // => 19 yazılacaktır. + printf("%d\n", x_array[1]); // => 19 yazılacaktır. + + // Ayrıca dinamik olarak bir bellek bloğunu standart kütüphanede bulunan + // malloc fonksiyonu ile uygulamanız için ayırabilirsiniz. Bu fonksiyon + // byte türünden ayırmak istediğiniz bloğun boyutunu parametre olarak alır. + int* my_ptr = (int*) malloc(sizeof(int) * 20); + for (xx=0; xx<20; xx++) { + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx 'de aynı zamanda çalışabilir + } // Bellekte 20, 19, 18, 17... 2, 1 (as ints) şeklinde oluşturulmuş olacaktır. + + // Eğer ayrımadığınız bir bellek adresini çağırırsanız + // öngörülmeyen bir değer dönecektir. + printf("%d\n", *(my_ptr + 21)); // => kim-bilir-ne-yazacak? + + // Malloc fonksiyonu ile ayrıdığınız bellek kısmı ile işiniz bittiğinde + // onu free fonksiyonu ile boşaltmalısınız, aksi durumda uygulamanız + // kapatılana kadar belleğin o kısmını kimse kullanamaz. + free(my_ptr); + + // Metin Dizileri(String) birer karakter dizisidir(char array), ama + // genelde karakter işaretçisi olarak kullanılır. + char* my_str = "This is my very own string"; + + printf("%c\n", *my_str); // => 'T' + + function_1(); } // main fonksiyon sonu /////////////////////////////////////// @@ -349,6 +406,10 @@ struct rectangle { int height; }; +// It's not generally true that +// sizeof(struct rectangle) == sizeof(int) + sizeof(int) +// due to potential padding between the structure members (this is for alignment +// reasons). [1] void function_1(){ @@ -414,4 +475,10 @@ typedef void (*my_fnp_type)(char *); Diğer bir iyi kaynak ise [Learn C the hard way](http://c.learncodethehardway.org/book/) +It's very important to use proper spacing, indentation and to be consistent with your coding style in general. +Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the +[Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle). + Diğer taraftan google sizin için bir arkadaş olabilir. + +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file -- cgit v1.2.3 From f33dea8b83bf64ecde36337a5e02cae77f5210de Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 19 Aug 2013 09:14:02 -0700 Subject: Updates --- README.markdown | 41 ++++- bash.html.markdown | 43 +++-- groovy.html.markdown | 60 ++++--- hu-hu/go.html.markdown | 444 ++++++++++++++++++++++++++----------------------- 4 files changed, 338 insertions(+), 250 deletions(-) diff --git a/README.markdown b/README.markdown index efc2fa07..701b12d7 100644 --- a/README.markdown +++ b/README.markdown @@ -9,18 +9,47 @@ commented code and explained as they go. ... to write more inline code tutorials. Just grab an existing file from this repo and copy the formatting (don't worry, it's all very simple). Make a new file, send a pull request, and if it passes muster I'll get it up pronto. -Remember to fill in the author and author\_url fields so you get credited +Remember to fill in the "contributors" fields so you get credited properly! ### Requests -The most requested languages are: +We've had a ton of interest, b -* Go -* ~~Scala~~ -* ~~Javascript~~ +### Contributing -... but there are many more requests to do "every language", so don't let that stop you. +All contributions welcome, from the tiniest typo to a brand new article. Translations +in all languages are welcome (or, for that matter, original articles in any language). + +#### Style Guidelines + +* Try to keep **line length in code blocks to 80 characters or fewer**, or they'll overflow + and look odd. + +* Try to use as few words as possible. Code examples are preferred over exposition in all cases. + +* We welcome newcomers, but the target audience for this site is programmers with some experience. + So, try to avoid explaining basic concepts except for those specific to the language in question, + to keep articles succinct and scannable. We all know how to use google here. + +* For translations (or english articles with non-ASCII characters), please make sure your file is + utf-8 encoded. + +#### Header configuration + +The actual site uses Middleman to generate HTML files from these markdown ones. Middleman, or at least +the custom scripts underpinning the site, required that some key information be defined in the header. + +The following fields are necessary for english articles about programming languages: + +* **language** The *programming language* in question +* **contributors** A list of [author, url] lists to credit + +Other fields: + +* **filename**: The filename for this article's code. It will be fetched, mashed together, and made downloadable. + For non-english articles, *filename* should have a language-specific suffix. +* **lang**: For translations, the human language this article is in. For categorization, mostly. ## License diff --git a/bash.html.markdown b/bash.html.markdown index 8cf7be18..7421f880 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -1,8 +1,10 @@ --- -language: bash +category: tool +tool: bash contributors: - - ["Max Yankov", "https://github.com/golergka" - "Darren Lin", "https://github.com/CogBear"] + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] filename: LearnBash.sh --- @@ -14,7 +16,8 @@ Nearly all examples below can be a part of a shell script or executed directly i ```bash #!/bin/sh -# First line of the script is shebang which tells the system how to execute the script: http://en.wikipedia.org/wiki/Shebang_(Unix) +# First line of the script is shebang which tells the system how to execute +# the script: http://en.wikipedia.org/wiki/Shebang_(Unix) # As you already figured, comments start with #. Shebang is also a comment. # Simple hello world example: @@ -27,12 +30,15 @@ echo 'This is the first line'; echo 'This is the second line' VARIABLE="Some string" # But not like this: -VARIABLE = "Some string" # Bash will decide that VARIABLE is a command he must execute and give an error because it couldn't be found. +VARIABLE = "Some string" +# Bash will decide that VARIABLE is a command it must execute and give an error +# because it couldn't be found. # Using the variable: echo $VARIABLE echo "$VARIABLE" -# When you use the variable itself — assign it, export it, or else — you write it's name without $. If you want to use variable's value, you should use $. +# 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 $. # Reading a value from input: echo "What's your name?" @@ -42,43 +48,46 @@ echo Hello, $NAME! # We have the usual if structure: if true then - echo "This is expected" + echo "This is expected" else - echo "And this is not" + echo "And this is not" fi # Expressions are denoted with the following format: echo $(( 10 + 5 )) -# Unlike other programming languages, bash is a shell — so it works in a context of current directory. -# You can list files and directories in the current directories with ls command: +# Unlike other programming languages, bash is a shell — so it works in a context +# of current directory. You can list files and directories in the current +# directories with ls command: ls # These commands have options that control their execution: ls -l # Lists every file and directory on a separate line # Results of the previous command can be passed to the next command as input. -# grep command filters the input with provided patterns. That's how we can list txt files in the current directory: +# grep command filters the input with provided patterns. That's how we can list +# txt files in the current directory: ls -l | grep "\.txt" # Commands can be substitued within other commands using $( ): -# The following command displays the number of files and directories in the current directory. +# The following command displays the number of files and directories in the +# current directory. echo "There are $(ls | wc -l) items here." -#Bash uses a case statement that works similarily to switch in Java and C++: +# Bash uses a case statement that works similarily to switch in Java and C++: case "$VARIABLE" in - #List patterns for the conditions you want to meet - 0) echo "There is a zero." - 1) echo "There is a one." - *) echo "It is not null." + #List patterns for the conditions you want to meet + 0) echo "There is a zero." + 1) echo "There is a one." + *) 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 do - echo "$VARIABLE" + echo "$VARIABLE" done ``` diff --git a/groovy.html.markdown b/groovy.html.markdown index e4c2180b..1a635e59 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -112,14 +112,31 @@ println devMap.values() When Groovy is compiled to bytecode, the following rules are used. - * If the name is declared with an access modifier (public, private or protected) then a field is generated. - * A name declared with no access modifier generates a private field with public getter and setter (i.e. a property). - * If a property is declared final the private field is created final and no setter is generated. + * If the name is declared with an access modifier (public, private or + protected) then a field is generated. + + * A name declared with no access modifier generates a private field with + public getter and setter (i.e. a property). + + * If a property is declared final the private field is created final and no + setter is generated. + * You can declare a property and also declare your own getter or setter. - * You can declare a property and a field of the same name, the property will use that field then. - * If you want a private or protected property you have to provide your own getter and setter which must be declared private or protected. - * If you access a property from within the class the property is defined in at compile time with implicit or explicit this (for example this.foo, or simply foo), Groovy will access the field directly instead of going though the getter and setter. - * If you access a property that does not exist using the explicit or implicit foo, then Groovy will access the property through the meta class, which may fail at runtime. + + * You can declare a property and a field of the same name, the property will + use that field then. + + * If you want a private or protected property you have to provide your own + getter and setter which must be declared private or protected. + + * If you access a property from within the class the property is defined in + at compile time with implicit or explicit this (for example this.foo, or + simply foo), Groovy will access the field directly instead of going though + the getter and setter. + + * If you access a property that does not exist using the explicit or + implicit foo, then Groovy will access the property through the meta class, + which may fail at runtime. */ @@ -185,13 +202,14 @@ for ( e in map ) { /* Operators - Operator Overloading for a list of the common operators that Groovy supports: http://groovy.codehaus.org/Operator+Overloading + Operator Overloading for a list of the common operators that Groovy supports: + http://groovy.codehaus.org/Operator+Overloading Helpful groovy operators */ //Spread operator: invoke an action on all items of an aggregate object. def technologies = ['Groovy','Grails','Gradle'] -technologies*.toUpperCase() //equivalent to: technologies.collect { it?.toUpperCase() } +technologies*.toUpperCase() // = to technologies.collect { it?.toUpperCase() } //Safe navigation operator: used to avoid a NullPointerException. def user = User.get(1) @@ -200,7 +218,8 @@ def username = user?.username /* Closures - A Groovy Closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point. + A Groovy Closure is like a "code block" or a method pointer. It is a piece of + code that is defined and then executed at a later point. More info at: http://groovy.codehaus.org/Closures+-+Formal+Definition */ @@ -219,16 +238,13 @@ def x = 5 def multiplyBy = { num -> num * x } println multiplyBy(10) -//If you have a Closure that takes a single argument, you may omit the parameter definition of the Closure +// If you have a Closure that takes a single argument, you may omit the +// parameter definition of the Closure def clos = { print it } clos( "hi" ) /* - Groovy can memorize closure results: - More info at: - http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ - http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize - http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html + Groovy can memorize closure results [1][2][3] */ def cl = {a, b -> sleep(3000) // simulate some time consuming processing @@ -256,9 +272,10 @@ callClosure(3, 4) /* Expando - The Expando class is a dynamic bean so we can add properties and we can add closures as methods to an instance of this class + The Expando class is a dynamic bean so we can add properties and we can add + closures as methods to an instance of this class - Reference: http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html + http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html */ def user = new Expando(name:"Roberto") assert 'Roberto' == user.name @@ -310,7 +327,8 @@ assertEquals "boo", f.boo /* TypeChecked and CompileStatic - Groovy, by nature, is and will always be a dynamic language but it supports typechecked and compilestatic + Groovy, by nature, is and will always be a dynamic language but it supports + typechecked and compilestatic More info: http://www.infoq.com/articles/new-groovy-20 */ @@ -373,7 +391,9 @@ Join a [Groovy user group](http://groovy.codehaus.org/User+Groups) * [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) - +[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ +[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize +[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html diff --git a/hu-hu/go.html.markdown b/hu-hu/go.html.markdown index b3e8c1ca..460e23ec 100644 --- a/hu-hu/go.html.markdown +++ b/hu-hu/go.html.markdown @@ -1,8 +1,7 @@ --- -name: Go -category: language language: Go -filename: learngo.go +lang: hu-hu +filename: learngo-hu.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] translators: @@ -20,276 +19,307 @@ a mai számítógépek több magos processzorait, ez nagy rendszerek építésé A Go alap könyvtára mindenre területre kiterjed, ennek köszönhetően a nyelvnek egyre növekvő tábora van. -```Go +```go // Egy soros komment /* Több soros komment */ -// Minden forrás fájl egy csomag-definícióval kezdődik, ez hasonlít a Python csomagkezelésére -// A main egy különleges csomagnév, ennek a fordítása futtatható állományt hoz létre egy könyvtár helyett. +// Minden forrás fájl egy csomag-definícióval kezdődik, ez hasonlít a Python +// csomagkezelésére +// A main egy különleges csomagnév, ennek a fordítása futtatható állományt hoz +// létre egy könyvtár helyett. package main -// Az import rész meghatározza melyik csomagokat kívánjuk használni ebben a forrásfájlban +// Az import rész meghatározza melyik csomagokat kívánjuk használni ebben a +// forrásfájlban import ( - "fmt" // A Go alap könyvtárának része - "net/http" // Beépített webszerver! - "strconv" // Stringek átalakítására szolgáló csomag + "fmt" // A Go alap könyvtárának része + "net/http" // Beépített webszerver! + "strconv" // Stringek átalakítására szolgáló csomag ) // Funkció deklarás, a main nevű funkció a program kezdőpontja. func main() { - // Println kiírja a beadott paramétereket a standard kimenetre. - // Ha más csomagot funkcióját akarjuk használni, akkor azt jelezni kell a csomag nevével - fmt.Println("Hello world!") + // Println kiírja a beadott paramétereket a standard kimenetre. + // Ha más csomagot funkcióját akarjuk használni, akkor azt jelezni kell a + // csomag nevével + fmt.Println("Hello world!") - // Meghívunk egy másik funkciót ebből a csomagból - beyondHello() + // Meghívunk egy másik funkciót ebből a csomagból + beyondHello() } // A függvények paraméterei zárójelek között vannak. // Ha nincsenek paraméterek, akkor is kötelező a zárójel-pár. func beyondHello() { - var x int // Változó deklaráció, használat előtt muszáj ezt megtenni. - x = 3 // Változó értékadás - // "Rövid" deklaráció is létezik, ez az érték alapján deklarálja, definiálja és értéket is ad a változónak - y := 4 - sum, prod := learnMultiple(x, y) // a függvényeknek több visszatérési értéke is lehet - fmt.Println("sum:", sum, "prod:", prod) // egyszerű kiíratás - learnTypes() + var x int // Változó deklaráció, használat előtt muszáj ezt megtenni. + x = 3 // Változó értékadás + // "Rövid" deklaráció is létezik, ez az érték alapján deklarálja, + // definiálja és értéket is ad a változónak + y := 4 + sum, prod := learnMultiple(x, y) // a függvényeknek több + // visszatérési értéke is lehet + fmt.Println("sum:", sum, "prod:", prod) // egyszerű kiíratás + learnTypes() } // A funkcióknak elnevezett visszatérési értékük is lehet func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // visszatérünk két értékkel - /* - sum = x + y - prod = x * y - return - Ez ugyanezzel az eredménnyel járt volna, mint a fenti sor. - Üres return esetén, az elnevezett visszatérési változók - aktuális értékeikkel térnek vissza. */ + return x + y, x * y // visszatérünk két értékkel + /* + sum = x + y + prod = x * y + return + Ez ugyanezzel az eredménnyel járt volna, mint a fenti sor. + Üres return esetén, az elnevezett visszatérési változók + aktuális értékeikkel térnek vissza. */ } // Beépített típusok func learnTypes() { - // Rövid deklarás az esetek többségében elég lesz a változókhoz - s := "Tanulj Go-t!" // string típus - - s2 := `A "nyers" stringekben lehetnek - újsorok is!` // de ettől még ez is ugyanolyan string mint az s, nincs külön típusa - - // nem ASCII karakterek. Minden Go forrás UTF-8 és a stringek is azok. - g := 'Σ' // rúna(rune) típus, megegyezik az uint32-vel, egy UTF-8 karaktert tárol - - f := 3.14195 // float64, az IEEE-754 szabványnak megfelelő 64-bites lebegőpontos szám - c := 3 + 4i // complex128, belsőleg két float64-el tárolva - - // Var szintaxis változó típus definiálással - var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az int-nél - var pi float32 = 22. / 7 - - // Rövid deklarásnál átalakítás is lehetséges - n := byte('\n') // byte típus, ami megegyezik az uint8-al - - // A tömböknek fordítás-időben fixált méretük van - var a4 [4]int // egy tömb 4 int-tel, mind 0-ra inicializálva - a3 := [...]int{3, 1, 5} // egy tömb 3 int-tel, láthatóan inicalizálva egyedi értékekre - - // Szeleteknek dinamikus a méretük. A szeleteknek és a tömböknek is meg vannak az előnyeik - // de a szeleteket sokkal gyakrabban használjuk. - s3 := []int{4, 5, 9} // vesd össze a3-al, nincsenek pontok. - s4 := make([]int, 4) // allokál 4 int-et, mind 0-ra inicializálva - var d2 [][]float64 // ez csak deklaráció, semmi sincs még allokálva - bs := []byte("a slice") // típus konverzió szintaxisa - - p, q := learnMemory() // deklarál két mutatót (p,q), két int-re - fmt.Println(*p, *q) // * követi a mutatót. Ez a sor kiírja a két int értékét. - - // A map a dinamikusan növelhető asszociatív tömb része a nyelvnek, hasonlít - // a hash és dictionary típusokra más nyelvekben. - m := map[string]int{"three": 3, "four": 4} - m["one"] = 1 - - // A felhasználatlan változók fordítás-idejű hibát okoznak a Go-ban. - // Az aláhúzással "használod" a változókat, de eldobod az értéküket. - _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs - // Kiíratás is természetesen használatnak minősül - fmt.Println(s, c, a4, s3, d2, m) - - learnFlowControl() + // Rövid deklarás az esetek többségében elég lesz a változókhoz + s := "Tanulj Go-t!" // string típus + + s2 := `A "nyers" stringekben lehetnek + újsorok is!` // de ettől még ez is ugyanolyan string mint az s, nincs külön + // típusa + + // nem ASCII karakterek. Minden Go forrás UTF-8 és a stringek is azok. + g := 'Σ' // rúna(rune) típus, megegyezik az uint32-vel, egy UTF-8 karaktert + // tárol + + f := 3.14195 // float64, az IEEE-754 szabványnak megfelelő 64-bites + // lebegőpontos szám + c := 3 + 4i // complex128, belsőleg két float64-el tárolva + + // Var szintaxis változó típus definiálással + var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az + // int-nél + var pi float32 = 22. / 7 + + // Rövid deklarásnál átalakítás is lehetséges + n := byte('\n') // byte típus, ami megegyezik az uint8-al + + // A tömböknek fordítás-időben fixált méretük van + var a4 [4]int // egy tömb 4 int-tel, mind 0-ra inicializálva + a3 := [...]int{3, 1, 5} // egy tömb 3 int-tel, láthatóan inicalizálva egyedi + // értékekre + + // Szeleteknek dinamikus a méretük. A szeleteknek és a tömböknek is meg + // vannak az előnyeik de a szeleteket sokkal gyakrabban használjuk. + s3 := []int{4, 5, 9} // vesd össze a3-al, nincsenek pontok. + s4 := make([]int, 4) // allokál 4 int-et, mind 0-ra inicializálva + var d2 [][]float64 // ez csak deklaráció, semmi sincs még allokálva + bs := []byte("a slice") // típus konverzió szintaxisa + + p, q := learnMemory() // deklarál két mutatót (p,q), két int-re + fmt.Println(*p, *q) // * követi a mutatót. Ez a sor kiírja a két int értékét. + + // A map a dinamikusan növelhető asszociatív tömb része a nyelvnek, hasonlít + // a hash és dictionary típusokra más nyelvekben. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // A felhasználatlan változók fordítás-idejű hibát okoznak a Go-ban. + // Az aláhúzással "használod" a változókat, de eldobod az értéküket. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Kiíratás is természetesen használatnak minősül + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() } -// A Go nyelv teljesen szemétgyűjtött (garbage-collected). Megtalálhatók benne mutatók, de nincs mutató aritmetika. -// Ez azt jelenti, hogy üres mutatóval még mindig hibázhatsz, de hozzáadni/műveleteket végezni már nem lehet. +// A Go nyelv teljesen szemétgyűjtött (garbage-collected). Megtalálhatók benne +// mutatók, de nincs mutató aritmetika. Ez azt jelenti, hogy üres mutatóval még +// mindig hibázhatsz, de hozzáadni/műveleteket végezni már nem lehet. func learnMemory() (p, q *int) { - // Elnevezett visszatérési változóknak int-re mutató a típusa - p = new(int) // a beépített "new" funkció, egy típusnak elegendő memóriát allokál, és visszaad rá egy mutatót. - // Az allokált int nullázva van, p többé nem üres mutató. - s := make([]int, 20) // allokáljunk 20 int változót egy memóriaterületen. - s[3] = 7 // adjunk értéket az egyiknek - r := -2 // hozzánk létre egy lokális változót - return &s[3], &r // A & megadja a memóriacímét a változónak + // Elnevezett visszatérési változóknak int-re mutató a típusa + p = new(int) // a beépített "new" funkció, egy típusnak elegendő memóriát + // allokál, és visszaad rá egy mutatót. + // Az allokált int nullázva van, p többé nem üres mutató. + s := make([]int, 20) // allokáljunk 20 int változót egy memóriaterületen. + s[3] = 7 // adjunk értéket az egyiknek + r := -2 // hozzánk létre egy lokális változót + return &s[3], &r // A & megadja a memóriacímét a változónak } func expensiveComputation() int { - return 1e6 + return 1e6 } func learnFlowControl() { - // Az elágazásoknak kötelező a kapcsos zárójel, a zárójel nem szükséges. - if true { - fmt.Println("megmondtam") - } - // A kód formátumát a nyelvvel járó "go" parancssori program "go fmt" parancsa szabványosítja - if false { - // így lehet - } else { - // if/else-t csinálni - } - // Használjunk switchet a hosszabb elágazások alkalmazása helyett. - x := 1 - switch x { - case 0: - case 1: - // Az "esetek" nem "esnek át", tehát - case 2: - // ez nem fog lefutni, nincs szükség break-ekre. - } - // A for ciklus sem használ zárójeleket - for x := 0; x < 3; x++ { - fmt.Println("iteráció", x) - } - // itt az x == 1. - - // A for az egyetlen ciklus fajta a Go-ban, de több formája van. - for { // végtelen ciklus - break // csak vicceltem - continue // soha nem fut le - } - // Akárcsak a for-nál, az if-ben is lehet rövid deklarással egy lokális változót létrehozni - // ami az blokk összes if/else-n keresztül érvényes marad. - if y := expensiveComputation(); y > x { - x = y - } - // Függvényeket használhatjuk closure-ként is. - xBig := func() bool { - return x > 100 // a switch felett deklarált x-et használjuk itt - } - fmt.Println("xBig:", xBig()) // igaz (utoljára 1e6 lett az értéke az x-nek) - x /= 1e5 // így most már x == 10 - fmt.Println("xBig:", xBig()) // 10 pedig kisebb mint 100, tehát hamis - - // Ha nagyon-nagyon szükséges, akkor használhatjuk a jó öreg goto-t. - goto love + // Az elágazásoknak kötelező a kapcsos zárójel, a zárójel nem szükséges. + if true { + fmt.Println("megmondtam") + } + // A kód formátumát a nyelvvel járó "go" parancssori program "go fmt" + // parancsa szabványosítja + if false { + // így lehet + } else { + // if/else-t csinálni + } + // Használjunk switchet a hosszabb elágazások alkalmazása helyett. + x := 1 + switch x { + case 0: + case 1: + // Az "esetek" nem "esnek át", tehát + case 2: + // ez nem fog lefutni, nincs szükség break-ekre. + } + // A for ciklus sem használ zárójeleket + for x := 0; x < 3; x++ { + fmt.Println("iteráció", x) + } + // itt az x == 1. + + // A for az egyetlen ciklus fajta a Go-ban, de több formája van. + for { // végtelen ciklus + break // csak vicceltem + continue // soha nem fut le + } + // Akárcsak a for-nál, az if-ben is lehet rövid deklarással egy lokális + // változót létrehozni ami az blokk összes if/else-n keresztül érvényes + // marad. + if y := expensiveComputation(); y > x { + x = y + } + // Függvényeket használhatjuk closure-ként is. + xBig := func() bool { + return x > 100 // a switch felett deklarált x-et használjuk itt + } + fmt.Println("xBig:", xBig()) // igaz (utoljára 1e6 lett az értéke az x-nek) + x /= 1e5 // így most már x == 10 + fmt.Println("xBig:", xBig()) // 10 pedig kisebb mint 100, tehát hamis + + // Ha nagyon-nagyon szükséges, akkor használhatjuk a jó öreg goto-t. + goto love love: - learnInterfaces() // Itt kezdődnek az érdekes dolgok! + learnInterfaces() // Itt kezdődnek az érdekes dolgok! } -// Definiáljuk a Stringert egy olyan interfésznek, amelynek egy metódusa van, a String, ami visszatér egy stringgel. +// Definiáljuk a Stringert egy olyan interfésznek, amelynek egy metódusa van, a +// String, ami visszatér egy stringgel. type Stringer interface { - String() string + String() string } -// Definiáljuk a pair-t egy olyan struktúrának amelynek két int változója van, x és y. +// Definiáljuk a pair-t egy olyan struktúrának amelynek két int változója van, +// x és y. type pair struct { - x, y int + x, y int } -// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer interf +// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer +// interf func (p pair) String() string { // p lesz a "vevő" - // Sprintf az fmt csomag egy publikus függvénye, műkődése megegyezik a C-s megfelelőjével. - // A pontokkal érjük el a mindenkori p struktúra elemeit - return fmt.Sprintf("(%d, %d)", p.x, p.y) + // Sprintf az fmt csomag egy publikus függvénye, műkődése megegyezik a C-s + // megfelelőjével. A pontokkal érjük el a mindenkori p struktúra elemeit + return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { - // A kapcsos zárójellel jelezzük, hogy egyből inicializálni - // szeretnénk a struktúra változóit a sorrendnek megfelelően. - p := pair{3, 4} - fmt.Println(p.String()) // meghívjuk a p String metódusát. - var i Stringer // deklaráljuk i-t Stringer típusú interfésznek - i = p // lehetséges, mert a pair struktúra eleget tesz a Stringer interfésznek - // Meghívjuk i String metódusát, az eredmény ugyanaz, mint az előbb. - fmt.Println(i.String()) - - // Az fmt csomag funckciói automatikusan meghívják a String funkciót - // hogy megtudják egy objektum szöveges reprezentációját. - fmt.Println(p) // ugyan az az eredmény mint az előbb, a Println meghívja a String metódust. - fmt.Println(i) // dettó - - learnErrorHandling() + // A kapcsos zárójellel jelezzük, hogy egyből inicializálni + // szeretnénk a struktúra változóit a sorrendnek megfelelően. + p := pair{3, 4} + fmt.Println(p.String()) // meghívjuk a p String metódusát. + var i Stringer // deklaráljuk i-t Stringer típusú interfésznek + i = p // lehetséges, mert a pair struktúra eleget tesz a + // Stringer interfésznek + // Meghívjuk i String metódusát, az eredmény ugyanaz, mint az előbb. + fmt.Println(i.String()) + + // Az fmt csomag funckciói automatikusan meghívják a String funkciót + // hogy megtudják egy objektum szöveges reprezentációját. + fmt.Println(p) // ugyan az az eredmény mint az előbb, a Println meghívja + // a String metódust. + fmt.Println(i) // dettó + + learnErrorHandling() } func learnErrorHandling() { - // ", ok" szokásos megoldás arra, hogy jól működött-e a függvény. - m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok hamis lesz, mert az 1 nincs benne a map-ban. - fmt.Println("nincs meg") - } else { - fmt.Print(x) // x lenne az érték, ha benne lenne a map-ban. - } - // A hiba érték többet is elmond a függvény kimeneteléről, mint hogy minden "ok" volt-e - if _, err := strconv.Atoi("non-int"); err != nil { // _ eldobja az értéket, úgy se lesz jó jelen esetben - // kiírja, hogy "strconv.ParseInt: parsing "non-int": invalid syntax" - fmt.Println(err) - } - // Az interfészekre még visszatérünk, addig is jöjjön a konkurens programozás! - learnConcurrency() + // ", ok" szokásos megoldás arra, hogy jól működött-e a függvény. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok hamis lesz, mert az 1 nincs benne a map-ban. + fmt.Println("nincs meg") + } else { + fmt.Print(x) // x lenne az érték, ha benne lenne a map-ban. + } + // A hiba érték többet is elmond a függvény kimeneteléről, mint hogy minden + // "ok" volt-e + if _, err := strconv.Atoi("non-int"); err != nil { // _ eldobja az értéket, + // úgy se lesz jó jelen + // esetben + // kiírja, hogy "strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // Az interfészekre még visszatérünk, addig is jöjjön a konkurens programozás! + learnConcurrency() } // c egy csatorna, egy konkurens-biztos kommunikációs objektum. func inc(i int, c chan int) { - c <- i + 1 // <- a "küldés" operátor, ha a bal oldalán csatorna van, így i+1-et küld be a csatornába + c <- i + 1 // <- a "küldés" operátor, ha a bal oldalán csatorna van, így + // i+1-et küld be a csatornába } // Az inc-et fogjuk arra használni, hogy konkurensen megnöveljünk számokat func learnConcurrency() { - // Ugyan az a make funkció amivel korábban szeleteket hoztunk létre. - // Make allokál mapokat, szeleteket és csatornákat. - c := make(chan int) - // Indítsunk három konkurens goroutine-t. A számok konkurensen lesznek - // megnövelve, ha a számítógép képes rá és jól be van állítva, akkor pedig paralellizálva/egymás mellett. - // Mind a 3 ugyanabba a csatornába küldi az eredményeket. - go inc(0, c) // A go utasítás indít el goroutine-okat. - go inc(10, c) - go inc(-805, c) - // Beolvassuk 3x a csatornából az eredményeket és kiírjuk őket a kimenetre. - // Nem lehet tudni milyen sorrendben fognak érkezni az eredmények! - fmt.Println(<-c, <-c, <-c) // hogyha a jobb oldalon csatorna van, akkor a "<-" a beolvasó/kapó operátor - - cs := make(chan string) // még egy csatorna, ez stringekkel kommunikál - cc := make(chan chan string) // egy csatorna csatornával - go func() { c <- 84 }() // indítsunk egy új goroutine-t, csak azért hogy küldjünk egy számot - go func() { cs <- "wordy" }() // ugyanez, csak a cs csatornába stringet küldünk - // A select olyan mint a switch, csak feltételek helyett csatorna műveletek vannak. - // Véletlenszerűen kiválasztja az első olyan esetet, ahol létrejöhet kommunikáció. - select { - case i := <-c: // a megkapott értéket el lehet tárolni egy változóban - fmt.Println("ez egy", i) - case <-cs: // vagy el lehet dobni az értékét - fmt.Println("ez egy string volt") - case <-cc: // üres csatorna, soha nem fog rajta semmi se érkezni - fmt.Println("sose futok le :'( ") - } - // Ezen a ponton vagy c vagy a cs goroutineja lefutott. - // Amelyik hamarabb végzett, annak a megfelelő case-e lefutott, a másik blokkolva vár. - - learnWebProgramming() // Go képes rá. Te is képes akarsz rá lenni. + // Ugyan az a make funkció amivel korábban szeleteket hoztunk létre. + // Make allokál mapokat, szeleteket és csatornákat. + c := make(chan int) + // Indítsunk három konkurens goroutine-t. A számok konkurensen lesznek + // megnövelve, ha a számítógép képes rá és jól be van állítva, akkor pedig + // paralellizálva/egymás mellett. Mind a 3 ugyanabba a csatornába küldi az + // eredményeket. + go inc(0, c) // A go utasítás indít el goroutine-okat. + go inc(10, c) + go inc(-805, c) + // Beolvassuk 3x a csatornából az eredményeket és kiírjuk őket a kimenetre. + // Nem lehet tudni milyen sorrendben fognak érkezni az eredmények! + fmt.Println(<-c, <-c, <-c) // hogyha a jobb oldalon csatorna van, akkor a + // "<-" a beolvasó/kapó operátor + + cs := make(chan string) // még egy csatorna, ez stringekkel kommunikál + cc := make(chan chan string) // egy csatorna csatornával + go func() { c <- 84 }() // indítsunk egy új goroutine-t, csak azért + // hogy küldjünk egy számot + go func() { cs <- "wordy" }() // ugyanez, csak a cs csatornába stringet + // küldünk + // A select olyan mint a switch, csak feltételek helyett csatorna műveletek + // vannak. Véletlenszerűen kiválasztja az első olyan esetet, ahol létrejöhet + // kommunikáció. + select { + case i := <-c: // a megkapott értéket el lehet tárolni egy változóban + fmt.Println("ez egy", i) + case <-cs: // vagy el lehet dobni az értékét + fmt.Println("ez egy string volt") + case <-cc: // üres csatorna, soha nem fog rajta semmi se érkezni + fmt.Println("sose futok le :'( ") + } + // Ezen a ponton vagy c vagy a cs goroutineja lefutott. + // Amelyik hamarabb végzett, annak a megfelelő case-e lefutott, a másik + // blokkolva vár. + + learnWebProgramming() // Go képes rá. Te is képes akarsz rá lenni. } // Egy funkció a http csomagból elindít egy webszervert. func learnWebProgramming() { - // A ListenAndServe első paramétre egy TCP port, amin kiszolgálunk majd. - // Második paramétere egy interfész, pontosabban a http.Handler interfész. - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // nem felejtük el kiírni az esetleges hibákat! + // A ListenAndServe első paramétre egy TCP port, amin kiszolgálunk majd. + // Második paramétere egy interfész, pontosabban a http.Handler interfész. + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // nem felejtük el kiírni az esetleges hibákat! } -// Csináljunk a pair-ból egy http.Handler-t úgy, hogy implementáljuk az egyetlen metódusát a ServeHTTP-t. +// Csináljunk a pair-ból egy http.Handler-t úgy, hogy implementáljuk az +// egyetlen metódusát a ServeHTTP-t. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Minden kapcsolatra elküldjük ezt a http.ResponseWriter-el - w.Write([]byte("Megtanultad a Go-t Y perc alatt!")) + // Minden kapcsolatra elküldjük ezt a http.ResponseWriter-el + w.Write([]byte("Megtanultad a Go-t Y perc alatt!")) } ``` -- cgit v1.2.3 From ee38941a0ba32160018abe07c9d27a41534ca2ec Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Mon, 19 Aug 2013 11:55:01 -0700 Subject: first draft of learn haxe 3 in 15 minutes --- haxe.html.markdown | 419 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 419 insertions(+) create mode 100644 haxe.html.markdown diff --git a/haxe.html.markdown b/haxe.html.markdown new file mode 100644 index 00000000..c51ae7ce --- /dev/null +++ b/haxe.html.markdown @@ -0,0 +1,419 @@ +--- +language: haxe +filename: LearnHaxe3.hx +contributors: + - ["Justin Donaldson", "https://github.com/jdonaldson/"] +--- + +Haxe is a web-oriented language that provides platform support for C++, C#, +Swf/ActionScript, Javascript, Java, and Neko byte code (also written by the +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 +// 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 +// compiler, while in the same directory as LearnHaxe.hx: +// haxe -main LearnHaxe3 -x + +// Let's start with comments... this is a single line comment + +/* + And this is multiline +*/ + +// A package declaration isn't necessary, but it's useful if you want to +// organize your code into modules later on. Also worth mentioning, all +// expressions in Haxe must end in a semicolon: +package; // empty package, no namespace. + +// if you import code from other files, it must be declared before the rest of +// the code. +import haxe.ds.ArraySort; + +// you can import many classes/modules at once with "*" +import haxe.ds.*; + +// you can also import classes in a special way, enabling them to extend the +// functionality of other classes. More on this later. +using StringTools; + +// Haxe files typically define classes, although they can also define other +// types of code... more on that later. + + +class LearnHaxe3{ + /* + If you want certain code to run automatically, you need to put it in + a static main function, and specify the class in the compiler arguments. + In this case, we've specified the "LearnHaxe3" class in the compiler + arguments above. + */ + static function main(){ + /* + Trace is the default method of printing haxe expressions to the + screen. Different targets will have different methods of + accomplishing this. E.g., java, c++, c#, etc. will print to std + out. Javascript will print to console.log, and flash will print to + an embedded TextField. All traces come with a default newline. + Finally, It's possible to prevent traces from showing by using the + "--no-traces" argument on the compiler. + */ + + + trace("Hello World, with trace()!"); + + /* + Trace can handle any type of value or object. It will try to print + a representation of the expression as best it can: + */ + trace( + " Integer: " + 10 + + " Float: " + 3.14 + + " Boolean: " + true); + + + /* + Remember what I said about expressions needing semicolons? You + can put more than one expression on a line if you want. + */ + trace('two expressions..'); trace('one line'); + + + ////////////////////////////////////////////////////////////////// + // Types & Variables + ////////////////////////////////////////////////////////////////// + trace("***Types & Variables***"); + + /* + You can save values and references to data structures using the + "var" keyword: + */ + + var an_integer:Int = 1; + trace(an_integer + " is the value for an_integer"); + + + /* + Haxe is statically typed, so "an_integer" is declared to have an + "Int" type, and the rest of the expression assigns the value "1" to + it. It's not necessary to declare the type in many cases. Here, + the haxe compiler is inferring that the type of another_integer + should be "Int". + */ + + var another_integer = 2; + trace(another_integer + " is the value for another_integer"); + + // The $type() method prints the type that the compiler assigns: + $type(another_integer); + + // You can also represent integers with hexadecimal: + var hex_integer = 0xffffff; + + /* + Haxe uses platform precision for Int and Float sizes. It also + uses the platform behavior for overflow. + (Other numeric types and behavior are possible using special + libraries) + */ + + /* + In addition to simple values like Integers, Floats, and Booleans, + Haxe provides standard library implementations for common data + structures like strings, arrays, lists, and maps: + */ + + var a_string = "some_string"; // strings can have double or single quotes + trace(a_string + " is the value for a_string"); + + /* + Strings are immutable, instance methods will return a copy of + parts or all of the string. + (See also the StringBuf class). + */ + var a_sub_string = a_string.substr(0,4); + trace(a_sub_string + " is the value for a_sub_string"); + + /* + Arrays are zero-indexed, dynamic, and mutable. Missing values are + defined as null. + */ + var a = new Array(); // an array that contains Strings + a[0] = 'foo'; + trace(a.length + " is the value for a.length"); + a[9] = 'bar'; + trace(a.length + " is the value for a.length (after modification)"); + trace(a[3] + " is the value for a[3]"); //null + + /* + Arrays are *generic*, so you can indicate which values they contain + with a type parameter: + */ + var a2 = new Array(); // an array of Ints + var a3 = new Array>(); // an Array of Arrays (of Strings). + + /* + Maps are simple key/value data structures. The key and the value + can be of any type. + */ + var m = new Map(); // The keys are strings, the values are Ints. + m.set('foo', 4); + // You can also use array notation; + m['bar'] = 5; + trace(m.exists('bar') + " is the value for m.exists('bar')"); + trace(m.get('bar') + " is the value for m.get('bar')"); + trace(m['bar'] + " is the value for m['bar']"); + + var m2 = ['foo' => 4, 'baz' => 6]; // Alternative map syntax + trace(m2 + " is the value for m2"); + + /* + Remember, you can use type inference. The Haxe compiler will + decide the type of the variable the first time you pass an + argument that sets a type parameter. + */ + var m3 = new Map(); + m3.set(6, 'baz'); // m2 is now a Map + trace(m3 + " is the value for m3"); + + /* + Haxe has many more common datastructures in the haxe.ds module, such as + List, Stack, and BalancedTree + */ + + + ////////////////////////////////////////////////////////////////// + // Operators + ////////////////////////////////////////////////////////////////// + + trace("***OPERATORS***"); + + // basic arithmetic + trace((4 + 3) + " is the value for (4 + 3)"); + trace((5 - 1) + " is the value for (5 - 1)"); + trace((2 * 4) + " is the value for (2 * 4)"); + trace((8 / 4) + " is the value for (8 / 3) (division always produces Floats)"); + trace((12 % 4) + " is the value for (12 % 4)"); + + + //basic comparison + trace(3 == 2 + " is the value for 3 == 2"); + trace(3 != 2 + " is the value for 3 != 2"); + trace(3 > 2 + " is the value for 3 > 2"); + trace(3 < 2 + " is the value for 3 < 2"); + trace(3 >= 2 + " is the value for 3 >= 2"); + trace(3 <= 2 + " is the value for 3 <= 2"); + + //bitwise operators + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + >>> Unsigned right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + //increments + var i = 0; + trace("Increments and decrements"); + trace(i++); //i = 1. Post-Incrementation + trace(++i); //i = 2. Pre-Incrementation + trace(i--); //i = 1. Post-Decrementation + trace(--i); //i = 0. Pre-Decrementation + + ////////////////////////////////////////////////////////////////// + // Control Structures + ////////////////////////////////////////////////////////////////// + trace("***CONTROL STRUCTURES***"); + + // if statements + var j = 10; + if (j == 10){ + trace("this is printed"); + } else if (j > 10){ + trace("not greater than 10, so not printed"); + } else { + trace("also not printed."); + } + + trace("Looping and Iteration"); + + // while loop + var k = 0; + while(k < 100){ + // trace(counter); // will print out numbers 0-99 + counter++; + } + + // do-while loop + var l = 0; + do{ + trace("do statement always runs at least once"); + } while (i > 0); + + // for loop + /* + There is no c-style for loop in Haxe, because they are prone + to error, and not necessary. Instead, Haxe has a much simpler + and safer version that uses Iterators (more on those later). + */ + var m = [1,2,3]; + for (val in m){ + trace(val + " is the value for val in the m array"); + } + + // Note that you can iterate on an index using a range + // (more on ranges later as well) + var n = ['foo', 'bar', 'baz']; + for (val in 0...n.length){ + trace(val + " is the value for val (an index for m)"); + } + + + trace("Array Comprehensions"); + + // Array comprehensions give you the ability to iterate over arrays + // while also creating filters and modifications. + var filtered_n = [for (val in n) if (n != "foo")]; + trace(filtered_n + " is the value for filtered_n"); + var modified_n = [for (val in n) n += '!']; + trace(modified_n + " is the value for modified_n"); + var filtered_and_modified_n [for (val in n) if (n != "foo") n += "!"]; + trace(filtered_and_modified_n + " is the value for filtered_and_modified_n"); + + + ////////////////////////////////////////////////////////////////// + // Switch Statements (Value Type) + ////////////////////////////////////////////////////////////////// + trace("***SWITCH STATEMENTS (VALUE TYPES)***"); + + /* + Switch statements in Haxe are very powerful. In addition to working + on basic values like strings and ints, they can also work on the + generalized algebraic data types in enums (more on enums later). + Here's some basic value examples for now: + */ + var my_dog_name = 'fido'; + var favorite_thing = ''; + switch(my_dog_name){ + case "fido" : favorite_thing = 'bone'; + case "rex" : favorite_thing = 'shoe'; + case "spot" : favorite_thing = 'tennis ball'; + case _ : favorite_thing = 'some unknown treat'; + } + // The "_" case above is a "wildcard" value + // that will match anything. + + trace("My dog's name is" + my_dog_name + + ", and his favorite thing is a: " + + favorite_thing); + + ////////////////////////////////////////////////////////////////// + // Converting Value Types + ////////////////////////////////////////////////////////////////// + + // You can convert strings to ints fairly easily. + + // string to integer + Std.parseInt("0"); // returns 0 + Std.parseFloat("0.4"); // returns 0.4; + + // integer to string + Std.toString(0); // returns "0"; + // concatenation with strings will auto-convert to string. + 0 + ""; // returns "0"; + true + ""; // returns "true"; + // See documentation for parsing in Std for more details. + + ////////////////////////////////////////////////////////////////// + // Basic Object Oriented Design + ////////////////////////////////////////////////////////////////// + trace("***BASIC OBJECT ORIENTED DESIGN***"); + + + var instance = new FooClass(3); + // read the public variable normally + trace(instance.public_any + " is the value for instance.public_any"); + + // we can read this variable + trace(instance.public_read + " is the value for instance.public_read"); + // but not write it, this will throw an error if uncommented: + //trace(instance.public_write + " is the value for instance.public_write"); + // trace(instance.public_write); // vice-versa for public write, etc. + + trace(instance + " is the value for instance"); // calls the toString method + + + // we can successfully pass the FooInstance to the BaseFooClass method, + // since it was extended from that. + BaseFooClass.acceptBaseFoo(instance); + } + +} + +/* + This is the "child class" of the main LearnHaxe3 Class + */ +class FooClass extends BaseFooClass implements BaseFooInterface{ + public var public_any:Int; // public variables are accessible anywhere + public var public_read (default,null): Int; // use this style to only enable public read + public var public_write (null, default): Int; // or public write + public var getter_setter (getValue, setValue): Int; // use this style to enable getters/setters + + // private variables are not available outside the class. + // see @:allow for ways around this. + var _private:Int; // variables are private if they are not marked public + + // a public constructor + public function new(arg:Int){ + super(); // call the constructor of the parent object, since we extended BaseFooClass + + this.public_any= 0; + this._private = arg; + + } + + // getter for _private + function getValue() : Int { + return _private; + } + + // setter for _private + function setValue(val:Int) : Void{ + _private = val; + } + + // special function that is called whenever an instance is cast to a string. + public function toString(){ + return _private + " with toString() method!"; + } + + // this class needs to have this function defined, since it implements + // the BaseFooInterface interface. + public function baseFunction(x: Int) : String{ + // convert the int to string automatically + return x + " was passed into baseFunction!"; + } +} + +class BaseFooClass { + var base_variable:Int; + public function new(){ + base_variable = 4; + } + public static function acceptBaseFoo(b:BaseFooClass){ + } + +} + +interface BaseFooInterface{ + public function baseFunction(x:Int):String; +} + + +``` + -- cgit v1.2.3 From 343c20b4e8f2bd71ade87ed70ee63c39e82c5154 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Mon, 19 Aug 2013 12:01:55 -0700 Subject: minor tweak to compiler args --- haxe.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index c51ae7ce..94b4ea82 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -15,7 +15,7 @@ references. // 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 // compiler, while in the same directory as LearnHaxe.hx: -// haxe -main LearnHaxe3 -x +// haxe -main LearnHaxe3 -x out // Let's start with comments... this is a single line comment -- cgit v1.2.3 From 1a9107e43d25bcf06cefc701dbf6784d33898b1a Mon Sep 17 00:00:00 2001 From: Simon Richardson Date: Mon, 19 Aug 2013 20:24:18 +0100 Subject: Update haxe.html.markdown I think one of Haxes strong point is the fact that control structures are expressions as well. We should point this out. --- haxe.html.markdown | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 94b4ea82..0b3c614d 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -284,8 +284,7 @@ class LearnHaxe3{ trace(modified_n + " is the value for modified_n"); var filtered_and_modified_n [for (val in n) if (n != "foo") n += "!"]; trace(filtered_and_modified_n + " is the value for filtered_and_modified_n"); - - + ////////////////////////////////////////////////////////////////// // Switch Statements (Value Type) ////////////////////////////////////////////////////////////////// @@ -311,7 +310,37 @@ class LearnHaxe3{ trace("My dog's name is" + my_dog_name + ", and his favorite thing is a: " + favorite_thing); - + + ////////////////////////////////////////////////////////////////// + // Expression Statements + ////////////////////////////////////////////////////////////////// + trace("***EXPRESSION STATEMENTS***"); + + /* + Haxe control statements are very powerful because every statement + is also an expression, consider: + */ + + // if statements + var k = if (true){ + 10; + } else { + 20; + } + + trace("K equals ", k); // outputs 10 + + var other_favorite_thing = switch(my_dog_name) { + case "fido" : 'teddy'; + case "rex" : 'stick'; + case "spot" : 'football'; + case _ : 'some unknown treat'; + } + + trace("My dog's name is" + my_dog_name + + ", and his other favorite thing is a: " + + other_favorite_thing); + ////////////////////////////////////////////////////////////////// // Converting Value Types ////////////////////////////////////////////////////////////////// -- cgit v1.2.3 From 3b278c3e59926a117dc00c50585045c7e932397a Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Mon, 19 Aug 2013 13:56:01 -0700 Subject: fix getter/setter styles --- haxe.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 0b3c614d..8dd8ba81 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -391,7 +391,7 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ public var public_any:Int; // public variables are accessible anywhere public var public_read (default,null): Int; // use this style to only enable public read public var public_write (null, default): Int; // or public write - public var getter_setter (getValue, setValue): Int; // use this style to enable getters/setters + public var property (get, set): Int; // use this style to enable getters/setters // private variables are not available outside the class. // see @:allow for ways around this. @@ -407,12 +407,12 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ } // getter for _private - function getValue() : Int { + function get_property() : Int { return _private; } // setter for _private - function setValue(val:Int) : Void{ + function set_property(val:Int) : Void{ _private = val; } -- cgit v1.2.3 From 64e889d011a6f0e9968b68b1a982bbe714525cb8 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Mon, 19 Aug 2013 14:09:18 -0700 Subject: fix the other lazy syntax errors --- haxe.html.markdown | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 8dd8ba81..9288fc87 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -199,12 +199,12 @@ class LearnHaxe3{ //basic comparison - trace(3 == 2 + " is the value for 3 == 2"); - trace(3 != 2 + " is the value for 3 != 2"); - trace(3 > 2 + " is the value for 3 > 2"); - trace(3 < 2 + " is the value for 3 < 2"); - trace(3 >= 2 + " is the value for 3 >= 2"); - trace(3 <= 2 + " is the value for 3 <= 2"); + trace((3 == 2) + " is the value for 3 == 2"); + trace((3 != 2) + " is the value for 3 != 2"); + trace((3 > 2) + " is the value for 3 > 2"); + trace((3 < 2) + " is the value for 3 < 2"); + trace((3 >= 2) + " is the value for 3 >= 2"); + trace((3 <= 2) + " is the value for 3 <= 2"); //bitwise operators /* @@ -246,7 +246,7 @@ class LearnHaxe3{ var k = 0; while(k < 100){ // trace(counter); // will print out numbers 0-99 - counter++; + k++; } // do-while loop @@ -278,11 +278,11 @@ class LearnHaxe3{ // Array comprehensions give you the ability to iterate over arrays // while also creating filters and modifications. - var filtered_n = [for (val in n) if (n != "foo")]; + var filtered_n = [for (val in n) if (val != "foo") val]; trace(filtered_n + " is the value for filtered_n"); - var modified_n = [for (val in n) n += '!']; + var modified_n = [for (val in n) val += '!']; trace(modified_n + " is the value for modified_n"); - var filtered_and_modified_n [for (val in n) if (n != "foo") n += "!"]; + var filtered_and_modified_n = [for (val in n) if (val != "foo") val += "!"]; trace(filtered_and_modified_n + " is the value for filtered_and_modified_n"); ////////////////////////////////////////////////////////////////// @@ -352,7 +352,7 @@ class LearnHaxe3{ Std.parseFloat("0.4"); // returns 0.4; // integer to string - Std.toString(0); // returns "0"; + Std.string(0); // returns "0"; // concatenation with strings will auto-convert to string. 0 + ""; // returns "0"; true + ""; // returns "true"; @@ -412,8 +412,9 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ } // setter for _private - function set_property(val:Int) : Void{ + function set_property(val:Int) : Int { _private = val; + return val; } // special function that is called whenever an instance is cast to a string. @@ -443,6 +444,5 @@ interface BaseFooInterface{ public function baseFunction(x:Int):String; } - ``` -- cgit v1.2.3 From c39c3680cf18be14fdda3740e8b3b6d348d54f34 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Mon, 19 Aug 2013 14:10:48 -0700 Subject: fix comment typo --- haxe.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 9288fc87..82031291 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -175,7 +175,7 @@ class LearnHaxe3{ argument that sets a type parameter. */ var m3 = new Map(); - m3.set(6, 'baz'); // m2 is now a Map + m3.set(6, 'baz'); // m3 is now a Map trace(m3 + " is the value for m3"); /* -- cgit v1.2.3 From cf90a62a7a21f93971bbf71e4d2188bbf97ab21e Mon Sep 17 00:00:00 2001 From: Billy Shih Date: Mon, 19 Aug 2013 15:19:48 -0700 Subject: Fixed a grammatical error --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index fb79949e..1dd6e2be 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -342,7 +342,7 @@ myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 // We mentioned that __proto__ was non-standard, and there's no standard way to -// change the prototype of an existing object. However, there's two ways to +// change the prototype of an existing object. However, there are two ways to // create a new object with a given prototype. // The first is Object.create, which is a recent addition to JS, and therefore -- cgit v1.2.3 From 78133a784f65c32f5904f57b6d665167b026cd4f Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Mon, 19 Aug 2013 21:54:38 -0700 Subject: misc reformat, and some small details --- haxe.html.markdown | 98 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 61 insertions(+), 37 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 82031291..90b2e250 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -12,22 +12,29 @@ may be applicable to older versions, but it is recommended to use other references. ```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 -// compiler, while in the same directory as LearnHaxe.hx: -// haxe -main LearnHaxe3 -x out +/* + 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 + compiler, while in the same directory as LearnHaxe.hx: + haxe -main LearnHaxe3 -x out + */ // Let's start with comments... this is a single line comment /* - And this is multiline -*/ + And this is multiline. Multiline comments are also used to generate + javadoc-style documentation for haxedoc. They will be used if they precede + a class, class function, or class variable. + */ -// A package declaration isn't necessary, but it's useful if you want to -// organize your code into modules later on. Also worth mentioning, all -// expressions in Haxe must end in a semicolon: +/* + A package declaration isn't necessary, but it's useful if you want to + organize your code into modules later on. Also worth mentioning, all + expressions in Haxe must end in a semicolon: + */ package; // empty package, no namespace. + // if you import code from other files, it must be declared before the rest of // the code. import haxe.ds.ArraySort; @@ -66,12 +73,14 @@ class LearnHaxe3{ /* Trace can handle any type of value or object. It will try to print - a representation of the expression as best it can: + a representation of the expression as best it can. You can also + concatenate strings with the "+" operator: */ trace( " Integer: " + 10 + " Float: " + 3.14 + - " Boolean: " + true); + " Boolean: " + true + ); /* @@ -113,9 +122,9 @@ class LearnHaxe3{ var hex_integer = 0xffffff; /* - Haxe uses platform precision for Int and Float sizes. It also - uses the platform behavior for overflow. - (Other numeric types and behavior are possible using special + Haxe uses platform precision for Int and Float sizes. It also + uses the platform behavior for overflow. + (Other numeric types and behavior are possible using special libraries) */ @@ -125,9 +134,12 @@ class LearnHaxe3{ structures like strings, arrays, lists, and maps: */ - var a_string = "some_string"; // strings can have double or single quotes + var a_string = "some" + 'string'; // strings can have double or single quotes trace(a_string + " is the value for a_string"); + var x = 1; + var an_interpolated_string = 'the value of x is $x'; + /* Strings are immutable, instance methods will return a copy of parts or all of the string. @@ -280,11 +292,13 @@ class LearnHaxe3{ // while also creating filters and modifications. var filtered_n = [for (val in n) if (val != "foo") val]; trace(filtered_n + " is the value for filtered_n"); + var modified_n = [for (val in n) val += '!']; trace(modified_n + " is the value for modified_n"); + var filtered_and_modified_n = [for (val in n) if (val != "foo") val += "!"]; trace(filtered_and_modified_n + " is the value for filtered_and_modified_n"); - + ////////////////////////////////////////////////////////////////// // Switch Statements (Value Type) ////////////////////////////////////////////////////////////////// @@ -310,41 +324,41 @@ class LearnHaxe3{ trace("My dog's name is" + my_dog_name + ", and his favorite thing is a: " + favorite_thing); - + ////////////////////////////////////////////////////////////////// // Expression Statements ////////////////////////////////////////////////////////////////// trace("***EXPRESSION STATEMENTS***"); - + /* Haxe control statements are very powerful because every statement is also an expression, consider: */ - + // if statements var k = if (true){ 10; } else { 20; } - + trace("K equals ", k); // outputs 10 - + var other_favorite_thing = switch(my_dog_name) { case "fido" : 'teddy'; case "rex" : 'stick'; case "spot" : 'football'; - case _ : 'some unknown treat'; + case _ : 'some unknown treat'; } - + trace("My dog's name is" + my_dog_name + ", and his other favorite thing is a: " + other_favorite_thing); - + ////////////////////////////////////////////////////////////////// // Converting Value Types ////////////////////////////////////////////////////////////////// - + // You can convert strings to ints fairly easily. // string to integer @@ -359,26 +373,31 @@ class LearnHaxe3{ // See documentation for parsing in Std for more details. ////////////////////////////////////////////////////////////////// - // Basic Object Oriented Design + // Basic Object Oriented Programming ////////////////////////////////////////////////////////////////// - trace("***BASIC OBJECT ORIENTED DESIGN***"); + trace("***BASIC OBJECT ORIENTED PROGRAMMING***"); + // create an instance of FooClass. The classes for this are at the + // end of the file. var instance = new FooClass(3); + // read the public variable normally trace(instance.public_any + " is the value for instance.public_any"); // we can read this variable trace(instance.public_read + " is the value for instance.public_read"); - // but not write it, this will throw an error if uncommented: - //trace(instance.public_write + " is the value for instance.public_write"); - // trace(instance.public_write); // vice-versa for public write, etc. + // but not write it + // instance.public_write = 4; // this will throw an error if uncommented: + // trace(instance.public_write); // as will this. trace(instance + " is the value for instance"); // calls the toString method + trace(instance.toString() + " is the value for instance.toString()"); // same thing - // we can successfully pass the FooInstance to the BaseFooClass method, - // since it was extended from that. + // instance has the "FooClass" type, while acceptBaseFoo has the + // BaseFooClass type. However, since FooClass extends BaseFooClass, + // it is accepted. BaseFooClass.acceptBaseFoo(instance); } @@ -389,12 +408,12 @@ class LearnHaxe3{ */ class FooClass extends BaseFooClass implements BaseFooInterface{ public var public_any:Int; // public variables are accessible anywhere - public var public_read (default,null): Int; // use this style to only enable public read + public var public_read (default,null): Int; // use this style to only enable public read public var public_write (null, default): Int; // or public write public var property (get, set): Int; // use this style to enable getters/setters // private variables are not available outside the class. - // see @:allow for ways around this. + // see @:allow for ways around this. var _private:Int; // variables are private if they are not marked public // a public constructor @@ -416,13 +435,13 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ _private = val; return val; } - + // special function that is called whenever an instance is cast to a string. public function toString(){ return _private + " with toString() method!"; } - // this class needs to have this function defined, since it implements + // this class needs to have this function defined, since it implements // the BaseFooInterface interface. public function baseFunction(x: Int) : String{ // convert the int to string automatically @@ -430,6 +449,9 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ } } +/* + A simple class to extend +*/ class BaseFooClass { var base_variable:Int; public function new(){ @@ -437,9 +459,11 @@ class BaseFooClass { } public static function acceptBaseFoo(b:BaseFooClass){ } - } +/* + A simple interface to implement +*/ interface BaseFooInterface{ public function baseFunction(x:Int):String; } -- cgit v1.2.3 From e70c6a7155992b2a649790245db360d9584349e6 Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Tue, 20 Aug 2013 09:59:49 +0300 Subject: turkish translation for php language --- tr-tr/php-tr.html.markdown | 682 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 682 insertions(+) create mode 100644 tr-tr/php-tr.html.markdown diff --git a/tr-tr/php-tr.html.markdown b/tr-tr/php-tr.html.markdown new file mode 100644 index 00000000..94bc31ff --- /dev/null +++ b/tr-tr/php-tr.html.markdown @@ -0,0 +1,682 @@ +--- +language: php +filename: learnphp-tr.php +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Haydar KULEKCI", "http://scanf.info/"] +lang: tr-tr +--- + +PHP 5+ versiyonu için geçerlidir. + +```php + +Hello World Again! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (öneki 0 olan sekizlik(octal) bir sayıyı gösterir) +$int4 = 0x0F; // => 15 (öneki 0x olanlar hex sayıları gösterir.) + +// Kayan Noktalı Sayılar +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Aritmetik +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// Aritmetik Kısayolları +$number = 0; +$number += 1; // $number değişkeninin değerini 1 artırır. +echo $number++; // 1 yazdırılır. (Yazdırıldıktan sonra artırılır.) +echo ++$number; // 3 yazdırılır. (yazdırılmadan önce artırılır.) +$number /= $float; // Bölünür ve bölüm $number değerine eşitlenir. + +// Karakter dizileri(strings) tek tırnak ile kullanılmalıdır. +$sgl_quotes = '$String'; // => '$String' + +// Bir değişken içermediği sürece çift tırnak kullanmaktan kaçının +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Özel karakterler sadece çift tırnak ile kullanılabilir. +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// Gerekirse bir değişkeni küme ayracı içine alın. +$money = "I have $${number} in the bank."; + +// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredocs will do string interpolation +$heredoc = << 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 ile yeni bir söz dizimi kullanılmaya başlandı +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // 1 yazdıracaktır. + +// Liste kullanımında index'ler tam sayıdır. +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + + +/******************************** + * Çıktı + */ + +echo('Hello World!'); +// Hello World! çıktısı stdout'a yazdırılır. +// Eğer bir web browser ile çalışıyorsanır Stdout bir web sayfasıdır. + +print('Hello World!'); // echo ile aynıdır. + +// Aslında echo bir dil sabitidir, parantezleri kullanmayabilirsiniz. +echo 'Hello World!'; +print 'Hello World!'; // Bu yazdırılacaktır. + +$paragraph = 'paragraph'; + +echo 100; // Echo ile doğrudan sayısal değer kullanımı +echo $paragraph; // veya değişken + +// PHP 5.4.0 veya daha üstü sürümlerde kısa açılış etiketi +// konfigürasyonları yapıldı ise, kısa açılış etiketini kullanabilirsiniz. +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +/******************************** + * Mantık + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// Argüman doğru değilse bir hata fırlatılacaktır. + +// Bu karşılaştırmalar tipler aynı olmasa bile her zaman true olacaktır. +assert($a == $b); // equality +assert($c != $a); // inequality +assert($c <> $a); // alternative inequality +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Aşağıdakiler yanlızca değer ve tip aynı olduğunda true olacaktır. +assert($c === $d); +assert($a !== $d); +assert(1 == '1'); +assert(1 !== '1'); + +// Değişkenler kullanıma bağlı olarak farklı tiplere çevrilebilir. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (Karakter dizisi tam sayıya çevrilmeye zorlanır) + +$string = 'one'; +echo $string + $string; // => 0 +// Çıktı 0 olacaktır, çünkü + operatörü karakter dizisi olan 'one' değerini +// bir sayıya çeviremez. + +// Veri tipi çevirileri bir değişkeni farklı bir türde +// düzenlemek için kullanılabilir. + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// Veri tiplerini çevirmek için bazı fonksiyonlar vardır. +$integer = 5; +$string = strval($integer); + +$var = null; // Null değeri. + + +/******************************** + * Kontrol Yapıları + */ + +if (true) { + print 'I get printed'; +} + +if (false) { + print 'I don\'t'; +} else { + print 'I get printed'; +} + +if (false) { + print 'Does not get printed'; +} elseif(true) { + print 'Does'; +} + +// Üçlü operatör +print (false ? 'Does not get printed' : 'Does'); + +$x = 0; +if ($x === '0') { + print 'Does not print'; +} elseif($x == '1') { + print 'Does not print'; +} else { + print 'Does print'; +} + + + +// Bu alternatif sözdizimi template'ler için kullanışlıdır. +?> + + +This is displayed if the test is truthy. + +This is displayed otherwise. + + + 2, 'car' => 4]; + +// Foreach döngüsü diziler üzerinde çalışır +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // "24" yazdırılacaktır. + +echo "\n"; + +// Key-Value değerlere ulaşabilirsiniz. +foreach ($wheels as $vehicle => $wheel_count) { + echo "A $vehicle has $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // while döngüsünden çıkar + } + echo $i++; +} // Prints "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Aktif döngüyü atlar + } + echo $i; +} // "0124" yazdırılacaktır. + + + +/******************************** + * Fonksiyonlar + */ + +// Bir fonksiyon tanımlamak için "function" kullanılır: +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// Geçerli bir fonksiyon ismi bir harf veya altçizgi ile başlar ve +// bir sayı, harf ya da alt çizgi ile devam eder. + +function add ($x, $y = 1) { // $y değeri isteğe bağlıdır ve + // varsayılan değeri 1'dir + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result fonksiyon dışında ulaşılabilir değildir. +// print $result; // Bir uyarı verecektir. + +// PHP 5.3'den beri bir anonymous fonksiyon tanımlayabilirsiniz; +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Fonksiyonlar bir fonksiyon dönebilir. +function bar ($x, $y) { + // Fonksiyona dışardan değişken gönderebilmek için 'use' komutunu kullanın. + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // "A - B - C" yazdırılacaktır. + +// Fonksiyonun ismini karakter dizinden çağırabilirsiniz. +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// Programatik olarak fonksiyonları çalıştırmak için yararlı olabilir +// veya, call_user_func(callable $callback [, $parameter [, ... ]]); kulanın. + + +/******************************** + * Includes + */ + +instanceProp = $instanceProp; + } + + // Sınıfın içerisinde metodlar fonksiyonlar gibi tanımlanır. + public function myMethod() + { + print 'MyClass'; + } + + final function youCannotOverrideMe() + { + } + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +echo MyClass::MY_CONST; // 'value' şeklinde çıktı verir; +echo MyClass::$staticVar; // 'static' şeklinde çıktı verir; +MyClass::myStaticMethod(); // 'I am static' şeklinde çıktı verir; + +// Sınıfların new ile kullanımı +$my_class = new MyClass('An instance property'); +// Eğer argüman göndermeyeceksek parantezler isteğe bağlıdır. + +// Sınıfın üyelerine erişim -> +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// "extends" ile sınıfı extend etmek +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Bir methodu ezmek + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // "protected" şeklinde çıktı verir. +$my_other_class->myMethod(); // "MyClass > MyOtherClass" şeklinde çıktı verir + +final class YouCannotExtendMe +{ +} + +// getter ve setter'ları oluşturmak için "magic method"ları kullanabilirsiniz. +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // __get() metodunu kullanacaktır. +$x->property = 'Something'; // __set() metodunu kullanacaktır. + +// Sınıflar abstract olabilir(abstract kelimesini kullanarak) veya +// interface'ler uygulanabilir (implements kelimesi kullanılarak). +// Bir interface "interface" kelimesi kullanılarak oluşturulur. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Sınıflar birden fazla interface kullanabilir. +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + + +/******************************** + * Traits + */ +// Trait'ler PHP 5.4.0'dan beri kullanılabilir ve "trait" kullanılarak +// tanımlanır. + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // "I have MyTrait" çıktısını verir. + + + +/******************************** + * İsim Uzayları + */ + +// Bu alan ayrılmıştır, çünkü isim uzayı tanımı bir dosyada en başta +// yapılmalıdır. Bu örnekte böyle olmadığını varsayalım. + + Date: Tue, 20 Aug 2013 10:52:50 +0200 Subject: Fixed typo's, cleaned up some sentences, added gobyexample.com ref --- hu-hu/go.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/hu-hu/go.html.markdown b/hu-hu/go.html.markdown index 460e23ec..69849858 100644 --- a/hu-hu/go.html.markdown +++ b/hu-hu/go.html.markdown @@ -14,7 +14,7 @@ praktikus megoldást nyújt a valós, üzleti problémákra. C-szerű szintaktikával és statikus típuskezeléssel rendelkezik. A fordító szempillantás alatt végez és egy gyorsan futó,statikus futtatható állományt hoz létre. -A nyelv könnyen érthető, üzenet-alapú konkurenciát tesz lehetővé, így könnyen ki lehet használni +A nyelv könnyen érthető, folyamatok közötti csatornákon áthaladó üzenetekkel kommunikáló konkurens programozást tesz lehetővé, így könnyen ki lehet használni a mai számítógépek több magos processzorait, ez nagy rendszerek építéséhez ideális. A Go alap könyvtára mindenre területre kiterjed, ennek köszönhetően a nyelvnek egyre növekvő tábora van. @@ -77,7 +77,7 @@ func learnMultiple(x, y int) (sum, prod int) { // Beépített típusok func learnTypes() { - // Rövid deklarás az esetek többségében elég lesz a változókhoz + // Rövid deklarálás az esetek többségében elég lesz a változókhoz s := "Tanulj Go-t!" // string típus s2 := `A "nyers" stringekben lehetnek @@ -90,7 +90,7 @@ func learnTypes() { f := 3.14195 // float64, az IEEE-754 szabványnak megfelelő 64-bites // lebegőpontos szám - c := 3 + 4i // complex128, belsőleg két float64-el tárolva + c := 3 + 4i // complex128, belsőleg két float64-gyel tárolva // Var szintaxis változó típus definiálással var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az @@ -107,7 +107,7 @@ func learnTypes() { // Szeleteknek dinamikus a méretük. A szeleteknek és a tömböknek is meg // vannak az előnyeik de a szeleteket sokkal gyakrabban használjuk. - s3 := []int{4, 5, 9} // vesd össze a3-al, nincsenek pontok. + s3 := []int{4, 5, 9} // vesd össze a3-mal, nincsenek pontok. s4 := make([]int, 4) // allokál 4 int-et, mind 0-ra inicializálva var d2 [][]float64 // ez csak deklaráció, semmi sincs még allokálva bs := []byte("a slice") // típus konverzió szintaxisa @@ -179,9 +179,9 @@ func learnFlowControl() { break // csak vicceltem continue // soha nem fut le } - // Akárcsak a for-nál, az if-ben is lehet rövid deklarással egy lokális - // változót létrehozni ami az blokk összes if/else-n keresztül érvényes - // marad. + + //Akárcsak a for-nál, az if-nél is lehet rövid deklarálással egy lokális változót létrehozni, + //ami a blokk összes if/else szerkezetén keresztül érvényes marad. if y := expensiveComputation(); y > x { x = y } @@ -212,8 +212,7 @@ type pair struct { x, y int } -// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer -// interf +// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer interfészt. func (p pair) String() string { // p lesz a "vevő" // Sprintf az fmt csomag egy publikus függvénye, műkődése megegyezik a C-s // megfelelőjével. A pontokkal érjük el a mindenkori p struktúra elemeit @@ -312,13 +311,13 @@ func learnWebProgramming() { // A ListenAndServe első paramétre egy TCP port, amin kiszolgálunk majd. // Második paramétere egy interfész, pontosabban a http.Handler interfész. err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // nem felejtük el kiírni az esetleges hibákat! + fmt.Println(err) // nem felejtjük el kiírni az esetleges hibákat! } // Csináljunk a pair-ból egy http.Handler-t úgy, hogy implementáljuk az // egyetlen metódusát a ServeHTTP-t. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Minden kapcsolatra elküldjük ezt a http.ResponseWriter-el + // Minden kapcsolatra elküldjük ezt a http.ResponseWriter-rel w.Write([]byte("Megtanultad a Go-t Y perc alatt!")) } ``` @@ -333,3 +332,4 @@ A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és Ha pedig jobban bele akarod vetni magad a Go-ba, akkor a standard könyvtárban a legjobb praktikákat kilesheted. TIPP: a dokumentációban kattints egy funkció nevére és rögtön megmutatja a hozzá tartozó kódot! +Ha pedig a nyelvnek egy bizonyos részéről szeretnél hasonló leírást találni, akkor a [gobyexample.com](https://gobyexample.com/)-on megtalálod, amit keresel. -- cgit v1.2.3 From 85745485718b54f62e057334323ebaeeb377f18e Mon Sep 17 00:00:00 2001 From: kultprok Date: Tue, 20 Aug 2013 13:26:50 +0200 Subject: Added a german translation for bash --- de-de/bash-de.html.markdown | 73 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 de-de/bash-de.html.markdown diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown new file mode 100644 index 00000000..c9cf3e78 --- /dev/null +++ b/de-de/bash-de.html.markdown @@ -0,0 +1,73 @@ +#!/bin/sh +# Die erste Zeile des Scripts nennt sich Shebang in gibt dem System an, wie +# wie das Script ausgeführt werden soll: http://de.wikipedia.org/wiki/Shebang +# Du hast es bestimmt schon mitgekriegt, Kommentare fangen mit # an. Das Shebang ist auch ein Kommentar + +# Ein einfaches Beispiel mit hello world: +echo Hello, world! + +# Jeder Befehl fängt auf einer neuen Zeile oder nach einem Semikolon an: +echo 'Dies ist die erste Zeile'; echo 'Dies die zweite Zeile' + +# Variablen deklariert man so: +VARIABLE="irgendein String" + +# Aber nicht so: +VARIABLE = "irgendein String" +# Bash wird VARIABLE für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben, +# weil es den Befehl nicht findet. + +# Eine Variable wird so benutzt: +echo $VARIABLE +echo "$VARIABLE" +# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anders –, +# dann über ihren Namen ohne $. Aber wenn du ihren zugewiesenen Wert willst, dann musst du $ voranstellen. + +# Einen Wert aus der Eingabe lesen: +echo "Wie heisst du?" +read NAME # Wir mussten nicht mal eine neue Variable deklarieren +echo Hello, $NAME! + +# Wir haben die übliche if-Struktur: +if true +then + echo "Wie erwartet" +else + echo "Und dies nicht" +fi + +# Ausdrücke werden im folgenden Format festgehalten: +echo $(( 10 + 5 )) + +# Anders als andere Programmiersprachen ist Bash eine Shell – es arbeitet also im Kontext von Verzeichnissen. +# Du kannst alle Dateien und Verzeichnisse im aktiven Verzeichnis mit ls auflisten: +ls + +# Diese Befehle haben Optionen, die ihre Ausführung beeinflussen: +ls -l # Liste alle Dateien und Unterverzeichnisse auf einer eigenen Zeile auf + +# Ergebnisse eines vorangegangenen Befehls können an den nächsten Befehl als Input übergeben werden. +# Der grep-Befehl filtert den Input nach dem vorgegebenen Muster. So können wir alle +# txt-Dateien im aktuellen Verzeichnis auflisten: +ls -l | grep "\.txt" + +# Befehle können innerhalb anderer Befehle mit $( ) erstetzt werden: +# Der folgende Befehl zeigt die Anzahl aller Dateien und Unterverzeichnisse +# im aktuellen Verzeichnis an. +echo "Dieser Ordner beinhaltet $(ls | wc -l) Dateien und Verzeichnisse." + +# Bash nutzt einen case-Ausdruck, der sich ähnlich wie switch in Java oder C++ verhält. +case "$VARIABLE" +in + # Liste der Fälle, die unterschieden werden sollen + 0) echo "Hier ist eine Null." + 1) echo "Hier ist eine Eins." + *) echo "Das ist nicht Null." +esac + +# loops iterieren über die angegebene Zahl von Argumenten: +# Der Inhalt von $VARIABLE wird dreimal ausgedruckt. +for $VARIABLE in x y z +do + echo "$VARIABLE" +done -- cgit v1.2.3 From 9475d643c1e252e19fce7330dae18f00e8507acd Mon Sep 17 00:00:00 2001 From: wikibook Date: Tue, 20 Aug 2013 23:42:22 +0900 Subject: fix typo in Java tutorial and resave lua tutorial as UTF-8 --- ko-kr/java-kr.html.markdown | 2 +- ko-kr/lua-kr.html.markdown | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ko-kr/java-kr.html.markdown b/ko-kr/java-kr.html.markdown index 76b05e45..5dd5769a 100644 --- a/ko-kr/java-kr.html.markdown +++ b/ko-kr/java-kr.html.markdown @@ -169,7 +169,7 @@ public class LearnJava { System.out.println(--i); //i = 0. 전치 감소 연산 /////////////////////////////////////// - // 에저 구조 + // 제어 구조 /////////////////////////////////////// System.out.println("\n->Control Structures"); diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index 04d119c4..c40d9ab0 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -1,4 +1,4 @@ ---- +--- language: lua category: language contributors: -- cgit v1.2.3 From 424fc8ce80af45cdf64037eee9de7773971194aa Mon Sep 17 00:00:00 2001 From: Goheeca Date: Tue, 20 Aug 2013 16:57:25 +0200 Subject: Fixing typos --- common-lisp.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index a917304c..0a8ce990 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -205,7 +205,7 @@ nil ; for false - and the empty list ;; Or use concatenate - -(concatenate +(concatenate 'list '(1 2) '(3 4)) ;; Lists are a very central type, so there is a wide variety of functionality for ;; them, a few examples: @@ -279,10 +279,10 @@ nil ; for false - and the empty list ;; not. ;; Retrieving a non-present value returns nil - (gethash *m* 'd) ;=> nil, nil + (gethash 'd *m*) ;=> nil, nil ;; You can provide a default value for missing keys -(gethash *m* 'd :not-found) ; => :NOT-FOUND +(gethash 'd *m* :not-found) ; => :NOT-FOUND ;; Let's handle the multiple return values here in code. @@ -457,8 +457,8 @@ nil ; for false - and the empty list :accessor velocity :initarg :velocity) (average-efficiency - :accessor average-efficiency) - :initarg :average-efficiency) + :accessor average-efficiency + :initarg :average-efficiency)) (:documentation "A human powered conveyance")) ;; defclass, followed by name, followed by the superclass list, @@ -506,7 +506,7 @@ nil ; for false - and the empty list ; Direct superclasses: STANDARD-OBJECT ; Direct subclasses: UNICYCLE, BICYCLE, CANOE ; Not yet finalized. -(defparameter *foo#\u03BBooo* nil) ; Direct slots: +; Direct slots: ; VELOCITY ; Readers: VELOCITY ; Writers: (SETF VELOCITY) -- cgit v1.2.3 From fc2757a87f7f3850624069a3254ba4175a2e4aff Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 20 Aug 2013 08:57:08 -0700 Subject: Fixes --- README.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/README.markdown b/README.markdown index 701b12d7..fe72df6c 100644 --- a/README.markdown +++ b/README.markdown @@ -12,10 +12,6 @@ Make a new file, send a pull request, and if it passes muster I'll get it up pro Remember to fill in the "contributors" fields so you get credited properly! -### Requests - -We've had a ton of interest, b - ### Contributing All contributions welcome, from the tiniest typo to a brand new article. Translations -- cgit v1.2.3 From 598fe61e1a9968eb633d97ef214b01c7d3f0d942 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 20 Aug 2013 08:58:01 -0700 Subject: Fixed de translations --- de-de/bash-de.html.markdown | 13 ++++++++++++- de-de/git-de.html.markdown | 2 +- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index c9cf3e78..f2a57511 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -1,4 +1,14 @@ -#!/bin/sh +--- +language: bash +contributors: + - ["Jake Prather", "http:#github.com/JakeHP"] + - ["kultprok", "http://www.kulturproktologie.de"] +filename: LearnBash-de.bash +lang: de-de +--- + +```bash +#!/bin/sh # Die erste Zeile des Scripts nennt sich Shebang in gibt dem System an, wie # wie das Script ausgeführt werden soll: http://de.wikipedia.org/wiki/Shebang # Du hast es bestimmt schon mitgekriegt, Kommentare fangen mit # an. Das Shebang ist auch ein Kommentar @@ -71,3 +81,4 @@ for $VARIABLE in x y z do echo "$VARIABLE" done +``` diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index 471c7641..88f4a643 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -4,7 +4,7 @@ tool: git contributors: - ["Jake Prather", "http:#github.com/JakeHP"] - ["kultprok", "http://www.kulturproktologie.de"] -filename: LearnGit.txt +filename: LearnGit-de.txt lang: de-de --- -- cgit v1.2.3 From edf839bfaefcdeb567ead6af0572d1e5195b4a3d Mon Sep 17 00:00:00 2001 From: Goheeca Date: Tue, 20 Aug 2013 17:58:33 +0200 Subject: added adjustable vectors --- common-lisp.html.markdown | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 0a8ce990..bf4844f3 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -219,7 +219,7 @@ nil ; for false - and the empty list ;;; Vectors -;; Vectors are fixed-length arrays +;; Vector's literals are fixed-length arrays #(1 2 3) ; => #(1 2 3) ;; Use concatenate to add vectors together @@ -253,6 +253,23 @@ nil ; for false - and the empty list ; => 0 +;;; Adjustable vectors + +;; Adjustable vectors have the same printed representation +;; as fixed-length vector's literals. + +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) + +*adjvec* ; => #(1 2 3) + +;; Adding new element: +(vector-push-extend 4 *adjvec*) ; => 3 + +*adjvec* ; => #(1 2 3 4) + + + ;;; Naively, sets are just lists: (set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) -- cgit v1.2.3 From b3f6ddad4ae4458f0dcc6feaf284a3dac769d147 Mon Sep 17 00:00:00 2001 From: Yury Date: Tue, 20 Aug 2013 21:42:00 +0400 Subject: Typos and stylistic fixes --- ru-ru/python-ru.html.markdown | 105 +++++++++++++++++++++--------------------- 1 file changed, 53 insertions(+), 52 deletions(-) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index 9163c8aa..3f457bdc 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -6,12 +6,12 @@ contributors: filename: learnpython-ru.py --- -Язык Python был создан Гвидо ван Россумом в ранние 90-е. Сегодня это один из самых популярных -языков. Я влюбился в него благодаря его понятному и доходчивому синтаксису - это почти что исполняемый псевдокод. +Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из самых популярных +языков. Я люблю его за его понятный и доходчивый синтаксис - это почти что исполняемый псевдокод. -Обратная связь будет высоко оценена! Вы можете связаться со мной: [@louiedinh](http://twitter.com/louiedinh) или louiedinh [at] [google's email service] +С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) или louiedinh [at] [google's email service] -Замечание: Эта статья относится к Python 2.7, но должна быть применима к Python 2.x. Скоро ожидается версия и для Python 3! +Замечание: Эта статья относится к Python 2.7, но должно работать и в Python 2.x. Скоро будет версия и для Python 3! ```python # Однострочные комментарии начинаются с hash-символа. @@ -21,25 +21,25 @@ filename: learnpython-ru.py """ #################################################### -## 1. Примитивные типы данных и операторв +## 1. Примитивные типы данных и операторов #################################################### # У вас есть числа 3 #=> 3 -# Математика работает так, как вы и думаете +# Математика работает вполне ожидаемо 1 + 1 #=> 2 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 -# Деление немного сложнее. Это деление целых чисел и результат -# автоматически округляется в меньшую сторону. +# А вот деление немного сложнее. В этом случае происходит деление +№ целых чисел и результат автоматически округляется в меньшую сторону. 5 / 2 #=> 2 # Чтобы научиться делить, сначала нужно немного узнать о дробных числах. -2.0 # Это дробное число. -11.0 / 4.0 #=> 2.75 вооот... гораздо лучше +2.0 # Это дробное число +11.0 / 4.0 #=> 2.75 Вооот... Так гораздо лучше # Приоритет операций указывается скобками (1 + 3) * 2 #=> 8 @@ -60,7 +60,7 @@ not False #=> True 1 != 1 #=> False 2 != 1 #=> True -# Больше сравнений +# Еще немного сравнений 1 < 10 #=> True 1 > 10 #=> False 2 <= 2 #=> True @@ -70,36 +70,36 @@ not False #=> True 1 < 2 < 3 #=> True 2 < 3 < 2 #=> False -# Строки создаются при символом " или ' +# Строки определяются символом " или ' "Это строка." 'Это тоже строка.' -# Строки тоже могут складываться! +# И строки тоже могут складываться! "Привет " + "мир!" #=> "Привет мир!" -# Со строкой можно работать как со списком символов +# Со строкой можно работать, как со списком символов "Это строка"[0] #=> 'Э' -# % используется для форматирования строк, например: +# Символ % используется для форматирования строк, например: "%s могут быть %s" % ("строки", "интерполированы") # Новый метод форматирования строк - использование метода format. # Это предпочитаемый способ. "{0} могут быть {1}".format("строки", "форматированы") -# Вы можете использовать ключевые слова, если не хотите считать. +# Если вы не хотите считать, можете использовать ключевые слова. "{name} хочет есть {food}".format(name="Боб", food="лазанью") # None является объектом None #=> None -# Не используйте оператор равенства `==` для сравнения -# объектов с None. Используйте для этого `is` +# Не используйте оператор равенства '=='' для сравнения +# объектов с None. Используйте для этого 'is' "etc" is None #=> False None is None #=> True # Оператор 'is' проверяет идентичность объектов. Он не # очень полезен при работе с примитивными типами, но -# очень полезен при работе с объектами. +# зато просто незаменим при работе с объектами. # None, 0, и пустые строки/списки равны False. # Все остальные значения равны True @@ -111,15 +111,15 @@ None is None #=> True ## 2. Переменные и коллекции #################################################### -# Печать довольно проста +# Печатать довольно просто print "Я Python. Приятно познакомиться!" -# Необязательно объявлять переменные перед присваиванием им значения. +# Необязательно объявлять переменные перед их инициализацией. some_var = 5 # По соглашению используется нижний_регистр_с_подчеркиваниями some_var #=> 5 -# При попытке доступа к переменной, которой не было ранее присвоено значение, +# При попытке доступа к неинициализированной переменной, # выбрасывается исключение. # См. раздел "Поток управления" для информации об исключениях. some_other_var # Выбрасывает ошибку именования @@ -133,25 +133,25 @@ li = [] other_li = [4, 5, 6] # Объекты добавляются в конец списка методом append -li.append(1) #li содержит [1] -li.append(2) #li содержит [1, 2] -li.append(4) #li содержит [1, 2, 4] -li.append(3) #li содержит [1, 2, 4, 3] -# Удаляются с конца методом pop -li.pop() #=> 3 и li содержит [1, 2, 4] -# Положим его обратно -li.append(3) # li содержит [1, 2, 4, 3] опять. +li.append(1) # [1] +li.append(2) # [1, 2] +li.append(4) # [1, 2, 4] +li.append(3) # [1, 2, 4, 3] +# И удаляются с конца методом pop +li.pop() #=> возвращает 3 и li становится равен [1, 2, 4] +# Положим элемент обратно +li.append(3) # [1, 2, 4, 3]. # Обращайтесь со списком, как с обычным массивом li[0] #=> 1 -# Посмотрим на последний элемент +# Обратимся к последнему элементу li[-1] #=> 3 -# Попытка выйти за границы массива приводит к IndexError +# Попытка выйти за границы массива приведет к IndexError li[4] # Выдает IndexError # Можно обращаться к диапазону, используя "кусочный синтаксис" (slice syntax) -# (Для тех из вас, кто любит математику, это замкнуто/открытый интервал.) +# (Для тех, кто любит математику, это называется замкнуто/открытый интервал.) li[1:3] #=> [2, 4] # Опускаем начало li[2:] #=> [4, 3] @@ -159,38 +159,38 @@ li[2:] #=> [4, 3] li[:3] #=> [1, 2, 4] # Удаляем произвольные элементы из списка оператором del -del li[2] # li содержит [1, 2, 3] +del li[2] # [1, 2, 3] # Вы можете складывать списки -li + other_li #=> [1, 2, 3, 4, 5, 6] - ЗАмечание: li и other_li остаются нетронутыми +li + other_li #=> [1, 2, 3, 4, 5, 6] - Замечание: li и other_li остаются нетронутыми # Конкатенировать списки можно методом extend li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6] -# Проверять элемент на вхождение на список оператором in +# Проверить элемент на вхождение в список можно оператором in 1 in li #=> True -# Длина списка вычисляется при помощи len +# Длина списка вычисляется функцией len len(li) #=> 6 -# Кортежи - это как списки, только неизменяемые +# Кортежи - это такие списки, только неизменяемые tup = (1, 2, 3) tup[0] #=> 1 tup[0] = 3 # Выдает TypeError -# Все те же штуки можно делать и с кортежами +# Все то же самое можно делать и с кортежами len(tup) #=> 3 tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) tup[:2] #=> (1, 2) 2 in tup #=> True # Вы можете распаковывать кортежи (или списки) в переменные -a, b, c = (1, 2, 3) # a теперь равно 1, b равно 2 и c равно 3 +a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 # Кортежи создаются по умолчанию, если опущены скобки d, e, f = 4, 5, 6 # Обратите внимание, как легко поменять местами значения двух переменных -e, d = d, e # d теперь равно 5 and e равно 4 +e, d = d, e # теперь d == 5, а e == 4 # Словари содержат ассоциативные массивы @@ -208,7 +208,7 @@ filled_dict.keys() #=> ["three", "two", "one"] # Можно получить и все значения в виде списка filled_dict.values() #=> [3, 2, 1] -# Замечание - то же самое, что и выше, насчет порядка ключей +# То же самое замечание насчет порядка ключей справедливо и здесь # При помощи оператора in можно проверять ключи на вхождение в словарь "one" in filled_dict #=> True @@ -260,7 +260,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6} ## 3. Поток управления #################################################### -# Давайте заведем переменную +# Для начала заведем переменную some_var = 5 # Так выглядит выражение if. Отступы в python очень важны! @@ -274,8 +274,9 @@ else: # Это тоже необязательно. """ -Циклы For проходят по циклам -результат: +Циклы For проходят по спискам + +Результат: собака это млекопитающее кошка это млекопитающее мышь это млекопитающее @@ -287,7 +288,7 @@ for animal in ["собака", "кошка", "мышь"]: """ `range(number)` возвращает список чисел от нуля до заданного числа -результат: +Результат: 0 1 2 @@ -298,7 +299,7 @@ for i in range(4): """ Циклы while продолжаются до тех пор, пока указанное условие не станет ложным. -результат: +Результат: 0 1 2 @@ -422,10 +423,10 @@ class Human(object): # Инстанцирование класса i = Human(name="Иван") -print i.say("привет") # выводит "Иван: привет" +print i.say("привет") # "Иван: привет" j = Human("Петр") -print j.say("Привет") #выводит "Петр: привет" +print j.say("Привет") # "Петр: привет" # Вызов метода класса i.get_species() #=> "H. sapiens" @@ -453,7 +454,7 @@ print ceil(3.7) #=> 4.0 print floor(3.7) #=> 3.0 # Можете импортировать все функции модуля. -# Предупреждение: не рекомендуется +# (Хотя это и не рекомендуется) from math import * # Можете сокращать имена модулей @@ -472,7 +473,7 @@ dir(math) ``` -## Хочется большего? +## Хотите еще? ### Бесплатные онлайн-материалы @@ -482,7 +483,7 @@ dir(math) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) -### Готовьте деньги +### Платные * [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 07b5c4934ce98d9f3431c23d5e56a46faba77360 Mon Sep 17 00:00:00 2001 From: mhauserr Date: Tue, 20 Aug 2013 23:50:15 +0100 Subject: Update c.html.markdown Added explanation of size_t --- c.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/c.html.markdown b/c.html.markdown index 24a96463..ae66fa78 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -81,6 +81,7 @@ int main() { // is not evaluated (except VLAs (see below)). // The value it yields in this case is a compile-time constant. int a = 1; + // size_t is an unsiged integer type of at least 2 bytes used to represent the size of an object size_t size = sizeof(a++); // a++ is not evaluated printf("sizeof(a++) = %zu where a = %d\n", size, a); // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) -- cgit v1.2.3 From c4c8c02df970c028bd96f2e133a8bf76d5811fc5 Mon Sep 17 00:00:00 2001 From: mhauserr Date: Wed, 21 Aug 2013 00:02:33 +0100 Subject: Added explanation of size_t --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index ae66fa78..3acf1a4d 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -81,7 +81,7 @@ int main() { // is not evaluated (except VLAs (see below)). // The value it yields in this case is a compile-time constant. int a = 1; - // size_t is an unsiged integer type of at least 2 bytes used to represent the size of an object + // size_t is an unsiged integer type of at least 2 bytes used to represent the size of an object. size_t size = sizeof(a++); // a++ is not evaluated printf("sizeof(a++) = %zu where a = %d\n", size, a); // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) -- cgit v1.2.3 From 12bbb737f6417cb39a1f5ef3cf5d50f1bccc34a4 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Tue, 20 Aug 2013 21:25:34 -0700 Subject: added ternary, some reformatting and fixes --- haxe.html.markdown | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 90b2e250..e6c2b49c 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -29,8 +29,8 @@ references. /* A package declaration isn't necessary, but it's useful if you want to - organize your code into modules later on. Also worth mentioning, all - expressions in Haxe must end in a semicolon: + organize your code into modules later on. Also worth mentioning, if you use + more than one expression in a code block, it must end in a semicolon: */ package; // empty package, no namespace. @@ -252,6 +252,9 @@ class LearnHaxe3{ trace("also not printed."); } + // there is also a "ternary" if: + (j == 10) ? trace("equals 10") : trace("not equals 10"); + trace("Looping and Iteration"); // while loop @@ -310,13 +313,14 @@ class LearnHaxe3{ generalized algebraic data types in enums (more on enums later). Here's some basic value examples for now: */ - var my_dog_name = 'fido'; - var favorite_thing = ''; + var my_dog_name = "fido"; + var favorite_thing = ""; switch(my_dog_name){ - case "fido" : favorite_thing = 'bone'; - case "rex" : favorite_thing = 'shoe'; - case "spot" : favorite_thing = 'tennis ball'; - case _ : favorite_thing = 'some unknown treat'; + case "fido" : favorite_thing = "bone"; + case "rex" : favorite_thing = "shoe"; + case "spot" : favorite_thing = "tennis ball"; + default : favorite_thing = "some unknown treat"; + // case _ : "some unknown treat"; // same as default } // The "_" case above is a "wildcard" value // that will match anything. @@ -345,10 +349,10 @@ class LearnHaxe3{ trace("K equals ", k); // outputs 10 var other_favorite_thing = switch(my_dog_name) { - case "fido" : 'teddy'; - case "rex" : 'stick'; - case "spot" : 'football'; - case _ : 'some unknown treat'; + case "fido" : "teddy"; + case "rex" : "stick"; + case "spot" : "football"; + default : "some unknown treat"; } trace("My dog's name is" + my_dog_name -- cgit v1.2.3 From c8c0808657417bc40150bb5f98994a98f4def1fd Mon Sep 17 00:00:00 2001 From: Korjavin Ivan Date: Thu, 22 Aug 2013 08:11:07 +0600 Subject: More tutorial links --- perl.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index 024bd851..f03e7244 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -114,5 +114,7 @@ perlfaq contains questions and answers related to many common tasks, and often p #### Further Reading -[Learn at www.perl.com](http://www.perl.org/learn.html) - and perldoc perlintro + - [perl-tutorial](http://perl-tutorial.org/) + - [Learn at www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - and perl built-in : `perldoc perlintro` -- cgit v1.2.3 From 9a36a51ccc1cb7d64baac17a067be71a7923afdd Mon Sep 17 00:00:00 2001 From: Korjavin Ivan Date: Thu, 22 Aug 2013 08:16:54 +0600 Subject: Few words about subs and file i/o --- perl.html.markdown | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/perl.html.markdown b/perl.html.markdown index f03e7244..18339dde 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -104,6 +104,35 @@ $a =~ s/foo/bar/; # replaces foo with bar in $a $a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $a +#### Files and I/O + +# You can open a file for input or output using the "open()" function. + +open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; +open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; +open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; + +# You can read from an open filehandle using the "<>" operator. In scalar context it reads a single line from +# the filehandle, and in list context it reads the whole file in, assigning each line to an element of the list: + +my $line = <$in>; +my @lines = <$in>; + +#### Writing subroutines + +# Writing subroutines is easy: + +sub logger { + my $logmessage = shift; + open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; + print $logfile $logmessage; +} + +# Now we can use the subroutine just as any other built-in function: + +logger("We have a logger subroutine!"); + + ``` #### Using Perl modules -- cgit v1.2.3 From 98278338e76fb6fbdacf44142777891f238bc984 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Wed, 21 Aug 2013 20:33:55 -0700 Subject: reformatting. Add details on swtiches and gadt enums --- haxe.html.markdown | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 103 insertions(+), 6 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index e6c2b49c..60f374d8 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -199,7 +199,6 @@ class LearnHaxe3{ ////////////////////////////////////////////////////////////////// // Operators ////////////////////////////////////////////////////////////////// - trace("***OPERATORS***"); // basic arithmetic @@ -376,14 +375,20 @@ class LearnHaxe3{ true + ""; // returns "true"; // See documentation for parsing in Std for more details. + + + ////////////////////////////////////////////////////////////////// // Basic Object Oriented Programming ////////////////////////////////////////////////////////////////// trace("***BASIC OBJECT ORIENTED PROGRAMMING***"); - // create an instance of FooClass. The classes for this are at the - // end of the file. + /* + Create an instance of FooClass. The classes for this are at the + end of the file. + */ + var instance = new FooClass(3); // read the public variable normally @@ -399,9 +404,11 @@ class LearnHaxe3{ trace(instance.toString() + " is the value for instance.toString()"); // same thing - // instance has the "FooClass" type, while acceptBaseFoo has the - // BaseFooClass type. However, since FooClass extends BaseFooClass, - // it is accepted. + /* + Instance has the "FooClass" type, while acceptBaseFoo has the + BaseFooClass type. However, since FooClass extends BaseFooClass, + it is accepted. + */ BaseFooClass.acceptBaseFoo(instance); } @@ -472,5 +479,95 @@ interface BaseFooInterface{ public function baseFunction(x:Int):String; } +////////////////////////////////////////////////////////////////// +// Enums and Switch Statements +////////////////////////////////////////////////////////////////// + +/* + Enums in Haxe are very powerful. In their simplest form, enums + are a type with a limited number of states: + */ + +enum SimpleEnum { + Foo; + Bar; + Baz; +} + +// Here's a class that uses it: + +class SimpleEnumTest{ + public static function example(){ + var e_explicit:SimpleEnum = SimpleEnum.Foo; // you can specify the "full" name + var e = Foo; // but inference will work as well. + switch(e){ + case Foo: trace("e was Foo"); + case Bar: trace("e was Bar"); + case Baz: trace("e was Baz"); // comment this line to throw an error. + } + + /* + This doesn't seem so different from simple value switches on strings. + However, if we don't include *all* of the states, the compiler will + complain. You can try it by commenting out a line above. + + You can also specify a default for enum switches as well: + */ + switch(e){ + case Foo: trace("e was Foo again"); + default : trace("default works here too"); + } + } +} + +/* + Enums go much further than simple states, we can also enumerate + *constructors*, but we'll need a more complex enum example + */ +enum ComplexEnum{ + IntEnum(i:Int); + MultiEnum(i:Int, j:String, k:Float); + SimpleEnumEnum(s:SimpleEnum); + ComplexEnumEnum(c:ComplexEnum); +} + +/* + Note: The enum above can include *other* enums as well. + */ + + +class ComplexEnumTest{ + public static function example(){ + var e1:ComplexEnum = IntEnum(4); // specifying the enum parameter + /* + Now we can switch on the enum, as well as extract any parameters + it might of had. + */ + switch(e1){ + case IntEnum(x) : trace("x was the parameter passed to e1"); + default: trace("Shouldn't be printed"); + } + + var e2 = SimpleEnumEnum(Foo); // another parameter here that is itself an enum... an enum enum? + switch(e2){ + case SimpleEnumEnum(s): trace('$s was the parameter passed to e2'); + default: trace("Shouldn't be printed"); + } + + var e3 = ComplexEnumEnum(ComplexEnumEnum(MultiEnum(4, 'hi', 4.3))); // enums all the way down + switch(e3){ + // You can look for certain nested enums by specifying them explicitly: + case ComplexEnumEnum(ComplexEnumEnum(MultiEnum(i,j,k)) : { + trace('$i, $j, and $k were passed into this nested monster'); + } + default: trace("Shouldn't be printed"); + } + /* + Check out generalized algebraic data types (GADT) for more details + on why these are so great. + */ + } +} + ``` -- cgit v1.2.3 From 27b3ab01e4b132a428a7fc2b26e8848f390dc179 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Wed, 21 Aug 2013 20:37:32 -0700 Subject: missing paren --- haxe.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 60f374d8..0c5fdf5d 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -557,7 +557,7 @@ class ComplexEnumTest{ var e3 = ComplexEnumEnum(ComplexEnumEnum(MultiEnum(4, 'hi', 4.3))); // enums all the way down switch(e3){ // You can look for certain nested enums by specifying them explicitly: - case ComplexEnumEnum(ComplexEnumEnum(MultiEnum(i,j,k)) : { + case ComplexEnumEnum(ComplexEnumEnum(MultiEnum(i,j,k))) : { trace('$i, $j, and $k were passed into this nested monster'); } default: trace("Shouldn't be printed"); -- cgit v1.2.3 From d9d57ee1a1c3e5239251efdd8aeb0a320cfbea49 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Wed, 21 Aug 2013 22:07:32 -0700 Subject: add examples for using, typedefs, and conditional comp. more refmt. --- haxe.html.markdown | 175 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 155 insertions(+), 20 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 0c5fdf5d..319c6902 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -28,27 +28,35 @@ references. */ /* - A package declaration isn't necessary, but it's useful if you want to - organize your code into modules later on. Also worth mentioning, if you use - more than one expression in a code block, it must end in a semicolon: + This is your first actual haxe code, 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). */ package; // empty package, no namespace. - -// if you import code from other files, it must be declared before the rest of -// the code. +/* + if you import code from other files, it must be declared before the rest of + the code. + */ import haxe.ds.ArraySort; // you can import many classes/modules at once with "*" import haxe.ds.*; -// you can also import classes in a special way, enabling them to extend the -// functionality of other classes. More on this later. +/* + you can also import classes in a special way, enabling them to extend the + functionality of other classes. More on 'using' later. + */ using StringTools; -// Haxe files typically define classes, although they can also define other -// types of code... more on that later. +/* + Typedefs are like variables... for types. They must be declared before any + code. More on this later. + */ +typedef FooString = String; +// Typedefs can also use "structural" types, more on that later as well! +typedef FooObject = { foo: String }; class LearnHaxe3{ /* @@ -254,6 +262,24 @@ class LearnHaxe3{ // there is also a "ternary" if: (j == 10) ? trace("equals 10") : trace("not equals 10"); + /* + Finally, there is another form of control structures that operates + at compile time: conditional compilation. + */ +#if neko + trace('hello from neko'); +#elseif js + trace('hello from js'); +#else + trace('hello from another platform!'); +#end + /* + The compiled code will change depending on the platform target. + Since we're compiling for neko (-x or -neko), we only get the neko + greeting. + */ + + trace("Looping and Iteration"); // while loop @@ -410,6 +436,15 @@ class LearnHaxe3{ it is accepted. */ BaseFooClass.acceptBaseFoo(instance); + + /* + The classes below have some more advanced examples, the "example()" + method will just run them here. + */ + SimpleEnumTest.example(); + ComplexEnumTest.example(); + TypedefsAndStructuralTypes.example(); + } } @@ -530,11 +565,7 @@ enum ComplexEnum{ SimpleEnumEnum(s:SimpleEnum); ComplexEnumEnum(c:ComplexEnum); } - -/* - Note: The enum above can include *other* enums as well. - */ - +// Note: The enum above can include *other* enums as well, including itself! class ComplexEnumTest{ public static function example(){ @@ -544,17 +575,19 @@ class ComplexEnumTest{ it might of had. */ switch(e1){ - case IntEnum(x) : trace("x was the parameter passed to e1"); + case IntEnum(x) : trace('$x was the parameter passed to e1'); default: trace("Shouldn't be printed"); } - var e2 = SimpleEnumEnum(Foo); // another parameter here that is itself an enum... an enum enum? + // another parameter here that is itself an enum... an enum enum? + var e2 = SimpleEnumEnum(Foo); switch(e2){ case SimpleEnumEnum(s): trace('$s was the parameter passed to e2'); default: trace("Shouldn't be printed"); } - var e3 = ComplexEnumEnum(ComplexEnumEnum(MultiEnum(4, 'hi', 4.3))); // enums all the way down + // enums all the way down + var e3 = ComplexEnumEnum(ComplexEnumEnum(MultiEnum(4, 'hi', 4.3))); switch(e3){ // You can look for certain nested enums by specifying them explicitly: case ComplexEnumEnum(ComplexEnumEnum(MultiEnum(i,j,k))) : { @@ -562,12 +595,114 @@ class ComplexEnumTest{ } default: trace("Shouldn't be printed"); } - /* - Check out generalized algebraic data types (GADT) for more details + /* + Check out "generalized algebraic data types" (GADT) for more details on why these are so great. */ } } +class TypedefsAndStructuralTypes { + public static function example(){ + // Here we're going to use typedef types, instead of base types. + var t1:FooString = "some string"; + + /* + We can use typedefs for "structural types". These types are defined + by their field structure, not by class inheritance. Here's an + anonymous object with a String field named "foo": + */ + + var fooObj = { foo: 'hi' }; + + /* + Remember back at the top where we declared the FooObj typedef? + Since fooObj matches that structure, we can use it anywhere that + a "FooObject" is expected. + */ + + var f = function(fo:FooObj){ trace('$fo was passed in to this function')}; + f(fooObj); // call the FooObject signature function with fooObj. + + /* + Note that typedefs can have optional fields as well, marked with "?" + + typedef OptionalFooObj = { + ?optionalString: String, + requiredInt: Int + } + */ + + /* + Typedefs work well with conditional compilation. For instance, + we could have included this at the top of the file: + +#if( js ) + typedef Surface = js.html.CanvasRenderingContext2D; +#elseif( nme ) + typedef Surface = nme.display.Graphics; +#elseif( !flash9 ) + typedef Surface = flash8.MovieClip; +#elseif( java ) + typedef Surface = java.awt.geom.GeneralPath; +#end + + That would give us a single "Surface" type to work with across + all of those platforms. + */ + } +} + +class UsingExample { + public static function example() { + + /* + The "using" import keyword is a special type of class import that + alters the behavior of any static methods in the class. + + In this file, we've applied "using" to "StringTools", which contains + a number of static methods for dealing with String types. + */ + trace(StringTools.endsWith("foobar", "bar") + " should be true!"); + + /* + With a "using" import, the first argument type is extended with the + method. What does that mean? Well, since "endsWith" has a first + argument type of "String", that means all String types now have the + "endsWith" method: + */ + trace("foobar".endsWith("bar") + " should be true!"); + + /* + This technique enables a good deal of expression for certain types, + while limiting the scope of modifications to a single file. + + Note that the String instance is *not* modified in the run time. + The newly attached method is not really part of the attached + instance, and the compiler still generates code equivalent to a + static method. + */ + } + +} + ``` +We're still only scratching the surface here of what Haxe can do. For a formal +overiew of all Haxe features, checkout the [online +manual](http://haxe.org/manual), the [online api](http://api.haxe.org/), and +"haxelib", the [haxe library repo] (http://lib.haxe.org/). + +For more advanced topics, consider checking out: + +* [Abstract types](http://haxe.org/manual/abstracts) +* [Macros](http://haxe.org/manual/macros), and [Compiler Macros](http://haxe.org/manual/macros_compiler) +* [Tips and Tricks](http://haxe.org/manual/tips_and_tricks) + + +Finally, please join us on [the mailing +list](http://haxe.org/manual/tips_and_tricks), on IRC [#haxe on +freenode](http://webchat.freenode.net/), or on +[Google+](https://plus.google.com/communities/103302587329918132234). + + -- cgit v1.2.3 From 92a6c9164440d60ecf549c9211312b069abab1e7 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Wed, 21 Aug 2013 22:11:01 -0700 Subject: type typo --- haxe.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 319c6902..e1ab645c 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -621,7 +621,9 @@ class TypedefsAndStructuralTypes { a "FooObject" is expected. */ - var f = function(fo:FooObj){ trace('$fo was passed in to this function')}; + var f = function(fo:FooObject){ + trace('$fo was passed in to this function'); + } f(fooObj); // call the FooObject signature function with fooObj. /* -- cgit v1.2.3 From 580f1a4fe0df112b89cf29d74e3cc765cd660cd9 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Wed, 21 Aug 2013 22:29:31 -0700 Subject: add note about untyped/Dynamic --- haxe.html.markdown | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/haxe.html.markdown b/haxe.html.markdown index e1ab645c..293cb2a0 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -387,6 +387,7 @@ class LearnHaxe3{ ////////////////////////////////////////////////////////////////// // Converting Value Types ////////////////////////////////////////////////////////////////// + trace("***CONVERTING VALUE TYPES***"); // You can convert strings to ints fairly easily. @@ -402,7 +403,51 @@ class LearnHaxe3{ // See documentation for parsing in Std for more details. + ////////////////////////////////////////////////////////////////// + // Dealing with Types + ////////////////////////////////////////////////////////////////// + + /* + + As mentioned before, Haxe is a statically typed language. All in + all, static typing is a wonderful thing. It enables + autocompletions, and can be used to check the correctness of a + program in very thorough ways. Plus, the Haxe compiler is super fast. + You probably won't be waiting on it very much. + *HOWEVER*, there are times when you just wish the compiler would let + something slide, and not throw a type error in a limited case. + + To do this, Haxe has two separate keywords. The first is the + "Dynamic" type: + */ + var dyn: Dynamic = "any type of variable, such as this string"; + + /* + All that you know for certain with a Dynamic variable is that the + compiler will no longer worry about what type it is. It is like a + wildcard variable: You can pass it instead of any variable type, + and you can assign any variable type you want. + + The other more extreme option is the "untyped" keyword + */ + + untyped { + var x:Int = 'foo'; + var y:String = 4; + } + + /* + The untyped keyword operates on entire *blocks* of code, skipping + any type checks that might be otherwise required. This keyword should + be used very sparingly, such as in limited conditionally-compiled + situations where type checking is a hinderance. + + In general, skipping type checks is *not* recommended. Use the + enum, inheritance, or structural type models in order to verify the + correctness of your program. Only when you're certain that none of + the type models work should you resort to "Dynamic" or "untyped". + */ ////////////////////////////////////////////////////////////////// // Basic Object Oriented Programming -- cgit v1.2.3 From 93adb27cc6e1adab29c3f7af98e25ef727ee9369 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Wed, 21 Aug 2013 22:36:45 -0700 Subject: invoke the using example method --- haxe.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/haxe.html.markdown b/haxe.html.markdown index 293cb2a0..ba6c464a 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -489,6 +489,7 @@ class LearnHaxe3{ SimpleEnumTest.example(); ComplexEnumTest.example(); TypedefsAndStructuralTypes.example(); + UsingExample.example(); } -- cgit v1.2.3 From 078cbd3299e4f17f67473bf099258a7a5d26c4bd Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Thu, 22 Aug 2013 10:54:51 -0700 Subject: fix mailing list link --- haxe.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index ba6c464a..5c488b30 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -748,8 +748,7 @@ For more advanced topics, consider checking out: * [Tips and Tricks](http://haxe.org/manual/tips_and_tricks) -Finally, please join us on [the mailing -list](http://haxe.org/manual/tips_and_tricks), on IRC [#haxe on +Finally, please join us on [the mailing list](https://groups.google.com/forum/#!forum/haxelang), on IRC [#haxe on freenode](http://webchat.freenode.net/), or on [Google+](https://plus.google.com/communities/103302587329918132234). -- cgit v1.2.3 From cd723d1245282e33dd0fd0c0f52222c7f91bc3bd Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Thu, 22 Aug 2013 10:58:46 -0700 Subject: more doc/example tweaks --- haxe.html.markdown | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 5c488b30..9ef69c64 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -418,16 +418,16 @@ class LearnHaxe3{ *HOWEVER*, there are times when you just wish the compiler would let something slide, and not throw a type error in a limited case. - To do this, Haxe has two separate keywords. The first is the + To do this, Haxe has two separate keywords. The first is the "Dynamic" type: */ var dyn: Dynamic = "any type of variable, such as this string"; /* - All that you know for certain with a Dynamic variable is that the - compiler will no longer worry about what type it is. It is like a + All that you know for certain with a Dynamic variable is that the + compiler will no longer worry about what type it is. It is like a wildcard variable: You can pass it instead of any variable type, - and you can assign any variable type you want. + and you can assign any variable type you want. The other more extreme option is the "untyped" keyword */ @@ -438,12 +438,12 @@ class LearnHaxe3{ } /* - The untyped keyword operates on entire *blocks* of code, skipping + The untyped keyword operates on entire *blocks* of code, skipping any type checks that might be otherwise required. This keyword should be used very sparingly, such as in limited conditionally-compiled situations where type checking is a hinderance. - In general, skipping type checks is *not* recommended. Use the + In general, skipping type checks is *not* recommended. Use the enum, inheritance, or structural type models in order to verify the correctness of your program. Only when you're certain that none of the type models work should you resort to "Dynamic" or "untyped". @@ -650,27 +650,32 @@ class ComplexEnumTest{ class TypedefsAndStructuralTypes { public static function example(){ - // Here we're going to use typedef types, instead of base types. + /* + Here we're going to use typedef types, instead of base types. + At the top we've declared the type "FooString" to mean a "String" type. + */ var t1:FooString = "some string"; /* - We can use typedefs for "structural types". These types are defined - by their field structure, not by class inheritance. Here's an - anonymous object with a String field named "foo": + We can use typedefs for "structural types" as well. These types are + defined by their field structure, not by class inheritance. Here's + an anonymous object with a String field named "foo": */ - var fooObj = { foo: 'hi' }; + var anon_obj = { foo: 'hi' }; /* - Remember back at the top where we declared the FooObj typedef? - Since fooObj matches that structure, we can use it anywhere that - a "FooObject" is expected. + The anon_obj variable doesn't have a type declared, and is an + anonymous object according to the compiler. However, remember back at + the top where we declared the FooObj typedef? Since anon_obj matches + that structure, we can use it anywhere that a "FooObject" type is + expected. */ var f = function(fo:FooObject){ trace('$fo was passed in to this function'); } - f(fooObj); // call the FooObject signature function with fooObj. + f(anon_obj); // call the FooObject signature function with anon_obj. /* Note that typedefs can have optional fields as well, marked with "?" -- cgit v1.2.3 From 7a31e5841ddc070e5a50b115161fec6ef267f19b Mon Sep 17 00:00:00 2001 From: kultprok Date: Thu, 22 Aug 2013 20:36:55 +0200 Subject: added introduction to bash in german. --- de-de/bash-de.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index f2a57511..107b8a07 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -7,6 +7,11 @@ filename: LearnBash-de.bash lang: de-de --- +Bash ist der Name der Unix-Shell, die als Shell des GNU-Betriebssystems und auch als Standard-Shell von Linux und Mac OS X ausgeliefert wurde. +Beinahe alle der folgenden Beispiele können als Teile eines Shell-Skripts oder direkt in der Shell ausgeführt werden. + +[Weitere Informationen \(Englisch\)](http://www.gnu.org/software/bash/manual/bashref.html) + ```bash #!/bin/sh # Die erste Zeile des Scripts nennt sich Shebang in gibt dem System an, wie -- cgit v1.2.3 From 1a8b22cb4f51b6302e1411ecd94851270fd42eaf Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 22 Aug 2013 15:26:26 -0500 Subject: Add while loop to bash --- bash.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 7421f880..1473e669 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -53,6 +53,13 @@ else echo "And this is not" fi +# And the usual while loop: +while [true] +do + echo "put loop content here..." + break +done + # Expressions are denoted with the following format: echo $(( 10 + 5 )) -- cgit v1.2.3 From 3f51d6b516b8543dc8d7f6d7a55f3e0210ccd817 Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Fri, 23 Aug 2013 00:00:54 +0300 Subject: turkish translation for python language --- tr-tr/python-tr.html.markdown | 528 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 528 insertions(+) create mode 100644 tr-tr/python-tr.html.markdown diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown new file mode 100644 index 00000000..410339dd --- /dev/null +++ b/tr-tr/python-tr.html.markdown @@ -0,0 +1,528 @@ +--- +language: python +filename: learnpython-tr.py +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Haydar KULEKCI", "http://scanf.info/"] +lang: tr-tr +--- +Python Guido Van Rossum tarafından 90'ların başında yaratılmıştır. Şu anda +varolanlar arasında en iyi dillerden birisidir. Ben (Louie Dinh) Python +dilinin syntax'ının belirginliğine aşığım. O basit olarak çalıştırılabilir +pseudocode'dur. + +Geri bildirimlerden son derece mutluluk duyarım! Bana [@louiedinh](http://twitter.com/louiedinh) +adresinden ya da louiedinh [at] [google's email service] adresinden ulaşabilirsiniz. + +Çeviri için geri bildirimleri de [@kulekci](http://twitter.com/kulekci) +adresine yapabilirsiniz. + +Not: Bu yazıdaki özellikler Python 2.7 için geçerlidir, ama Python 2.x için de +uygulanabilir. Python 3 için başka bir zaman tekrar bakınız. + + +```python +# Tek satır yorum hash işareti ile başlar. +""" Çoklu satır diziler üç tane çift tırnak + arasında yazılır. Ve yorum olarak da + kullanılabilir +""" + + +#################################################### +## 1. İlkel Veri Tipleri ve Operatörler +#################################################### + +# Sayılar +3 #=> 3 + +# Matematik beklediğiniz gibi +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Bölünme biraz ilginç. EĞer tam sayılar üzerinde bölünme işlemi yapıyorsanız +# sonuç otomatik olarak kırpılır. +5 / 2 #=> 2 + +# Bölünme işlemini düzenlemek için kayan noktalı sayıları bilmeniz gerekir. +2.0 # Bu bir kayan noktalı sayı +11.0 / 4.0 #=> 2.75 ahhh...daha iyi + +# İşlem önceliğini parantezler ile sağlayabilirsiniz. +(1 + 3) * 2 #=> 8 + +# Boolean değerleri bilindiği gibi +True +False + +# not ile nagatif(mantıksal) değerini alma +not True #=> False +not False #=> True + +# Eşitlik == +1 == 1 #=> True +2 == 1 #=> False + +# Eşitsizlik != +1 != 1 #=> False +2 != 1 #=> True + +# Daha fazla karşılaştırma +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Karşılaştırma zincirleme yapılabilir! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Karakter dizisi " veya ' ile oluşturulabilir +"This is a string." +'This is also a string.' + +# Karakter dizileri birbirleri ile eklenebilir +"Hello " + "world!" #=> "Hello world!" + +# A string can be treated like a list of characters +# Bir string'e karakter listesi gibi davranabilirsiniz. +"This is a string"[0] #=> 'T' + +# % karakter dizisini(string) formatlamak için kullanılır, bunun gibi: +"%s can be %s" % ("strings", "interpolated") + +# String'leri formatlamanın yeni bir yöntem ise format metodudur. +# Bu metod tercih edilen yöntemdir. +"{0} can be {1}".format("strings", "formatted") +# Eğer saymak istemiyorsanız anahtar kelime kullanabilirsiniz. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# None bir objedir +None #=> None + +# `==` eşitliğini non objesi ile karşılaştırmak için kullanmayın. +# Onun yerine `is` kullanın. +"etc" is None #=> False +None is None #=> True + +# 'is' operatörü obje kimliği için test etmektedir. Bu ilkel değerler +# için kullanışlı değildir, ama objeleri karşılaştırmak için kullanışlıdır. + +# None, 0 ve boş string/list'ler False olarak değerlendirilir. +# Tüm eşitlikler True döner +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Değişkenler ve Kolleksiyonlar +#################################################### + +# Ekrana yazdırma oldukça kolaydır. +print "I'm Python. Nice to meet you!" + + +# Değişkenlere bir değer atamadan önce tanımlamaya gerek yoktur. +some_var = 5 # Değişken isimlerinde gelenek küçük karakter ve alt çizgi + # kullanmaktır. +some_var #=> 5 + +# Daha önceden tanımlanmamış ya da assign edilmemeiş bir değişkene erişmeye +# çalıştığınızda bir hata fırlatılacaktır. Hata ayıklama hakkında daha fazla +# bilgi için kontrol akışı kısmına göz atınız. +some_other_var # isim hatası fırlatılır + +# isterseniz `if`i bir ifade gibi kullanabilirsiniz. +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listeler +li = [] +# Önceden değerleri tanımlanmış listeler +other_li = [4, 5, 6] + +# Bir listenin sonuna birşeyler eklemek +li.append(1) #li şu anda [1] +li.append(2) #li şu anda [1, 2] +li.append(4) #li şu anda [1, 2, 4] +li.append(3) #li şu anda [1, 2, 4, 3] +# pop ile sondan birşeyler silmek +li.pop() #=> 3 and li is now [1, 2, 4] +# Tekrar sonuna eklemek +li.append(3) # li is now [1, 2, 4, 3] again. + +# Dizi gibi listenin elemanlarına erişmek +li[0] #=> 1 +# Son elemanın değerine ulaşmak +li[-1] #=> 3 + +# Listede bulunmayan bir index'teki elemana erişirken `IndexError` hatası +# fırlatılır +li[4] # IndexError fırlatılır + +# slice syntax'ı ile belli aralıktakı değerlere bakabilirsiniz. +# (Açık ve kapalı aralıklıdır.) +li[1:3] #=> [2, 4] +# Başlangıcı ihmal etme +li[2:] #=> [4, 3] +# Sonu ihmal etme +li[:3] #=> [1, 2, 4] + +# `del` ile istenilen bir elemanı listeden silmek +del li[2] # li is now [1, 2, 3] + +# Listeleri birbiri ile birleştirebilirsiniz. +li + other_li #=> [1, 2, 3, 4, 5, 6] - Not: li ve other_li yanlız bırakılır + +# extend ile listeleri birleştirmek +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# bir değerin liste içerisinde varlığını `in` ile kontrol etmek +1 in li #=> True + +# "len" ile listenin uzunluğunu bulmak +len(li) #=> 6 + +# Tüpler listeler gibidir sadece değişmezler(immutable) +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # TypeError fırlatılır. + +# Litelerde yapılanların hepsini tüplerde de yapılabilir +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Tüplerin(veya listelerin) içerisindeki değerleri değişkenelere +# atanabilir +a, b, c = (1, 2, 3) # a şu anda 1, b şu anda 2 ve c şu anda 3 +# Eğer parantez kullanmaz iseniz tüpler varsayılan olarak oluşturulur +d, e, f = 4, 5, 6 +# şimdi iki değeri değiş tokuş etmek çok kolaydır. +e, d = d, e # d şimdi 5 ve e şimdi 4 + + +# Sözlükler (Dictionaries) key-value saklanır. +empty_dict = {} +# Sözlüklere önceden değer atama örneği +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Değere ulaşmak için [] kullanılır +filled_dict["one"] #=> 1 + +# Tüm anahtarlara(key) `keys()` metodu ile ulaşılır +filled_dict.keys() #=> ["three", "two", "one"] +# Not - Sözlüklerin anahtarlarının sıralı geleceği garanti değildir +# Sonuçlarınız değer listesini aldığınızda tamamen eşleşmeyebilir + +# Tüm değerleri almak için `values()` kullanabilirsiniz. +filled_dict.values() #=> [3, 2, 1] +# Not - Sıralama ile ilgili anahtarlar ile aynı durum geçerlidir. + +# Bir anahtarın sözlükte oluş olmadığını `in` ile kontrol edilebilir +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Olmayan bir anahtar çağrıldığında KeyError fırlatılır. +filled_dict["four"] # KeyError + +# `get()` metodu KeyError fırlatılmasını önler +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# get() metodu eğer anahtar mevcut değilse varsayılan bir değer atama +# imknaı sağlar. +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# `setdefault()` metodu sözlüğe yeni bir key-value eşleşmesi eklemenin +# güvenli bir yoludur. +filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 + + +# Sets store ... well sets +empty_set = set() +# Bir demek değer ile bir "set" oluşturmak +some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4]) + +# Python 2.7'den beri {}'ler bir "set" tanımlaman için kullanılabilir +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Bir set'e daha fazla eleman eklemek +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# "&" işareti ile iki set'in kesişimlerini alınabilir +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# | işareti ile +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# "-" işareti ile iki set'in farkları alınabilir +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# "in" ile değerin set içerisinde olup olmadığını kontrol edebilirsiniz +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Akış Denetimi +#################################################### + +# Bir değişken oluşturmak +some_var = 5 + +# Buradaki bir if ifadesi. Girintiler(Intentation) Python'da önemlidir! +# "some_var is smaller than 10" yazdırılır. +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # elif ifadesi isteğe bağlıdır + print "some_var is smaller than 10." +else: # Bu da isteğe bağlıdır. + print "some_var is indeed 10." + + +""" +For döngüleri listeler üzerinde iterasyon yapar +Ekrana yazdırılan: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # Biçimlendirmeleri string'e katmak için % kullanabilirsiniz + print "%s is a mammal" % animal + +""" +`range(number)` ifadesi sıfırdan verilen sayıya kadar bir sayı listesi döner +Ekrana yazdırılan: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While döngüsü koşul sağlanmayana kadar devam eder +Ekrana yazdırılan: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Shorthand for x = x + 1 + +# try/except bloğu ile hatalar ayıklanabilir + +# Python 2.6 ve üstü için çalışacaktır: +try: + # "raise" bir hata fırlatmak için kullanılabilir + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. + + +#################################################### +## 4. Fonksiyonlar +#################################################### + + +# Yeni bir fonksiyon oluşturmak için `def` kullanılır +def add(x, y): + print "x is %s and y is %s" % (x, y) + return x + y # Return values with a return statement + +# Fonksiyonu parametre ile çağırmak +add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11 + +# Diğer bir yol fonksiyonları anahtar argümanları ile çağırmak +add(y=6, x=5) # Anahtar argümanlarının sırası farklı da olabilir + +# Değişken sayıda parametresi olan bir fonksiyon tanımlayabilirsiniz +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + +# Değişken sayıda anahtar argümanlı parametre alan fonksiyonlar da +# tanımlayabilirsiniz. +def keyword_args(**kwargs): + return kwargs + +# Şu şekilde kullanılacaktır +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Eğer isterseniz ikisini aynı anda da yapabilirsiniz +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} +""" + +# Fonksiyonu çağırırken, args/kwargs'ın tam tersini de yapabilirsiniz! +# Tüpü yaymak için * ve kwargs'ı yaymak için ** kullanın. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # foo(1, 2, 3, 4) ile eşit +all_the_args(**kwargs) # foo(a=3, b=4) ile eşit +all_the_args(*args, **kwargs) # foo(1, 2, 3, 4, a=3, b=4) ile eşit + +# Python first-class fonksiyonlara sahiptir +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Anonymous fonksiyonlar da vardır +(lambda x: x > 2)(3) #=> True + +# Dahili yüksek seviye fonksiyonlar vardır +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Map etme(maps) ve filtreleme(filtres) için liste kullanabiliriz. +[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. Sınıflar +#################################################### + +# We subclass from object to get a class. +class Human(object): + + # Bir sınıf özelliği. Bu sınıfın tüm `instance`larına paylaşılmıştır. + species = "H. sapiens" + + # Basic initializer + def __init__(self, name): + # Metoda gelen argümanın değerini sınıfın elemanı olan `name` + # değişkenine atama + self.name = name + + # Bir instance metodu. Tüm metodlar ilk argüman olarak `self` + # parametresini alır + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Bir sınıf metodu tüm `instance`lar arasında paylaşılır + # İlk argüman olarak sınıfı çağırarak çağrılırlar + @classmethod + def get_species(cls): + return cls.species + + # bBir statik metod bir sınıf ya da instance referansı olmadan çağrılır + @staticmethod + def grunt(): + return "*grunt*" + + +# Bir sınıf örneği oluşturmak +i = Human(name="Ian") +print i.say("hi") # "Ian: hi" çıktısı verir + +j = Human("Joel") +print j.say("hello") # "Joel: hello" çıktısı verir + +# Sınıf metodunu çağıralım +i.get_species() #=> "H. sapiens" + +# Paylaşılan sınıf özellik değiştirelim. +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Statik metodu çağırma +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Modüller +#################################################### + +# Modülleri sayfaya dahil edebilirsiniz +import math +print math.sqrt(16) #=> 4 + +# Modül içerisinden spesifik bir fonksiyonu getirebilirsiniz +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Modüldeki tüm fonksiyonları dahil edebilirsiniz +# Uyarı: bu önerilmez +from math import * + +# Modülün adını kısaltabilirsiniz +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Python modülleri sıradan python dosyalarıdır. Kendinize bir modül +# yazabilirsiniz, ve dahil edebilirsiniz. Modülün adı ile dosya adı +# aynı olmalıdır. + +# Modüllerde tanımlanmış fonksiyon ve metodları öğrenebilirsiniz. +import math +dir(math) + + + +``` + +## Daha fazlası için hazır mısınız? + +### Ücretsiz Dökümanlar + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### 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 8c1a1d8a7b55761f71c0a202967fdc7547b506f1 Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Fri, 23 Aug 2013 00:06:47 +0300 Subject: some python keywords, which are in comments, enclosed in quotation marks to become clear (understandable) --- python.html.markdown | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index f0b74d08..f44c23e9 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -158,19 +158,19 @@ li[2:] #=> [4, 3] # Omit the end li[:3] #=> [1, 2, 4] -# Remove arbitrary elements from a list with del +# Remove arbitrary elements from a list with `del` del li[2] # li is now [1, 2, 3] # You can add lists li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li and other_li is left alone -# Concatenate lists with extend +# 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 +# Check for existence in a list with `in` 1 in li #=> True -# Examine the length with len +# Examine the length with `len()` len(li) #=> 6 @@ -201,37 +201,37 @@ filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with [] filled_dict["one"] #=> 1 -# Get all keys as a list +# Get all keys as a list with `keys()` filled_dict.keys() #=> ["three", "two", "one"] # Note - Dictionary key ordering is not guaranteed. # Your results might not match this exactly. -# Get all values as a list +# Get all values as a list with `values()` filled_dict.values() #=> [3, 2, 1] # Note - Same as above regarding key ordering. -# Check for existence of keys in a dictionary with in +# 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 +# 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 method is a safe way to add new key-value pair into dictionary +# `setdefault()` method is a safe way to add new key-value pair into dictionary filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 # Sets store ... well sets empty_set = set() -# Initialize a set with a bunch of values +# Initialize a "set()" with a bunch of values 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 @@ -312,7 +312,7 @@ while x < 4: # Works on Python 2.6 and up: try: - # Use raise to raise an error + # 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. @@ -322,7 +322,7 @@ except IndexError as e: ## 4. Functions #################################################### -# Use def to create new functions +# Use `def` to create new functions def add(x, y): print "x is %s and y is %s" % (x, y) return x + y # Return values with a return statement @@ -359,7 +359,7 @@ all_the_args(1, 2, a=3, b=4) prints: {"a": 3, "b": 4} """ -# When calling functions, you can do the opposite of varargs/kwargs! +# 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} @@ -402,7 +402,7 @@ class Human(object): # Assign the argument to the instance's name attribute self.name = name - # An instance method. All methods take self as the first argument + # An instance method. All methods take `self` as the first argument def say(self, msg): return "%s: %s" % (self.name, msg) -- cgit v1.2.3 From 06144440549539c6a5fb714ca0dc7515028a195a Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Fri, 23 Aug 2013 00:09:16 +0300 Subject: removed whitespace from end of the file --- tr-tr/python-tr.html.markdown | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown index 410339dd..f7314f0f 100644 --- a/tr-tr/python-tr.html.markdown +++ b/tr-tr/python-tr.html.markdown @@ -500,29 +500,3 @@ dir(math) * [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 f11d5cf90c69d7777d5c022e01921fe3bd5961b6 Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Thu, 22 Aug 2013 16:38:07 -0700 Subject: add more doc details, some more examples --- haxe.html.markdown | 90 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 50 insertions(+), 40 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 9ef69c64..1fa84a6d 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -16,27 +16,37 @@ references. 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 compiler, while in the same directory as LearnHaxe.hx: - haxe -main LearnHaxe3 -x out - */ + $> haxe -main LearnHaxe3 -x out -// Let's start with comments... this is a single line comment + Look for the slash-star marks surrounding these paragraphs. We are inside + a "Multiline comment". We can leave some notes here that will get ignored + by the compiler. + + Multiline comments are also used to generate javadoc-style documentation for + haxedoc. They will be used for haxedoc if they immediately precede a class, + class function, or class variable. -/* - And this is multiline. Multiline comments are also used to generate - javadoc-style documentation for haxedoc. They will be used if they precede - a class, class function, or class variable. */ +// Double slashes like this will give a single-line comment + + /* - This is your first actual haxe code, 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). + 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). */ package; // empty package, no namespace. /* - if you import code from other files, it must be declared before the rest of - the code. + 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. + + 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: */ import haxe.ds.ArraySort; @@ -44,8 +54,8 @@ import haxe.ds.ArraySort; import haxe.ds.*; /* - you can also import classes in a special way, enabling them to extend the - functionality of other classes. More on 'using' later. + 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. */ using StringTools; @@ -55,9 +65,13 @@ using StringTools; */ typedef FooString = String; -// Typedefs can also use "structural" types, more on that later as well! +// Typedefs can also reference "structural" types, more on that later as well. typedef FooObject = { foo: String }; +/* + Here's the class definition. It's the main class for the file, since it has + the same name (LearnHaxe3). + */ class LearnHaxe3{ /* If you want certain code to run automatically, you need to put it in @@ -66,6 +80,7 @@ class LearnHaxe3{ arguments above. */ static function main(){ + /* Trace is the default method of printing haxe expressions to the screen. Different targets will have different methods of @@ -75,8 +90,6 @@ class LearnHaxe3{ Finally, It's possible to prevent traces from showing by using the "--no-traces" argument on the compiler. */ - - trace("Hello World, with trace()!"); /* @@ -84,16 +97,11 @@ class LearnHaxe3{ a representation of the expression as best it can. You can also concatenate strings with the "+" operator: */ - trace( - " Integer: " + 10 + - " Float: " + 3.14 + - " Boolean: " + true - ); - + trace( " Integer: " + 10 + " Float: " + 3.14 + " Boolean: " + true); /* - Remember what I said about expressions needing semicolons? You - can put more than one expression on a line if you want. + In Haxe, it's required to separate expressions in the same block with + semicolons. But, you can put two expressions on one line: */ trace('two expressions..'); trace('one line'); @@ -107,7 +115,6 @@ class LearnHaxe3{ You can save values and references to data structures using the "var" keyword: */ - var an_integer:Int = 1; trace(an_integer + " is the value for an_integer"); @@ -119,7 +126,6 @@ class LearnHaxe3{ the haxe compiler is inferring that the type of another_integer should be "Int". */ - var another_integer = 2; trace(another_integer + " is the value for another_integer"); @@ -156,6 +162,12 @@ class LearnHaxe3{ var a_sub_string = a_string.substr(0,4); trace(a_sub_string + " is the value for a_sub_string"); + /* + 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')))"); + /* Arrays are zero-indexed, dynamic, and mutable. Missing values are defined as null. @@ -199,7 +211,7 @@ class LearnHaxe3{ trace(m3 + " is the value for m3"); /* - Haxe has many more common datastructures in the haxe.ds module, such as + Haxe has some more common datastructures in the haxe.ds module, such as List, Stack, and BalancedTree */ @@ -225,7 +237,7 @@ class LearnHaxe3{ trace((3 >= 2) + " is the value for 3 >= 2"); trace((3 <= 2) + " is the value for 3 <= 2"); - //bitwise operators + // standard bitwise operators /* ~ Unary bitwise complement << Signed left shift @@ -411,12 +423,11 @@ class LearnHaxe3{ As mentioned before, Haxe is a statically typed language. All in all, static typing is a wonderful thing. It enables - autocompletions, and can be used to check the correctness of a - program in very thorough ways. Plus, the Haxe compiler is super fast. - You probably won't be waiting on it very much. + precise autocompletions, and can be used to thoroughly check the + correctness of a program. Plus, the Haxe compiler is super fast. *HOWEVER*, there are times when you just wish the compiler would let - something slide, and not throw a type error in a limited case. + something slide, and not throw a type error in a given case. To do this, Haxe has two separate keywords. The first is the "Dynamic" type: @@ -429,12 +440,12 @@ class LearnHaxe3{ wildcard variable: You can pass it instead of any variable type, and you can assign any variable type you want. - The other more extreme option is the "untyped" keyword + The other more extreme option is the "untyped" keyword: */ untyped { - var x:Int = 'foo'; - var y:String = 4; + var x:Int = 'foo'; // this can't be right! + var y:String = 4; // madness! } /* @@ -444,9 +455,9 @@ class LearnHaxe3{ situations where type checking is a hinderance. In general, skipping type checks is *not* recommended. Use the - enum, inheritance, or structural type models in order to verify the - correctness of your program. Only when you're certain that none of - the type models work should you resort to "Dynamic" or "untyped". + enum, inheritance, or structural type models in order to help ensure + the correctness of your program. Only when you're certain that none + of the type models work should you resort to "Dynamic" or "untyped". */ ////////////////////////////////////////////////////////////////// @@ -459,7 +470,6 @@ class LearnHaxe3{ Create an instance of FooClass. The classes for this are at the end of the file. */ - var instance = new FooClass(3); // read the public variable normally -- cgit v1.2.3 From de027ddf9e1c8124dd47f077c3ba2ed01d9cefdd Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Fri, 23 Aug 2013 09:54:21 +0300 Subject: regular quotes instead of `. --- python.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index f44c23e9..bad9a360 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -93,8 +93,8 @@ not False #=> True # None is an object None #=> None -# Don't use the equality `==` symbol to compare objects to None -# Use `is` instead +# Don't use the equality "==" symbol to compare objects to None +# Use "is" instead "etc" is None #=> False None is None #=> True @@ -158,19 +158,19 @@ li[2:] #=> [4, 3] # Omit the end li[:3] #=> [1, 2, 4] -# Remove arbitrary elements from a list with `del` +# Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] # You can add lists li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li and other_li is left alone -# Concatenate lists with `extend()` +# 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` +# Check for existence in a list with "in" 1 in li #=> True -# Examine the length with `len()` +# Examine the length with "len()" len(li) #=> 6 @@ -201,30 +201,30 @@ filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with [] filled_dict["one"] #=> 1 -# Get all keys as a list with `keys()` +# Get all keys as a list with "keys()" filled_dict.keys() #=> ["three", "two", "one"] # Note - Dictionary key ordering is not guaranteed. # Your results might not match this exactly. -# Get all values as a list with `values()` +# Get all values as a list with "values()" filled_dict.values() #=> [3, 2, 1] # Note - Same as above regarding key ordering. -# Check for existence of keys in a dictionary with `in` +# 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 +# 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()` method is a safe way to add new key-value pair into dictionary +# "setdefault()" method is a safe way to add new key-value pair into dictionary filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 @@ -284,7 +284,7 @@ for animal in ["dog", "cat", "mouse"]: 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 @@ -312,7 +312,7 @@ while x < 4: # Works on Python 2.6 and up: try: - # Use `raise` to raise an error + # 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. @@ -322,7 +322,7 @@ except IndexError as e: ## 4. Functions #################################################### -# Use `def` to create new functions +# Use "def" to create new functions def add(x, y): print "x is %s and y is %s" % (x, y) return x + y # Return values with a return statement @@ -402,7 +402,7 @@ class Human(object): # Assign the argument to the instance's name attribute self.name = name - # An instance method. All methods take `self` as the first argument + # An instance method. All methods take "self" as the first argument def say(self, msg): return "%s: %s" % (self.name, msg) -- cgit v1.2.3 From aaca821ee6886cf3888023bb770010f54015812d Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Fri, 23 Aug 2013 09:55:56 +0300 Subject: regular quotes instead of `. --- tr-tr/python-tr.html.markdown | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown index f7314f0f..01285080 100644 --- a/tr-tr/python-tr.html.markdown +++ b/tr-tr/python-tr.html.markdown @@ -103,8 +103,8 @@ not False #=> True # None bir objedir None #=> None -# `==` eşitliğini non objesi ile karşılaştırmak için kullanmayın. -# Onun yerine `is` kullanın. +# "==" eşitliğini non objesi ile karşılaştırmak için kullanmayın. +# Onun yerine "is" kullanın. "etc" is None #=> False None is None #=> True @@ -135,7 +135,7 @@ some_var #=> 5 # bilgi için kontrol akışı kısmına göz atınız. some_other_var # isim hatası fırlatılır -# isterseniz `if`i bir ifade gibi kullanabilirsiniz. +# isterseniz "if"i bir ifade gibi kullanabilirsiniz. "yahoo!" if 3 > 2 else 2 #=> "yahoo!" # Listeler @@ -158,7 +158,7 @@ li[0] #=> 1 # Son elemanın değerine ulaşmak li[-1] #=> 3 -# Listede bulunmayan bir index'teki elemana erişirken `IndexError` hatası +# Listede bulunmayan bir index'teki elemana erişirken "IndexError" hatası # fırlatılır li[4] # IndexError fırlatılır @@ -170,7 +170,7 @@ li[2:] #=> [4, 3] # Sonu ihmal etme li[:3] #=> [1, 2, 4] -# `del` ile istenilen bir elemanı listeden silmek +# "del" ile istenilen bir elemanı listeden silmek del li[2] # li is now [1, 2, 3] # Listeleri birbiri ile birleştirebilirsiniz. @@ -179,7 +179,7 @@ li + other_li #=> [1, 2, 3, 4, 5, 6] - Not: li ve other_li yanlız bırakılır # extend ile listeleri birleştirmek li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] -# bir değerin liste içerisinde varlığını `in` ile kontrol etmek +# bir değerin liste içerisinde varlığını "in" ile kontrol etmek 1 in li #=> True # "len" ile listenin uzunluğunu bulmak @@ -213,23 +213,23 @@ filled_dict = {"one": 1, "two": 2, "three": 3} # Değere ulaşmak için [] kullanılır filled_dict["one"] #=> 1 -# Tüm anahtarlara(key) `keys()` metodu ile ulaşılır +# Tüm anahtarlara(key) "keys()" metodu ile ulaşılır filled_dict.keys() #=> ["three", "two", "one"] # Not - Sözlüklerin anahtarlarının sıralı geleceği garanti değildir # Sonuçlarınız değer listesini aldığınızda tamamen eşleşmeyebilir -# Tüm değerleri almak için `values()` kullanabilirsiniz. +# Tüm değerleri almak için "values()" kullanabilirsiniz. filled_dict.values() #=> [3, 2, 1] # Not - Sıralama ile ilgili anahtarlar ile aynı durum geçerlidir. -# Bir anahtarın sözlükte oluş olmadığını `in` ile kontrol edilebilir +# Bir anahtarın sözlükte oluş olmadığını "in" ile kontrol edilebilir "one" in filled_dict #=> True 1 in filled_dict #=> False # Olmayan bir anahtar çağrıldığında KeyError fırlatılır. filled_dict["four"] # KeyError -# `get()` metodu KeyError fırlatılmasını önler +# "get()" metodu KeyError fırlatılmasını önler filled_dict.get("one") #=> 1 filled_dict.get("four") #=> None # get() metodu eğer anahtar mevcut değilse varsayılan bir değer atama @@ -237,7 +237,7 @@ filled_dict.get("four") #=> None filled_dict.get("one", 4) #=> 1 filled_dict.get("four", 4) #=> 4 -# `setdefault()` metodu sözlüğe yeni bir key-value eşleşmesi eklemenin +# "setdefault()" metodu sözlüğe yeni bir key-value eşleşmesi eklemenin # güvenli bir yoludur. filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 @@ -298,7 +298,7 @@ for animal in ["dog", "cat", "mouse"]: print "%s is a mammal" % animal """ -`range(number)` ifadesi sıfırdan verilen sayıya kadar bir sayı listesi döner +"range(number)" ifadesi sıfırdan verilen sayıya kadar bir sayı listesi döner Ekrana yazdırılan: 0 1 @@ -336,7 +336,7 @@ except IndexError as e: #################################################### -# Yeni bir fonksiyon oluşturmak için `def` kullanılır +# Yeni bir fonksiyon oluşturmak için "def" kullanılır def add(x, y): print "x is %s and y is %s" % (x, y) return x + y # Return values with a return statement @@ -407,27 +407,27 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] # We subclass from object to get a class. class Human(object): - # Bir sınıf özelliği. Bu sınıfın tüm `instance`larına paylaşılmıştır. + # Bir sınıf özelliği. Bu sınıfın tüm "instance"larına paylaşılmıştır. species = "H. sapiens" # Basic initializer def __init__(self, name): - # Metoda gelen argümanın değerini sınıfın elemanı olan `name` + # Metoda gelen argümanın değerini sınıfın elemanı olan "name" # değişkenine atama self.name = name - # Bir instance metodu. Tüm metodlar ilk argüman olarak `self` + # Bir instance metodu. Tüm metodlar ilk argüman olarak "self" # parametresini alır def say(self, msg): return "%s: %s" % (self.name, msg) - # Bir sınıf metodu tüm `instance`lar arasında paylaşılır + # Bir sınıf metodu tüm "instance"lar arasında paylaşılır # İlk argüman olarak sınıfı çağırarak çağrılırlar @classmethod def get_species(cls): return cls.species - # bBir statik metod bir sınıf ya da instance referansı olmadan çağrılır + # Bir statik metod bir sınıf ya da instance referansı olmadan çağrılır @staticmethod def grunt(): return "*grunt*" -- cgit v1.2.3 From 0f82b183493a1f6142a6e7335d37891aae67c3dc Mon Sep 17 00:00:00 2001 From: Justin Donaldson Date: Fri, 23 Aug 2013 16:24:35 -0700 Subject: add more details on interpolated strings, clean up the naming for oop section --- haxe.html.markdown | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 1fa84a6d..f4694fcb 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -151,8 +151,14 @@ class LearnHaxe3{ var a_string = "some" + 'string'; // strings can have double or single quotes trace(a_string + " is the value for a_string"); + /* + Strings can be "interpolated" by inserting variables into specific + positions. The string must be single quoted, and the variable must + be preceded with "$". Expressions can be enclosed in ${...}. + */ var x = 1; var an_interpolated_string = 'the value of x is $x'; + var another_interpolated_string = 'the value of x + 1 is ${x + 1}'; /* Strings are immutable, instance methods will return a copy of @@ -470,27 +476,27 @@ class LearnHaxe3{ Create an instance of FooClass. The classes for this are at the end of the file. */ - var instance = new FooClass(3); + var foo_instance = new FooClass(3); // read the public variable normally - trace(instance.public_any + " is the value for instance.public_any"); + trace(foo_instance.public_any + " is the value for foo_instance.public_any"); // we can read this variable - trace(instance.public_read + " is the value for instance.public_read"); + trace(foo_instance.public_read + " is the value for foo_instance.public_read"); // but not write it - // instance.public_write = 4; // this will throw an error if uncommented: - // trace(instance.public_write); // as will this. + // foo_instance.public_write = 4; // this will throw an error if uncommented: + // trace(foo_instance.public_write); // as will this. - trace(instance + " is the value for instance"); // calls the toString method - trace(instance.toString() + " is the value for instance.toString()"); // same thing + trace(foo_instance + " is the value for foo_instance"); // calls the toString method + trace(foo_instance.toString() + " is the value for foo_instance.toString()"); // same thing /* - Instance has the "FooClass" type, while acceptBaseFoo has the - BaseFooClass type. However, since FooClass extends BaseFooClass, - it is accepted. + The foo_instance has the "FooClass" type, while acceptBarInstance + has the BarClass type. However, since FooClass extends BarClass, it + is accepted. */ - BaseFooClass.acceptBaseFoo(instance); + BarClass.acceptBarInstance(foo_instance); /* The classes below have some more advanced examples, the "example()" @@ -508,7 +514,7 @@ class LearnHaxe3{ /* This is the "child class" of the main LearnHaxe3 Class */ -class FooClass extends BaseFooClass implements BaseFooInterface{ +class FooClass extends BarClass implements BarInterface{ public var public_any:Int; // public variables are accessible anywhere public var public_read (default,null): Int; // use this style to only enable public read public var public_write (null, default): Int; // or public write @@ -520,7 +526,7 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ // a public constructor public function new(arg:Int){ - super(); // call the constructor of the parent object, since we extended BaseFooClass + super(); // call the constructor of the parent object, since we extended BarClass this.public_any= 0; this._private = arg; @@ -544,7 +550,7 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ } // this class needs to have this function defined, since it implements - // the BaseFooInterface interface. + // the BarInterface interface. public function baseFunction(x: Int) : String{ // convert the int to string automatically return x + " was passed into baseFunction!"; @@ -554,19 +560,19 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ /* A simple class to extend */ -class BaseFooClass { +class BarClass { var base_variable:Int; public function new(){ base_variable = 4; } - public static function acceptBaseFoo(b:BaseFooClass){ + public static function acceptBarInstance(b:BarClass){ } } /* A simple interface to implement */ -interface BaseFooInterface{ +interface BarInterface{ public function baseFunction(x:Int):String; } -- cgit v1.2.3 From f88b0ba326f40a9e14b24438ecc1963d0138973f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20B=C3=BCttner?= Date: Sat, 24 Aug 2013 12:23:41 +0100 Subject: Fixed typo in Julia document Element was popped from wrong array. --- julia.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 1023e303..cf3a464b 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -147,7 +147,7 @@ push!(a,3) #=> [1,2,4,3] append!(a,b) #=> [1,2,4,3,4,5,6] # Remove from the end with pop -pop!(a) #=> 6 and b is now [4,5] +pop!(b) #=> 6 and b is now [4,5] # Let's put it back push!(b,6) # b is now [4,5,6] again. -- cgit v1.2.3 From 0fc4b4d5d53a677cfc8c9889af328427c2fa6e24 Mon Sep 17 00:00:00 2001 From: alswl Date: Sat, 24 Aug 2013 23:27:50 +0800 Subject: add xiaoqi's translation --- zh-cn/r-cn.html.markdown | 691 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 691 insertions(+) create mode 100644 zh-cn/r-cn.html.markdown diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown new file mode 100644 index 00000000..1bd83c60 --- /dev/null +++ b/zh-cn/r-cn.html.markdown @@ -0,0 +1,691 @@ + +# Comments start with hashtags. +# 评论以 # 开始 + +# You can't make a multi-line comment per se, +# but you can stack multiple comments like so. +# 你不能在每一个se下执行多个注释, +# 但是你可以像这样把命注释内容堆叠起来. +# in Windows, hit COMMAND-ENTER to execute a line +# 在windows下,点击回车键来执行一条命令 + + +################################################################### +# Stuff you can do without understanding anything about programming +# 素材可以使那些不懂编程的人同样得心用手 +################################################################### + +data() # Browse pre-loaded data sets +data() # 浏览预加载的数据集 +data(rivers) # Lengths of Major North American Rivers +data(rivers) # 北美主要河流的长度(数据集) +ls() # Notice that "rivers" appears in the workspace +ls() # 在工作站中查看”河流“文件夹是否出现 +head(rivers) # peek at the dataset +head(rivers) # 浏览数据集 +# 735 320 325 392 524 450 +length(rivers) # how many rivers were measured? +# 141 +length(rivers) # 测量了多少条河流 +summary(rivers) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 +#查看”河流“数据集的特征 +# 最小值. 1st Qu. 中位数 平均值 最大值 +# 135.0 310.0 425.0 591.2 680.0 3710.0 +stem(rivers) #stem-and-leaf plot (like a histogram) +stem(rivers) #茎叶图(一种类似于直方图的展现形式) + + + + +# The decimal point is 2 digit(s) to the right of the | +# 小数点向|右边保留两位数字 +# +# 0 | 4 +# 2 | 011223334555566667778888899900001111223333344455555666688888999 +# 4 | 111222333445566779001233344567 +# 6 | 000112233578012234468 +# 8 | 045790018 +# 10 | 04507 +# 12 | 1471 +# 14 | 56 +# 16 | 7 +# 18 | 9 +# 20 | +# 22 | 25 +# 24 | 3 +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | +# 36 | 1 + +stem(log(rivers)) #Notice that the data are neither normal nor log-normal! Take that, Bell Curve fundamentalists. +stem(log(rivers)) #查看数据集的方式既不是标准形式,也不是取log后的结果! 看起来,是钟形曲线形式的基本数据集 + +# The decimal point is 1 digit(s) to the left of the | +# 小数点向|左边保留一位数字 +# +# 48 | 1 +# 50 | +# 52 | 15578 +# 54 | 44571222466689 +# 56 | 023334677000124455789 +# 58 | 00122366666999933445777 +# 60 | 122445567800133459 +# 62 | 112666799035 +# 64 | 00011334581257889 +# 66 | 003683579 +# 68 | 0019156 +# 70 | 079357 +# 72 | 89 +# 74 | 84 +# 76 | 56 +# 78 | 4 +# 80 | +# 82 | 2 + + +hist(rivers, col="#333333", border="white", breaks=25) #play around with these parameters +hist(rivers, col="#333333", border="white", breaks=25) #给river做统计频数直方图,包含了这些参数(名称,颜色,边界,空白) +hist(log(rivers), col="#333333", border="white", breaks=25) #you'll do more plotting later +hist(log(rivers), col="#333333", border="white", breaks=25) #稍后你还可以做更多的绘图,统计频数直方图,包含了这些参数(river数据集的log值,颜色,边界,空白) +hist(rivers, col="#333333", border="white", breaks=25) #play around with these parameters +hist(rivers, col="#333333", border="white", breaks=25) #运行同济频数直方图的这些参数 + +#Here's another neat data set that comes pre-loaded. R has tons of these. data() +#这里还有其他一些简洁的数据集可以被提前加载。R语言包括大量这种类型的数据集 +data(discoveries) +#数据集(发现) +plot(discoveries, col="#333333", lwd=3, xlab="Year", main="Number of important discoveries per year") +#绘图(发现,颜色负值,宽度负值,X轴名称,主题:Number of important discoveries per year) + + + +#rather than leaving the default ordering (by year) we could also sort to see what's typical +#宁可舍弃也不执行排序(按照年份完成)我们可以分类来查看这是那些类型 +sort(discoveries) #给(发现)分类 +# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 +# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 +# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 +# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 + +stem(discoveries, scale=2) +#茎叶图(发现,在原来的基础上降尺度扩大两倍) +# +# The decimal point is at the | +# 小数点在| +# +# 0 | 000000000 +# 1 | 000000000000 +# 2 | 00000000000000000000000000 +# 3 | 00000000000000000000 +# 4 | 000000000000 +# 5 | 0000000 +# 6 | 000000 +# 7 | 0000 +# 8 | 0 +# 9 | 0 +# 10 | 0 +# 11 | +# 12 | 0 + +max(discoveries) +#最大值(发现) +# 12 + +summary(discoveries) +#数据集特征(发现) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 + + + + +#Basic statistical operations don't require any programming knowledge either +#基本的统计学操作也不需要任何编程知识 + +#roll a die a few times +#随机输出数据 +round(runif(7, min=.5, max=6.5)) +#round(产生均匀分布的随机数,进行四舍五入(7个, 最小值为0.5, max=6.5)) +# 1 4 6 1 4 6 4 + +#your numbers will differ from mine unless we set the same random.seed(31337) +#你输出的结果将会与我们给出的不同,除非我们设置了同样的随机种子 random.seed(31337) + + +#draw from a standard Gaussian 9 times +#从标准高斯函数中随机的提取9次结果 +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + + + + + + + +######################### +# Basic programming stuff +# 基本的编程素材 +######################### + +# NUMBERS + +# "numeric" means double-precision floating-point numbers +#“数值”指的是双精度的浮点数 +5 # 5 +class(5) # "numeric" +#定义(5)为数值型变量 # "numeric" +5e4 # 50000 #handy when dealing with large,small,or variable orders of magnitude +#5×104次方 可以手写输入改变数量级的大小将变量扩大 +6.02e23 # Avogadro's number +#阿伏伽德罗常数 +1.6e-35 # Planck length +#布朗克长度 + +# long-storage integers are written with L +#长存储整数并用L书写 +5L # 5 +#输出5L +class(5L) # "integer" +#(5L)的类型, 整数型 + +# Try ?class for more information on the class() function +#可以自己试一试?用class()功能函数定义更多的信息 +# In fact, you can look up the documentation on `xyz` with ?xyz +#事实上,你可以找一些文件查阅“xyz”以及xyz的差别 +# or see the source for `xyz` by evaluating xyz +#或者通过评估xyz来查看“xyz”的来源 + +# Arithmetic +#算法 +10 + 66 # 76 +53.2 - 4 # 49.2 +2 * 2.0 # 4 +3L / 4 # 0.75 +3 %% 2 # 1 + +# Weird number types +#超自然数的类型 +class(NaN) # "numeric" +class(Inf) # "numeric" +class(-Inf) # "numeric" #used in for example integrate( dnorm(x), 3, Inf ) -- which obviates Z-score tables +#定义以上括号内的数均为数值型变量,利用实例中的整数(正态分布函数(X),3,Inf )消除Z轴列表 + +# but beware, NaN isn't the only weird type... +# 但要注意,NaN并不是仅有的超自然类型。。。 +class(NA) # see below +#定义(NA)下面的部分会理解 +class(NULL) # NULL +#定义(NULL)无效的 + + +# SIMPLE LISTS +#简单的数据集 +c(6, 8, 7, 5, 3, 0, 9) # 6 8 7 5 3 0 9 +#输出数值型向量(6 8 7 5 3 0 9) +c('alef', 'bet', 'gimmel', 'dalet', 'he') +#输出字符型变量# "alef" "bet" "gimmel" "dalet" "he" +c('Z', 'o', 'r', 'o') == "Zoro" # FALSE FALSE FALSE FALSE +#输出逻辑型变量FALSE FALSE FALSE FALSE + +#some more nice built-ins +#一些优雅的内置功能 +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +#从5-15输出,以进度为1递增 + +seq(from=0, to=31337, by=1337) +#输出序列(从0到31337,以1337递增) +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 + +letters +#字符型变量,26个 +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" + +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" +#表示月份的变量 + + +# Access the n'th element of a list with list.name[n] or sometimes list.name[[n]] +#访问数据集名字为[n]的第n个元素 + +letters[18] # "r" +#访问其中的第18个变量 +LETTERS[13] # "M" +#用大写访问其中的第13个变量 +month.name[9] # "September" +#访问名字文件中第9个变量 +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +#访问向量中的第三个变量 + + + +# CHARACTERS +#特性 +# There's no difference between strings and characters in R +# 字符串和字符在R语言中没有区别 +"Horatio" # "Horatio" +#字符输出"Horatio" +class("Horatio") # "character" +#字符串输出("Horatio") # "character" +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +#提取字符串("Fortuna multis dat nimis, nulli satis.", 第9个到15个之前并输出) +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." +#替换字符春,用ø替换u + + + +# LOGICALS +#逻辑值 + +# booleans +#布尔运算 +class(TRUE) # "logical" +#定义为真,逻辑型 +class(FALSE) # "logical" +#定义为假,逻辑型 +# Behavior is normal +#表现的标准形式 +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE +# Missing data (NA) is logical, too +#缺失数据也是逻辑型的 +class(NA) # "logical" +#定义NA为逻辑型 + + + +# FACTORS +#因子 +# The factor class is for categorical data +#因子是分类数据的定义函数 +# which can be ordered (like childrens' grade levels) +#可以使有序的(就像儿童的等级水平) +# or unordered (like gender) +#也可以是无序的(就像性别) +levels(factor(c("female", "male", "male", "female", "NA", "female"))) # "female" "male" "NA" +#c("female", "male", "male", "female", "NA", "female")向量,变量是字符型,levels factor()因子的等级水平 + +factor(c("female", "female", "male", "NA", "female")) +# female female male NA female +# Levels: female male NA + +data(infert) #Infertility after Spontaneous and Induced Abortion +#数据集(感染) 自然以及引产导致的不育症 +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" +#等级(感染与教育程度) 输出 + + + +# VARIABLES +#变量 + +# Lots of way to assign stuff +#许多种方式用来分配素材 +x = 5 # this is possible +#x = 5可能的 +y <- "1" # this is preferred +#y <- "1" 优先级的 +TRUE -> z # this works but is weird +#输出真实的,存在一个超自然数满足条件 + +# We can use coerce variables to different classes +#我们还可以使用枪支变量去进行不同的定义 +as.numeric(y) # 1 +#定义数值型 +as.character(x) # "5" +#字符型 + + +# LOOPS +#循环 + +# We've got for loops +#循环语句 +for (i in 1:4) { + print(i) +} +#定义一个i,从1-4输出 + +# We've got while loops +#我们可以获取循环结构 +a <- 10 +while (a > 4) { + cat(a, "...", sep = "") + a <- a - 1 +} +#把10负值为a,a<4,输出文件(a,"...",sep="" ),跳出继续下一个循环取a=a-1,如此循环,直到a=10终止 +# Keep in mind that for and while loops run slowly in R +#在R语言中牢记 for和它的循环结构 +# Operations on entire vectors (i.e. a whole row, a whole column) +#牢记矢量中附带的操作(例如,整行和整列) +# or apply()-type functions (we'll discuss later) are preferred +#或者优先使用()-函数,稍后会进行讨论 + +# IF/ELSE +#判断分支 + +# Again, pretty standard +#再一次,看这些优雅的标准 +if (4 > 3) { + print("Huzzah! It worked!") +} else { + print("Noooo! This is blatantly illogical!") +} + +# => +# [1] "Huzzah! It worked!" + +# FUNCTIONS +#功能函数 + +# Defined like so: +#定义如下 +jiggle <- function(x) { + x+ rnorm(x, sd=.1) #add in a bit of (controlled) noise + return(x) +} +#把功能函数x负值给jiggle, + +# Called like any other R function: +jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 + +######################### +# Fun with data: vectors, matrices, data frames, and arrays +# 数据参数:向量,矩阵,数据框,数组, +######################### + +# ONE-DIMENSIONAL +#单维度 +# You can vectorize anything, so long as all components have the same type +#你可以将任何东西矢量化,因此所有的组分都有相同的类型 +vec <- c(8, 9, 10, 11) +vec # 8 9 10 11 +# The class of a vector is the class of its components +#矢量class表示这一组分的类型 +class(vec) # "numeric" +# If you vectorize items of different classes, weird coercions happen +#如果你强制的将不同类型的classes矢量化,会发生超自然形式的函数,例如都转变成数值型、字符型 +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" + +# We ask for specific components like so (R starts counting from 1) +#我们可以找寻特定的组分,例如这个例子(R从1算起) +vec[1] # 8 +# We can also search for the indices of specific components, +#我们也可以从这些特定组分中找寻这些指标 +which(vec %% 2 == 0) # 1 3 +# or grab just the first or last entry in the vector +#抓取矢量中第1个和最后一个字符 +head(vec, 1) # 8 +tail(vec, 1) # 11 +#如果指数结束或不存在即"goes over" 可以获得NA +# If an index "goes over" you'll get NA: +vec[6] # NA +# You can find the length of your vector with length() +#你也可以找到矢量的长度 +length(vec) # 4 + +# You can perform operations on entire vectors or subsets of vectors +#你可以将整个矢量或者子矢量集进行展示 +vec * 4 # 16 20 24 28 +# +vec[2:3] * 5 # 25 30 +# and there are many built-in functions to summarize vectors +#这里有许多内置的功能函数,并且可对矢量特征进行总结 +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 + +# TWO-DIMENSIONAL (ALL ONE CLASS) +#二维函数 + +# You can make a matrix out of entries all of the same type like so: +#你可以建立矩阵,保证所有的变量形式相同 +mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +#建立mat矩阵,3行2列,从1到6排列,默认按列排布 +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Unlike a vector, the class of a matrix is "matrix", no matter what's in it +class(mat) # => "matrix" +# Ask for the first row +#访问第一行的字符 +mat[1,] # 1 4 +# Perform operation on the first column +#优先输入第一列,分别×3输出 +3 * mat[,1] # 3 6 9 +# Ask for a specific cell +#访问特殊的单元,第3行第二列 +mat[3,2] # 6 +# Transpose the whole matrix +#转置整个矩阵,变成2行3列 +t(mat) +# => +# [,1] [,2] [,3] +# [1,] 1 2 3 +# [2,] 4 5 6 + +# cbind() sticks vectors together column-wise to make a matrix +把两个矩阵按列合并,形成新的矩阵 +mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) +mat2 +# => +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" +# [4,] "4" "dog" +class(mat2) # matrix +#定义mat2矩阵 +# Again, note what happened! +#同样的注释 +# Because matrices must contain entries all of the same class, +#矩阵必须包含同样的形式 +# everything got converted to the character class +#每一个变量都可以转化成字符串形式 +c(class(mat2[,1]), class(mat2[,2])) + +# rbind() sticks vectors together row-wise to make a matrix +#按行合并两个向量,建立新的矩阵 +mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 2 4 5 +# [2,] 6 7 0 4 +# Aah, everything of the same class. No coercions. Much better. + +# TWO-DIMENSIONAL (DIFFERENT CLASSES) +##二维函数(不同的变量类型) + +# For columns of different classes, use the data frame +利用数组可以将不同类型放在一起 +dat <- data.frame(c(5,2,1,4), c("dog", "cat", "bird", "dog")) +#dat<-数据集(c(5,2,1,4), c("dog", "cat", "bird", "dog")) +names(dat) <- c("number", "species") # name the columns +#给每一个向量命名 +class(dat) # "data.frame" +#建立数据集dat +dat +# => +# number species +# 1 5 dog +# 2 2 cat +# 3 1 bird +# 4 4 dog +class(dat$number) # "numeric" +class(dat[,2]) # "factor" +# The data.frame() function converts character vectors to factor vectors +#数据集,将字符特征转化为因子矢量 + +# There are many twisty ways to subset data frames, all subtly unalike +#这里有许多种生成数据集的方法,所有的都很巧妙但又不相似 +dat$number # 5 2 1 4 +dat[,1] # 5 2 1 4 +dat[,"number"] # 5 2 1 4 + +# MULTI-DIMENSIONAL (ALL OF ONE CLASS) +#多维函数 +# Arrays creates n-dimensional tables +#利用数组创造一个n维的表格 +# You can make a two-dimensional table (sort of like a matrix) +#你可以建立一个2维表格(类型和矩阵相似) +array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +#数组(c(c(1,2,4,5),c(8,9,3,6)),有前两个向量组成,2行4列 +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 4 8 3 +# [2,] 2 5 9 6 +# You can use array to make three-dimensional matrices too +#你也可以利用数组建立一个三维的矩阵 +array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +# => +# , , 1 +# +# [,1] [,2] +# [1,] 2 8 +# [2,] 300 9 +# [3,] 4 0 +# +# , , 2 +# +# [,1] [,2] +# [1,] 5 66 +# [2,] 60 7 +# [3,] 0 847 + +# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES) +#列表(多维的,不同类型的) + +# Finally, R has lists (of vectors) +#R语言有列表的形式 +list1 <- list(time = 1:40) +list1$price = c(rnorm(40,.5*list1$time,4)) # random +list1 + +# You can get items in the list like so +#你可以获得像上面列表的形式 +list1$time +# You can subset list items like vectors +#你也可以获取他们的子集,一种类似于矢量的形式 +list1$price[4] + +######################### +# The apply() family of functions +#apply()函数家族的应用 +######################### + +# Remember mat? +#输出mat矩阵 +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X +#使用(X, MARGIN, FUN)将一个function功能函数根据其特征应用到矩阵x中 +# over rows (MAR = 1) or columns (MAR = 2) +#规定行列,其边界分别为1,2 +# That is, R does FUN to each row (or column) of X, much faster than a +#即就是,R定义一个function使每一行/列的x快于一个for或者while循环 +# for or while loop would do +apply(mat, MAR = 2, myFunc) +# => +# [,1] [,2] +# [1,] 3 15 +# [2,] 7 19 +# [3,] 11 23 +# Other functions: ?lapply, ?sapply +其他的功能函数, + +# Don't feel too intimidated; everyone agrees they are rather confusing +#不要被这些吓到,许多人在此都会容易混淆 +# The plyr package aims to replace (and improve upon!) the *apply() family. +#plyr程序包的作用是用来改进family函数家族 + +install.packages("plyr") +require(plyr) +?plyr + +######################### +# Loading data +######################### + +# "pets.csv" is a file on the internet +#"pets.csv" 是网上的一个文本 +pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") +#首先读取这个文本 +pets +head(pets, 2) # first two rows +#显示前两行 +tail(pets, 1) # last row +#显示最后一行 + +# To save a data frame or matrix as a .csv file +#以.csv格式来保存数据集或者矩阵 +write.csv(pets, "pets2.csv") # to make a new .csv file +#输出新的文本pets2.csv +# set working directory with setwd(), look it up with getwd() +#改变工作路径setwd(),查找工作路径getwd() + +# Try ?read.csv and ?write.csv for more information +#试着做一做以上学到的,或者运行更多的信息 + +######################### +# Plots +#画图 +######################### + +# Scatterplots! +#散点图 +plot(list1$time, list1$price, main = "fake data") +#作图,横轴list1$time,纵轴list1$price,主题fake data +# Regressions! +#退回 +linearModel <- lm(price ~ time, data = list1) +# 线性模型,数据集为list1,以价格对时间做相关分析模型 +linearModel # outputs result of regression +#输出拟合结果,并退出 +# Plot regression line on existing plot +#将拟合结果展示在图上,颜色设为红色 +abline(linearModel, col = "red") +# Get a variety of nice diagnostics +#也可以获取各种各样漂亮的分析图 +plot(linearModel) + +# Histograms! +#直方图 +hist(rpois(n = 10000, lambda = 5), col = "thistle") +#统计频数直方图() + +# Barplots! +#柱状图 +barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) +#作图,柱的高度负值c(1,4,5,1,2),各个柱子的名称"red","blue","purple","green","yellow" + +# Try the ggplot2 package for more and better graphics +#可以尝试着使用ggplot2程序包来美化图片 +install.packages("ggplot2") +require(ggplot2) +?ggplot2 + + -- cgit v1.2.3 From b921f8bb4b6ec221a2584fee89fd5577f0f11784 Mon Sep 17 00:00:00 2001 From: Mendor Date: Sat, 24 Aug 2013 20:54:31 +0400 Subject: Russian translation for Erlang page --- ru-ru/erlang-ru.html.markdown | 255 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 ru-ru/erlang-ru.html.markdown diff --git a/ru-ru/erlang-ru.html.markdown b/ru-ru/erlang-ru.html.markdown new file mode 100644 index 00000000..88d07c09 --- /dev/null +++ b/ru-ru/erlang-ru.html.markdown @@ -0,0 +1,255 @@ +--- +language: erlang +contributors: + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] + - ["Nikita Kalashnikov", "https://root.yuuzukiyo.net/"] +filename: learnerlang-ru.erl +lang: ru-ru +--- + +```erlang +% Символ процента предваряет однострочный комментарий. + +%% Два символа процента обычно используются для комментариев к функциям. + +%%% Три символа процента используются для комментариев к модулям. + +% Пунктуационные знаки, используемые в Erlang: +% Запятая (`,`) разделяет аргументы в вызовах функций, структурах данных и +% образцах. +% Точка (`.`) (с пробелом после них) разделяет функции и выражения в +% оболочке. +% Точка с запятой (`;`) разделяет выражения в следующих контекстах: +% формулы функций, выражения `case`, `if`, `try..catch` и `receive`. + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 1. Переменные и сопоставление с образцом. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +Num = 42. % Все названия переменных начинаются с большой буквы. + +% Erlang использует единичное присваивание переменным. Если вы попытаетесь +% присвоить другое значение переменной `Num`, вы получите ошибку. +Num = 43. % ** exception error: no match of right hand side value 43 + +% В большинстве языков `=` обозначает операцию присвоения. В отличие от них, в +% Erlang `=` — операция сопоставления с образцом. `Lhs = Rhs` на самом +% деле подразумевает «вычисли правую часть выражения (Rhs) и затем сопоставь +% результат с образцом слева (Lhs)». +Num = 7 * 6. + +% Числа с плавающей точкой. +Pi = 3.14159. + +% Атомы используются для представления различных нечисловых констант. Названия +% атомов начинаются с буквы в нижнем регистре, за которой могут следовать другие +% буквы английского алфавита, цифры, символ подчёркивания (`_`) или «собака» +% (`@`). +Hello = hello. +OtherNode = example@node. + +% Если в имени атома нужно использовать другие символы, кроме допустимых, +% имя атома необходимо взять в одинарные кавычки (`'`). +AtomWithSpace = 'some atom with space'. + +% Кортежы подобны структурам в языке C. +Point = {point, 10, 45}. + +% Если нужно извлечь определённые данные из кортежа, используется оператор +% сопоставления с образцом — `=`. +{point, X, Y} = Point. % X = 10, Y = 45 + +% Символ `_` может использоваться как «заполнитель» для переменных, значения +% которых в текущем выражении нас не интересуют. Он называется анонимной +% переменной. В отличие от остальных переменных, множественные использования +% `_` в одном образце не требуют, чтобы все значения, присваевыемые этой +% переменной, были идентичными. +Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}. +{_, {_, {_, Who}, _}, _} = Person. % Who = joe + +% Список создаётся путём заключения его элементов в квадратные скобки и +% разделения их запятыми. Отдельные элементы списка могут быть любого типа. +% Первый элемент списка называется головой списка. Список, получающийся в +% результате отделения головы, называется хвостом списка. +ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}]. + +% Если `T` — список, то `[H|T]` — тоже список, где `H` является головой, а `T` — +% хвостом. Вертикальная черта (`|`) разделяет голову и хвост списка. +% `[]` — пустой список. +% Мы можем извлекать элементы из списка с помощью сопоставления с образцом. +% Если у нас есть непустой список `L`, тогда выражение `[X|Y] = L`, где `X` и +% `Y` — свободные (не связанные с другими значениям) переменные, извлечёт голову +% списка в `X` и его хвост в `Y`. +[FirstThing|OtherThingsToBuy] = ThingsToBuy. +% FirstThing = {apples, 10} +% OtherThingsToBuy = {pears, 6}, {milk, 3} + +% В Erlang нет строк как отдельного типа. Все используемые в программах строки +% являются обычным списком целых чисел. Строковые значения всегда должны быть в +% двойных кавычках (`"`). +Name = "Hello". +[72, 101, 108, 108, 111] = "Hello". + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 2. Последовательное программирование. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Модуль — основная единица кода в Erlang. В них пишутся и сохраняются все +% функции. Модули хранятся в файлах с расширением `.erl`. +% Модули должны быть скомпилированы перед тем, как использовать код из них. +% Скомпилированный файл модуля имеет разрешение `.beam`. +-module(geometry). +-export([area/1]). % список функций, экспортируемых из модуля. + +% Функция `area` состоит из двух формул (clauses). Формулы отделяются друг от +% друга точкой с запятой, после последнего определения должна стоять точка с +% пробелом после неё. +% Каждое определение имеет заголовок и тело. Заголовок состоит из названия +% функции и образца (в скобках); тело состоит из последовательных выражений, +% вычисляемых, когда аргументы функции совпадают с образцом в заголовке. +% Сопоставление с образцами в заголовках происходит в том порядке, в котором +% они перечислены в определении функции. +area({rectangle, Width, Ht}) -> Width * Ht; +area({circle, R}) -> 3.14159 * R * R. + +% Компиляция файла с исходным кодом geometry.erl. +c(geometry). % {ok,geometry} + +% Необходимо указывать имя модуля вместе с именем функции для определения, какую +% именно фукнцию мы хотим вызвать. +geometry:area({rectangle, 10, 5}). % 50 +geometry:area({circle, 1.4}). % 6.15752 + +% В Erlang две функции с разной арностью (числом аргументов) в пределах одного +% модуля представляются как две разные функции. +-module(lib_misc). +-export([sum/1]). % экспорт функции `sum` с арностью 1, принимающую один аргумент. +sum(L) -> sum(L, 0). +sum([], N) -> N; +sum([H|T], N) -> sum(T, H+N). + +% Fun'ы — анонимные функции, называемые так по причине отсутствия имени. Зато +% их можно присваивать переменным. +Double = fun(X) -> 2*X end. % `Double` указывает на анонимную функцию с идентификатором: #Fun +Double(2). % 4 + +% Функции могут принимать fun'ы как параметры и возвращать их в качестве +% результата вычислений. +Mult = fun(Times) -> ( fun(X) -> X * Times end ) end. +Triple = Mult(3). +Triple(5). % 15 + +% Выделения списоков (list comprehensions) — выражения, создающие списки без +% применения анонимных функций, фильтров или map'ов. +% Запись `[F(X) || X <- L]` значит «список `F(X)`, где `X` последовательно +% выбирается из списка `L`». +L = [1,2,3,4,5]. +[2*X || X <- L]. % [2,4,6,8,10] +% В выделениях списков могут быть генераторы и фильтры для отделения подмножеств +% генерируемых значений. +EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] + +% Охранные выражения используются для простых проверок переменных в образцах, +% что значительно расширяет возможности сопоставления. Они могут использоваться +% в заголовках определений функций, предварённые ключевым словом `when`, а также +% в условных конструкциях. +max(X, Y) when X > Y -> X; +max(X, Y) -> Y. + +% Охранные выражения можно группировать, разделяя запятой. +% Последовательность `GuardExpr1, GuardExpr2, ..., GuardExprN` является истинной +% только в том случае, когда все выражения, которые она содержат, являются +% истинными. +is_cat(A) when is_atom(A), A =:= cat -> true; +is_cat(A) -> false. +is_dog(A) when is_atom(A), A =:= dog -> true; +is_dog(A) -> false. + +% Последовательность охранных выражений, разделённых точками с запятой, является +% истинной в том случае, если хотя бы одно выражение из списка `G1; G2; ...; Gn` +% является истинным. +is_pet(A) when is_dog(A); is_cat(A) -> true; +is_pet(A) -> false. + +% Записи предоставляют возможность именования определённых элементов в кортежах. +% Определения записей могут быть включены в исходный код модулей Erlang или же +% в заголовочные файлы с расширением `.hrl`. +-record(todo, { + status = reminder, % Значение по умолчанию. + who = joe, + text +}). + +% Для чтения определений записей из файлов в оболочке можно использовать команду +% `rr`. +rr("records.hrl"). % [todo] + +% Создание и изменение записей. +X = #todo{}. +% #todo{status = reminder, who = joe, text = undefined} +X1 = #todo{status = urgent, text = "Fix errata in book"}. +% #todo{status = urgent, who = joe, text = "Fix errata in book"} +X2 = X1#todo{status = done}. +% #todo{status = done,who = joe,text = "Fix errata in book"} + +% Условное выражение `case`. +% Функция `filter` возвращет список всех элементов `X` из списка `L`, для +% которых выражение `P(X)` является истинным. +filter(P, [H|T]) -> + case P(H) of + true -> [H|filter(P, T)]; + false -> filter(P, T) + end; +filter(P, []) -> []. +filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4] + +% Условное выражение `if`. +max(X, Y) -> + if + X > Y -> X; + X < Y -> Y; + true -> nil; + end. + +% Внимание: в выражении `if` должно быть как минимум одно охранное выраженние, +% вычисляющееся в true, иначе возникнет исключение. + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 3. Обработка исключений. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Исключения возникают в случае внутренних ошибок системы или вызываются +% непосредственно из кода программы с помощью вызовов `throw(Exception)`, +% `exit(Exception)` или `erlang:error(Exception)`. +generate_exception(1) -> a; +generate_exception(2) -> throw(a); +generate_exception(3) -> exit(a); +generate_exception(4) -> {'EXIT', a}; +generate_exception(5) -> erlang:error(a). + +% В Erlang есть два способа обработки исключений. Первый заключается в +% использовании выражения `try..catch` в функции, в которой возможен выброс +% исключения. +catcher(N) -> + try generate_exception(N) of + Val -> {N, normal, Val} + catch + throw:X -> {N, caught, thrown, X}; + exit:X -> {N, caught, exited, X}; + error:X -> {N, caught, error, X} + end. + +% Второй способ заключается в использовании `catch`. Во время поимки исключения +% оно преобразуется в кортеж с информацией об ошибке. +catcher(N) -> catch generate_exception(N). + +``` + +## Ссылки: + +* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/) +* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang) +* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/) +* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) -- cgit v1.2.3 From 7bebfa3b9d946759d356c9b0c1c7be0e5aee552d Mon Sep 17 00:00:00 2001 From: Osvaldo Mendoza Date: Sun, 25 Aug 2013 01:32:33 -0400 Subject: Added MATLAB as a new language --- matlab.html.markdown | 260 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 matlab.html.markdown diff --git a/matlab.html.markdown b/matlab.html.markdown new file mode 100644 index 00000000..507e9c85 --- /dev/null +++ b/matlab.html.markdown @@ -0,0 +1,260 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] +--- + +Matlab stands for Matrix Laboratory. It is a powerful numerical computing language commonly used in engineering and mathematics. + +If you have any feedback please feel free to reach me at +[@the_ozzinator](https://twitter.com/the_ozzinator), or +[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). + +```Matlab + + + +% Comments start with a percent sign. + +%{ Multi line comments look +something +like +this %} + +clear % Erases all your variables from memory +clc % Erases the writing on your Command Window +who % Displays all variables in memory +diary % History of session +ctrl-c % Abort current computation + +help command % Displays documentation for command in Command Window +lookfor command % Searches for a given command + + +% Output formatting +format short % 4 decimals in a floating number +format long % 15 decimals +fprintf + +% Variables & Expressions +myVariable = 4 % Notice Workspace pane shows newly created variable +myVariable = 4; % Semi colon suppresses output to the Command Window +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + +% Logicals +1 > 5 % ans = 0 +10 >= 10 % ans = 1 +3 ~= 4 % Not equal to -> ans = 1 +3 == 3 % equal to -> ans = 1 +3 > 1 && 4 > 1 % AND -> ans = 1 +3 > 1 || 4 > 1 % OR -> ans = 1 +~1 % NOT -> ans = 0 + +% Strings +a = 'MyString' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString + + +% Cells +a = {'one', 'two', 'three'} +a(1) % ans = 'one' - returns a cell +char(a(1)) % ans = one - returns a string + + +% Vectors +x = [4 32 53 7 1] +x(2) % ans = 32, indices in Matlab start 1, not 0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Column vector + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + +% Matrices +A = [1 2 3; 4 5 6; 7 8 9] +% Rows are seperated with a semi colon, each element is seperated with space or comma +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6, A(row, column) +A(2,3) = 42 % Update row 2 col 3 with 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Creates a new matrix from the old one +%ans = + +% 5 42 +% 8 9 + +A(:,1) % All rows in column 1 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % All columns in row 1 +%ans = + +% 1 2 3 + +A(:, [3 1 2]) %Rearrange the columns of original matrix +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +A(1, :) =[] %Delete the first row of the matrix + +size(A) % ans = 3 3 + +A' % Transpose the matrix + +[A ; A] % Concatenation of matrices +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + + +%Element by Element Arithmetic VS Matrix Arithmetic +A * B % Matrix multiplication +A .* B % Multiple each element in A by its corresponding element in B + + +%Plotting +x = 0:.10:2*pi % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 +y = sin(x) +plot(x,y) +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 + + +% .mat files +% Save the variables in your Workspace + +%M-file Scripts +%A script file is an external file that contains a sequence of statements. +%Better than typing your code in the Command Window +%Have .m extensions + + +%M-file Functions +%Programs that accept inputs and return an output +%Have .m extensions +% double_input.m - naming your ,m file the same as you call it in the file is required +function output = double_input(x) + %double_input(x) returns twice the value of x + output = 2*x; +end +double_input(6) % ans = 12 + +%User input +a = input('Enter the value: ') + +%Reading in data +fopen(filename) + +%Output +disp(a) % Print out the value of variable a +disp('Hello World') % Print out a string +fprintf % More control display to Command Window + +%Conditional statements +if a > 15 + disp('Greater than 15') +elseif a == 23 + disp('a is 23') +else + disp('neither condition met') +end + +%Looping +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + + +%Connecting to a MySQL Database +dbname = 'database_name'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] %Example sql statement +a = fetch(conn, sql) %a will contain your data + + +% Common math functions +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand +randi + +% Common constants +pi +NaN +inf + +% 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 +inv(A) % Inverse of matrix A +det(A) % Determinant of A +eig(A) %Eigenvalues and eigenvectors of A +isempty(A) % Tests if array is empty +isequal(A, B) %Tests equality of two arrays +numel(A) %Number of elements in matrix + + + +``` + +## More on Matlab + +* The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) -- cgit v1.2.3 From ef0601bab5c3f7f57e584594fc34da87cf8cce9c Mon Sep 17 00:00:00 2001 From: Afaq Date: Sun, 25 Aug 2013 11:43:07 -0400 Subject: Updated PHP doc to include print_r() and var_dump() --- php.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index 083574ee..1a07777a 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -176,6 +176,11 @@ $y = 0; echo $x; // => 2 echo $z; // => 0 +// Dumps type and value of variable to stdout +var_dumb($z); // prints int(3) + +// Prints variable to stdout in human-readable format +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) /******************************** * Logic -- cgit v1.2.3 From 7af1a853d474fce4feae2429d5e194649fc59105 Mon Sep 17 00:00:00 2001 From: Afaq Date: Sun, 25 Aug 2013 11:49:49 -0400 Subject: Correction to variable output of var_dump() --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index 1a07777a..1cc6d2c5 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -177,7 +177,7 @@ echo $x; // => 2 echo $z; // => 0 // Dumps type and value of variable to stdout -var_dumb($z); // prints int(3) +var_dumb($z); // prints int(0) // Prints variable to stdout in human-readable format print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) -- cgit v1.2.3 From c7a1136772588e57a3f9c20be9102a80a6f7f3e8 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 27 Aug 2013 21:23:09 -0700 Subject: Edits --- bash.html.markdown | 2 -- de-de/bash-de.html.markdown | 11 +++++++---- de-de/git-de.html.markdown | 4 ++-- git.html.markdown | 3 +-- haxe.html.markdown | 2 +- zh-cn/go-zh.html.markdown | 8 ++++---- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 7421f880..a0c43c12 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -1,12 +1,10 @@ --- - category: tool tool: bash contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Darren Lin", "https://github.com/CogBear"] filename: LearnBash.sh - --- Bash is a name of the unix shell, which was also distributed as the shell for the GNU operating system and as default shell on Linux and Mac OS X. diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index 107b8a07..9e3d7bc8 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -1,10 +1,13 @@ --- -language: bash +category: tool +tool: bash +lang: de-de contributors: - - ["Jake Prather", "http:#github.com/JakeHP"] + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] +translators: - ["kultprok", "http://www.kulturproktologie.de"] -filename: LearnBash-de.bash -lang: de-de +filename: LearnBash-de.sh --- Bash ist der Name der Unix-Shell, die als Shell des GNU-Betriebssystems und auch als Standard-Shell von Linux und Mac OS X ausgeliefert wurde. diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index 88f4a643..10deefd5 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -2,9 +2,9 @@ category: tool tool: git contributors: - - ["Jake Prather", "http:#github.com/JakeHP"] + - ["Jake Prather", "http://github.com/JakeHP"] +translators: - ["kultprok", "http://www.kulturproktologie.de"] -filename: LearnGit-de.txt lang: de-de --- diff --git a/git.html.markdown b/git.html.markdown index d8537300..abe8e3a7 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -2,9 +2,8 @@ category: tool tool: git contributors: - - ["Jake Prather", "http:#github.com/JakeHP"] + - ["Jake Prather", "http://github.com/JakeHP"] filename: LearnGit.txt - --- Git is a distributed version control and source code management system. diff --git a/haxe.html.markdown b/haxe.html.markdown index f4694fcb..eb39834e 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. -```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 diff --git a/zh-cn/go-zh.html.markdown b/zh-cn/go-zh.html.markdown index 8f7cb2af..0af5bbe3 100644 --- a/zh-cn/go-zh.html.markdown +++ b/zh-cn/go-zh.html.markdown @@ -1,8 +1,8 @@ --- -名字:Go -分类:编程语言 -文件名:learngo.go -贡献者: +language: Go +lang: zh-cn +filename: learngo.go +contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["pantaovay", "https://github.com/pantaovay"] --- -- cgit v1.2.3 From 5858b8d861438b66ac9ca0209c8b1f0d281570a0 Mon Sep 17 00:00:00 2001 From: wikibook Date: Thu, 29 Aug 2013 13:15:38 +0900 Subject: fixed merge errors --- ko-kr/java-kr.html.markdown | 5 ----- 1 file changed, 5 deletions(-) diff --git a/ko-kr/java-kr.html.markdown b/ko-kr/java-kr.html.markdown index 5dd5769a..dc7a356f 100644 --- a/ko-kr/java-kr.html.markdown +++ b/ko-kr/java-kr.html.markdown @@ -255,13 +255,8 @@ public class LearnJava { // String // 형변환 -<<<<<<< HEAD - // 자바 객체 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이 많을뿐더러 - // 다소 중급 수준에 해당하는 개념들도 다뤄야 합니다. -======= // 자바 객체 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이 // 많을뿐더러 다소 중급 수준에 해당하는 개념들도 다뤄야 합니다. ->>>>>>> f33dea8b83bf64ecde36337a5e02cae77f5210de // 이와 관련된 사항은 아래 링크를 참고하세요. // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html -- cgit v1.2.3 From 92e921e8f3a9138bdb94b19a15cb76081cc90689 Mon Sep 17 00:00:00 2001 From: ipscott Date: Thu, 29 Aug 2013 23:50:11 -0500 Subject: Update php.html.markdown added a better description for static functions and properties --- php.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index 1cc6d2c5..aa73c547 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -468,10 +468,16 @@ class MyClass print 'MyClass'; } + //final keyword would make a function unoverridable final function youCannotOverrideMe() { } +/* +Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. +A property declared as static can not be accessed with an instantiated class object (though a static method can). +*/ + public static function myStaticMethod() { print 'I am static'; -- cgit v1.2.3 From c03de38c77e9d560d89bbae8eacc39e3b99be3d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szab=C3=B3=20Kriszti=C3=A1n?= Date: Fri, 30 Aug 2013 07:38:22 +0200 Subject: Fixed typo --- hu-hu/go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hu-hu/go.html.markdown b/hu-hu/go.html.markdown index 69849858..621ebdbf 100644 --- a/hu-hu/go.html.markdown +++ b/hu-hu/go.html.markdown @@ -38,7 +38,7 @@ import ( "strconv" // Stringek átalakítására szolgáló csomag ) -// Funkció deklarás, a main nevű funkció a program kezdőpontja. +// Funkció deklarálás, a main nevű funkció a program kezdőpontja. func main() { // Println kiírja a beadott paramétereket a standard kimenetre. // Ha más csomagot funkcióját akarjuk használni, akkor azt jelezni kell a -- cgit v1.2.3 From 43beddb4f65f88e7b375f8def93fcc930e868c65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gregor=20Gro=C3=9Fe-B=C3=B6lting?= Date: Fri, 30 Aug 2013 17:37:33 +0200 Subject: translated javascript-tutorial --- de-de/javascript-de.html.markdown | 449 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 449 insertions(+) create mode 100644 de-de/javascript-de.html.markdown diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown new file mode 100644 index 00000000..56a41af0 --- /dev/null +++ b/de-de/javascript-de.html.markdown @@ -0,0 +1,449 @@ +--- +language: JavaScript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["ggb", "http://www.ideen-und-soehne.de"] +filename: learnjavascript.js +lang: de-de +--- + +(Anmerkungen des Original-Autors:) +JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzent zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java. + +Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, dass eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer. + +Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@adambrenecki](https://twitter.com/adambrenecki) oder [adam@brenecki.id.au](mailto:adam@brenecki.id.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.id.au). + +```js +// Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei +// Slashes +/* während mehrzeilige Kommentare mit einem +Slash und einem Stern anfangen und enden */ + +// Statements können mit einem Semikolon beendet werden +machWas(); + +// ...müssen sie aber nicht, weil Semikola automatisch eingefügt werden, wenn +// eine neue Zeile beginnt, abgesehen von einigen Ausnahmen. +machWas() + +// Obwohl wir uns für den Anfang nicht um diese Ausnahmen kümmern müssen ist +// es besser die Semikola immer zu setzen. + +/////////////////////////////////// +// 1. Nummern, Strings und Operationen + +// JavaScript hat einen Nummern-Typ (64-bit IEEE 754 double). +3; // = 3 +1.5; // = 1.5 + +// Alle grundlegenden arithmetischen Operationen arbeiten wie erwartet. +1 + 1; // = 2 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Division funktioniert auch mit einem Ergebnis nach dem Komma. +5 / 2; // = 2.5 + +// Bit-weise Operationen sind auch möglich; wenn eine Bit-weise Operation +// ausgeführt wird, wird die Fließkomma-Zahl in einen 32-bit Integer (mit +// Vorzeichen) umgewandelt. +1 << 2; // = 4 + +// Die Rangfolge der Operationen kann mit Klammern erzwungen werden. +(1 + 3) * 2; // = 8 + +// Es gibt drei spezielle, nicht-reale Nummern-Werte: +Infinity; // Ergebnis von z. B. 1 / 0 +-Infinity; // Ergebnis von z. B. -1 / 0 +NaN; // Ergebnis von z. B. 0 / 0 + +// Es gibt auch einen Boolean-Typ (für Wahrheitswerte). +true; +false; + +// Strings werden mit ' oder " erzeugt. +'abc'; +"Hello, world"; + +// Für die Negation wird das ! benutzt. +!true; // = false +!false; // = true + +// Gleichheit wird mit == geprüft. +1 == 1; // = true +2 == 1; // = false + +// Ungleichheit wird mit != überprüft. +1 != 1; // = false +2 != 1; // = true + +// Andere Vergleichsoperatoren sind +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Strings können mit + verbunden +"Hello " + "world!"; // = "Hello world!" + +// und mit < und > verglichen werden. +"a" < "b"; // = true + +// Für den Vergleich von Werten wird eine Typumwandlung erzwungen... +"5" == 5; // = true + +// ...solange man nicht === verwendet. +"5" === 5; // = false + +// Auf einzelne Buchstaben innerhalb eines Strings kann mit der Methode +// charAt zugegriffen werden +"This is a string".charAt(0); // = "T" + +// Es gibt außerdem die Werte 'null' und 'undefined' +null; // wird verwendet um einen vorsätzlich gewählten 'Nicht'-Wert anzuzeigen +undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht + // verfügbar ist (obwohl genau genommen undefined selbst einen Wert + // darstellt) + +// false, null, undefined, NaN, 0 und "" sind 'falsy', d. h. alles andere ist +// wahr. Man beachte, dass 0 falsch und "0" wahr ist, obwohl 0 == "0". + +/////////////////////////////////// +// 2. Variablen, Arrays und Objekte + +// Variablen werden mit dem Schlüsselwort 'var' und einem frei wählbaren +// Bezeichner deklariert. JavaScript ist dynamisch typisiert, so dass man einer +// Variable keinen Typ zuweisen muss. Die Zuweisung verwendet ein einfaches =. +var einWert = 5; + + // Wenn man das Schlüsselwort 'var' weglässt, bekommt man keinen Fehler +einAndererWert = 10; + +// ...aber die Variable wird im globalen Kontext erzeugt, nicht in dem Kontext, +// in dem sie erzeugt wurde. + +// Variablen die erzeugt wurden ohne ihnen einen Wert zuzuweisen, erhalten den +// Wert 'undefined'. +var einDritterWert; // = undefined + +// Es existiert eine Kurzform, um mathematische Operationen mit Variablen +// auszuführen: +einWert += 5; // äquivalent zu einWert = einWert + 5; einWert ist nun also 10 +einWert *= 10; // einWert ist nach dieser Operation 100 + +// Und es existiert eine weitere, sogar noch kürzere Form, um 1 zu addieren +// oder zu subtrahieren +einWert++; // nun ist einWert 101 +einWert--; // wieder 100 + +// Arrays sind geordnete Listen von Werten irgendeines Typs +var myArray = ["Hello", 45, true]; + +// Auf einzelne Elemente eines Arrays kann zugegriffen werden, in dem der Index +// in eckigen Klammern hinter das Array geschrieben werden. Die Indexierung +// beginnt bei 0. +myArray[1]; // = 45 + +// Die Objekte in JavaScript entsprechen 'dictionaries' oder 'maps' in anderen +// Sprachen: es handelt sich um ungeordnete Schlüssel-Wert-Paare. +var myObj = { key1: "Hello", key2: "World" }; + +// Schlüssel sind Strings, aber es werden keine Anführungszeichen benötigt, +// sofern es sich um reguläre JavaScript-Bezeichner handelt. Werte können von +// jedem Typ sein. +var myObj = { myKey: "myValue", "my other key": 4 }; + +// Auf Attribute von Objekten kann ebenfalls mit eckigen Klammern zugegriffen +// werden, +myObj["my other key"]; // = 4 + +// ... oder in dem man die Punkt-Notation verwendet, vorausgesetzt es handelt +// sich bei dem Schlüssel um einen validen Bezeichner. +myObj.myKey; // = "myValue" + +// Objekte sind veränderlich, Werte können verändert und neue Schlüssel +// hinzugefügt werden. +myObj.myThirdKey = true; + +// Der Zugriff auf einen noch nicht definierten Schlüssel, liefert ein +// undefined. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Logik und Kontrollstrukturen + +// Die if-Struktur arbeitet, wie man es erwartet. +var count = 1; +if (count == 3){ + // wird evaluiert, wenn count gleich 3 ist +} else if (count == 4) { + // wird evaluiert, wenn count gleich 4 ist +} else { + // wird evaluiert, wenn es weder 3 noch 4 ist +} + +// Genauso 'while'. +while (true) { + // Eine unendliche Schleife! +} + +// Do-while-Scheifen arbeiten wie while-Schleifen, abgesehen davon, dass sie +// immer mindestens einmal ausgeführt werden. +var input; +do { + input = getInput(); +} while ( !isValid( input ) ) + +// Die for-Schleife arbeitet genau wie in C und Java: +// Initialisierung; Bedingung, unter der die Ausführung fortgesetzt wird; +// Iteration. +for ( var i = 0; i < 5; i++ ) { + // wird 5-mal ausgeführt +} + +// '&&' ist das logische und, '||' ist das logische oder +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; + // Die Größe des Hauses ist groß und die Farbe blau. +} +if (colour == "red" || colour == "blue"){ + // Die Farbe ist entweder rot oder blau. +} + +// Die Auswertung von '&&' und '||' erfolgt so, dass abgebrochen wird, wenn die +// Bedingung erfüllt ist (bei oder) oder nicht-erfüllt ist (bei und). Das ist +// nützlich, um einen Default-Wert zu setzen. +var name = otherName || "default"; + +/////////////////////////////////// +// 4. Funktionen, Geltungsbereich und Closures + +// In JavaScript werden Funktionen mit dem Schlüsselwort 'function' deklariert. +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// In JavaScript sind Funktionen 'Bürger erster Klasse', also können sie wie +// Variablen verwendet und als Parameter anderen Funktionen übergeben werden +// - zum Beispiel, um einen 'event handler' zu 'beliefern'. +function myFunction() { + // wird ausgeführt, nachdem 5 Sekunden vergangen sind +} +setTimeout(myFunction, 5000); + +// Funktionen können auch deklariert werden, ohne ihnen einen Namen zuzuweisen. +// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument +// einer anderen Funktion zu definieren. +setTimeout(function() { + // wird ausgeführt, nachdem 5 Sekunden vergangen sind +}, 5000); + +// JavaScript hat einen Geltungsbereich, der sich auf Funktionen erstreckt: +// Funktionen haben ihren eigenen Geltungsbereich, andere Blöcke nicht. +if(true) { + var i = 5; +} +i; // = 5 - nicht undefined, wie man es von einer Sprache erwarten würde, die + // ihren Geltungsbereich nach Blöcken richtet + +// Daraus ergibt sich ein bestimmtes Muster für sofort-ausführbare, anonyme +// Funktionen, die es vermeiden, dass der globale Geltungsbereich von Variablen +// 'verschmutzt' wird. +(function(){ + var temporary = 5; + // Auf eine Variable im globalen Geltungsbereich kann zugegriffen werden, + // sofern sie im globalen Objekt definiert ist (in einem Webbrowser ist + // dies immer das 'window'-Objekt, in anderen Umgebungen, bspw. Node.js, + // kann das anders aussehen). + window.permanent = 10; +})(); +temporary; // wirft einen ReferenceError +permanent; // = 10 + +// Eines der mächtigsten Charakteristika von JavaScript sind Closures. Wird +// eine Funktion innerhalb einer anderen Funktion definiert, dann hat die +// innere Funktion Zugriff auf alle Variablen der äußeren Funktion, sogar dann, +// wenn die äußere Funktion beendet wurde. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds + // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein' + // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere + // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die + // Variable prompt. +} +sayHelloInFiveSeconds("Adam"); // wird nach 5 Sekunden ein Popup mit der + // Nachricht "Hello, Adam!" öffnen. + +/////////////////////////////////// +// 5. Mehr über Objekte, Konstruktoren und Prototypen + +// Objekte können Funktionen enthalten. +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +// Wenn Funktionen aufgerufen werden, die zu einem Objekt gehören, können sie +// auf das eigene Objekt mit dem Schlüsselwort 'this' zugreifen. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +// Worauf 'this' gesetzt wird, ist davon abhängig, wie die Funktion aufgerufen +// wird, nicht wo sie definiert wurde. Unsere Funktion wird daher nicht +// funktionieren, sofern sie außerhalb des Kontextes des Objekts aufgerufen +// wird. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Umgekehrt ist es möglich eine Funktion einem Objekt zuzuweisen und dadurch +// Zugriff auf den this-Kontext zu erhalten, sogar dann, wenn die Funktion dem +// Objekt nach dessen Definition zugewiesen wird. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +// Wenn eine Funktion mit dem Schlüsselwort 'new' aufgerufen wird, dann wird +// ein neues Objekt erzeugt. Funktionen, die darauf ausgelegt sind in dieser +// Art aufgerufen zu werden, werden Konstruktoren genannt. +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Jedes JavaScript-Objekt hat einen Prototyp. Wenn man versucht auf eine +// Eigenschaft des Objekts zuzugreifen, das nicht im Objekt selbst existiert, +// schaut der Interpreter in dessen Prototyp nach. + +// Einige JavaScript-Implementierungen erlauben den direkten Zugriff auf den +// Prototyp eines Objekts durch die magische Eigenschaft __proto__. Obwohl das +// nützlich ist, um Prototypen im Allgemeinen zu erklären, ist das nicht Teil +// des Standards; zum Standard-Weg der Nutzung von Prototypen kommen wir +// später. +var myObj = { + myString: "Hello world!", +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// Das funktioniert auch bei Funktionen. +myObj.myFunc(); // = "hello world!" + +// Sollte die Eigenschaft nicht im Prototypen des Objekts enthalten sein, dann +// wird im Prototypen des Prototypen nachgesehen und so weiter. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Dafür wird nichts hin und her kopiert; jedes Objekt speichert eine Referenz +// auf seinen Prototypen. Das heißt wenn der Prototyp geändert wird, dann +// werden die Änderungen überall sichtbar. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Es wurde bereits erwähnt, dass __proto__ nicht zum Standard gehört und es +// gibt ebenso keinen Standard-Weg, um den Prototyp eines existierenden Objekts +// zu ändern. Es gibt dennoch zwei Wege, wie man ein neues Objekt mit einem +// gegebenen Prototypen erzeugt. + +// Der erste Weg ist die Methode Object.create, die eine jüngere Ergänzung des +// JavaScript-Standards ist und daher noch nicht in allen Implementierungen +// verfügbar. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Der zweite Weg, der immer funktioniert, hat mit den Konstruktoren zu tun. +// Konstruktoren haben eine Eigenschaft, die Prototyp heißt. Dabei handelt es +// sich *nicht* um den Prototypen der Konstruktor-Funktion; stattdessen handelt +// es sich um den Prototypen, der einem neuen Objekt mitgegeben wird, wenn es +// mit dem Konstruktor und dem Schlüsselwort 'new' erzeugt wird. +myConstructor.prototype = { + getMyNumber: function(){ + return this.myNumber + } +}; +var myNewObj2 = new myConstructor(); +myNewObj2.getMyNumber(); // = 5 + +// Die eingebauten Typen, also strings und numbers, haben auch Konstruktoren, +// die zu dem Typ äquivalente Wrapper-Objekte erzeugen. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Genau genommen: Sie sind nicht exakt äquivalent. +typeof(myNumber); // = 'number' +typeof(myNumberObj); // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist. +} +if (Number(0)){ + // Dieser Teil des Codes wird ausgeführt, weil Number(0) zu wahr evaluiert. +} + +// Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen +// Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen +// hinzuzufügen. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Diese Tatsache wird häufig bei einer Methode mit dem Namen 'polyfilling' +// verwendet: Dabei wird ein neues Feature von JavaScript in einer älteren +// Untermenge der Sprache integriert, so dass bestimmte Funktionen auch in +// älteren Umgebungen und Browsern verwendet werden können. + +// Ein Beispiel: Es wurde erwähnt, dass die Methode Object.create nicht in +// allen Umgebungen verfügbar ist - wir können sie dennoch verwenden, mit einem +// 'polyfill': +if (Object.create === undefined){ // überschreib nichts, was eventuell bereits + // existiert + Object.create = function(proto){ + // erstelle einen vorübergehenden Konstruktor mit dem richtigen + // Prototypen + var Constructor = function(){}; + Constructor.prototype = proto; + // verwende es dann, um ein neues Objekt mit einem passenden + // Prototypen zurückzugeben + return new Constructor(); + } +} +``` + +## Zur weiteren Lektüre (englisch) + +Das [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) bietet eine ausgezeichnete Dokumentation für die Verwendung von JavaScript im Browser. Es ist außerdem ein Wiki und ermöglicht es damit anderen zu helfen, wenn man selbst ein wenig Wissen angesammelt hat. + +MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) führt sehr viele der hier vorgestellten Konzepte im Detail aus. + +Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den Einsatz in Websites zu lernen, ist es ein guter Start etwas über das [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) zu lernen. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache. + +Zusätzlich zu direkten Beiträgen zu diesem Artikel ist der Inhalt in Anlehnung an Louie Dinh's Python-Tutorial auf dieser Seite und das [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) des Mozilla Developer Network entstanden. \ No newline at end of file -- cgit v1.2.3 From e13b5111d569903c6620d448f0703707ed1dc8e8 Mon Sep 17 00:00:00 2001 From: Marcos Brizeno Date: Fri, 30 Aug 2013 21:58:23 -0300 Subject: Adding explanation about variables scope and naming --- ruby.html.markdown | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 3a233d98..80682682 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Luke Holder", "http://twitter.com/lukeholder"] - ["Tristan Hume", "http://thume.ca/"] - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] --- ```ruby @@ -339,6 +340,23 @@ dwight.name #=> "Dwight K. Schrute" # Call the class method Human.say("Hi") #=> "Hi" +# Variable's scopes are defined by the way we name them. +# Variables that start with $ have global scope +$var = "I'm a global var" +defined? $var #=> "global-variable" + +# Variables that start with @ have instance scope +@var = "I'm an instance var" +defined? @var #=> "instance-variable" + +# Variables that start with @@ have class scope +@@var = "I'm a class var" +defined? @@var #=> "class variable" + +# Variables that start with a capital letter are constants +Var = "I'm a constant" +defined? Var #=> "constant" + # Class also is object in ruby. So class can have instance variables. # Class variable is shared among the class and all of its descendants. -- cgit v1.2.3 From 4d522544f2644d2fdbc8bcd41fd3afa0fcc11583 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20Hern=C3=A1ndez=20Blas?= Date: Sat, 31 Aug 2013 04:09:41 -0500 Subject: Spanish translation for Clojure. --- es-es/clojure-es.html.markdown | 395 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 395 insertions(+) create mode 100644 es-es/clojure-es.html.markdown diff --git a/es-es/clojure-es.html.markdown b/es-es/clojure-es.html.markdown new file mode 100644 index 00000000..7102b361 --- /dev/null +++ b/es-es/clojure-es.html.markdown @@ -0,0 +1,395 @@ +--- +language: clojure +filename: learnclojure-es.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Antonio Hernández Blas", "https://twitter.com/nihilipster"] +lang: es-es +--- + +Clojure es un lenguaje de la familia Lisp desarrollado para la Máquina Virtual +de Java. Tiene un énfasis más fuerte en la [programación funcional](https://es.wikipedia.org/wiki/Programación_funcional) pura +que Common Lisp, pero incluye varias facilidades de [SMT](https://es.wikipedia.org/wiki/Memoria_transacional) para manipular +el estado según se presente. + +Esta combinación le permite manejar el procesamiento concurrente muy simple, +y a menudo automáticamente. + +(Necesitas la versión de Clojure 1.2 o nueva) + + +```clojure +; Los comentatios inician con punto y coma. + +; Clojure es escrito en "forms" (patrones), los cuales son solo +; listas de objectos dentro de paréntesis, separados por espacios en blanco. + +; El reader (lector) de Clojure asume que el primer objeto es una +; función o una macro a llamar, y que el resto son argumentos. + +; La primera llamada en un archivo debe ser ns, para establecer el espacio de +; nombre +(ns learnclojure) + +; Más ejemplos básicos: + +; str creará una cadena de caracteres a partir de sus argumentos +(str "Hello" " " "World") ; => "Hello World" + +; Las matemáticas son sencillas +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 + +; La igualdad es = +(= 1 1) ; => true +(= 2 1) ; => false + +; Necesitas de la negación para la lógica, también +(not true) ; => false + +; Los patrones anidados funcionan como lo esperas +(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 + +; Tipos +;;;;;;;;;;;;; + +; Clojure usa los tipos de objetos de Java para booleanos,cadenas de +; caracteres y números. +; Usa class para inspeccionarlos. +(class 1); Los enteros literales son java.lang.Long por default +(class 1.); Los flotantes literales son java.lang.Double +(class ""); Las cadenas de caracteres van entre comillas dobles, y son +; son java.lang.String +(class false); Los Booleanos son java.lang.Boolean +(class nil); El valor "null" es llamado nil + +; Si quieres crear una lista literal de datos, precede la con una comilla +; simple para evitar su evaluación +'(+ 1 2) ; => (+ 1 2) +; (abreviatura de (quote (+ 1 2)) + +; Puedes evaluar una lista precedida por comilla simple con eval +(eval '(+ 1 2)) ; => 3 + +; Colecciones & Secuencias +;;;;;;;;;;;;;;;;;;; + +; Las Listas están basadas en listas enlazadas, mientras que los Vectores en +; arreglos. +; ¡Los Vectores y las Listas son clases de Java también! +(class [1 2 3]); => clojure.lang.PersistentVector +(class '(1 2 3)); => clojure.lang.PersistentList + +; Una lista podría ser escrita como (1 2 3), pero debemos precidirla con +; comilla simple para evitar que el lector piense que es una función. +; Además, (list 1 2 3) es lo mismo que '(1 2 3) + +; Las "Colecciones" son solo grupos de datos +; Tanto las listas como los vectores son colecciones: +(coll? '(1 2 3)) ; => true +(coll? [1 2 3]) ; => true + +; Las "Secuencias" (seqs) son descripciones abstractas de listas de datos. +; Solo las listas son seqs. +(seq? '(1 2 3)) ; => true +(seq? [1 2 3]) ; => false + +; Una seq solo necesita proporcionar una entrada cuando es accedida. +; Así que, las seqs pueden ser perezosas -- pueden establecer series infinitas: +(range 4) ; => (0 1 2 3) +(range) ; => (0 1 2 3 4 ...) (una serie infinita) +(take 4 (range)) ; (0 1 2 3) + +; Usa cons para agregar un elemento al inicio de una lista o vector +(cons 4 [1 2 3]) ; => (4 1 2 3) +(cons 4 '(1 2 3)) ; => (4 1 2 3) + +; conj agregará un elemento a una colección en la forma más eficiente. +; Para listas, se agrega al inicio. Para vectores, al final. +(conj [1 2 3] 4) ; => [1 2 3 4] +(conj '(1 2 3) 4) ; => (4 1 2 3) + +; Usa concat para concatenar listas o vectores +(concat [1 2] '(3 4)) ; => (1 2 3 4) + +; Usa filter, map para actuar sobre colecciones +(map inc [1 2 3]) ; => (2 3 4) +(filter even? [1 2 3]) ; => (2) + +; Usa reduce para reducirlos +(reduce + [1 2 3 4]) +; = (+ (+ (+ 1 2) 3) 4) +; => 10 + +; reduce puede tomar un argumento como valor inicial también +(reduce conj [] '(3 2 1)) +; = (conj (conj (conj [] 3) 2) 1) +; => [3 2 1] + +; Funciones +;;;;;;;;;;;;;;;;;;;;; + +; Usa fn para crear nuevas funciones. Una función siempre regresa +; su última expresión +(fn [] "Hello World") ; => fn + +; (Necesitas encerrarlo en paréntesis para llamarlo) +((fn [] "Hello World")) ; => "Hello World" + +; Puedes crear una var (variable) usando def +(def x 1) +x ; => 1 + +; Asigna una función a una var +(def hello-world (fn [] "Hello World")) +(hello-world) ; => "Hello World" + +; Puedes acortar este proceso al usar defn +(defn hello-world [] "Hello World") + +; El [] es el vector de argumentos para la función. +(defn hello [name] + (str "Hello " name)) +(hello "Steve") ; => "Hello Steve" + +; Puedes usar también esta abreviatura para crear funciones: +(def hello2 #(str "Hello " %1)) +(hello2 "Fanny") ; => "Hello Fanny" + +; Puedes tener funciones multi-variadic (múltiple numero variable de +; argumentos), también +(defn hello3 + ([] "Hello World") + ([name] (str "Hello " name))) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" + +; Las funciones pueden colocar argumentos extras dentro de una seq por ti +(defn count-args [& args] + (str "You passed " (count args) " args: " args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" + +; Puedes mezclar argumentos regulares y dentro de una seq +(defn hello-count [name & args] + (str "Hello " name ", you passed " (count args) " extra args")) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" + + +; Mapas +;;;;;;;;;; + +; Mapas de Hash y mapas de Arreglos comparten una interfaz. Los mapas de Hash +; tienen búsquedas más rápidas pero no mantienen el orden de las llaves. +(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap +(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap + +; Los mapas de Arreglos serán convertidos en mapas de Hash en la mayoría de +; operaciones si crecen lo suficiente, así que no necesitas preocuparte. + +; Los mapas pueden usar cualquier tipo para sus llaves, pero usualmente las +; keywords (llaves) son mejor. +; Las keywords son como cadenas de caracteres con algunas ventajas en eficiencia +(class :a) ; => clojure.lang.Keyword + +(def stringmap {"a" 1, "b" 2, "c" 3}) +stringmap ; => {"a" 1, "b" 2, "c" 3} + +(def keymap {:a 1, :b 2, :c 3}) +keymap ; => {:a 1, :c 3, :b 2} + +; Por cierto, las comas son siempre tratadas como espacios en blanco y no hacen +; nada. + +; Recupera un valor de un mapa tratando la como una función +(stringmap "a") ; => 1 +(keymap :a) ; => 1 + +; ¡Las keywords pueden ser usadas para recuperar su valor del mapa, también! +(:b keymap) ; => 2 + +; No intentes ésto con cadenas de caracteres. +;("a" stringmap) +; => Exception: java.lang.String cannot be cast to clojure.lang.IFn + +; Recuperando un valor no presente regresa nil +(stringmap "d") ; => nil + +; Usa assoc para agregar nuevas llaves a los mapas de Hash +(def newkeymap (assoc keymap :d 4)) +newkeymap ; => {:a 1, :b 2, :c 3, :d 4} + +; Pero recuerda, ¡los tipos de clojure son inmutables! +keymap ; => {:a 1, :b 2, :c 3} + +; Usa dissoc para remover llaves +(dissoc keymap :a :b) ; => {:c 3} + +; Conjuntos +;;;;;; + +(class #{1 2 3}) ; => clojure.lang.PersistentHashSet +(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} + +; Agrega un miembro con conj +(conj #{1 2 3} 4) ; => #{1 2 3 4} + +; Remueve uno con disj +(disj #{1 2 3} 1) ; => #{2 3} + +; Comprueba la existencia tratando al conjunto como una función: +(#{1 2 3} 1) ; => 1 +(#{1 2 3} 4) ; => nil + +; Hay más funciones en el espacio de nombre clojure.sets + +; Patrones útiles +;;;;;;;;;;;;;;;;; + +; Las construcciones lógicas en clojure son macros, y tienen el mismo aspecto +; que todo lo demás +(if false "a" "b") ; => "b" +(if false "a") ; => nil + +; Usa let para crear una binding (asociación) temporal +(let [a 1 b 2] + (> a b)) ; => false + +; Agrupa expresiones con do +(do + (print "Hello") + "World") ; => "World" (prints "Hello") + +; Las funciones tienen un do implicito +(defn print-and-say-hello [name] + (print "Saying hello to " name) + (str "Hello " name)) +(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") + +; De igual forma let +(let [name "Urkel"] + (print "Saying hello to " name) + (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Modulos +;;;;;;;;;;;;;;; + +; Usa use para obtener todas las funciones del modulo +(use 'clojure.set) + +; Ahora podemos usar operaciones de conjuntos +(intersection #{1 2 3} #{2 3 4}) ; => #{2 3} +(difference #{1 2 3} #{2 3 4}) ; => #{1} + +; Puedes escoger un subgrupo de funciones a importar, también +(use '[clojure.set :only [intersection]]) + +; Usa require para importar un modulo +(require 'clojure.string) + +; Usa / para llamar funciones de un modulo +; Aquí, el modulo es clojure.string y la función es blank? +(clojure.string/blank? "") ; => true + +; Puedes asignarle una abreviatura a un modulo al importarlo +(require '[clojure.string :as str]) +(str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." +; (#"" es una expresión regular literal) + +; Puedes usar require (y use, pero no lo hagas) desde un espacio de nombre +; usando :require, +; No necesitas preceder con comilla simple tus módulos si lo haces de esta +; forma. +(ns test + (:require + [clojure.string :as str] + [clojure.set :as set])) + +; Java +;;;;;;;;;;;;;;;;; + +; Java tiene una enorme y útil librería estándar, así que +; querrás aprender como llegar a ella. + +; Usa import para cargar un modulo de java +(import java.util.Date) + +; Puedes importar desde un ns también. +(ns test + (:import java.util.Date + java.util.Calendar)) + +; Usa el nombre de la clase con un "." al final para crear una nueva instancia +(Date.) ; + +; Usa "." para llamar a métodos. O, usa el atajo ".método" +(. (Date.) getTime) ; +(.getTime (Date.)) ; exactamente la misma cosa + +; Usa / para llamar métodos estáticos. +(System/currentTimeMillis) ; (System siempre está presente) + +; Usa doto para hacer frente al uso de clases (mutables) más tolerable +(import java.util.Calendar) +(doto (Calendar/getInstance) + (.set 2000 1 1 0 0 0) + .getTime) ; => A Date. set to 2000-01-01 00:00:00 + +; STM +;;;;;;;;;;;;;;;;; + +; Software Transactional Memory es un mecanismo que clojure usa para manejar +; el estado persistente. Hay algunas cuantas construcciones en clojure que +; usan esto. + +; Un atom es el más simple. Dale una valor inicial +(def my-atom (atom {})) + +; Actualiza un atom con swap! +; swap! toma una función y la llama con el valor actual del atom +; como su primer argumento, y cualquier argumento restante como el segundo +(swap! my-atom assoc :a 1) ; Establece my-atom al resultado de (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Establece my-atom al resultado de (assoc {:a 1} :b 2) + +; Usa '@' para no referenciar al atom y obtener su valor +my-atom ;=> Atom<#...> (Regresa el objeto Atom) +@my-atom ; => {:a 1 :b 2} + +; Aquí está un simple contador usando un atom +(def counter (atom 0)) +(defn inc-counter [] + (swap! counter inc)) + +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) + +@counter ; => 5 + +; Otros constructores STM son refs y agents. +; Refs: http://clojure.org/refs +; Agents: http://clojure.org/agents +``` + +### Lectura adicional + +Ésto queda lejos de ser exhaustivo, pero espero que sea suficiente para +encaminarte. + +Clojure.org tiene muchos artículos: +[http://clojure.org/](http://clojure.org/) + +Clojuredocs.org tiene documentación con ejemplos para la mayoría de +funciones core: +[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) + +4Clojure es una grandiosa forma de fortalecer tus habilidades con clojure/FP: +[http://www.4clojure.com/](http://www.4clojure.com/) + +Clojure-doc.org (sí, de verdad) tiene un número de artículos para empezar: +[http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From e2cd18ba463279a650c2393f68f37131a52b4c4d Mon Sep 17 00:00:00 2001 From: Avjinder Date: Sat, 31 Aug 2013 17:05:04 +0530 Subject: Update bash.html.markdown In the case statement, the "in" keyword should be on the same line as case $VARIABLE. Also, ;; should be present at the end of each command. Shell executes all statements up to the two semicolons that are next to each other. --- bash.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index a0c43c12..76c794c6 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -73,12 +73,11 @@ ls -l | grep "\.txt" echo "There are $(ls | wc -l) items here." # Bash uses a case statement that works similarily to switch in Java and C++: -case "$VARIABLE" -in +case "$VARIABLE" in #List patterns for the conditions you want to meet - 0) echo "There is a zero." - 1) echo "There is a one." - *) echo "It is not null." + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; esac #For loops iterate for as many arguments given: -- cgit v1.2.3 From 58cd4b274f4ef6dce15bf30eccad4691aaf835ed Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 09:50:13 -0500 Subject: add special characters to c --- c.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index 24a96463..c8c3e33b 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -20,6 +20,12 @@ memory management and C will take you as far as you need to go. Multi-line comments look like this. They work in C89 as well. */ +//Special characters: +'\n' // newline character +'\t' // tab character +'\b' // backspace character +'\0' // null character + // Import headers with #include #include #include -- cgit v1.2.3 From deaaf3412d01a69fdc4354564fba5506ef65f4c8 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 10:51:48 -0500 Subject: Add print formatting characters --- c.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index c8c3e33b..a9fd8e50 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -23,9 +23,22 @@ Multi-line comments look like this. They work in C89 as well. //Special characters: '\n' // newline character '\t' // tab character +'\v' // vertical tab +'\f' // new page +'\r' // carriage return '\b' // backspace character '\0' // null character +//print formatting: +"%d" // integer +"%3d" // minimum length of 3 digits for integer (right justifies text) +"%s" // string +"%f" // float +"%3.2f" // minimum 3 digits left and 2 digits right decimal float +"%7.4s" // (can do with strings too) +"%c" // char +"%p" // pointer + // Import headers with #include #include #include -- cgit v1.2.3 From e03cda583dd6127831a32fcc8bd8cd8b53399794 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 11:44:45 -0500 Subject: Add more to string formatting. --- c.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index a9fd8e50..4e1e1e56 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -22,7 +22,7 @@ Multi-line comments look like this. They work in C89 as well. //Special characters: '\n' // newline character -'\t' // tab character +'\t' // tab character (left justifies text) '\v' // vertical tab '\f' // new page '\r' // carriage return @@ -38,6 +38,12 @@ Multi-line comments look like this. They work in C89 as well. "%7.4s" // (can do with strings too) "%c" // char "%p" // pointer +"%x" // hexidecimal +"%o" // octal +"%%" // prints % + +// Constants: use #define keyword, no semicolon at end. +#define DAYS_IN_YEAR = 365 // Import headers with #include #include -- cgit v1.2.3 From dba7ec8b9643f693bdb023f9827999b2b14d008b Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 12:50:58 -0500 Subject: Add getchar(), putchar(), EOF to C --- c.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index 4e1e1e56..7010b9d5 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -427,6 +427,16 @@ void str_reverse(char *str_in) } } +// Built in functions: +// from stdio.h: +int c = getchar(); //reads character from user. If user types hello, only h is read. +// getchar() can be stored into int or char. I am using int because char is not large +// enough to store EOF used below. +while (c != EOF) { // EOF is value for "end of file". Linux: CTRL+D, Windows: CTRL+X + putchar(c); //prints character (without newline at end) + char c = getchar(); +} + /* char c[] = "This is a test."; str_reverse(c); -- cgit v1.2.3 From f1b1fd8e2efd6c30e553aae1c4f6cc28a6554e8f Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 13:06:37 -0500 Subject: Add clarity to EOF. Add %ld for longs in C --- c.html.markdown | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 7010b9d5..869ab984 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -34,6 +34,7 @@ Multi-line comments look like this. They work in C89 as well. "%3d" // minimum length of 3 digits for integer (right justifies text) "%s" // string "%f" // float +"%ld" // long "%3.2f" // minimum 3 digits left and 2 digits right decimal float "%7.4s" // (can do with strings too) "%c" // char @@ -429,10 +430,12 @@ void str_reverse(char *str_in) // Built in functions: // from stdio.h: -int c = getchar(); //reads character from user. If user types hello, only h is read. -// getchar() can be stored into int or char. I am using int because char is not large -// enough to store EOF used below. -while (c != EOF) { // EOF is value for "end of file". Linux: CTRL+D, Windows: CTRL+X +int c = getchar(); //reads character from input. If input = hi, only h is read. +// getchar() can be stored into int or char. I am using int because +// char is not large enough to store EOF used below. +while ((c = getchar()) != EOF) { // EOF constant "end of file". + // Linux: CTRL+D, Windows: CTRL+X + // must have () around getchar() as != is run before =. putchar(c); //prints character (without newline at end) char c = getchar(); } -- cgit v1.2.3 From b0c5ca0a1cc5a62fc8569fffffcdf35bf44e8dc8 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 15:57:18 -0500 Subject: Add note about loops C --- c.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index 869ab984..166c43e6 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -231,6 +231,12 @@ int main() { printf("I print\n"); } + // Notes: + // Loops MUST always have a body. If no body is needed, do this: + for (i = 0; i <= 5; i++) { + ; // use semicolon to act as the body (null statement) + } + // While loops exist int ii = 0; while (ii < 10) { -- cgit v1.2.3 From 5c711eb30fe8cd810627742a30c016f458bd773c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 16:24:56 -0500 Subject: Add more shorthand notes, array notes to C --- c.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 166c43e6..c6fee5d7 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -166,6 +166,10 @@ int main() { int i1 = 1, i2 = 2; // Shorthand for multiple declaration float f1 = 1.0, f2 = 2.0; + //more shorthands: + int a, b, c; + a = b = c = 0; + // Arithmetic is straightforward i1 + i2; // => 3 i2 - i1; // => 1 @@ -339,7 +343,7 @@ int main() { printf("%d\n", x); // => Prints 1 // Arrays are a good way to allocate a contiguous block of memory - int x_array[20]; + int x_array[20]; //declares array of size 20 (cannot change size) int xx; for (xx = 0; xx < 20; xx++) { x_array[xx] = 20 - xx; -- cgit v1.2.3 From dfd8afb4969c76b71a852e7bc8378b7e7f8f4bb3 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 16:36:16 -0500 Subject: Add ASCII chars to Types of C file. --- c.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index c6fee5d7..96f253b7 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -98,6 +98,10 @@ int main() { unsigned int ux_int; unsigned long long ux_long_long; + // chars inside single quotes '*' are ASCII versions of + '0' //==> 48 on the ASCII table. + 'A' //==> 65 on the ASCII table. + // sizeof(T) gives you the size of a variable with type T in bytes // sizeof(obj) yields the size of the expression (variable, literal, etc.). printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) -- cgit v1.2.3 From 79fdd62c6bcb13c550050efe02d6753d198a5a83 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 16:51:35 -0500 Subject: Add function prototype to C. --- c.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index 96f253b7..75025b0c 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -422,6 +422,16 @@ int add_two_ints(int x1, int x2) return x1 + x2; // Use return to return a value } +// Must declare a 'funtion prototype' before main() when creating functions +// in file. +int getInt(char c); // function prototype +int main() { + return 0; +} +int getInt(char w) { //parameter name does not need to match function prototype + return 1; +} + /* Functions are pass-by-value, but you can make your own references with pointers so functions can mutate their values. -- cgit v1.2.3 From 41f65bb3415e7002ef171c351376c1c4d5336746 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 17:04:47 -0500 Subject: Clarified function call by value description. --- c.html.markdown | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 75025b0c..e6e2559e 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -433,8 +433,12 @@ int getInt(char w) { //parameter name does not need to match function prototype } /* -Functions are pass-by-value, but you can make your own references -with pointers so functions can mutate their values. +Functions are call by value. So when a function is called, the arguments passed +to the function are copies of original arguments (except arrays). Anything you +do to your arguments do not change the value of the actual argument where the +function was called. + +You can use pointers if you need to edit the original argument values. Example: in-place string reversal */ -- cgit v1.2.3 From 394ca958b3b61853b1fe8ec1063b3adb03239178 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 18:42:05 -0500 Subject: Add more notes to null character in C --- c.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index e6e2559e..90d0d358 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -27,7 +27,8 @@ Multi-line comments look like this. They work in C89 as well. '\f' // new page '\r' // carriage return '\b' // backspace character -'\0' // null character +'\0' // null character. Usually put at end of strings in C lang. + // hello\n\0. \0 used by convention to mark end of string. //print formatting: "%d" // integer -- cgit v1.2.3 From d632203255085171ce79a106a40797d1d5fa54a3 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 18:54:07 -0500 Subject: Add more notes to function prototype in C. --- c.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 90d0d358..ee60d168 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -425,13 +425,16 @@ int add_two_ints(int x1, int x2) // Must declare a 'funtion prototype' before main() when creating functions // in file. -int getInt(char c); // function prototype +void getInt(char c); // function prototype int main() { return 0; } -int getInt(char w) { //parameter name does not need to match function prototype - return 1; +void getInt(char w) { //parameter name does not need to match function prototype + ; } +//if function takes no parameters, do: int getInt(void); for function prototype +// and for the function declaration: int getInt(void) {} +// this is to keep compatibility with older versions of C. /* Functions are call by value. So when a function is called, the arguments passed -- cgit v1.2.3 From 8caf3768fb4a1f0fa14ca4765e7f168534c7cd8f Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 19:24:15 -0500 Subject: Add extern notes to C. --- c.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index ee60d168..2a828ab7 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -99,7 +99,7 @@ int main() { unsigned int ux_int; unsigned long long ux_long_long; - // chars inside single quotes '*' are ASCII versions of + // chars inside single quotes '*' are character constants. '0' //==> 48 on the ASCII table. 'A' //==> 65 on the ASCII table. @@ -472,6 +472,12 @@ while ((c = getchar()) != EOF) { // EOF constant "end of file". char c = getchar(); } +//if referring to external variables outside function, must use extern keyword. +int i = 0; +void testFunc() { + extern int i; //i here is now using external variable i +} + /* char c[] = "This is a test."; str_reverse(c); -- cgit v1.2.3 From 411d9a9813e8c7174f35540198b6dadc8c0b665c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 19:29:25 -0500 Subject: Add more escape sequences to C. --- c.html.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 2a828ab7..4764c38e 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -21,14 +21,21 @@ Multi-line comments look like this. They work in C89 as well. */ //Special characters: +'\a' // alert (bell) character '\n' // newline character '\t' // tab character (left justifies text) '\v' // vertical tab -'\f' // new page +'\f' // new page (formfeed) '\r' // carriage return '\b' // backspace character '\0' // null character. Usually put at end of strings in C lang. // hello\n\0. \0 used by convention to mark end of string. +'\\' // backspace +'\?' // question mark +'\'' // single quote +'\"' // double quote +'\xhh' // hexadecimal number. Example: '\xb' = vertical tab character +'\ooo' // octal number. Example: '\013' = vertical tab character //print formatting: "%d" // integer -- cgit v1.2.3 From ab4633f6a413d226e270badad6b9405805ecf147 Mon Sep 17 00:00:00 2001 From: Prajit Ramachandran Date: Sat, 31 Aug 2013 18:38:33 -0700 Subject: Tutorial for the Brainfuck programming language. Brainfuck is a minimal programming language that is rather difficult to wrap one's head around. It only uses the characters +-[],.>< --- brainfuck.html.markdown | 79 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 brainfuck.html.markdown diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown new file mode 100644 index 00000000..2b7ce4db --- /dev/null +++ b/brainfuck.html.markdown @@ -0,0 +1,79 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io"] +--- + +Brainfuck is an extremely minimal programming language (just 8 commands) and +is Turing complete. + +``` +Any character not "><+-.,[]" (excluding quotation marks) is ignored. + +Brainfuck is represented by an array with 30,000 cells initialized to zero +and a data pointer pointing at the current cell. + +There are eight commands: ++ : Increments the value at the current cell by one. +- : Decrements the value at the current cell by one. +> : Moves the data pointer to the next cell (cell on the right). +< : Moves the data pointer to the previous cell (cell on the left). +. : Prints the ASCII value at the current cell (i.e. 65 = 'A'). +, : Reads a single input character into the current cell. +[ : If the value at the current cell is zero, skips to the corresponding ] . + Otherwise, move to the next instruction. +] : If the value at the current cell is zero, move to the next instruction. + Otherwise, move backwards in the instructions to the corresponding [ . + +[ and ] form a while loop. Obviously, they must be balanced. + +Let's look at some basic Brainfuck programs. + +++++++ [ > ++++++++++ < - ] > +++++ . + +This program prints out the letter 'A'. First, it increments cell #1 to 6. +Cell #1 will be used for looping. Then, it enters the loop ([) and moves +to cell #2. It increments cell #2 10 times, moves back to cell #1, and +decrements cell #1. This loop happens 6 times (it takes 6 decrements for +cell #1 to reach 0, at which point it skips to the corresponding ] and +continues on). + +At this point, we're on cell #1, which has a value of 0, while cell #2 has a +value of 60. We move on cell #2, increment 5 times, for a value of 65, and then +print cell #2's value. 65 is 'A' in ASCII, so 'A' is printed to the terminal. + + +, [ > + < - ] > . + +This program reads a character from the user input, copies the character into +another cell, and prints out the same character. + +, reads in a character from the user into cell #1. Then we start a loop. Move +to cell #2, increment the value at cell #2, move back to cell #1, and decrement +the value at cell #1. This continues on 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 +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, +we also increment cell #4, and then recopy cell #4 into cell #2. +``` + +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, trying writing a Brainfuck interpreter... in Brainfuck. -- cgit v1.2.3 From 2e8e2b5f3552bd9541a4eac6abba94a767dda8e4 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 20:51:11 -0500 Subject: Add enum to C. --- c.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index 4764c38e..0ac603a7 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -54,6 +54,10 @@ Multi-line comments look like this. They work in C89 as well. // Constants: use #define keyword, no semicolon at end. #define DAYS_IN_YEAR = 365 +//enumeration constants are also ways to declare constants. +enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; +// MON gets 2 automatically, TUE gets 3, etc. + // Import headers with #include #include #include -- cgit v1.2.3 From ca32d7a5f2edfe9dad2b43fc849b1495c2b5f889 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 21:16:32 -0500 Subject: Add clarity to characters in character set. --- c.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 0ac603a7..4e7dae5c 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -110,9 +110,9 @@ int main() { unsigned int ux_int; unsigned long long ux_long_long; - // chars inside single quotes '*' are character constants. - '0' //==> 48 on the ASCII table. - 'A' //==> 65 on the ASCII table. + // chars inside single quotes '*' are integers in your character set. + '0' //==> 48 on the ASCII character set. + 'A' //==> 65 on the ASCII character set. // sizeof(T) gives you the size of a variable with type T in bytes // sizeof(obj) yields the size of the expression (variable, literal, etc.). -- cgit v1.2.3 From e9c92321f4442ca4af75f6cce16d435287dad750 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 31 Aug 2013 21:18:59 -0500 Subject: Add include statement to popular C standar libraries. --- c.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/c.html.markdown b/c.html.markdown index 4e7dae5c..6d95f28b 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -62,6 +62,7 @@ enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; #include #include #include +#include // (File names between are headers from the C standard library.) // For your own headers, use double quotes instead of angle brackets: -- cgit v1.2.3 From 6071e57cd962462e720f33ec7870810cd67ba528 Mon Sep 17 00:00:00 2001 From: afaqurk Date: Sat, 31 Aug 2013 23:29:51 -0400 Subject: spelling error on php function: var_dumb() = var_dump() --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index 1cc6d2c5..0ff31dd2 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -177,7 +177,7 @@ echo $x; // => 2 echo $z; // => 0 // Dumps type and value of variable to stdout -var_dumb($z); // prints int(0) +var_dump($z); // prints int(0) // Prints variable to stdout in human-readable format print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) -- cgit v1.2.3 From ba17d5b9877f324fa633c1670c49e6a867ba5734 Mon Sep 17 00:00:00 2001 From: afaqurk Date: Sat, 31 Aug 2013 23:44:15 -0400 Subject: Added unset function to arrays and variables. Added the unset function to show the varying effects of deleting/removing variables and elements of an array. --- php.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index 0ff31dd2..19f507ad 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -59,6 +59,9 @@ $float = 1.234; $float = 1.2e3; $float = 7E-10; +// Delete variable +unset($int1) + // Arithmetic $sum = 1 + 1; // 2 $difference = 2 - 1; // 1 @@ -136,6 +139,11 @@ echo $associative['One']; // prints 1 $array = ['One', 'Two', 'Three']; echo $array[0]; // => "One" +// Add an element to the end of an array +$array[] = 'Four'; + +// Remove element from array +unset($array[3]); /******************************** * Output -- cgit v1.2.3 From 642e7c551e0f6292be403ed893a6695130cf350a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 1 Sep 2013 10:44:55 -0500 Subject: Add note to while loop in C. --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 6d95f28b..f63adc05 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -260,7 +260,7 @@ int main() { // While loops exist int ii = 0; - while (ii < 10) { + while (ii < 10) { //ANY value not zero is true. printf("%d, ", ii++); // ii++ increments ii in-place // after yielding its value ("postincrement"). } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " -- cgit v1.2.3 From 977d226d26c056094a33f38da79d1d9395915f52 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 1 Sep 2013 10:59:30 -0500 Subject: Reworded incrementing operators in C. --- c.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index f63adc05..c5ac7708 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -261,8 +261,7 @@ int main() { // While loops exist int ii = 0; while (ii < 10) { //ANY value not zero is true. - printf("%d, ", ii++); // ii++ increments ii in-place - // after yielding its value ("postincrement"). + printf("%d, ", ii++); // ii++ increments ii AFTER using it's current value. } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); @@ -270,8 +269,7 @@ int main() { int kk = 0; do { printf("%d, ", kk); - } while (++kk < 10); // ++kk increments kk in-place, and yields - // the already incremented value ("preincrement") + } while (++kk < 10); // ++kk increments kk BEFORE using it's current value. // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); -- cgit v1.2.3 From 2fab4dc971e3c249dc8be7c365309afb8ab9c209 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 1 Sep 2013 11:10:04 -0500 Subject: Add specific examples of increment and decrement operators to C. --- c.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index c5ac7708..e6179ba6 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -226,6 +226,17 @@ int main() { 0 || 1; // => 1 (Logical or) 0 || 0; // => 0 + //Increment and decrement operators: + int j = 0; + char s[]; + int w = 0; + j++; //difference between postfix and prefix explained below + ++j; // in string example. + j--; + --j; + s[j++]; //returns value of j to s THEN increments value of j. + s[++j]; //increments value of j THEN returns value of j to s. + // Bitwise operators! ~0x0F; // => 0xF0 (bitwise negation, "1's complement") 0x0F & 0xF0; // => 0x00 (bitwise AND) -- cgit v1.2.3 From 0ab144ff976c7a701acef552cc8e33b38faa7dbc Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 1 Sep 2013 11:51:25 -0500 Subject: Add conditinal expression (?:) to C. --- c.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index e6179ba6..ea047ea0 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -226,6 +226,10 @@ int main() { 0 || 1; // => 1 (Logical or) 0 || 0; // => 0 + //Conditional expression ( ?: ) + int a, b, z; + z = (a > b) ? a : b; // z = max(a, b); + //Increment and decrement operators: int j = 0; char s[]; -- cgit v1.2.3 From c4f541dc92ae149947a49a885292d8ad7ead7aa6 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 1 Sep 2013 13:17:26 -0500 Subject: Add order of evaluation table to C. --- c.html.markdown | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index ea047ea0..fd0b7964 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -593,6 +593,31 @@ typedef void (*my_fnp_type)(char *); // ... // my_fnp_type f; + +/////////////////////////////////////// +// Order of Evaluation +/////////////////////////////////////// + +//---------------------------------------------------// +// Operators | Associativity // +//---------------------------------------------------// +// () [] -> . | left to right // +// ! ~ ++ -- + = *(type)sizeof | right to left // +// * / % | left to right // +// + - | left to right // +// << >> | left to right // +// < <= > >= | left to right // +// == != | left to right // +// & | left to right // +// ^ | left to right // +// | | left to right // +// && | left to right // +// || | left to right // +// ?: | right to left // +// = += -= *= /= %= &= ^= |= <<= >>= | right to left // +// , | left to right // +//---------------------------------------------------// + ``` ## Further Reading -- cgit v1.2.3 From 39b96dd2db1de1c8d31ef6ce1c05543e7f690659 Mon Sep 17 00:00:00 2001 From: Tim Yates Date: Mon, 2 Sep 2013 12:53:05 +0100 Subject: Highlight code as Groovy, not cpp --- groovy.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index 1a635e59..e440ef00 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -8,7 +8,7 @@ filename: learngroovy.groovy Groovy - A dynamic language for the Java platform [Read more here.](http://groovy.codehaus.org) -```cpp +```groovy /* Set yourself up: -- cgit v1.2.3 From 68f26804c54280ad86ce639ae428fdf3b670de8b Mon Sep 17 00:00:00 2001 From: Tim Yates Date: Mon, 2 Sep 2013 12:57:29 +0100 Subject: Added a few more examples for List manipulation --- groovy.html.markdown | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index e440ef00..63cef76b 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -54,15 +54,26 @@ println x //Creating an empty list def technologies = [] -//Add an element to the list -technologies << "Groovy" +/*** Adding a elements to the list ***/ + +// As with Java technologies.add("Grails") + +// Left shift adds, and returns the list +technologies << "Groovy" + +// Add multiple elements technologies.addAll(["Gradle","Griffon"]) -//Remove an element from the list +/*** Removing elements from the list ***/ + +// As with Java technologies.remove("Griffon") -//Iterate over elements of a list +// Subtraction works also +technologies = technologies - 'Grails' + +// Iterate over elements of a list technologies.each { println "Technology: $it"} technologies.eachWithIndex { it, i -> println "$i: $it"} -- cgit v1.2.3 From 6f444bece417a18127782d909a518c91962823c9 Mon Sep 17 00:00:00 2001 From: Tim Yates Date: Mon, 2 Sep 2013 12:59:18 +0100 Subject: Mention mutating with List.sort --- groovy.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index 63cef76b..135efc0f 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -51,6 +51,7 @@ println x /* Collections and maps */ + //Creating an empty list def technologies = [] @@ -81,9 +82,12 @@ technologies.eachWithIndex { it, i -> println "$i: $it"} technologies.contains('Groovy') technologies.containsAll(['Groovy','Grails']) -//Sort a list +// Sort a list (mutates original list) technologies.sort() +// To sort without mutating original, you can do: +sortedTechnologies = technologies.sort( false ) + //Replace all elements in the list Collections.replaceAll(technologies, 'Gradle', 'gradle') -- cgit v1.2.3 From 95058aea96036fbdb4829d5245f5521541abdf0c Mon Sep 17 00:00:00 2001 From: Tim Yates Date: Mon, 2 Sep 2013 13:02:53 +0100 Subject: Another way of checking List.contains and some headers --- groovy.html.markdown | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index 135efc0f..8fb1b346 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -74,20 +74,33 @@ technologies.remove("Griffon") // Subtraction works also technologies = technologies - 'Grails' +/*** Iterating Lists ***/ + // Iterate over elements of a list technologies.each { println "Technology: $it"} technologies.eachWithIndex { it, i -> println "$i: $it"} +/*** Checking List contents ***/ + //Evaluate if a list contains element(s) (boolean) -technologies.contains('Groovy') +contained = technologies.contains( 'Groovy' ) + +// Or +contained = 'Groovy' in technologies + +// Check for multiple contents technologies.containsAll(['Groovy','Grails']) +/*** Sorting Lists ***/ + // Sort a list (mutates original list) technologies.sort() // To sort without mutating original, you can do: sortedTechnologies = technologies.sort( false ) +/*** Manipulating Lists ***/ + //Replace all elements in the list Collections.replaceAll(technologies, 'Gradle', 'gradle') -- cgit v1.2.3 From 3a09a727ac9720df81a2fcea4efff57e8863f959 Mon Sep 17 00:00:00 2001 From: Guillermo Vaya Date: Tue, 3 Sep 2013 00:25:40 +0200 Subject: From robot to human, corrected gender, some clojure idioms reverted to unsranslated (no one uses the spanish translation for some), general review --- es-es/clojure-es.html.markdown | 190 ++++++++++++++++++++--------------------- 1 file changed, 94 insertions(+), 96 deletions(-) diff --git a/es-es/clojure-es.html.markdown b/es-es/clojure-es.html.markdown index 7102b361..1ccdc50e 100644 --- a/es-es/clojure-es.html.markdown +++ b/es-es/clojure-es.html.markdown @@ -5,39 +5,40 @@ contributors: - ["Adam Bard", "http://adambard.com/"] translators: - ["Antonio Hernández Blas", "https://twitter.com/nihilipster"] + - ["Guillermo Vayá Pérez", "http://willyfrog.es"] lang: es-es --- -Clojure es un lenguaje de la familia Lisp desarrollado para la Máquina Virtual -de Java. Tiene un énfasis más fuerte en la [programación funcional](https://es.wikipedia.org/wiki/Programación_funcional) pura -que Common Lisp, pero incluye varias facilidades de [SMT](https://es.wikipedia.org/wiki/Memoria_transacional) para manipular +Clojure es un lenguaje de la familia Lisp desarrollado sobre la Máquina Virtual +de Java. Tiene un énfasis mayor en la [programación funcional](https://es.wikipedia.org/wiki/Programación_funcional) pura +que Common Lisp, pero incluyendo la posibilidad de usar [SMT](https://es.wikipedia.org/wiki/Memoria_transacional) para manipular el estado según se presente. -Esta combinación le permite manejar el procesamiento concurrente muy simple, +Esta combinación le permite gestionar la concurrencia de manera muy sencilla y a menudo automáticamente. -(Necesitas la versión de Clojure 1.2 o nueva) +(Necesitas la versión de Clojure 1.2 o posterior) ```clojure -; Los comentatios inician con punto y coma. +; Los comentatios comienzan con punto y coma. -; Clojure es escrito en "forms" (patrones), los cuales son solo -; listas de objectos dentro de paréntesis, separados por espacios en blanco. +; Clojure se escribe mediante "forms" (patrones), los cuales son +; listas de objectos entre paréntesis, separados por espacios en blanco. -; El reader (lector) de Clojure asume que el primer objeto es una -; función o una macro a llamar, y que el resto son argumentos. +; El "reader" (lector) de Clojure asume que el primer objeto es una +; función o una macro que se va a llamar, y que el resto son argumentos. -; La primera llamada en un archivo debe ser ns, para establecer el espacio de -; nombre +; El primer form en un archivo debe ser ns, para establecer el namespace (espacio de +; nombres) (ns learnclojure) -; Más ejemplos básicos: +; Algunos ejemplos básicos: -; str creará una cadena de caracteres a partir de sus argumentos +; str crea una cadena de caracteres a partir de sus argumentos (str "Hello" " " "World") ; => "Hello World" -; Las matemáticas son sencillas +; Las operaciones matemáticas son sencillas (+ 1 1) ; => 2 (- 2 1) ; => 1 (* 1 2) ; => 2 @@ -47,44 +48,44 @@ y a menudo automáticamente. (= 1 1) ; => true (= 2 1) ; => false -; Necesitas de la negación para la lógica, también +; También es necesaria la negación para las operaciones lógicas (not true) ; => false -; Los patrones anidados funcionan como lo esperas +; Cuando se anidan Los patrones, estos funcionan de la manera esperada (+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 ; Tipos ;;;;;;;;;;;;; -; Clojure usa los tipos de objetos de Java para booleanos,cadenas de -; caracteres y números. -; Usa class para inspeccionarlos. -(class 1); Los enteros literales son java.lang.Long por default -(class 1.); Los flotantes literales son java.lang.Double -(class ""); Las cadenas de caracteres van entre comillas dobles, y son +; Clojure usa los tipos de objetos de Java para booleanos, strings (cadenas de +; caracteres) y números. +; Usa class para saber de qué tipo es. +(class 1); Los enteros son java.lang.Long por defecto +(class 1.); Los numeros en coma flotante son java.lang.Double +(class ""); Los strings van entre comillas dobles, y son ; son java.lang.String (class false); Los Booleanos son java.lang.Boolean -(class nil); El valor "null" es llamado nil +(class nil); El valor "null" se escribe nil -; Si quieres crear una lista literal de datos, precede la con una comilla +; Si quieres crear una lista de datos, precedela con una comilla ; simple para evitar su evaluación '(+ 1 2) ; => (+ 1 2) -; (abreviatura de (quote (+ 1 2)) +; (que es una abreviatura de (quote (+ 1 2)) -; Puedes evaluar una lista precedida por comilla simple con eval +; Puedes evaluar una lista precedida por comilla con eval (eval '(+ 1 2)) ; => 3 ; Colecciones & Secuencias ;;;;;;;;;;;;;;;;;;; -; Las Listas están basadas en listas enlazadas, mientras que los Vectores en -; arreglos. -; ¡Los Vectores y las Listas son clases de Java también! +; Las Listas están basadas en las listas enlazadas, mientras que los Vectores en +; arrays. +; ¡Los Vectores y las Listas también son clases de Java! (class [1 2 3]); => clojure.lang.PersistentVector (class '(1 2 3)); => clojure.lang.PersistentList -; Una lista podría ser escrita como (1 2 3), pero debemos precidirla con -; comilla simple para evitar que el lector piense que es una función. +; Una lista podría ser escrita como (1 2 3), pero debemos ponerle una +; comilla simple delante para evitar que el reader piense que es una función. ; Además, (list 1 2 3) es lo mismo que '(1 2 3) ; Las "Colecciones" son solo grupos de datos @@ -108,23 +109,23 @@ y a menudo automáticamente. (cons 4 '(1 2 3)) ; => (4 1 2 3) ; conj agregará un elemento a una colección en la forma más eficiente. -; Para listas, se agrega al inicio. Para vectores, al final. +; Para listas, se añade al inicio. Para vectores, al final. (conj [1 2 3] 4) ; => [1 2 3 4] (conj '(1 2 3) 4) ; => (4 1 2 3) ; Usa concat para concatenar listas o vectores (concat [1 2] '(3 4)) ; => (1 2 3 4) -; Usa filter, map para actuar sobre colecciones +; Usa filter y map para actuar sobre colecciones (map inc [1 2 3]) ; => (2 3 4) (filter even? [1 2 3]) ; => (2) -; Usa reduce para reducirlos +; Usa reduce para combinar sus elementos (reduce + [1 2 3 4]) ; = (+ (+ (+ 1 2) 3) 4) ; => 10 -; reduce puede tomar un argumento como valor inicial también +; reduce puede tener un argumento indicando su valor inicial. (reduce conj [] '(3 2 1)) ; = (conj (conj (conj [] 3) 2) 1) ; => [3 2 1] @@ -132,14 +133,14 @@ y a menudo automáticamente. ; Funciones ;;;;;;;;;;;;;;;;;;;;; -; Usa fn para crear nuevas funciones. Una función siempre regresa +; Usa fn para crear nuevas funciones. Una función siempre devuelve ; su última expresión (fn [] "Hello World") ; => fn -; (Necesitas encerrarlo en paréntesis para llamarlo) +; (Necesitas rodearlo con paréntesis para invocarla) ((fn [] "Hello World")) ; => "Hello World" -; Puedes crear una var (variable) usando def +; Puedes crear una var (variable) mediante def (def x 1) x ; => 1 @@ -147,32 +148,32 @@ x ; => 1 (def hello-world (fn [] "Hello World")) (hello-world) ; => "Hello World" -; Puedes acortar este proceso al usar defn +; Puedes defn como atajo para lo anterior (defn hello-world [] "Hello World") -; El [] es el vector de argumentos para la función. +; El [] es el vector de argumentos de la función. (defn hello [name] (str "Hello " name)) (hello "Steve") ; => "Hello Steve" -; Puedes usar también esta abreviatura para crear funciones: +; Otra abreviatura para crear funciones es: (def hello2 #(str "Hello " %1)) (hello2 "Fanny") ; => "Hello Fanny" -; Puedes tener funciones multi-variadic (múltiple numero variable de -; argumentos), también +; Puedes tener funciones multi-variadic: funciones con un numero variable de +; argumentos (defn hello3 ([] "Hello World") ([name] (str "Hello " name))) (hello3 "Jake") ; => "Hello Jake" (hello3) ; => "Hello World" -; Las funciones pueden colocar argumentos extras dentro de una seq por ti +; Las funciones pueden usar argumentos extras dentro de un seq utilizable en la función (defn count-args [& args] (str "You passed " (count args) " args: " args)) (count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" -; Puedes mezclar argumentos regulares y dentro de una seq +; Y puedes mezclarlos con el resto de argumentos declarados de la función. (defn hello-count [name & args] (str "Hello " name ", you passed " (count args) " extra args")) (hello-count "Finn" 1 2 3) @@ -182,17 +183,17 @@ x ; => 1 ; Mapas ;;;;;;;;;; -; Mapas de Hash y mapas de Arreglos comparten una interfaz. Los mapas de Hash -; tienen búsquedas más rápidas pero no mantienen el orden de las llaves. +; Mapas de Hash y mapas de arrays comparten una misma interfaz. Los mapas de Hash +; tienen búsquedas más rápidas pero no mantienen el orden de las claves. (class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap (class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap -; Los mapas de Arreglos serán convertidos en mapas de Hash en la mayoría de -; operaciones si crecen lo suficiente, así que no necesitas preocuparte. +; Los mapas de arrays se convertidos en mapas de Hash en la mayoría de +; operaciones si crecen mucho, por lo que no debes preocuparte. -; Los mapas pueden usar cualquier tipo para sus llaves, pero usualmente las -; keywords (llaves) son mejor. -; Las keywords son como cadenas de caracteres con algunas ventajas en eficiencia +; Los mapas pueden usar cualquier tipo para sus claves, pero generalmente las +; keywords (palabras clave) son lo habitual. +; Las keywords son parecidas a cadenas de caracteres con algunas ventajas de eficiencia (class :a) ; => clojure.lang.Keyword (def stringmap {"a" 1, "b" 2, "c" 3}) @@ -201,31 +202,31 @@ stringmap ; => {"a" 1, "b" 2, "c" 3} (def keymap {:a 1, :b 2, :c 3}) keymap ; => {:a 1, :c 3, :b 2} -; Por cierto, las comas son siempre tratadas como espacios en blanco y no hacen +; Por cierto, las comas son equivalentes a espacios en blanco y no hacen ; nada. -; Recupera un valor de un mapa tratando la como una función +; Recupera un valor de un mapa tratandolo como una función (stringmap "a") ; => 1 (keymap :a) ; => 1 ; ¡Las keywords pueden ser usadas para recuperar su valor del mapa, también! (:b keymap) ; => 2 -; No intentes ésto con cadenas de caracteres. +; No lo intentes con strings. ;("a" stringmap) ; => Exception: java.lang.String cannot be cast to clojure.lang.IFn -; Recuperando un valor no presente regresa nil +; Si preguntamos por una clave que no existe nos devuelve nil (stringmap "d") ; => nil -; Usa assoc para agregar nuevas llaves a los mapas de Hash +; Usa assoc para añadir nuevas claves a los mapas de Hash (def newkeymap (assoc keymap :d 4)) newkeymap ; => {:a 1, :b 2, :c 3, :d 4} -; Pero recuerda, ¡los tipos de clojure son inmutables! +; Pero recuerda, ¡los tipos de Clojure son inmutables! keymap ; => {:a 1, :b 2, :c 3} -; Usa dissoc para remover llaves +; Usa dissoc para eliminar llaves (dissoc keymap :a :b) ; => {:c 3} ; Conjuntos @@ -234,70 +235,70 @@ keymap ; => {:a 1, :b 2, :c 3} (class #{1 2 3}) ; => clojure.lang.PersistentHashSet (set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} -; Agrega un miembro con conj +; Añade un elemento con conj (conj #{1 2 3} 4) ; => #{1 2 3 4} -; Remueve uno con disj +; Elimina elementos con disj (disj #{1 2 3} 1) ; => #{2 3} -; Comprueba la existencia tratando al conjunto como una función: +; Comprueba su existencia usando el conjunto como una función: (#{1 2 3} 1) ; => 1 (#{1 2 3} 4) ; => nil -; Hay más funciones en el espacio de nombre clojure.sets +; Hay más funciones en el namespace clojure.sets ; Patrones útiles ;;;;;;;;;;;;;;;;; -; Las construcciones lógicas en clojure son macros, y tienen el mismo aspecto -; que todo lo demás +; Las construcciones lógicas en clojure son macros, y presentan el mismo aspecto +; que el resto de forms. (if false "a" "b") ; => "b" (if false "a") ; => nil -; Usa let para crear una binding (asociación) temporal +; Usa let para crear un binding (asociación) temporal (let [a 1 b 2] (> a b)) ; => false -; Agrupa expresiones con do +; Agrupa expresiones mediante do (do (print "Hello") "World") ; => "World" (prints "Hello") -; Las funciones tienen un do implicito +; Las funciones tienen implicita la llamada a do (defn print-and-say-hello [name] (print "Saying hello to " name) (str "Hello " name)) (print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") -; De igual forma let +; Y el let también (let [name "Urkel"] (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") -; Modulos +; Módulos ;;;;;;;;;;;;;;; -; Usa use para obtener todas las funciones del modulo +; Usa use para obtener todas las funciones del módulo (use 'clojure.set) -; Ahora podemos usar operaciones de conjuntos +; Ahora podemos usar más operaciones de conjuntos (intersection #{1 2 3} #{2 3 4}) ; => #{2 3} (difference #{1 2 3} #{2 3 4}) ; => #{1} ; Puedes escoger un subgrupo de funciones a importar, también (use '[clojure.set :only [intersection]]) -; Usa require para importar un modulo +; Usa require para importar un módulo (require 'clojure.string) -; Usa / para llamar funciones de un modulo -; Aquí, el modulo es clojure.string y la función es blank? +; Usa / para llamar a las funciones de un módulo +; Aquí, el módulo es clojure.string y la función es blank? (clojure.string/blank? "") ; => true ; Puedes asignarle una abreviatura a un modulo al importarlo (require '[clojure.string :as str]) (str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." -; (#"" es una expresión regular literal) +; (#"" es una expresión regular) ; Puedes usar require (y use, pero no lo hagas) desde un espacio de nombre ; usando :require, @@ -311,10 +312,10 @@ keymap ; => {:a 1, :b 2, :c 3} ; Java ;;;;;;;;;;;;;;;;; -; Java tiene una enorme y útil librería estándar, así que -; querrás aprender como llegar a ella. +; Java tiene una enorme librería estándar, por lo que resulta util +; aprender como interactuar con ella. -; Usa import para cargar un modulo de java +; Usa import para cargar un módulo de java (import java.util.Date) ; Puedes importar desde un ns también. @@ -325,7 +326,7 @@ keymap ; => {:a 1, :b 2, :c 3} ; Usa el nombre de la clase con un "." al final para crear una nueva instancia (Date.) ; -; Usa "." para llamar a métodos. O, usa el atajo ".método" +; Usa "." para llamar a métodos o usa el atajo ".método" (. (Date.) getTime) ; (.getTime (Date.)) ; exactamente la misma cosa @@ -341,11 +342,11 @@ keymap ; => {:a 1, :b 2, :c 3} ; STM ;;;;;;;;;;;;;;;;; -; Software Transactional Memory es un mecanismo que clojure usa para manejar -; el estado persistente. Hay algunas cuantas construcciones en clojure que -; usan esto. +; Software Transactional Memory es un mecanismo que usa clojure para gestionar +; el estado persistente. Hay unas cuantas construcciones en clojure que +; hacen uso de este mecanismo. -; Un atom es el más simple. Dale una valor inicial +; Un atom es el más sencillo. Se le da un valor inicial (def my-atom (atom {})) ; Actualiza un atom con swap! @@ -354,11 +355,11 @@ keymap ; => {:a 1, :b 2, :c 3} (swap! my-atom assoc :a 1) ; Establece my-atom al resultado de (assoc {} :a 1) (swap! my-atom assoc :b 2) ; Establece my-atom al resultado de (assoc {:a 1} :b 2) -; Usa '@' para no referenciar al atom y obtener su valor +; Usa '@' para no referenciar al atom sino para obtener su valor my-atom ;=> Atom<#...> (Regresa el objeto Atom) @my-atom ; => {:a 1 :b 2} -; Aquí está un simple contador usando un atom +; Un sencillo contador usando un atom sería (def counter (atom 0)) (defn inc-counter [] (swap! counter inc)) @@ -371,25 +372,22 @@ my-atom ;=> Atom<#...> (Regresa el objeto Atom) @counter ; => 5 -; Otros constructores STM son refs y agents. +; Otros forms que utilizan STM son refs y agents. ; Refs: http://clojure.org/refs ; Agents: http://clojure.org/agents -``` - ### Lectura adicional -Ésto queda lejos de ser exhaustivo, pero espero que sea suficiente para -encaminarte. +Ésto queda lejos de ser exhaustivo, pero espero que sea suficiente para que puedas empezar tu camino. Clojure.org tiene muchos artículos: [http://clojure.org/](http://clojure.org/) -Clojuredocs.org tiene documentación con ejemplos para la mayoría de -funciones core: +Clojuredocs.org contiene documentación con ejemplos para la mayoría de +funciones principales (pertenecientes al core): [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) -4Clojure es una grandiosa forma de fortalecer tus habilidades con clojure/FP: +4Clojure es una genial forma de mejorar tus habilidades con clojure/FP: [http://www.4clojure.com/](http://www.4clojure.com/) -Clojure-doc.org (sí, de verdad) tiene un número de artículos para empezar: +Clojure-doc.org (sí, de verdad) tiene un buen número de artículos con los que iniciarse en Clojure: [http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From 727927f68dc1f03a19c2cc3bef1356f7b46a4e1d Mon Sep 17 00:00:00 2001 From: agum onkey Date: Tue, 3 Sep 2013 02:05:43 +0200 Subject: [minor] s/Paul Khoung/Paul Khuong/g --- common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index bf4844f3..a672b682 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -619,4 +619,4 @@ nil ; for false - and the empty list Lots of thanks to the Scheme people for rolling up a great starting point which could be easily moved to Common Lisp. -- [Paul Khoung](https://github.com/pkhuong) for some great reviewing. +- [Paul Khuong](https://github.com/pkhuong) for some great reviewing. -- cgit v1.2.3 From 6150eff5ba962d74ef0c79b7d17fcf801538637b Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 2 Sep 2013 21:33:26 -0700 Subject: ARGH --- de-de/javascript-de.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index 56a41af0..d767815e 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -1,9 +1,9 @@ --- -language: JavaScript +language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["ggb", "http://www.ideen-und-soehne.de"] -filename: learnjavascript.js +filename: learnjavascript-de.js lang: de-de --- @@ -104,8 +104,8 @@ false; // Es gibt außerdem die Werte 'null' und 'undefined' null; // wird verwendet um einen vorsätzlich gewählten 'Nicht'-Wert anzuzeigen undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht - // verfügbar ist (obwohl genau genommen undefined selbst einen Wert - // darstellt) + // verfügbar ist (obwohl genau genommen undefined selbst einen Wert + // darstellt) // false, null, undefined, NaN, 0 und "" sind 'falsy', d. h. alles andere ist // wahr. Man beachte, dass 0 falsch und "0" wahr ist, obwohl 0 == "0". @@ -255,9 +255,9 @@ i; // = 5 - nicht undefined, wie man es von einer Sprache erwarten würde, die (function(){ var temporary = 5; // Auf eine Variable im globalen Geltungsbereich kann zugegriffen werden, - // sofern sie im globalen Objekt definiert ist (in einem Webbrowser ist - // dies immer das 'window'-Objekt, in anderen Umgebungen, bspw. Node.js, - // kann das anders aussehen). + // sofern sie im globalen Objekt definiert ist (in einem Webbrowser ist + // dies immer das 'window'-Objekt, in anderen Umgebungen, bspw. Node.js, + // kann das anders aussehen). window.permanent = 10; })(); temporary; // wirft einen ReferenceError @@ -274,13 +274,13 @@ function sayHelloInFiveSeconds(name){ } setTimeout(inner, 5000); // setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds - // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein' - // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere - // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die - // Variable prompt. + // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein' + // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere + // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die + // Variable prompt. } sayHelloInFiveSeconds("Adam"); // wird nach 5 Sekunden ein Popup mit der - // Nachricht "Hello, Adam!" öffnen. + // Nachricht "Hello, Adam!" öffnen. /////////////////////////////////// // 5. Mehr über Objekte, Konstruktoren und Prototypen @@ -423,14 +423,14 @@ String.prototype.firstCharacter = function(){ // allen Umgebungen verfügbar ist - wir können sie dennoch verwenden, mit einem // 'polyfill': if (Object.create === undefined){ // überschreib nichts, was eventuell bereits - // existiert + // existiert Object.create = function(proto){ // erstelle einen vorübergehenden Konstruktor mit dem richtigen - // Prototypen + // Prototypen var Constructor = function(){}; Constructor.prototype = proto; // verwende es dann, um ein neues Objekt mit einem passenden - // Prototypen zurückzugeben + // Prototypen zurückzugeben return new Constructor(); } } @@ -446,4 +446,4 @@ Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den E [JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache. -Zusätzlich zu direkten Beiträgen zu diesem Artikel ist der Inhalt in Anlehnung an Louie Dinh's Python-Tutorial auf dieser Seite und das [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) des Mozilla Developer Network entstanden. \ No newline at end of file +Zusätzlich zu direkten Beiträgen zu diesem Artikel ist der Inhalt in Anlehnung an Louie Dinh's Python-Tutorial auf dieser Seite und das [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) des Mozilla Developer Network entstanden. -- cgit v1.2.3 From e546f9cd9c87733fc9e502746109a8abe0a12f86 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 2 Sep 2013 21:33:53 -0700 Subject: Add file download to javascript.js --- javascript.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 1dd6e2be..bc2a973a 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -1,7 +1,8 @@ --- language: javascript -author: Adam Brenecki -author_url: http://adam.brenecki.id.au +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] +filename: javascript.js --- Javascript was created by Netscape's Brendan Eich in 1995. It was originally -- cgit v1.2.3 From 0f708d94ffefdeb22e652f62062043d031d8410b Mon Sep 17 00:00:00 2001 From: netpyoung Date: Wed, 4 Sep 2013 00:26:28 +0900 Subject: Korean version of clojure tutorial added --- ko-kr/clojure-kr.html.markdown | 383 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 383 insertions(+) create mode 100644 ko-kr/clojure-kr.html.markdown diff --git a/ko-kr/clojure-kr.html.markdown b/ko-kr/clojure-kr.html.markdown new file mode 100644 index 00000000..0b9d13b2 --- /dev/null +++ b/ko-kr/clojure-kr.html.markdown @@ -0,0 +1,383 @@ +--- +language: clojure +filename: learnclojure.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["netpyoung", "http://netpyoung.github.io/"] +lang: ko-kr +--- + +Clojure는 Java 가상머신을 위해 개발된 Lisp 계통의 언어입니다 +이는 Common Lisp보다 순수 [함수형 프로그래밍](https://en.wikipedia.org/wiki/Functional_programming)을 더욱 강조했으며, +상태를 있는 그대로 다루기 위해 다양한 [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) 을 지원하는 프로그램들을 갖췄습니다. + +이를 조합하여, 병행처리(concurrent processing)를 매우 단순하게 처리할 수 있으며, +대게 자동으로 처리될 수 있도록 만들 수 있습니다. + +(Clojure 1.2 이상의 버전이 필요로 합니다.) + + +```clojure +; 주석은 세미콜론(;)으로 시작합니다. + +; Clojure는 "폼(forms)"으로 구성되었으며, +; 폼은 괄호로 감싸져있으며, 공백으로 구분된 것들이 나열된 것입니다. +; +; clojure의 reader는 첫번째로 오는 것을 +; 함수 혹은 매크로를 호출하는 것, 그리고 나머지를 인자라고 가정합니다. + +; namespace를 지정하기 위해, 파일에서 우선적으로 호출해야될 것은 ns입니다. +(ns learnclojure) + +; 간단한 예제들: + +; str 은 인자로 받은 것들을 하나의 문자열로 만들어줍니다. +(str "Hello" " " "World") ; => "Hello World" + +; 직관적인 수학 함수들을 갖고 있습니다. +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 + +; = 로 동일성을 판별할 수 있습니다. +(= 1 1) ; => true +(= 2 1) ; => false + +; 논리연산을 위한 not 역시 필요합니다. +(not true) ; => false + +; 중첩된 폼(forms)은 기대한대로 동작합니다. +(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 + +; 타입 +;;;;;;;;;;;;; + +; Clojure는 부울(boolean), 문자열, 숫자를 위해 Java의 object 타입을 이용합니다. +; `class` 를 이용하여 이를 확인할 수 있습니다. +(class 1) ; 정수는 기본적으로 java.lang.Long입니다. +(class 1.); 소수는 java.lang.Double입니다. +(class ""); 문자열은 쌍따옴표로 감싸져 있으며, java.lang.String입니다. +(class false) ; 부울값은 java.lang.Boolean입니다. +(class nil); nil은 "null"값입니다. + +; 데이터 리스트 자체를 만들고자 한다면, +; '를 이용하여 평가(evaluate)되지 않도록 막아야 합니다. +'(+ 1 2) ; => (+ 1 2) +; (quote (+ 1 2)) 를 줄여서 쓴것 + +; quote 가 된 리스트를 평가할 수 도 있습니다. +(eval '(+ 1 2)) ; => 3 + +; 컬렉션(Collections) & 시퀀스(Sequences) +;;;;;;;;;;;;;;;;;;; + +; 리스트(List)는 연결된(linked-list) 자료구조이며, 벡터(Vector)는 배열이 뒤로붙는(array-backed) 자료구조입니다. +; 리스트와 벡터 모두 java 클래스입니다! +(class [1 2 3]); => clojure.lang.PersistentVector +(class '(1 2 3)); => clojure.lang.PersistentList + +; 간단하게 (1 2 3)로 리스트를 나타낼 수 있지만, +; reader가 함수라고 여기지 못하게 quote(')를 해줘야 합니다. +; 따라서, (list 1 2 3)는 '(1 2 3)와 같습니다. + +; "컬렉션"은 단순하게 데이터의 그룹입니다. +; 리스트와 벡터 모두 컬렉션입니다: +(coll? '(1 2 3)) ; => true +(coll? [1 2 3]) ; => true + +; "시퀀스" (seq) 는 데이터 리스트를 추상적으로 기술한 것입니다. +; 리스트는 시퀀스입니다. +(seq? '(1 2 3)) ; => true +(seq? [1 2 3]) ; => false + +; 시퀀스는 접근하고자 하는 항목만 제공해주면 됩니다. +; 따라서, 시퀀스는 lazy 할 수 있습니다 -- 무한하게 늘어나는 것을 정의할 수 있습니다: +(range 4) ; => (0 1 2 3) +(range) ; => (0 1 2 3 4 ...) (an infinite series) +(take 4 (range)) ; (0 1 2 3) + +; cons 를 이용하여 리스트나 벡터의 시작부에 항목을 추가할 수 있습니다. +(cons 4 [1 2 3]) ; => (4 1 2 3) +(cons 4 '(1 2 3)) ; => (4 1 2 3) + +; conj 는 컬렉션에 가장 효율적인 방식으로 항목을 추가합니다. +; 리스트는 시작부분에 삽입하고, 벡터는 끝부분에 삽입합니다. +(conj [1 2 3] 4) ; => [1 2 3 4] +(conj '(1 2 3) 4) ; => (4 1 2 3) + +; concat 을 이용하여 리스트와 벡터를 서로 합칠 수 있습니다. +(concat [1 2] '(3 4)) ; => (1 2 3 4) + +; filter, map 을 이용하여 컬렉션을 다룰 수 있습니다. +(map inc [1 2 3]) ; => (2 3 4) +(filter even? [1 2 3]) ; => (2) + +; reduce 를 이용하여 줄여나갈 수 있습니다. +(reduce + [1 2 3 4]) +; = (+ (+ (+ 1 2) 3) 4) +; => 10 + +; reduce 는 초기 값을 인자로 취할 수 도 있습니다. +(reduce conj [] '(3 2 1)) +; = (conj (conj (conj [] 3) 2) 1) +; => [3 2 1] + +; 함수 +;;;;;;;;;;;;;;;;;;;;; + +; fn 을 이용하여 함수를 만들 수 있습니다 . +; 함수는 항상 마지막 문장을 반환합니다. +(fn [] "Hello World") ; => fn + +; (정의한 것을 호출하기 위해선, 괄호가 더 필요합니다.) +((fn [] "Hello World")) ; => "Hello World" + +; def 를 이용하여 var 를 만들 수 있습니다. +(def x 1) +x ; => 1 + +; var 에 함수를 할당시켜보겠습니다. +(def hello-world (fn [] "Hello World")) +(hello-world) ; => "Hello World" + +; defn 을 이용하여 짧게 쓸 수 도 있습니다. +(defn hello-world [] "Hello World") + +; [] 는 함수의 인자 목록을 나타냅니다. +(defn hello [name] + (str "Hello " name)) +(hello "Steve") ; => "Hello Steve" + +; 약자(shorthand)를 써서 함수를 만들 수 도 있습니다: +(def hello2 #(str "Hello " %1)) +(hello2 "Fanny") ; => "Hello Fanny" + +; 함수가 다양한 인자를 받도록 정의할 수 도 있습니다. +(defn hello3 + ([] "Hello World") + ([name] (str "Hello " name))) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" + +; 함수는 여러 인자를 시퀀스로 취할 수 있습니다. +(defn count-args [& args] + (str "You passed " (count args) " args: " args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" + +; 개별적으로 받는 것과, 시퀀스로 취하는 것을 같이 쓸 수 도 있습니다. +(defn hello-count [name & args] + (str "Hello " name ", you passed " (count args) " extra args")) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" + + +; 맵(Maps) +;;;;;;;;;; + +; 해쉬맵(hash map)과 배열맵(array map)은 공통된 인터페이스를 공유합니다. +; 해쉬맵은 찾기가 빠르지만, 키의 순서가 유지되지 않습니다. +(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap +(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap + +; 배열맵은 여러 연산을 거쳐 자연스레 해쉬맵이 됩니다. +; 만일 이게 커진다 하더라도, 걱정할 필요가 없습니다. + +; 맵은 해쉬가 가능한 타입이라면 어떠한 것이든 키로써 활용이 가능하지만, 보통 키워드를 이용하는 것이 가장 좋습니다. +; 키워드(Keyword)는 문자열과 비슷하지만, 보다 효율적인 면이 있습니다. +(class :a) ; => clojure.lang.Keyword + +(def stringmap {"a" 1, "b" 2, "c" 3}) +stringmap ; => {"a" 1, "b" 2, "c" 3} + +(def keymap {:a 1, :b 2, :c 3}) +keymap ; => {:a 1, :c 3, :b 2} + +; 여기서, 쉽표가 공백으로 취급되며, 아무 일도 하지 않는다는 것을 주목하시기 바랍니다. + +; 맵에서 값을 얻어오기 위해선, 함수로써 맵을 호출해야 합니다. +(stringmap "a") ; => 1 +(keymap :a) ; => 1 + +; 키워드 역시 맵에서 함수를 얻어올 때 사용할 수 있습니다! +(:b keymap) ; => 2 + +; 하지만, 문자열로는 하면 안됩니다. +;("a" stringmap) +; => Exception: java.lang.String cannot be cast to clojure.lang.IFn + +; 없는 값을 얻어오고자 하면, nil이 반환됩니다. +(stringmap "d") ; => nil + +; assoc 를 이용하여 해쉬맵에 새로운 키를 추가할 수 있습니다. +(def newkeymap (assoc keymap :d 4)) +newkeymap ; => {:a 1, :b 2, :c 3, :d 4} + +; 하지만, 변경할 수 없는(immutable) clojure 타입이라는 것을 기억해야 합니다! +keymap ; => {:a 1, :b 2, :c 3} + +; dissoc 를 이용하여 키를 제거할 수 있습니다. +(dissoc keymap :a :b) ; => {:c 3} + +; 쎗(Set:집합) +;;;;;; + +(class #{1 2 3}) ; => clojure.lang.PersistentHashSet +(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} + +; conj 로 항목을 추가할 수 있습니다. +(conj #{1 2 3} 4) ; => #{1 2 3 4} + +; disj 로 제거할 수 도 있습니다. +(disj #{1 2 3} 1) ; => #{2 3} + +; 존재하는지 확인할 목적으로, 쎗을 함수로 사용할 수 도 있습니다. +(#{1 2 3} 1) ; => 1 +(#{1 2 3} 4) ; => nil + +; clojure.sets 네임스페이스(namespace)에는 더 많은 함수들이 있습니다. + +; 유용한 폼(forms) +;;;;;;;;;;;;;;;;; + +; clojure에선, if 와 매크로(macro)를 가지고, +; 다른 여러 논리 연산들을 만들 수 있습니다. +(if false "a" "b") ; => "b" +(if false "a") ; => nil + +; let 을 이용하여 임시적으로 바인딩(binding)을 구축할 수 있습니다. +(let [a 1 b 2] + (> a b)) ; => false + +; do 로 문단을 묶을 수 도 있습니다. +(do + (print "Hello") + "World") ; => "World" (prints "Hello") + +; 함수는 암시적으로 do 를 가지고 있습니다. +(defn print-and-say-hello [name] + (print "Saying hello to " name) + (str "Hello " name)) +(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") + +; let 역시 그러합니다. +(let [name "Urkel"] + (print "Saying hello to " name) + (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; 모듈(Modules) +;;;;;;;;;;;;;;; + +; "use" 를 이용하여 module에 있는 모든 함수들을 얻어올 수 있습니다. +(use 'clojure.set) + +; 이제 쎗(set:집합)연산을 사용 할 수 있습니다. +(intersection #{1 2 3} #{2 3 4}) ; => #{2 3} +(difference #{1 2 3} #{2 3 4}) ; => #{1} + +; 함수들 중에 일 부분만을 가져올 수 도 있습니다. +(use '[clojure.set :only [intersection]]) + +; require 를 이용하여 모듈을 import할 수 있습니다. +(require 'clojure.string) + +; / 를 이용하여 모듈에 있는 함수를 호출 할 수 있습니다. +; 여기, clojure.string 라는 모듈에, blank? 라는 함수가 있습니다. +(clojure.string/blank? "") ; => true + +; import시, 모듈에 짧은 이름을 붙여줄 수 있습니다. +(require '[clojure.string :as str]) +(str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." +; (#"" denotes a regular expression literal) + +; :require 를 이용하여, 네임스페이스에서 require 를 사용할 수 있습니다. +; 아레와 같은 방법을 이용하면, 모듈을 quote하지 않아도 됩니다. +(ns test + (:require + [clojure.string :as str] + [clojure.set :as set])) + +; Java +;;;;;;;;;;;;;;;;; + +; Java는 유용한 많은 표준 라이브러리를 가지고 있으며, +; 이를 어떻게 활용할 수 있는지 알아보도록 하겠습니다. + +; import 로 java 모듈을 불러올 수 있습니다. +(import java.util.Date) + +; ns 와 함께 import 를 할 수 도 있습니다. +(ns test + (:import java.util.Date + java.util.Calendar)) + +; 새로운 인스턴스를 만들기 위해선, 클래스 이름 끝에 "."을 찍습니다. +(Date.) ;
+ +; . 을 이용하여 메소드를 호출할 수 있습니다. +; 아니면, 줄여서 ".메소드"로도 호출 할 수 있습니다. +(. (Date.) getTime) ; +(.getTime (Date.)) ; exactly the same thing. + +; / 를 이용하여 정적메소드를 호출 할 수 있습니다. +(System/currentTimeMillis) ; (system is always present) + +; doto 를 이용하여 상태가 변하는(mutable) 클래스들을 좀 더 편하게(tolerable) 다룰 수 있습니다. +(import java.util.Calendar) +(doto (Calendar/getInstance) + (.set 2000 1 1 0 0 0) + .getTime) ; => A Date. set to 2000-01-01 00:00:00 + +; STM +;;;;;;;;;;;;;;;;; + +; Software Transactional Memory 는 clojure가 영구적인(persistent) 상태를 다루는 방식입니다. +; clojure가 이용하는 몇몇 자료형(construct)이 있습니다. + +; 가장 단순한 것은 atom 입니다. 초기 값을 넣어보도록 하겠습니다. +(def my-atom (atom {})) + +; swap! 으로 atom을 갱신(update)할 수 있습니다! +; swap! 은 함수를 인자로 받아, 그 함수에 대해 현재 atom에 들어있는 값을 첫번째 인자로, +; 나머지를 두번째 인자로 하여 호출합니다. +(swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2) + +; '@' 를 이용하여 atom을 역참조(dereference)하여 값을 얻을 수 있습니다. +my-atom ;=> Atom<#...> (atom 객체가 반환됩니다.) +@my-atom ; => {:a 1 :b 2} + +; 여기 atom을 이용한 단순한 카운터가 있습니다. +(def counter (atom 0)) +(defn inc-counter [] + (swap! counter inc)) + +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) + +@counter ; => 5 + +; STM을 구성하는 다른 것들에는 ref 와 agent 가 있습니다. +; Refs: http://clojure.org/refs +; Agents: http://clojure.org/agents +``` + +### 읽어볼거리 + +부족한 것이 많았지만, 다행히도 채울 수 있는 것들이 많이 있습니다. + +Clojure.org에 많은 문서들이 보관되어 있습니다: +[http://clojure.org/](http://clojure.org/) + +Clojuredocs.org는 core 함수들에 대해 다양한 예제와 문서를 보유하고 있습니다: +[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) + +4Clojure는 clojure/FP 스킬을 올릴 수 있는 좋은 길입니다: +[http://www.4clojure.com/](http://www.4clojure.com/) + +Clojure-doc.org는 많고 많은 문서들을 보유하고 있습니다: +[http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From c7a623b6494fc2c3cbacb31bed52996c98283655 Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Tue, 3 Sep 2013 23:21:03 +0300 Subject: update latest commits. --- tr-tr/c-tr.html.markdown | 4 ++++ tr-tr/php-tr.html.markdown | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 50bca246..128901de 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -95,6 +95,10 @@ int main() { // is not evaluated (except VLAs (see below)). // The value it yields in this case is a compile-time constant. int a = 1; + + // size_t bir objeyi temsil etmek için kullanılan 2 byte uzunluğundaki bir + // işaretsiz tam sayı tipidir + size_t size = sizeof(a++); // a++ is not evaluated printf("sizeof(a++) = %zu where a = %d\n", size, a); // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) diff --git a/tr-tr/php-tr.html.markdown b/tr-tr/php-tr.html.markdown index 94bc31ff..c5576fd7 100644 --- a/tr-tr/php-tr.html.markdown +++ b/tr-tr/php-tr.html.markdown @@ -67,6 +67,9 @@ $float = 1.234; $float = 1.2e3; $float = 7E-10; +// Değişken Silmek +unset($int1) + // Aritmetik $sum = 1 + 1; // 2 $difference = 2 - 1; // 1 @@ -183,6 +186,13 @@ $y = 0; echo $x; // => 2 echo $z; // => 0 +// Dump'lar değişkenin tipi ve değerini yazdırır +var_dump($z); // int(0) yazdırılacaktır + +// Print'ler ise değişkeni okunabilir bir formatta yazdıracaktır. +print_r($array); // Çıktı: Array ( [0] => One [1] => Two [2] => Three ) + + /******************************** * Mantık */ @@ -478,10 +488,18 @@ class MyClass print 'MyClass'; } + //final anahtar kelimesi bu metodu override edilemez yapacaktır. final function youCannotOverrideMe() { } +/* +Bir sınıfın özelliğini ya da metodunu statik yaptığınız takdirde sınıfın bir +objesini oluşturmadan bu elemana erişebilirsiniz. Bir özellik statik tanımlanmış +ise obje üzerinden bu elemana erişilemez. (Statik metodlar öyle değildir.) +*/ + + public static function myStaticMethod() { print 'I am static'; -- cgit v1.2.3 From d2ff3969a6f4aa66a3b13c15c600d758136060af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olfran=20Jim=C3=A9nez?= Date: Tue, 3 Sep 2013 16:27:06 -0430 Subject: Spanish translation for the csharp article --- es-es/csharp-es.html.markdown | 631 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 631 insertions(+) create mode 100644 es-es/csharp-es.html.markdown diff --git a/es-es/csharp-es.html.markdown b/es-es/csharp-es.html.markdown new file mode 100644 index 00000000..7d1a1201 --- /dev/null +++ b/es-es/csharp-es.html.markdown @@ -0,0 +1,631 @@ +--- +language: c# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] + - ["Max Yankov", "https://github.com/golergka"] +translators: + - ["Olfran Jiménez", "https://twitter.com/neslux"] +filename: LearnCSharp-es.cs +--- + +C# es un lenguaje orientado a objetos elegante y de tipado seguro que +permite a los desarrolladores construir una variedad de aplicaciones +seguras y robustas que se ejecutan en el Framework .NET. + +[Lee más aquí.](http://msdn.microsoft.com/es-es/library/vstudio/z1zx9t92.aspx) + +```c# +// Los comentarios de una sola línea comienzan con // +/* +Los comentarios de múltiples líneas son de esta manera +*/ +/// +/// Este es un comentario de documentación XML +/// + +// Especifica el espacio de nombres que estará usando la aplicación +using System; +using System.Collections.Generic; + + +// Define un ambito para organizar el código en "paquetes" +namespace Learning +{ + // Cada archivo .cs debe contener al menos una clase con el mismo nombre que el archivo + // Se permite colocar cualquier nombre, pero no deberías por cuestiones de consistencia. + public class LearnCSharp + { + // Una aplicación de consola debe tener un método main como punto de entrada + public static void Main(string[] args) + { + // Usa Console.WriteLine para imprimir líneas + Console.WriteLine("Hello World"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Para imprimir sin una nueva línea, usa Console.Write + Console.Write("Hello "); + Console.Write("World"); + + + /////////////////////////////////////////////////// + // Variables y Tipos + // + // Declara una variable usando + /////////////////////////////////////////////////// + + // Sbyte - Entero de 8 bits con signo + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Entero de 8 bits sin signo + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - Entero de 16 bits con signo + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Ushort - Entero de 16 bits sin signo + // (0 <= ushort <= 65,535) + ushort fooUshort = 10000; + + // Integer - Entero de 32 bits con signo + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Uinteger - Entero de 32 bits sin signo + // (0 <= uint <= 4,294,967,295) + uint fooUint = 1; + + // Long - Entero de 64 bits con signo + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L es usado para indicar que esta variable es de tipo long o ulong + // un valor sin este sufijo es tratado como int o uint dependiendo del tamaño. + + // Ulong - Entero de 64 bits sin signo + // (0 <= ulong <= 18,446,744,073,709,551,615) + ulong fooUlong = 100000L; + + // Float - Precisión simple de 32 bits. IEEE 754 Coma flotante + // Precisión: 7 dígitos + float fooFloat = 234.5f; + // f es usado para indicar que el valor de esta variable es de tipo float + // de otra manera sería tratado como si fuera de tipo double. + + // Double - Doble precisión de 32 bits. IEEE 754 Coma flotante + // Precisión: 15-16 dígitos + double fooDouble = 123.4; + + // Bool - true & false (verdadero y falso) + bool fooBoolean = true; + bool barBoolean = false; + + // Char - Un solo caracter Unicode de 16 bits + char fooChar = 'A'; + + // Strings + string fooString = "My string is here!"; + Console.WriteLine(fooString); + + // Formato de cadenas + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + Console.WriteLine(fooFormattedString); + + // Formato de fechas + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // \n es un caracter de escape que comienza una nueva línea + string barString = "Printing on a new line?\nNo Problem!"; + Console.WriteLine(barString); + + // Puede ser escrito mejor usando el símbolo @ + string bazString = @"Here's some stuff + on a new line!"; + Console.WriteLine(bazString); + + // Las comillas deben ser escapadas + // usa \" para escaparlas + string quotedString = "some \"quoted\" stuff"; + Console.WriteLine(quotedString); + + // usa "" cuando las cadenas comiencen con @ + string quotedString2 = @"some MORE ""quoted"" stuff"; + Console.WriteLine(quotedString2); + + // Usa const o readonly para hacer las variables inmutables + // los valores const son calculados en tiempo de compilación + const int HOURS_I_WORK_PER_WEEK = 9001; + + // Tipos que aceptan valores NULL (Nullable) + // cualquier tipo de dato puede ser un tipo nulo añadiendole el sufijo ? + // ? = + int? nullable = null; + Console.WriteLine("Nullable variable: " + nullable); + + // Para usar valores nulos, tienes que usar la propiedad Value + // o usar conversión explícita + string? nullableString = "not null"; + Console.WriteLine("Nullable value is: " + nullableString.Value + " or: " + (string) nullableString ); + + // ?? is una manera corta de especificar valores por defecto + // en caso de que la variable sea null + int notNullable = nullable ?? 0; + Console.WriteLine("Not nullable variable: " + notNullable); + + // var - el compilador escogerá el tipo de dato más apropiado basado en el valor + var fooImplicit = true; + + /////////////////////////////////////////////////// + // Estructura de datos + /////////////////////////////////////////////////// + Console.WriteLine("\n->Data Structures"); + + // Arreglos + // El tamaño del arreglo debe decidirse al momento de la declaración + // El formato para declarar un arreglo es el siguiente: + // [] = new []; + int[] intArray = new int[10]; + string[] stringArray = new string[1]; + bool[] boolArray = new bool[100]; + + // Otra forma de declarar e inicializar un arreglo + int[] y = { 9000, 1000, 1337 }; + + // Indexar arreglos - Acceder a un elemento + Console.WriteLine("intArray @ 0: " + intArray[0]); + + // Los arreglos son de índice cero y son mutables. + intArray[1] = 1; + Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1 + + // Listas + // Las listas son usadas más frecuentemente que los arreglos ya que son más flexibles + // El formato para declarar una lista es el siguiente: + // List = new List(); + List intList = new List(); + List stringList = new List(); + + // Otra forma de declarar e inicializar una lista + List z = new List { 9000, 1000, 1337 }; + + // Indexar una lista - Acceder a un elemento + // Las listas son de índice cero y son mutables. + Console.WriteLine("z @ 0: " + z[2]); + + // Las listas no tienen valores por defecto; + // Un valor debe ser añadido antes de acceder al índice + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + + // Otras estructuras de datos a chequear: + // + // Pilas/Colas + // Diccionarios + // Colecciones de sólo lectura + // Tuplas (.Net 4+) + + + /////////////////////////////////////// + // Operadores + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Modo corto para múltiples declaraciones + + // La aritmética es sencilla + Console.WriteLine("1+2 = " + (i1 + i2)); // => 3 + Console.WriteLine("2-1 = " + (i2 - i1)); // => 1 + Console.WriteLine("2*1 = " + (i2 * i1)); // => 2 + Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) + + // Módulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Operadores de comparación + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Operadores a nivel de bits + /* + ~ Complemento a nivel de bits + << Desplazamiento a la izquierda con signo + >> Desplazamiento a la derecha con signo + >>> Desplazamiento a la derecha sin signo + & AND a nivel de bits + ^ XOR a nivel de bits + | OR a nivel de bits + */ + + // Incremento + int i = 0; + Console.WriteLine("\n->Inc/Dec-remento"); + Console.WriteLine(i++); //i = 1. Posincrementación + Console.WriteLine(++i); //i = 2. Preincremento + Console.WriteLine(i--); //i = 1. Posdecremento + Console.WriteLine(--i); //i = 0. Predecremento + + + /////////////////////////////////////// + // Estructuras de control + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // Las condiciones if son como en lenguaje c + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Operador ternario + // Un simple if/else puede ser escrito de la siguiente manera; + // ? : + string isTrue = (true) ? "True" : "False"; + Console.WriteLine("Ternary demo: " + isTrue); + + + // Bucle while + int fooWhile = 0; + while (fooWhile < 100) + { + //Console.WriteLine(fooWhile); + //Incrementar el contador + //Iterar 99 veces, fooWhile 0->99 + fooWhile++; + } + Console.WriteLine("fooWhile Value: " + fooWhile); + + // Bucle Do While + int fooDoWhile = 0; + do + { + //Console.WriteLine(fooDoWhile); + //Incrementar el contador + //Iterar 99 veces, fooDoWhile 0->99 + fooDoWhile++; + } while (fooDoWhile < 100); + Console.WriteLine("fooDoWhile Value: " + fooDoWhile); + + // Bucle For + int fooFor; + //Estructura del bucle for => for(; ; ) + for (fooFor = 0; fooFor < 10; fooFor++) + { + //Console.WriteLine(fooFor); + //Iterated 10 times, fooFor 0->9 + } + Console.WriteLine("fooFor Value: " + fooFor); + + // Switch Case + // El switch funciona con los tipos de datos byte, short, char e int + // También funciona con las enumeraciones (discutidos en in Tipos Enum), + // la clase string y algunas clases especiales que encapsulan + // tipos primitivos: Character, Byte, Short, Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + default: + monthString = "Some other month"; + break; + } + Console.WriteLine("Switch Case Result: " + monthString); + + + //////////////////////////////// + // Conversión de tipos de datos + //////////////////////////////// + + // Convertir datos + + // Convertir String a Integer + // esto generará una excepción al fallar la conversión + int.Parse("123");//retorna una versión entera de "123" + + // TryParse establece la variable a un tipo por defecto + // en este caso: 0 + int tryInt; + int.TryParse("123", out tryInt); + + // Convertir Integer a String + // La clase Convert tiene algunos métodos para facilitar las conversiones + Convert.ToString(123); + + /////////////////////////////////////// + // Clases y Funciones + /////////////////////////////////////// + + Console.WriteLine("\n->Classes & Functions"); + + // (Definición de la clase Bicycle (Bicicleta)) + + // Usar new para instanciar una clase + Bicycle trek = new Bicycle(); + + // Llamar a los métodos del objeto + trek.speedUp(3); // Siempre deberías usar métodos setter y métodos getter + trek.setCadence(100); + + // ToString es una convención para mostrar el valor del objeto. + Console.WriteLine("trek info: " + trek.ToString()); + + // Instanciar otra nueva bicicleta + Bicycle octo = new Bicycle(5, 10); + Console.WriteLine("octo info: " + octo.ToString()); + + // Instanciar un Penny Farthing (Biciclo) + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.ToString()); + + Console.Read(); + } // Fin del método main + + + } // Fin de la clase LearnCSharp + + // Puedes incluir otras clases en un archivo .cs + + + // Sintaxis para la declaración de clases: + // class { + // //campos, constructores, funciones todo adentro de la clase. + // //las funciones son llamadas métodos como en java. + // } + + public class Bicycle + { + // Campos/Variables de la clase Bicycle + public int cadence; // Public: Accesible desde cualquier lado + private int _speed; // Private: Sólo es accesible desde dentro de la clase + protected int gear; // Protected: Accesible desde clases y subclases + internal int wheels; // Internal: Accesible en el ensamblado + string name; // Todo es privado por defecto: Sólo es accesible desde dentro de esta clase + + // Enum es un tipo valor que consiste un una serie de constantes con nombres + public enum Brand + { + AIST, + BMC, + Electra, + Gitane + } + // Definimos este tipo dentro de la clase Bicycle, por lo tanto es un tipo anidado + // El código afuera de esta clase debería referenciar este tipo como Bicycle.Brand + + public Brand brand; // Declaramos un tipo enum, podemos declarar un campo de este tipo + + // Los miembros estáticos pertenecen al tipo mismo, no a un objeto en específico. + static public int bicyclesCreated = 0; + // Puedes acceder a ellos sin referenciar ningún objeto: + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + + // Los valores readonly (Sólo lectura) son establecidos en tiempo de ejecución + // sólo pueden ser asignados al momento de la declaración o dentro de un constructor + readonly bool hasCardsInSpokes = false; // privado de sólo lectura + + // Los constructores son una forma de crear clases + // Este es un constructor por defecto + private Bicycle() + { + gear = 1; + cadence = 50; + _speed = 5; + name = "Bontrager"; + brand = Brand.AIST; + bicyclesCreated++; + } + + // Este es un constructor específico (contiene argumentos) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, Brand brand) + { + this.gear = startGear; // La palabra reservada "this" señala el objeto actual + this.cadence = startCadence; + this._speed = startSpeed; + this.name = name; // Puede ser útil cuando hay un conflicto de nombres + this.hasCardsInSpokes = hasCardsInSpokes; + this.brand = brand; + } + + // Los constructores pueden ser encadenados + public Bicycle(int startCadence, int startSpeed, Brand brand) : + this(startCadence, startSpeed, 0, "big wheels", true) + { + } + + // Sintaxis para Funciones: + // () + + // Las clases pueden implementar getters y setters para sus campos + // o pueden implementar propiedades + + // Sintaxis para la declaración de métodos: + // <ámbito> () + public int GetCadence() + { + return cadence; + } + + // Los métodos void no requieren usar return + public void SetCadence(int newValue) + { + cadence = newValue; + } + + // La palabra reservada virtual indica que este método puede ser sobrescrito + public virtual void SetGear(int newValue) + { + gear = newValue; + } + + // Los parámetros de un método pueden tener valores por defecto. + // En este caso, los métodos pueden ser llamados omitiendo esos parámetros + public void SpeedUp(int increment = 1) + { + _speed += increment; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // Propiedades y valores get/set + // Cuando los datos sólo necesitan ser accedidos, considera usar propiedades. + // Las propiedades pueden tener get, set o ambos + private bool _hasTassles; // variable privada + public bool HasTassles // acceso público + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + // Las propiedades pueden ser auto implementadas + public int FrameSize + { + get; + // Puedes especificar modificadores de acceso tanto para get como para set + // esto significa que sólo dentro de la clase Bicycle se puede modificar Framesize + private set; + } + + //Método para mostrar los valores de atributos de este objeto. + public override string ToString() + { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + _speed + + " name: " + name + + " cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + + // Los métodos también pueden ser estáticos. Puede ser útil para métodos de ayuda + public static bool DidWeCreateEnoughBycles() + { + // Dentro de un método esático, + // Sólo podemos hacer referencia a miembros estáticos de clases + return bicyclesCreated > 9000; + } // Si tu clase sólo necesita miembros estáticos, + // considera establecer la clase como static. + + } // fin de la clase Bicycle + + // PennyFarthing es una subclase de Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings son las bicicletas con una rueda delantera enorme. + // No tienen engranajes.) + + // llamar al constructor de la clase padre + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true) + { + } + + public override void SetGear(int gear) + { + gear = 0; + } + + public override string ToString() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Llamar a la versión base del método + return reuslt; + } + } + + // Las interfaces sólo contienen las declaraciones + // de los miembros, sin la implementación. + interface IJumpable + { + void Jump(int meters); // todos los miembros de interfaces son implícitamente públicos + } + + interface IBreakable + { + // Las interfaces pueden contener tanto propiedades como métodos, campos y eventos + bool Broken { get; } + } + + // Las clases sólo heredan de alguna otra clase, pero pueden implementar + // cualquier cantidad de interfaces + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public void Broken + { + get + { + return damage > 100; + } + } + } +} // Fin del espacio de nombres + +``` + +## Temas no cubiertos + + * Flags + * Attributes + * Generics (T), Delegates, Func, Actions, lambda expressions + * Static properties + * Exceptions, Abstraction + * LINQ + * ASP.NET (Web Forms/MVC/WebMatrix) + * Winforms + * Windows Presentation Foundation (WPF) + + + +## Lecturas recomendadas + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/es-es/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + + + +[Convenciones de código de C#](http://msdn.microsoft.com/es-es/library/vstudio/ff926074.aspx) -- cgit v1.2.3 From dde956286abf4e90f74cbbb773c57c7838d6b812 Mon Sep 17 00:00:00 2001 From: Jens Rantil Date: Wed, 4 Sep 2013 09:37:26 +0200 Subject: parens => parentheses --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 4db76a49..5d5d974b 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -46,7 +46,7 @@ func main() { } // Functions have parameters in parentheses. -// If there are no parameters, empty parens are still required. +// If there are no parameters, empty parentheses are still required. func beyondHello() { var x int // Variable declaration. Variables must be declared before use. x = 3 // Variable assignment. -- cgit v1.2.3 From d3ccd75c999d68a68fe82a61d1cb871b4d99a6e3 Mon Sep 17 00:00:00 2001 From: Mathias Bynens Date: Wed, 4 Sep 2013 10:24:15 +0200 Subject: brainfuck: A few corrections --- brainfuck.html.markdown | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown index 2b7ce4db..9282381f 100644 --- a/brainfuck.html.markdown +++ b/brainfuck.html.markdown @@ -1,11 +1,12 @@ --- language: brainfuck contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io"] + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] --- -Brainfuck is an extremely minimal programming language (just 8 commands) and -is Turing complete. +Brainfuck (not capitalized except at the start of a sentence) is an extremely +minimal Turing-complete programming language with just 8 commands. ``` Any character not "><+-.,[]" (excluding quotation marks) is ignored. @@ -27,7 +28,7 @@ There are eight commands: [ and ] form a while loop. Obviously, they must be balanced. -Let's look at some basic Brainfuck programs. +Let's look at some basic brainfuck programs. ++++++ [ > ++++++++++ < - ] > +++++ . @@ -45,21 +46,18 @@ print cell #2's value. 65 is 'A' in ASCII, so 'A' is printed to the terminal. , [ > + < - ] > . -This program reads a character from the user input, copies the character into -another cell, and prints out the same character. - -, reads in a character from the user into cell #1. Then we start a loop. Move -to cell #2, increment the value at cell #2, move back to cell #1, and decrement -the value at cell #1. This continues on 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. +This program reads a character from the user input and copies the character into +cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, +move back to cell #1, and decrement the value at cell #1. This continues on +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 -could just as easily write it as +could just as easily write it as: ,[>+<-]>. - Try and figure out what this program does: ,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> @@ -73,7 +71,7 @@ problem: at the end of the inner loop, cell #2 is zero. To solve this problem, we also increment cell #4, and then recopy cell #4 into cell #2. ``` -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, trying writing a Brainfuck interpreter... in Brainfuck. +masochist, try writing a brainfuck interpreter… in brainfuck. -- cgit v1.2.3 From abb903caba70b2813cc2194d294ee8e802dbec15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20=C5=A0uppa?= Date: Wed, 4 Sep 2013 11:30:50 +0200 Subject: chan chan string -> channel of string channels --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 4db76a49..9ffe9ed5 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -251,7 +251,7 @@ func learnConcurrency() { fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. cs := make(chan string) // another channel, this one handles strings. - cc := make(chan chan string) // a channel of channels. + cc := make(chan chan string) // a channel of string channels. go func() { c <- 84 }() // start a new goroutine just to send a value go func() { cs <- "wordy" }() // again, for cs this time // Select has syntax like a switch statement but each case involves -- cgit v1.2.3 From 6c53c05dcc25e74885411832839aa19ff46ee66a Mon Sep 17 00:00:00 2001 From: Rob Hoelz Date: Wed, 4 Sep 2013 11:39:15 +0200 Subject: Clarify self-referential local functions The current language used implies that `local function f() ... end` does not allow f to invoke itself. This has been clarified via the addition of an example of a local function that may *not* invoke itself. --- lua.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua.html.markdown b/lua.html.markdown index 7325a1cf..35d68e9b 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -125,6 +125,9 @@ f = function (x) return x * x end -- And so are these: local function g(x) return math.sin(x) end +local g = function(x) return math.xin(x) end +-- Equivalent to local function g(x)..., except referring +-- to g in the function body won't work as expected. local g; g = function (x) return math.sin(x) end -- the 'local g' decl makes g-self-references ok. -- cgit v1.2.3 From 57e0ac7e95a55ede7408a36dc7524649bbc8e4c2 Mon Sep 17 00:00:00 2001 From: Rob Hoelz Date: Wed, 4 Sep 2013 11:41:42 +0200 Subject: Add another example of function call without parens Function calls using a table literal as its sole parameter may also omit parentheses --- lua.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lua.html.markdown b/lua.html.markdown index 35d68e9b..9f9fd77b 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -136,6 +136,10 @@ local g; g = function (x) return math.sin(x) end -- Calls with one string param don't need parens: print 'hello' -- Works fine. +-- Calls with one table param don't need parens +-- either (more on tables below): +print {} -- Works fine too. + ---------------------------------------------------- -- 3. Tables. -- cgit v1.2.3 From edea434d89049b700a58f8523fbd57590de5855d Mon Sep 17 00:00:00 2001 From: Rob Hoelz Date: Wed, 4 Sep 2013 11:43:09 +0200 Subject: Use local variables for function examples Currently, the example functions create variables in global scope. --- lua.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua.html.markdown b/lua.html.markdown index 9f9fd77b..369de908 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -210,7 +210,7 @@ f2 = {a = 2, b = 3} metafraction = {} function metafraction.__add(f1, f2) - sum = {} + local sum = {} sum.b = f1.b * f2.b sum.a = f1.a * f2.b + f2.a * f1.b return sum @@ -273,7 +273,7 @@ eatenBy = myFavs.animal -- works! thanks, metatable Dog = {} -- 1. function Dog:new() -- 2. - newObj = {sound = 'woof'} -- 3. + local newObj = {sound = 'woof'} -- 3. self.__index = self -- 4. return setmetatable(newObj, self) -- 5. end @@ -308,7 +308,7 @@ mrDog:makeSound() -- 'I say woof' -- 8. LoudDog = Dog:new() -- 1. function LoudDog:makeSound() - s = self.sound .. ' ' -- 2. + local s = self.sound .. ' ' -- 2. print(s .. s .. s) end @@ -329,7 +329,7 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- If needed, a subclass's new() is like the base's: function LoudDog:new() - newObj = {} + local newObj = {} -- set up newObj self.__index = self return setmetatable(newObj, self) -- cgit v1.2.3 From 284f1ea407b576dad1b92bc59d9330c608b7adf6 Mon Sep 17 00:00:00 2001 From: NKCSS Date: Wed, 4 Sep 2013 11:52:57 +0200 Subject: Changed Print function to show the variable type This is to follow the way the string value is presented, and the format string is written (... is a ... infers a stype specification) --- go.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 4db76a49..853775c4 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -1,4 +1,4 @@ ---- +--- name: Go category: language language: Go @@ -259,7 +259,7 @@ func learnConcurrency() { // that are ready to communicate. select { case i := <-c: // the value received can be assigned to a variable - fmt.Println("it's a", i) + fmt.Printf("it's a %T", i) case <-cs: // or the value received can be discarded fmt.Println("it's a string") case <-cc: // empty channel, not ready for communication. -- cgit v1.2.3 From 01150e5309c2c924df02405c66d9b5cfb759eac9 Mon Sep 17 00:00:00 2001 From: Dave Caunt Date: Wed, 4 Sep 2013 12:38:47 +0100 Subject: Fixed For loop example so that jj is not incremented twice in each iteration of the loop --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 9e9f43e7..e8c979d8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -160,7 +160,7 @@ int main (int argc, const char * argv[]) int jj; for (jj=0; jj < 4; jj++) { - NSLog(@"%d,", jj++); + NSLog(@"%d,", jj); } // => prints "0," // "1," // "2," -- cgit v1.2.3 From 29002c1a6fe62c996363f91320288bd762fe8e9e Mon Sep 17 00:00:00 2001 From: Ovidiu Ciule Date: Wed, 4 Sep 2013 13:50:59 +0200 Subject: Add romanian python translation. Expect spelling corrections. --- ro-ro/python-ro.html.markdown | 490 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 490 insertions(+) create mode 100644 ro-ro/python-ro.html.markdown diff --git a/ro-ro/python-ro.html.markdown b/ro-ro/python-ro.html.markdown new file mode 100644 index 00000000..677f4356 --- /dev/null +++ b/ro-ro/python-ro.html.markdown @@ -0,0 +1,490 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Ovidiu Ciule", "https://github.com/ociule"] lang: ro-ro filename: python-ro.html.markdown +filename: learnpython.py +--- + +Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a devenit astăzi unul din +cele mai populare limbaje de programare. M-am indrăgostit de Python pentru claritatea sa sintactică. +Python este aproape pseudocod executabil. + +Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) sau ociule [at] [google's email service] +Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] + +Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. O versiune Python 3 va apărea +în curând, în limba engleză mai întâi. + +```python +# Comentariile pe o singură linie încep cu un caracter diez. +""" Şirurile de caractere pe mai multe linii pot fi încadrate folosind trei caractere ", şi sunt des + folosite ca şi comentarii pe mai multe linii. +""" + +#################################################### +## 1. Operatori şi tipuri de date primare +#################################################### + +# Avem numere +3 #=> 3 + +# Matematica se comportă cum ne-am aştepta +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere întregi şi rotunjeşte +# automat spre valoarea mai mică +5 / 2 #=> 2 + +# Pentru a folosi împărţirea fără rest avem nevoie de numere reale +2.0 # Acesta e un număr real +11.0 / 4.0 #=> 2.75 ahhh ... cum ne aşteptam + +# Ordinea operaţiilor se poate forţa cu paranteze +(1 + 3) * 2 #=> 8 + +# Valoriile boolene sunt şi ele valori primare +True +False + +# Pot fi negate cu operatorul not +not True #=> False +not False #=> True + +# Egalitatea este == +1 == 1 #=> True +2 == 1 #=> False + +# Inegalitate este != +1 != 1 #=> False +2 != 1 #=> True + +# Comparaţii +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Comparaţiile pot fi inlănţuite! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Şirurile de caractere pot fi încadrate cu " sau ' +"Acesta e un şir de caractere." +'Şi acesta este un şir de caractere.' + +# Şirurile de caractere pot fi adăugate! +"Hello " + "world!" #=> "Hello world!" + +# Un şir de caractere poate fi folosit ca o listă +"Acesta e un şir de caractere"[0] #=> 'A' + +# Caracterul % (procent) poate fi folosit pentru a formata şiruri de caractere : +"%s pot fi %s" % ("şirurile", "interpolate") + +# O metodă mai nouă de a formata şiruri este metoda "format" +# Este metoda recomandată +"{0} pot fi {1}".format("şirurile", "formatate") +# Puteţi folosi cuvinte cheie dacă nu doriţi sa număraţi +"{nume} vrea să mănânce {fel}".format(nume="Bob", fel="lasagna") + +# "None", care reprezintă valoarea nedefinită, e un obiect +None #=> None + +# Nu folosiţi operatorul == pentru a compara un obiect cu None +# Folosiţi operatorul "is" +"etc" is None #=> False +None is None #=> True + +# Operatorul "is" testeaza dacă obiectele sunt identice. +# Acastă operaţie nu e foarte folositoare cu tipuri primare, +# dar e foarte folositoare cu obiecte. + +# None, 0, şi şiruri de caractere goale sunt evaluate ca si fals, False. +# Toate celelalte valori sunt adevărate, True. +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Variabile şi colecţii +#################################################### + +# Printarea este uşoară +print "Eu sunt Python. Încântat de cunoştinţă!" + + +# Nu este nevoie sa declari variabilele înainte de a le folosi +o_variabila = 5 # Convenţia este de a folosi caractere_minuscule_cu_underscore +o_variabila #=> 5 + +# Dacă accesăm o variabilă nefolosită declanşăm o excepţie. +# Vezi secţiunea Control de Execuţie pentru mai multe detalii despre excepţii. +alta_variabila # Declanşează o eroare de nume + +# "If" poate fi folosit într-o expresie. +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listele sunt folosite pentru colecţii +li = [] +# O listă poate avea valori de la început +alta_li = [4, 5, 6] + +# Se adaugă valori la sfârşitul lister cu append +li.append(1) #li e acum [1] +li.append(2) #li e acum [1, 2] +li.append(4) #li e acum [1, 2, 4] +li.append(3) #li este acum [1, 2, 4, 3] +# Se şterg de la sfarşit cu pop +li.pop() #=> 3 şi li e acum [1, 2, 4] +# Să o adaugăm înapoi valoarea +li.append(3) # li e din nou [1, 2, 4, 3] + +# Putem accesa valorile individuale dintr-o listă cu operatorul index +li[0] #=> 1 +# Valoarea speciala -1 pentru index accesează ultima valoare +li[-1] #=> 3 + +# Dacă depaşim limitele listei declanşăm o eroare IndexError +li[4] # Declanşează IndexError + +# Putem să ne uităm la intervale folosind sintaxa de "felii" +# În Python, intervalele sunt închise la început si deschise la sfârşit. +li[1:3] #=> [2, 4] +# Fără început +li[2:] #=> [4, 3] +# Fără sfarşit +li[:3] #=> [1, 2, 4] + +# Putem şterge elemente arbitrare din lista cu operatorul "del" care primeşte indexul lor +del li[2] # li e acum [1, 2, 3] + +# Listele pot fi adăugate +li + alta_li #=> [1, 2, 3, 4, 5, 6] - Notă: li si alta_li nu sunt modificate! + +# Concatenăm liste cu "extend()" +li.extend(alta_li) # Acum li este [1, 2, 3, 4, 5, 6] + +# Se verifică existenţa valorilor in lista cu "in" +1 in li #=> True + +# Şi lungimea cu "len()" +len(li) #=> 6 + + +# Tuplele sunt ca şi listele dar imutabile +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Declanşează TypeError + +# Pot fi folosite ca şi liste +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Tuplele pot fi despachetate +a, b, c = (1, 2, 3) # a este acum 1, b este acum 2 şi c este acum 3 +# Tuplele pot fi folosite şi fără paranteze +d, e, f = 4, 5, 6 +# Putem inversa valori foarte uşor! +e, d = d, e # d este acum 5 şi e este acum 4 + + +# Dicţionarele stochează chei şi o valoare pentru fiecare cheie +dict_gol = {} +# Şi un dicţionar cu valori +dict_cu_valori = {"unu": 1, "doi": 2, "trei": 3} + +# Căutaţi valori cu [] +dict_cu_valori["unu"] #=> 1 + +# Obţinem lista cheilor cu "keys()" +dict_cu_valori.keys() #=> ["trei", "doi", "unu"] +# Notă - ordinea cheilor obţinute cu keys() nu este garantată. +# Puteţi obţine rezultate diferite de exemplul de aici. + +# Obţinem valorile cu values() +dict_cu_valori.values() #=> [3, 2, 1] +# Notă - aceeaşi ca mai sus, aplicată asupra valorilor. + +# Verificăm existenţa unei valori cu "in" +"unu" in dict_cu_valori #=> True +1 in dict_cu_valori #=> False + +# Accesarea unei chei care nu exista declanşează o KeyError +dict_cu_valori["four"] # KeyError + +# Putem folosi metoda "get()" pentru a evita KeyError +dict_cu_valori.get("one") #=> 1 +dict_cu_valori.get("four") #=> None +# Metoda get poate primi ca al doilea argument o valoare care va fi returnată +# când cheia nu este prezentă. +dict_cu_valori.get("one", 4) #=> 1 +dict_cu_valori.get("four", 4) #=> 4 + +# "setdefault()" este o metodă pentru a adăuga chei-valori fără a le modifica, dacă cheia există deja +dict_cu_valori.setdefault("five", 5) #dict_cu_valori["five"] este acum 5 +dict_cu_valori.setdefault("five", 6) #dict_cu_valori["five"] exista deja, nu este modificată, tot 5 + + +# Set este colecţia mulţime +set_gol = set() +# Putem crea un set cu valori +un_set = set([1,2,2,3,4]) # un_set este acum set([1, 2, 3, 4]), amintiţi-vă ca mulţimile garantează unicatul! + +# În Python 2.7, {} poate fi folosit pentru un set +set_cu_valori = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Putem adăuga valori cu add +set_cu_valori.add(5) # set_cu_valori este acum {1, 2, 3, 4, 5} + +# Putem intersecta seturi +alt_set = {3, 4, 5, 6} +set_cu_valori & alt_set #=> {3, 4, 5} + +# Putem calcula uniunea cu | +set_cu_valori | alt_set #=> {1, 2, 3, 4, 5, 6} + +# Diferenţa între seturi se face cu - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Verificăm existenţa cu "in" +2 in set_cu_valori #=> True +10 in set_cu_valori #=> False + + +#################################################### +## 3. Controlul Execuţiei +#################################################### + +# O variabilă +o_variabila = 5 + +# Acesta este un "if". Indentarea este importanta în python! +# Printează "o_variabila este mai mică ca 10" +if o_variabila > 10: + print "o_variabila e mai mare ca 10." +elif o_variabila < 10: # Clauza elif e opţională. + print "o_variabila este mai mică ca 10." +else: # Şi else e opţional. + print "o_variabila este exact 10." + + +""" +Buclele "for" pot fi folosite pentru a parcurge liste +Vom afişa: + câinele este un mamifer + pisica este un mamifer + şoarecele este un mamifer +""" +for animal in ["câinele", "pisica", "şoarecele"]: + # Folosim % pentru a compune mesajul + print "%s este un mamifer" % animal + +""" +"range(număr)" crează o lista de numere +de la zero la numărul dat +afişează: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While repetă pana când condiţia dată nu mai este adevărată. +afişează: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Prescurtare pentru x = x + 1 + +# Recepţionăm excepţii cu blocuri try/except + +# Acest cod e valid in Python > 2.6: +try: + # Folosim "raise" pentru a declanşa o eroare + raise IndexError("Asta este o IndexError") +except IndexError as e: + pass # Pass nu face nimic. În mod normal aici ne-am ocupa de eroare. + + +#################################################### +## 4. Funcţii +#################################################### + +# Folosim "def" pentru a defini funcţii +def add(x, y): + print "x este %s şi y este %s" % (x, y) + return x + y # Funcţia poate returna valori cu "return" + +# Apelăm funcţia "add" cu parametrii +add(5, 6) #=> Va afişa "x este 5 şi y este 6" şi va returna 11 + +# Altă cale de a apela funcţii: cu parametrii numiţi +add(y=6, x=5) # Ordinea parametrilor numiţi nu contează + +# Putem defini funcţii care primesc un număr variabil de parametrii nenumiţi +# Aceşti parametrii nenumiţi se cheamă si poziţinali +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Şi putem defini funcţii care primesc un număr variabil de parametrii numiţi +def keyword_args(**kwargs): + return kwargs + +# Hai să vedem cum merge +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Se pot combina +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) va afişa: + (1, 2) + {"a": 3, "b": 4} +""" + +# Când apelăm funcţii, putem face inversul args/kwargs! +# Folosim * pentru a expanda tuple şi ** pentru a expanda kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # echivalent cu foo(1, 2, 3, 4) +all_the_args(**kwargs) # echivalent cu foo(a=3, b=4) +all_the_args(*args, **kwargs) # echivalent cu foo(1, 2, 3, 4, a=3, b=4) + +# În Python, funcţiile sunt obiecte primare +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Funcţiile pot fi anonime +(lambda x: x > 2)(3) #=> True + +# Există funcţii de ordin superior (care operează pe alte funcţii) predefinite +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Putem folosi scurtături de liste pentru a simplifica munca cu map si filter +[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. Clase +#################################################### + +# Moştenim object pentru a crea o nouă clasă +class Om(object): + + # Acesta este un atribut al clasei. Va fi moştenit de toate instanţele. + species = "H. sapiens" + + # Constructor (mai degrabă, configurator de bază) + def __init__(self, nume): + # Valoarea parametrului este stocată in atributul instanţei + self.nume = nume + + # Aceasta este o metoda a instanţei. + # Toate metodele primesc "self" ca si primul argument. + def spune(self, mesaj): + return "%s: %s" % (self.nume, mesaj) + + # O metodă a clasei. Este partajată de toate instanţele. + # Va primi ca si primul argument clasa căreia îi aparţine. + @classmethod + def get_species(cls): + return cls.species + + # O metoda statica nu primeste un argument automat. + @staticmethod + def exclama(): + return "*Aaaaaah*" + + +# Instanţiem o clasă +i = Om(nume="Ion") +print i.spune("salut") # afişează: "Ion: salut" + +j = Om("George") +print j.spune("ciau") # afişează George: ciau" + +# Apelăm metoda clasei +i.get_species() #=> "H. sapiens" + +# Modificăm atributul partajat +Om.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Apelăm metoda statică +Om.exclama() #=> "*Aaaaaah*" + + +#################################################### +## 6. Module +#################################################### + +# Pentru a folosi un modul, trebuie importat +import math +print math.sqrt(16) #=> 4 + +# Putem importa doar anumite funcţii dintr-un modul +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Putem importa toate funcţiile dintr-un modul, dar nu este o idee bună +# Nu faceţi asta! +from math import * + +# Numele modulelor pot fi modificate la import, de exemplu pentru a le scurta +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Modulele python sunt pur şi simplu fişiere cu cod python. +# Puteţi sa creaţi modulele voastre, şi sa le importaţi. +# Numele modulului este acelasi cu numele fişierului. + +# Cu "dir" inspectăm ce funcţii conţine un modul +import math +dir(math) + + +``` + +## Doriţi mai mult? + +### Gratis online, in limba engleză + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Cărţi + +* [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 147cc58761c8199a56605b71db741422330f940f Mon Sep 17 00:00:00 2001 From: Dave Caunt Date: Wed, 4 Sep 2013 12:56:58 +0100 Subject: Fixed typo in Parameter --- objective-c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index e8c979d8..98204a9a 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -241,7 +241,7 @@ int main (int argc, const char * argv[]) + (NSString *)classMethod; // - for instance method -- (NSString *)instanceMethodWithParmeter:(NSString *)string; +- (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; @end @@ -271,7 +271,7 @@ int main (int argc, const char * argv[]) return [[self alloc] init]; } -- (NSString *)instanceMethodWithParmeter:(NSString *)string +- (NSString *)instanceMethodWithParameter:(NSString *)string { return @"New string"; } -- cgit v1.2.3 From 8df74f0aceacd983a10c224d6cdf4c6f6c19743a Mon Sep 17 00:00:00 2001 From: Ovidiu Ciule Date: Wed, 4 Sep 2013 13:57:36 +0200 Subject: Corrections. --- ro-ro/python-ro.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ro-ro/python-ro.html.markdown b/ro-ro/python-ro.html.markdown index 677f4356..0654fc8f 100644 --- a/ro-ro/python-ro.html.markdown +++ b/ro-ro/python-ro.html.markdown @@ -12,7 +12,6 @@ cele mai populare limbaje de programare. M-am indrăgostit de Python pentru clar Python este aproape pseudocod executabil. Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) sau ociule [at] [google's email service] -Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. O versiune Python 3 va apărea în curând, în limba engleză mai întâi. @@ -474,7 +473,7 @@ dir(math) ## Doriţi mai mult? -### Gratis online, in limba engleză +### Gratis online, în limba engleză * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) @@ -482,7 +481,7 @@ dir(math) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) -### Cărţi +### Cărţi, în limba engleză * [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 1e6aff4a7b43b8f528951b0c9cb753ae62c9c649 Mon Sep 17 00:00:00 2001 From: Dave Caunt Date: Wed, 4 Sep 2013 12:58:06 +0100 Subject: Fixed inconsistencies in class implementation and protocol naming --- objective-c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 98204a9a..926a4a0d 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -223,7 +223,7 @@ int main (int argc, const char * argv[]) // } // -/+ (type) Method declarations; // @end -@interface MyClass : NSObject +@interface MyClass : NSObject { int count; id data; @@ -248,7 +248,7 @@ int main (int argc, const char * argv[]) // Implement the methods in an implementation (MyClass.m) file: -@implementation UserObject +@implementation MyClass // Call when the object is releasing - (void)dealloc -- cgit v1.2.3 From 078f6bbc9d3677c497a54c9286dc692a0cf815a7 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Wed, 4 Sep 2013 13:39:02 +0100 Subject: =?UTF-8?q?Corrected=20comment:=20utf-8=20=E2=86=92=20unicode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Runes hold the raw unicode code point, not utf-8. Storing utf-8 inside of a uint32 would be highly inefficient. Runes are essentially utf-32. --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 4db76a49..d7622ded 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -71,7 +71,7 @@ func learnTypes() { can include line breaks.` // same string type // non-ASCII literal. Go source is UTF-8. - g := 'Σ' // rune type, an alias for uint32, holds a UTF-8 code point + g := 'Σ' // rune type, an alias for uint32, holds a unicode code point f := 3.14195 // float64, an IEEE-754 64-bit floating point number c := 3 + 4i // complex128, represented internally with two float64s -- cgit v1.2.3 From f6c800dd2aac61c69563a6d51b786928a1d6b329 Mon Sep 17 00:00:00 2001 From: Nathan Hoad Date: Thu, 5 Sep 2013 01:29:59 +1000 Subject: Fixed typo in c.html.markdown --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 3acf1a4d..3ec4aeef 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -294,7 +294,7 @@ int main() { printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); // => Prints "8, 4" on a typical 64-bit system - // To retreive the value at the address a pointer is pointing to, + // To retrievve the value at the address a pointer is pointing to, // put * in front to de-reference it. // Note: yes, it may be confusing that '*' is used for _both_ declaring a // pointer and dereferencing it. -- cgit v1.2.3 From 995013c92119395564d303a2b6b5e67fcb66a5fc Mon Sep 17 00:00:00 2001 From: Madison Dickson Date: Wed, 4 Sep 2013 11:30:44 -0400 Subject: Including for each loop example --- java.html.markdown | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index cdcf620c..a2fc3630 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -210,7 +210,19 @@ public class LearnJava { //Iterated 10 times, fooFor 0->9 } System.out.println("fooFor Value: " + fooFor); - + + // For Each Loop + // An automatic iteration through an array or list of objects. + int[] fooList = {1,2,3,4,5,6,7,8,9}; + //for each loop structure => for( : ) + //reads as: for each object in the array + //note: the object type must match the array. + + for( int bar : fooList ){ + //System.out.println(bar); + //Iterates 9 times and prints 1-9 on new lines + } + // Switch Case // A switch works with the byte, short, char, and int data types. // It also works with enumerated types (discussed in Enum Types), -- cgit v1.2.3 From ee8bed8c98df81e63b430ab5e61096f8140f09b5 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 4 Sep 2013 09:36:51 -0700 Subject: Fixed up potential conflicts --- ko-kr/clojure-kr.html.markdown | 2 +- ko-kr/python-kr.html.markdown | 4 ++-- ro-ro/python-ro.html.markdown | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ko-kr/clojure-kr.html.markdown b/ko-kr/clojure-kr.html.markdown index 0b9d13b2..1d9e53cd 100644 --- a/ko-kr/clojure-kr.html.markdown +++ b/ko-kr/clojure-kr.html.markdown @@ -1,6 +1,6 @@ --- language: clojure -filename: learnclojure.clj +filename: learnclojure-kr.clj contributors: - ["Adam Bard", "http://adambard.com/"] translators: diff --git a/ko-kr/python-kr.html.markdown b/ko-kr/python-kr.html.markdown index a131e9a2..ed377a99 100644 --- a/ko-kr/python-kr.html.markdown +++ b/ko-kr/python-kr.html.markdown @@ -3,7 +3,7 @@ language: python category: language contributors: - ["Louie Dinh", "http://ldinh.ca"] -filename: learnpython.py +filename: learnpython-ko.py translators: - ["wikibook", "http://wikibook.co.kr"] lang: ko-kr @@ -481,4 +481,4 @@ dir(math) * [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) \ No newline at end of file +* [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) diff --git a/ro-ro/python-ro.html.markdown b/ro-ro/python-ro.html.markdown index 0654fc8f..36ea78ec 100644 --- a/ro-ro/python-ro.html.markdown +++ b/ro-ro/python-ro.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - ["Ovidiu Ciule", "https://github.com/ociule"] lang: ro-ro filename: python-ro.html.markdown -filename: learnpython.py +filename: learnpython-ro.py --- Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a devenit astăzi unul din -- cgit v1.2.3 From 358f357a46f2a6c72014a9d7e5e5d6d46c4924df Mon Sep 17 00:00:00 2001 From: Tom Hebbron Date: Wed, 4 Sep 2013 19:56:17 +0100 Subject: Update r.html.markdown Fixed a problem with the jiggle function - variable x wasn't being updated before being returned, and the rnorm function was being asked to return x output values, rather than one. After testing, the values given the documentation are now correct. --- r.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/r.html.markdown b/r.html.markdown index 03aa1dd2..9c17e8ca 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -298,7 +298,7 @@ if (4 > 3) { # Defined like so: jiggle <- function(x) { - x+ rnorm(x, sd=.1) #add in a bit of (controlled) noise + x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise return(x) } -- cgit v1.2.3 From 65d2460cd760812c0a0e7a08771d859f13eac3af Mon Sep 17 00:00:00 2001 From: Nathan Hoad Date: Thu, 5 Sep 2013 07:13:28 +1000 Subject: Fixed typo in c.html.markdown that I introduced --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 3ec4aeef..12f862bc 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -294,7 +294,7 @@ int main() { printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); // => Prints "8, 4" on a typical 64-bit system - // To retrievve the value at the address a pointer is pointing to, + // To retrieve the value at the address a pointer is pointing to, // put * in front to de-reference it. // Note: yes, it may be confusing that '*' is used for _both_ declaring a // pointer and dereferencing it. -- cgit v1.2.3 From 61dcca33407b75cb44ccc042ff213c1be0c2a5c8 Mon Sep 17 00:00:00 2001 From: Adrian Espinosa Date: Wed, 4 Sep 2013 23:32:18 +0200 Subject: Fix long line --- c.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 3acf1a4d..bc7bd37c 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -81,7 +81,8 @@ int main() { // is not evaluated (except VLAs (see below)). // The value it yields in this case is a compile-time constant. int a = 1; - // size_t is an unsiged integer type of at least 2 bytes used to represent the size of an object. + // size_t is an unsiged integer type of at least 2 bytes used to represent + // the size of an object. size_t size = sizeof(a++); // a++ is not evaluated printf("sizeof(a++) = %zu where a = %d\n", size, a); // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) -- cgit v1.2.3 From febe5f499465edfed92aeea5e9349a660b8d5f7d Mon Sep 17 00:00:00 2001 From: Matthew Wyatt Date: Wed, 4 Sep 2013 20:46:45 -0700 Subject: Added links to source and package documentation. Also reformatted line lengths to accommdate links. --- go.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 3a3800dd..eec03845 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -294,8 +294,9 @@ There you can follow the tutorial, play interactively, and read lots. The language definition itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) -On the reading list for students of Go is the source code to the standard -library. Comprehensively documented, it demonstrates the best of readable -and understandable Go, Go style, and Go idioms. Click on a function name -in the documentation and the source code comes up! +On the reading list for students of Go is the [source code to the standard +library](http://golang.org/src/pkg/). Comprehensively documented, it +demonstrates the best of readable and understandable Go, Go style, and Go +idioms. Or you can click on a function name in [the +documentation](http://golang.org/pkg/) and the source code comes up! -- cgit v1.2.3 From 3fb4aa64a11999160842ff9a48c57d885e30ae83 Mon Sep 17 00:00:00 2001 From: Yadong Wen Date: Thu, 5 Sep 2013 22:23:34 +1200 Subject: add Chinese translation of perl.html.markdown --- zh-cn/perl-cn.html.markdown | 151 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 zh-cn/perl-cn.html.markdown diff --git a/zh-cn/perl-cn.html.markdown b/zh-cn/perl-cn.html.markdown new file mode 100644 index 00000000..8f99ccbf --- /dev/null +++ b/zh-cn/perl-cn.html.markdown @@ -0,0 +1,151 @@ +--- +name: perl +category: language +language: perl +filename: learnperl.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] +translators: + - ["Yadong Wen", "https://github.com/yadongwen"] +--- + +Perl 5是一个功能强大、特性齐全的编程语言,有25年的历史。 + +Perl 5可以在包括便携式设备和大型机的超过100个平台上运行,既适用于快速原型构建,也适用于大型项目开发。 + +```perl +# 单行注释以#号开头 + + +#### Perl的变量类型 + +# 变量以$号开头。 +# 合法变量名以英文字母或者下划线起始, +# 后接任意数目的字母、数字或下划线。 + +### Perl有三种主要的变量类型:标量、数组和哈希。 + +## 标量 +# 标量类型代表单个值: +my $animal = "camel"; +my $answer = 42; + +# 标量类型值可以是字符串、整型或浮点类型,Perl会根据需要自动进行类型转换。 + +## 数组 +# 数组类型代表一列值: +my @animals = ("camel", "llama", "owl"); +my @numbers = (23, 42, 69); +my @mixed = ("camel", 42, 1.23); + + + +## 哈希 +# 哈希类型代表一个键/值对的集合: + +my %fruit_color = ("apple", "red", "banana", "yellow"); + +# 可以使用空格和“=>”操作符更清晰的定义哈希: + +my %fruit_color = ( + apple => "red", + banana => "yellow", + ); +# perldata中有标量、数组和哈希更详细的介绍。 (perldoc perldata). + +# 可以用引用构建更复杂的数据类型,比如嵌套的列表和哈希。 + +#### 逻辑和循环结构 + +# Perl有大多数常见的逻辑和循环控制结构 + +if ( $var ) { + ... +} elsif ( $var eq 'bar' ) { + ... +} else { + ... +} + +unless ( condition ) { + ... + } +# 上面这个比"if (!condition)"更可读。 + +# 有Perl特色的后置逻辑结构 +print "Yow!" if $zippy; +print "We have no bananas" unless $bananas; + +# while + while ( condition ) { + ... + } + + +# for和foreach +for ($i = 0; $i <= $max; $i++) { + ... + } + +foreach (@array) { + print "This element is $_\n"; + } + + +#### 正则表达式 + +# Perl对正则表达式有深入广泛的支持,perlrequick和perlretut等文档有详细介绍。简单来说: + +# 简单匹配 +if (/foo/) { ... } # 如果 $_ 包含"foo"逻辑为真 +if ($a =~ /foo/) { ... } # 如果 $a 包含"foo"逻辑为真 + +# 简单替换 + +$a =~ s/foo/bar/; # 将$a中的foo替换为bar +$a =~ s/foo/bar/g; # 将$a中所有的foo替换为bar + + +#### 文件和输入输出 + +# 可以使用“open()”函数打开文件用于输入输出。 + +open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; +open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; +open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; + +# 可以用"<>"操作符读取一个打开的文件句柄。 在标量语境下会读取一行, +# 在列表环境下会将整个文件读入并将每一行赋给列表的一个元素: + +my $line = <$in>; +my @lines = <$in>; + +#### 子程序 + +# 写子程序很简单: + +sub logger { + my $logmessage = shift; + open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; + print $logfile $logmessage; +} + +# 现在可以像内置函数一样调用子程序: + +logger("We have a logger subroutine!"); + + +``` + +#### 使用Perl模块 + +Perl模块提供一系列特性来帮助你避免重新发明轮子,CPAN是下载模块的好地方( http://www.cpan.org/ )。Perl发行版本身也包含很多流行的模块。 + +perlfaq有很多常见问题和相应回答,也经常有对优秀CPAN模块的推荐介绍。 + +#### 深入阅读 + + - [perl-tutorial](http://perl-tutorial.org/) + - [www.perl.com的learn站点](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - 以及 perl 内置的: `perldoc perlintro` -- cgit v1.2.3 From 0fe8117a407d30a0995f7248ec8010fa9acc270f Mon Sep 17 00:00:00 2001 From: ggb Date: Thu, 5 Sep 2013 18:42:52 +0200 Subject: elixir: german translation --- de-de/elixir-de.html.markdown | 417 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 417 insertions(+) create mode 100644 de-de/elixir-de.html.markdown diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown new file mode 100644 index 00000000..5f89e1f5 --- /dev/null +++ b/de-de/elixir-de.html.markdown @@ -0,0 +1,417 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Gregor Große-Bölting", "http://www.ideen-und-soehne.de"] +filename: learnelixir-de.ex +--- + +Elixir ist eine moderne, funktionale Sprache für die Erlang VM. Sie ist voll +kompatibel mit Erlang, verfügt aber über eine freundlichere Syntax und bringt +viele Features mit. + +```ruby + +# Einzeilige Kommentare werden mit der Raute gesetzt. + +# Es gibt keine mehrzeiligen Kommentare; +# es ist aber problemlos möglich mehrere einzeilige Kommentare hintereinander +# zu setzen (so wie hier). + +# Mit 'iex' ruft man die Elixir-Shell auf. +# Zum kompilieren von Modulen dient der Befehl 'elixirc'. + +# Beide Befehle sollten als Umgebungsvariable gesetzt sein, wenn Elixir korrekt +# installiert wurde. + +## --------------------------- +## -- Basistypen +## --------------------------- + +# Es gibt Nummern: +3 # Integer +0x1F # Integer +3.0 # Float + +# Atome, das sind Literale, sind Konstanten mit Namen. Sie starten mit einem +# ':'. +:hello # Atom + +# Außerdem gibt es Tupel, deren Werte im Arbeitsspeicher vorgehalten werden. +{1,2,3} # Tupel + +# Die Werte innerhalb eines Tupels können mit der 'elem'-Funktion ausgelesen +# werden: +elem({1, 2, 3}, 0) # => 1 + +# Listen sind als verkettete Listen implementiert. +[1, 2, 3] # list + +# Auf Kopf und Rest einer Liste kann wie folgt zugegriffen werden: +[ kopf | rest ] = [1,2,3] +kopf # => 1 +rest # => [2, 3] + +# In Elixir, wie auch in Erlang, kennzeichnet '=' ein 'pattern matching' +# (Musterabgleich) und keine Zuweisung. +# Das heißt, dass die linke Seite auf die rechte Seite 'abgeglichen' wird. +# Auf diese Weise kann im Beispiel oben auf Kopf und Rest der Liste zugegriffen +# werden. + +# Ein Musterabgleich wird einen Fehler werfen, wenn die beiden Seiten nicht +# zusammenpassen. +# Im folgenden Beispiel haben die Tupel eine unterschiedliche Anzahl an +# Elementen: +{a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Es gibt außerdem 'binaries', +<<1,2,3>> # binary. + +# Strings und 'char lists' +"hello" # String +'hello' # Char-Liste + +# ... und mehrzeilige Strings +""" +Ich bin ein +mehrzeiliger String. +""" +#=> "Ich bin ein\nmehrzeiliger String.\n" + +# Alles Strings werden in UTF-8 enkodiert: +"héllò" #=> "héllò" + +# Eigentlich sind Strings in Wahrheit nur binaries und 'char lists' einfach +# Listen. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# In Elixir gibt `?a` den ASCII-Integer für den Buchstaben zurück. +?a #=> 97 + +# Um Listen zu verbinden gibt es den Operator '++', für binaries nutzt man '<>' +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'hello ' ++ 'world' #=> 'hello world' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"hello " <> "world" #=> "hello world" + +## --------------------------- +## -- Operatoren +## --------------------------- + +# Einfache Arithmetik +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# In Elixir gibt der Operator '/' immer einen Float-Wert zurück. + +# Für Division mit ganzzahligen Ergebnis gibt es 'div' +div(10, 2) #=> 5 + +# Um den Rest der ganzzahligen Division zu erhalten gibt es 'rem' +rem(10, 3) #=> 1 + +# Natürlich gibt es auch Operatoren für Booleans: 'or', 'and' und 'not'. Diese +# Operatoren erwarten einen Boolean als erstes Argument. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir bietet auch '||', '&&' und '!', die Argumente jedweden Typs +# akzeptieren. Alle Werte außer 'false' und 'nil' werden zu wahr evaluiert. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil + +!true #=> false + +# Für Vergleiche gibt es die Operatoren `==`, `!=`, `===`, `!==`, `<=`, `>=`, +# `<` und `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# '===' und '!==' sind strikter beim Vergleich von Integern und Floats: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Es ist außerdem möglich zwei verschiedene Datentypen zu vergleichen: +1 < :hello #=> true + +# Die gesamte Ordnung über die Datentypen ist wie folgt definiert: +# number < atom < reference < functions < port < pid < tuple < list < bitstring + +# Um Joe Armstrong zu zitieren: "The actual order is not important, but that a +# total ordering is well defined is important." + +## --------------------------- +## -- Kontrollstrukturen +## --------------------------- + +# Es gibt die `if`-Verzweigung +if false do + "Dies wird nie jemand sehen..." +else + "...aber dies!" +end + +# ...und ebenso `unless` +unless true do + "Dies wird nie jemand sehen..." +else + "...aber dies!" +end + +# Du erinnerst dich an 'pattern matching'? Viele Kontrollstrukturen in Elixir +# arbeiten damit. + +# 'case' erlaubt es uns Werte mit vielerlei Mustern zu vergleichen. +case {:one, :two} do + {:four, :five} -> + "Das wird nicht passen" + {:one, x} -> + "Das schon und außerdem wird es ':two' dem Wert 'x' zuweisen." + _ -> + "Dieser Fall greift immer." +end + +# Es ist eine übliche Praxis '_' einen Wert zuzuweisen, sofern dieser Wert +# nicht weiter verwendet wird. +# Wenn wir uns zum Beispiel nur für den Kopf einer Liste interessieren: +[kopf | _] = [1,2,3] +kopf #=> 1 + +# Für bessere Lesbarkeit können wir auch das Folgende machen: +[kopf | _rest] = [:a, :b, :c] +kopf #=> :a + +# Mit 'cond' können diverse Bedingungen zur selben Zeit überprüft werden. Man +# benutzt 'cond' statt viele if-Verzweigungen zu verschachteln. +cond do + 1 + 1 == 3 -> + "Ich werde nie aufgerufen." + 2 * 5 == 12 -> + "Ich auch nicht." + 1 + 2 == 3 -> + "Aber ich!" +end + +# Es ist üblich eine letzte Bedingung einzufügen, die immer zu wahr evaluiert. +cond do + 1 + 1 == 3 -> + "Ich werde nie aufgerufen." + 2 * 5 == 12 -> + "Ich auch nicht." + true -> + "Aber ich! (dies ist im Grunde ein 'else')" +end + +# 'try/catch' wird verwendet um Werte zu fangen, die zuvor 'geworfen' wurden. +# Das Konstrukt unterstützt außerdem eine 'after'-Klausel die aufgerufen wird, +# egal ob zuvor ein Wert gefangen wurde. +try do + throw(:hello) +catch + nachricht -> "#{nachricht} gefangen." +after + IO.puts("Ich bin die 'after'-Klausel.") +end +#=> Ich bin die 'after'-Klausel. +# ":hello gefangen" + +## --------------------------- +## -- Module und Funktionen +## --------------------------- + +# Anonyme Funktionen (man beachte den Punkt) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# Anonyme Funktionen unterstützen auch 'pattern' und 'guards'. Guards erlauben +# es die Mustererkennung zu justieren und werden mit dem Schlüsselwort 'when' +# eingeführt: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir bietet zahlreiche eingebaute Funktionen. Diese sind im gleichen +# Geltungsbereich ('scope') verfügbar. +is_number(10) #=> true +is_list("hello") #=> false +elem({1,2,3}, 0) #=> 1 + +# Mehrere Funktionen können in einem Modul gruppiert werden. Innerhalb eines +# Moduls ist es möglich mit dem Schlüsselwort 'def' eine Funktion zu +# definieren. +defmodule Math do + def sum(a, b) do + a + b + end + + def square(x) do + x * x + end +end + +Math.sum(1, 2) #=> 3 +Math.square(3) #=> 9 + +# Um unser einfaches Mathe-Modul zu kompilieren muss es unter 'math.ex' +# gesichert werden. Anschließend kann es mit 'elixirc' im Terminal aufgerufen +# werden: elixirc math.ex + +# Innerhalb eines Moduls definieren wir private Funktionen mit 'defp'. Eine +# Funktion, die mit 'def' erstellt wurde, kann von anderen Modulen aufgerufen +# werden; eine private Funktion kann nur lokal angesprochen werden. +defmodule PrivateMath do + def sum(a, b) do + do_sum(a, b) + end + + defp do_sum(a, b) do + a + b + end +end + +PrivateMath.sum(1, 2) #=> 3 +# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) + +# Auch Funktionsdeklarationen unterstützen 'guards' und Mustererkennung: +defmodule Geometry do + def area({:rectangle, w, h}) do + w * h + end + + def area({:circle, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometry.area({:rectangle, 2, 3}) #=> 6 +Geometry.area({:circle, 3}) #=> 28.25999999999999801048 +# Geometry.area({:circle, "not_a_number"}) +#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 + +# Wegen der Unveränderlichkeit von Variablen ist Rekursion ein wichtiger +# Bestandteil von Elixir. +defmodule Recursion do + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end + + def sum_list([], acc) do + acc + end +end + +Recursion.sum_list([1,2,3], 0) #=> 6 + +# Elixir-Module unterstützen Attribute. Es gibt eingebaute Attribute, ebenso +# ist es möglich eigene Attribute hinzuzufügen. +defmodule MyMod do + @moduledoc """ + Dies ist ein eingebautes Attribut in einem Beispiel-Modul + """ + + @my_data 100 # Dies ist ein selbst-definiertes Attribut. + IO.inspect(@my_data) #=> 100 +end + +## --------------------------- +## -- 'Records' und Ausnahmebehandlung +## --------------------------- + +# 'Records' sind im Grunde Strukturen, die es erlauben einem Wert einen eigenen +# Namen zuzuweisen. +defrecord Person, name: nil, age: 0, height: 0 + +joe_info = Person.new(name: "Joe", age: 30, height: 180) +#=> Person[name: "Joe", age: 30, height: 180] + +# Zugriff auf den Wert von 'name' +joe_info.name #=> "Joe" + +# Den Wert von 'age' überschreiben +joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] + +# Der 'try'-Block wird zusammen mit dem 'rescue'-Schlüsselwort dazu verwendet, +# um Ausnahmen beziehungsweise Fehler zu behandeln. +try do + raise "Irgendein Fehler." +rescue + RuntimeError -> "Laufzeit-Fehler gefangen." + _error -> "Und dies fängt jeden Fehler." +end + +# Alle Ausnahmen haben das Attribut 'message' +try do + raise "ein Fehler" +rescue + x in [RuntimeError] -> + x.message +end + +## --------------------------- +## -- Nebenläufigkeit +## --------------------------- + +# Elixir beruht auf dem Aktoren-Model zur Behandlung der Nebenläufigkeit. Alles +# was man braucht um in Elixir nebenläufige Programme zu schreiben sind drei +# Primitive: Prozesse erzeugen, Nachrichten senden und Nachrichten empfangen. + +# Um einen neuen Prozess zu erzeugen nutzen wir die 'spawn'-Funktion, die +# wiederum eine Funktion als Argument entgegen nimmt. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# 'spawn' gibt eine pid (einen Identifikator des Prozesses) zurück. Diese kann +# nun verwendet werden, um Nachrichten an den Prozess zu senden. Um +# zu senden nutzen wir den '<-' Operator. Damit das alles Sinn macht müssen wir +# in der Lage sein Nachrichten zu empfangen. Dies wird mit dem +# 'receive'-Mechanismus sichergestellt: +defmodule Geometry do + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Area = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Area = #{3.14 * r * r}") + area_loop() + end + end +end + +# Kompiliere das Modul, starte einen Prozess und gib die 'area_loop' Funktion +# in der Shell mit, etwa so: +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> + +# Sende eine Nachricht an die 'pid', die ein Muster im 'receive'-Ausdruck +# erfüllt: +pid <- {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +pid <- {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} + +# Die Shell selbst ist ein Prozess und mit dem Schlüsselwort 'self' kann man +# die aktuelle pid herausfinden. +self() #=> #PID<0.27.0> + +``` + +## Referenzen und weitere Lektüre + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) auf der [elixir Website](http://elixir-lang.org) +* [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) von Fred Hebert +* "Programming Erlang: Software for a Concurrent World" von Joe Armstrong \ No newline at end of file -- cgit v1.2.3 From b04a5786b5b84b615065e1b9dfcfa9a8171d565d Mon Sep 17 00:00:00 2001 From: Nuno Antunes Date: Thu, 5 Sep 2013 17:49:41 +0100 Subject: Add Portuguese translation of go.html.markdown --- pt-br/go-pt.html.markdown | 308 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 308 insertions(+) create mode 100644 pt-br/go-pt.html.markdown diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown new file mode 100644 index 00000000..41a02c37 --- /dev/null +++ b/pt-br/go-pt.html.markdown @@ -0,0 +1,308 @@ +--- +name: Go +category: language +language: Go +filename: learngo-pt.go +lang: pt-pt +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] +translators: + - ["Nuno Antunes", "https://github.com/ntns"] +--- + +A linguagem Go foi criada a partir da necessidade de ver trabalho feito. Não +é a última moda em ciências da computação, mas é a mais recente e mais rápida +forma de resolver os problemas do mundo real. + +Tem conceitos familiares de linguagens imperativas com tipagem estática. É +rápida a compilar e rápida a executar, acrescentando mecanismos de concorrência +fáceis de entender para tirar partido dos CPUs multi-core de hoje em dia, e tem +recursos para ajudar com a programação em larga escala. + +Go vem com uma biblioteca padrão exaustiva e uma comunidade entusiasta. + +```go +// Comentário de uma linha +/* Comentário de + várias linhas */ + +// A cláusula package aparece no início de cada arquivo. +// Main é um nome especial declarando um executável ao invés de uma biblioteca. +package main + +// A cláusula Import declara os pacotes referenciados neste arquivo. +import ( + "fmt" // Um pacote da biblioteca padrão da linguagem Go + "net/http" // Sim, um servidor web! + "strconv" // Conversão de Strings +) + +// Definição de uma função. Main é especial. É o ponto de entrada para o +// programa executável. Goste-se ou não, a linguagem Go usa chavetas. +func main() { + // A função Println envia uma linha para stdout. + // É necessário qualifica-la com o nome do pacote, fmt. + fmt.Println("Olá Mundo!") + + // Chama outra função dentro deste pacote. + beyondHello() +} + +// As funções declaram os seus parâmetros dentro de parênteses. Se a função +// não receber quaisquer parâmetros, é obrigatório usar parênteses vazios. +func beyondHello() { + var x int // Declaração de variável. Tem de ser declarada antes de usar. + x = 3 // Atribuição de variável. + // Declarações "curtas" usam := para inferir o tipo, declarar e atribuir. + y := 4 + sum, prod := learnMultiple(x, y) // a função retorna dois valores + fmt.Println("soma:", sum, "produto:", prod) + learnTypes() // continuar a aprender! +} + +// As funções podem receber parâmetros e retornar (vários!) valores. +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // retorna dois valores +} + +// Alguns tipos e literais básicos. +func learnTypes() { + // Declarações "curtas" geralmente servem para o que pretendemos. + s := "Aprender Go!" // tipo string + + s2 := `Uma string em "bruto" +pode incluir quebras de linha.` // mesmo tipo string + + // literal não-ASCII. A linguagem Go utiliza de raiz a codificação UTF-8. + g := 'Σ' // tipo rune, um alias para uint32, que contém um código unicode + + f := 3.14195 // float64, número de vírgula flutuante de 64bit (IEEE-754) + c := 3 + 4i // complex128, representado internamente com dois float64s + + // Declaração de variáveis, com inicialização. + var u uint = 7 // inteiro sem sinal, tamanho depende da implementação do Go + var pi float32 = 22. / 7 + + // Sintaxe de conversão de tipo, com declaração "curta". + n := byte('\n') // byte é um alias para uint8 + + // Os arrays têm tamanho fixo e definido antes da compilação. + var a4 [4]int // um array de 4 ints, inicializado com ZEROS + a3 := [...]int{3, 1, 5} // um array de 3 ints, inicializado como mostrado + + // As slices têm tamanho dinâmico. Os arrays e as slices têm cada um as + // suas vantagens mas o uso de slices é muito mais comum. + s3 := []int{4, 5, 9} // compare com a3. sem reticências aqui + s4 := make([]int, 4) // aloca uma slice de 4 ints, inicializada com ZEROS + var d2 [][]float64 // declaração apenas, nada é alocado + bs := []byte("uma slice") // sintaxe de conversão de tipos + + p, q := learnMemory() // learnMemory retorna dois apontadores para int. + fmt.Println(*p, *q) // * segue um apontador. isto imprime dois ints. + + // Os maps são um tipo de matriz associativa, semelhante aos tipos hash + // ou dictionary que encontramos noutras linguagens. + m := map[string]int{"três": 3, "quatro": 4} + m["um"] = 1 + + // As variáveis não usadas são um erro em Go. + // O traço inferior permite "usar" uma variável, mas descarta o seu valor. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Enviar para o stdout conta como utilização de uma variável. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() +} + +// A linguagem Go é totalmente garbage collected. Tem apontadores mas não +// permite que os apontadores sejam manipulados com aritmética. Pode-se cometer +// um erro com um apontador nulo, mas não por incrementar um apontador. +func learnMemory() (p, q *int) { + // A função retorna os valores p e q, que são do tipo apontador para int. + p = new(int) // a função new aloca memória, neste caso para um int. + // O int alocado é inicializado com o valor 0, p deixa de ser nil. + s := make([]int, 20) // alocar 20 ints como um único bloco de memória + s[3] = 7 // atribui o valor 7 a um deles + r := -2 // declarar outra variável local + return &s[3], &r // & obtém o endereço de uma variável. +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // As instruções if exigem o uso de chavetas, e não requerem parênteses. + if true { + fmt.Println("eu avisei-te") + } + // A formatação do código-fonte é "estandardizada" através do comando + // da linha de comandos "go fmt." + if false { + // reclamar + } else { + // exultar + } + // Preferir o uso de switch em vez de ifs em cadeia. + x := 1 + switch x { + case 0: + case 1: + // os cases não fazem "fall through" + case 2: + // esta linha só é executada se e só se x=2 + } + // Tal como a instrução if, a instrução for não usa parênteses. + for x := 0; x < 3; x++ { // x++ é uma instrução, nunca uma expressão + fmt.Println("iteração", x) + } + // note que, x == 1 aqui. + + // A instrução for é a única para ciclos, mas assume várias formas. + for { // ciclo infinito + break // brincadeirinha + continue // nunca executado + } + // O uso de := numa instrução if permite criar uma variável local, + // que existirá apenas dentro do bloco if. + if y := expensiveComputation(); y > x { + x = y + } + // As funções podem ser closures. + xBig := func() bool { + return x > 100 // referencia x, declarado acima da instrução switch. + } + fmt.Println("xBig:", xBig()) // true (1e6 é o último valor de x) + x /= 1e5 // agora temos x == 10 + fmt.Println("xBig:", xBig()) // false + + // Quando for mesmo necessário, pode usar o velho goto. + goto love +love: + + learnInterfaces() // Mais coisas interessantes chegando! +} + +// Define Stringer como uma interface consistindo de um método, String. +type Stringer interface { + String() string +} + +// Define pair como uma struct com dois campos ints chamados x e y. +type pair struct { + x, y int +} + +// Define um método para o tipo pair. O tipo pair implementa agora a +// interface Stringer. +func (p pair) String() string { // p é chamado de "receptor" + // Sprintf é outra função pública no pacote fmt. + // Uso de pontos para referenciar os campos de p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // Uma struct pode ser inicializada com os valores dos seus campos dentro + // de chavetas, seguindo a mesma ordem com que os campos foram definidos. + p := pair{3, 4} + fmt.Println(p.String()) // chama o método String de p, que tem tipo pair. + var i Stringer // declara i do tipo interface Stringer. + i = p // válido, porque pair implementa Stringer + // Chama o método String de i, que tem tipo Stringer. Mesmo que acima. + fmt.Println(i.String()) + + // As funções no pacote fmt chamam o método String para pedir a um objecto + // uma representação textual de si mesmo. + fmt.Println(p) // mesmo que acima. Println chama o método String. + fmt.Println(i) // mesmo que acima. + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" forma idiomática usada para saber se algo funcionou ou não. + m := map[int]string{3: "três", 4: "quatro"} + if x, ok := m[1]; !ok { // ok vai ser false porque 1 não está no map m. + fmt.Println("ninguem lá") + } else { + fmt.Print(x) // x seria o valor, se 1 estivesse no map. + } + // Um valor de erro comunica mais informação sobre o problema. + if _, err := strconv.Atoi("non-int"); err != nil { // _ descarta o valor + // imprime "strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // Vamos revisitar as interfaces um pouco mais tarde. Entretanto, + learnConcurrency() +} + +// c é um channel, um objecto para comunicação concurrency-safe. +func inc(i int, c chan int) { + c <- i + 1 // <- é operador "enviar" quando um channel aparece à esquerda. +} + +// Vamos usar a função inc para incrementar números de forma concorrente. +func learnConcurrency() { + // A mesma função make usada anteriormente para alocar uma slice. + // Make aloca e inicializa slices, maps, e channels. + c := make(chan int) + // Inicia três goroutines concorrentes. Os números serão incrementados de + // forma concorrente, talvez em paralelo se a máquina for capaz e estiver + // configurada correctamente. As três goroutines enviam para o mesmo canal. + go inc(0, c) // go é a instrução para iniciar uma goroutine. + go inc(10, c) + go inc(-805, c) + // Lê três resultados do channel c e imprime os seus valores. + // Não se pode dizer em que ordem os resultados vão chegar! + fmt.Println(<-c, <-c, <-c) // channel na direita, <- é operador "receptor". + + cs := make(chan string) // outro channel, este lida com strings. + cc := make(chan chan string) // channel que lida com channels de strings. + go func() { c <- 84 }() // inicia uma goroutine para enviar um valor + go func() { cs <- "palavroso" }() // outra vez, para o channel cs desta vez + // A instrução select tem uma sintaxe semelhante à instrução switch mas + // cada caso envolve uma operação com channels. Esta instrução seleciona, + // de forma aleatória, um caso que esteja pronto para comunicar. + select { + case i := <-c: // o valor recebido pode ser atribuído a uma variável + fmt.Printf("é um %T", i) + case <-cs: // ou o valor recebido pode ser descartado + fmt.Println("é uma string") + case <-cc: // channel vazio, não se encontra pronto para comunicar. + fmt.Println("não aconteceu") + } + // Neste ponto um valor foi recebido de um dos channels c ou cs. Uma das + // duas goroutines iniciadas acima completou, a outra continua bloqueada. + + learnWebProgramming() // Go faz. Você quer faze-lo também. +} + +// Basta apenas uma função do pacote http para iniciar um servidor web. +func learnWebProgramming() { + // O primeiro parâmetro de ListenAndServe é o endereço TCP onde escutar. + // O segundo parâmetro é uma interface, especificamente http.Handler. + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // não ignorar erros +} + +// Tornar pair um http.Handler ao implementar o seu único método, ServeHTTP. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Servir dados com um método de http.ResponseWriter + w.Write([]byte("Aprendeu Go em Y minutos!")) +} +``` + +## Leitura Recomendada + +A principal fonte de informação é o [web site oficial Go](http://golang.org/). +Lá é possível seguir o tutorial, experimentar de forma iterativa, e ler muito. + +A própria especificação da linguagem é altamente recomendada. É fácil de ler e +incrivelmente curta (em relação ao que é habitual hoje em dia). + +Na lista de leitura para os aprendizes de Go deve constar o [código fonte da +biblioteca padrão](http://golang.org/src/pkg/). Exaustivamente documentado, é +a melhor demonstração de código fácil de ler e de perceber, do estilo Go, e da +sua escrita idiomática. Ou então clique no nome de uma função na [documentação] +(http://golang.org/pkg/) e veja o código fonte aparecer! + -- cgit v1.2.3 From 5a87423e209ee77b53e20f70ccc87c26511c4869 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 5 Sep 2013 10:52:17 -0700 Subject: Update README.markdown --- README.markdown | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/README.markdown b/README.markdown index fe72df6c..dc379a9b 100644 --- a/README.markdown +++ b/README.markdown @@ -12,12 +12,24 @@ Make a new file, send a pull request, and if it passes muster I'll get it up pro Remember to fill in the "contributors" fields so you get credited properly! -### Contributing +## Contributing All contributions welcome, from the tiniest typo to a brand new article. Translations in all languages are welcome (or, for that matter, original articles in any language). +Send a pull request or open an issue any time of day or night. -#### Style Guidelines +**Please tag your issues pull requests with [language/lang-code] at the beginning** +**(e.g. [python/en] for english python).** This will help everyone pick out things they +care about. + +### Style Guidelines + +* **Keep lines under 80 chars** +* **Prefer example to exposition** +* **Eschew surplusage** +* **Use utf-8** + +Long version: * Try to keep **line length in code blocks to 80 characters or fewer**, or they'll overflow and look odd. @@ -29,9 +41,9 @@ in all languages are welcome (or, for that matter, original articles in any lang to keep articles succinct and scannable. We all know how to use google here. * For translations (or english articles with non-ASCII characters), please make sure your file is - utf-8 encoded. + utf-8 encoded, and try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in vim) -#### Header configuration +### Header configuration The actual site uses Middleman to generate HTML files from these markdown ones. Middleman, or at least the custom scripts underpinning the site, required that some key information be defined in the header. @@ -47,6 +59,19 @@ Other fields: For non-english articles, *filename* should have a language-specific suffix. * **lang**: For translations, the human language this article is in. For categorization, mostly. +Here's an example header for an esperanto translation of Ruby: + +```yaml +--- +language: ruby +filename: learnruby-epo.ruby +contributors: + - ["Doktor Esperanto", "http://example.com/"] + - ["Someone else", "http://someoneelseswebsite.com/"] +lang: ep-ep +--- +``` + ## License Contributors retain copyright to their work, and can request removal at any time. -- cgit v1.2.3 From d184d0337b91c8b329238d7f30b166ca2a52e7b9 Mon Sep 17 00:00:00 2001 From: Guilherme Heuser Prestes Date: Thu, 5 Sep 2013 15:09:18 -0300 Subject: added PT-BR Erlang version --- pt-br/erlang-pt.html.markdown | 254 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 254 insertions(+) create mode 100644 pt-br/erlang-pt.html.markdown diff --git a/pt-br/erlang-pt.html.markdown b/pt-br/erlang-pt.html.markdown new file mode 100644 index 00000000..e0a689a0 --- /dev/null +++ b/pt-br/erlang-pt.html.markdown @@ -0,0 +1,254 @@ +--- +language: erlang +contributors: + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] +translators: + - ["Guilherme Heuser Prestes", "http://twitter.com/gprestes"] +lang: pt-br +filename: learnerlang_pt.erl +--- + +```erlang +% Símbolo de porcento começa comentários de uma linha. + +%% Dois caracteres de porcento devem ser usados para comentar funções. + +%%% Três caracteres de porcento devem ser usados para comentar módulos. + +% Nós usamos três tipos de pontuação em Erlang. +% Vírgulas (`,`) separam argumentos em chamadas de função, construtores de +% dados, e padrões. +% Pontos finais (`.`) separam totalmente funções e expressões no prompt. +% Ponto e vírgulas (`;`) separam cláusulas. Nós encontramos cláusulas em +% vários contextos: definições de função e em expressões com `case`, `if`, +% `try..catch` e `receive`. + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 1. Variáveis e casamento de padrões. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +Num = 42. % Todos nomes de variáveis devem começar com uma letra maiúscula. + +% Erlang tem atribuição única de variáveis, se você tentar atribuir um valor +% diferente à variável `Num`, você receberá um erro. +Num = 43. % ** exception error: no match of right hand side value 43 + +% Na maioria das linguagens, `=` denota um comando de atribuição. Em Erlang, no +% entanto, `=` denota uma operação de casamento de padrão. `Lhs = Rhs` realmente +% significa isso: avalia o lado direito (Rhs), e então casa o resultado com o +% padrão no lado esquerdo (Lhs). +Num = 7 * 6. + +% Número de ponto flutuante. +Pi = 3.14159. + +% Átomos são usados para representar diferentes valores constantes não +% numéricos. Átomos começam com letras minúsculas seguidas por uma sequência de +% caracteres alfanuméricos ou sinais de subtraço (`_`) ou arroba (`@`). +Hello = hello. +OtherNode = example@node. + +% Átomos com valores alfanuméricos podem ser escritos colocando aspas por fora +% dos átomos. +AtomWithSpace = 'some atom with space'. + +% Tuplas são similares a structs em C. +Point = {point, 10, 45}. + +% Se nós queremos extrair alguns valores de uma tupla, nós usamos o operador `=`. +{point, X, Y} = Point. % X = 10, Y = 45 + +% Nós podemos usar `_` para ocupar o lugar de uma variável que não estamos interessados. +% O símbolo `_` é chamado de variável anônima. Ao contrário de variáveis regulares, +% diversas ocorrências de _ no mesmo padrão não precisam se amarrar ao mesmo valor. +Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}. +{_, {_, {_, Who}, _}, _} = Person. % Who = joe + +% Nós criamos uma lista colocando valores separados por vírgula entre colchetes. +% Cada elemento de uma lista pode ser de qualquer tipo. +% O primeiro elemento de uma lista é a cabeça da lista. Se removermos a cabeça +% da lista, o que sobra é chamado de cauda da lista. +ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}]. + +% Se `T` é uma lista, então `[H|T]` também é uma lista, com cabeça `H` e cauda `T`. +% A barra vertical (`|`) separa a cabeça de uma lista de sua cauda. +% `[]` é uma lista vazia. +% Podemos extrair elementos de uma lista com uma operação de casamento de +% padrão. Se temos uma lista não-vazia `L`, então a expressão `[X|Y] = L`, onde +% `X` e `Y` são variáveis desamarradas, irá extrair a cabeça de uma lista para +% `X` e a cauda da lista para `Y`. +[FirstThing|OtherThingsToBuy] = ThingsToBuy. +% FirstThing = {apples, 10} +% OtherThingsToBuy = {pears, 6}, {milk, 3} + +% Não existe o tipo string em Erlang. Strings são somente listas de inteiros. +% Strings são representadas dentro de aspas duplas (`"`). +Name = "Hello". +[72, 101, 108, 108, 111] = "Hello". + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 2. Programação sequencial. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Módulos são a unidade básica de código em Erlang. Todas funções que +% escrevemos são armazenadas em módulos. Módulos são armazenados em arquivos +% com extensão `.erl`. +% Módulos devem ser compilados antes que o código possa ser rodado. Um módulo +% compilado tem a extensão `.beam`. +-module(geometry). +-export([area/1]). % lista de funções exportadas de um módulo. + +% A função `area` consiste de duas cláusulas. As cláusulas são separadas por um +% ponto e vírgula, e a cláusula final é terminada por um ponto final. +% Cada cláusula tem uma cabeça em um corpo; a cabeça consiste de um nome de +% função seguido por um padrão (entre parêntesis), e o corpo consiste de uma +% sequência de expressões, que são avaliadas se o padrão na cabeça é um par bem +% sucedido dos argumentos da chamada. Os padrões são casados na ordem que +% aparecem na definição da função. +area({rectangle, Width, Ht}) -> Width * Ht; +area({circle, R}) -> 3.14159 * R * R. + +% Compila o código no arquivo geometry.erl. +c(geometry). % {ok,geometry} + +% Nós precisamos incluir o nome do módulo junto com o nome da função de maneira +% a identificar exatamente qual função queremos chamar. +geometry:area({rectangle, 10, 5}). % 50 +geometry:area({circle, 1.4}). % 6.15752 + +% Em Erlang, duas funções com o mesmo nome e diferentes aridades (números de +% argumentos) no mesmo módulo representam funções totalmente diferentes. +-module(lib_misc). +-export([sum/1]). % exporta a função `sum` de aridade 1 aceitando um argumento: lista de inteiros. +sum(L) -> sum(L, 0). +sum([], N) -> N; +sum([H|T], N) -> sum(T, H+N). + +% Funs são funções "anônimas". Elas são chamadas desta maneira por que elas não +% têm nome. No entanto podem ser atribuídas a variáveis. +Double = fun(X) -> 2*X end. % `Double` aponta para uma função anônima com referência: #Fun +Double(2). % 4 + +% Funções aceitam funs como seus argumentos e podem retornar funs. +Mult = fun(Times) -> ( fun(X) -> X * Times end ) end. +Triple = Mult(3). +Triple(5). % 15 + +% Compreensão de lista são expressões que criam listas sem precisar usar funs, +% maps, ou filtros. +% A notação `[F(X) || X <- L]` significa "a lista de `F(X)` onde `X` é tomada +% da lista `L`." +L = [1,2,3,4,5]. +[2*X || X <- L]. % [2,4,6,8,10] +% Uma compreensão de lista pode ter geradores e filtros que selecionam +% subconjuntos dos valores gerados. +EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] + +% Sentinelas são contruções que podemos usar para incrementar o poder de +% casamento de padrão. Usando sentinelas, podemos executar testes simples e +% comparações nas variáveis em um padrão. +% Você pode usar sentinelas nas cabeças das definições de função onde eles são +% introduzidos pela palavra-chave `when`, ou você pode usá-los em qualquer +% lugar na linguagem onde uma expressão é permitida. +max(X, Y) when X > Y -> X; +max(X, Y) -> Y. + +% Um sentinela é uma série de expressões sentinelas, separadas por +% vírgulas (`,`). +% O sentinela `GuardExpr1, GuardExpr2, ..., GuardExprN` é verdadeiro se todas +% expressões sentinelas `GuardExpr1, GuardExpr2, ...` forem verdadeiras. +is_cat(A) when is_atom(A), A =:= cat -> true; +is_cat(A) -> false. +is_dog(A) when is_atom(A), A =:= dog -> true; +is_dog(A) -> false. + +% Uma `sequência sentinela` é um sentinela ou uma série de sentinelas separados +% por ponto e vírgula (`;`). A sequência sentinela `G1; G2; ...; Gn` é +% verdadeira se pelo menos um dos sentinelas `G1, G2, ...` for verdadeiro. +is_pet(A) when is_dog(A); is_cat(A) -> true; +is_pet(A) -> false. + +% Registros provêem um método para associar um nome com um elemento particular +% em uma tupla. +% Definições de registro podem ser incluídas em arquivos fonte Erlang ou em +% arquivos com extensão `.hrl`, que então são incluídos em arquivos fonte Erlang. +-record(todo, { + status = reminder, % Default value + who = joe, + text +}). + +% Nós temos que ler definições de registro no prompt antes que possamos definir +% um registro. Nós usamos a função de prompt `rr` (abreviação de read records) +% para fazer isso. +rr("records.hrl"). % [todo] + +% Criando e atualizando registros: +X = #todo{}. +% #todo{status = reminder, who = joe, text = undefined} +X1 = #todo{status = urgent, text = "Fix errata in book"}. +% #todo{status = urgent, who = joe, text = "Fix errata in book"} +X2 = X1#todo{status = done}. +% #todo{status = done,who = joe,text = "Fix errata in book"} + +% Expressões `case`. +% A função `filter` retorna uma lista de todos elementos `X` em uma lista `L` +% para qual `P(X)` é verdadeiro. +filter(P, [H|T]) -> + case P(H) of + true -> [H|filter(P, T)]; + false -> filter(P, T) + end; +filter(P, []) -> []. +filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4] + +% Expressões `if`. +max(X, Y) -> + if + X > Y -> X; + X < Y -> Y; + true -> nil; + end. + +% Aviso: pelo menos um dos sentinelas na expressão `if` deve retornar +% verdadeiro; Caso contrário, uma exceção será levantada. + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 3. Exceções. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Exceções são levantadas pelo sistema quando erros internos são encontrados ou +% explicitamente em código pela chamada `throw(Exception)`, `exit(Exception)` +% ou `erlang:error(Exception)`. +generate_exception(1) -> a; +generate_exception(2) -> throw(a); +generate_exception(3) -> exit(a); +generate_exception(4) -> {'EXIT', a}; +generate_exception(5) -> erlang:error(a). + +% Erlang tem dois métodos para capturar uma exceção. Uma é encapsular a chamada +% para a função que levanta uma exceção dentro de uma expressão `try...catch`. +catcher(N) -> + try generate_exception(N) of + Val -> {N, normal, Val} + catch + throw:X -> {N, caught, thrown, X}; + exit:X -> {N, caught, exited, X}; + error:X -> {N, caught, error, X} + end. + +% O outro é encapsular a chamada em uma expressão `catch`. Quando você captura +% uma exceção, é convertida em uma tupla que descreve o erro. +catcher(N) -> catch generate_exception(N). + +``` + +## Referências + +* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/) +* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang2/programming-erlang) +* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/) +* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) + -- cgit v1.2.3 From cfa0593731131684832e2b181f4c41310fa50891 Mon Sep 17 00:00:00 2001 From: Guilherme Heuser Prestes Date: Thu, 5 Sep 2013 21:07:47 -0300 Subject: updated header to reflect instructions --- pt-br/erlang-pt.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pt-br/erlang-pt.html.markdown b/pt-br/erlang-pt.html.markdown index e0a689a0..6a86aafc 100644 --- a/pt-br/erlang-pt.html.markdown +++ b/pt-br/erlang-pt.html.markdown @@ -1,11 +1,10 @@ --- language: erlang +filename: learnerlang-pt.erl contributors: - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] -translators: - ["Guilherme Heuser Prestes", "http://twitter.com/gprestes"] lang: pt-br -filename: learnerlang_pt.erl --- ```erlang -- cgit v1.2.3 From 9190044dee9fd71520fb67bc5fb3dd5a871ba3a8 Mon Sep 17 00:00:00 2001 From: Harshad Sabne Date: Fri, 6 Sep 2013 19:58:05 +0530 Subject: Update matlab.html.markdown Multiple function additions to "Common matrix functions" subsection. --- matlab.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 507e9c85..290e620c 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -250,7 +250,11 @@ eig(A) %Eigenvalues and eigenvectors of A isempty(A) % Tests if array is empty 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 +cross(A,B) % Returns the cross product of the vectors A and B +dot(A,B) % Returns the scalar product of the vectors A and B. A and B must be vectors of the same length. +transpose(A) % Returns the transpose of A ``` -- cgit v1.2.3 From 53e121b37df986f418168ec6a3b6287857d8464e Mon Sep 17 00:00:00 2001 From: Harshad Sabne Date: Fri, 6 Sep 2013 20:54:32 +0530 Subject: Update matlab.html.markdown Added subsection "Common vector functions" --- matlab.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/matlab.html.markdown b/matlab.html.markdown index 290e620c..3bcc4bbc 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -256,6 +256,17 @@ cross(A,B) % Returns the cross product of the vectors A and B dot(A,B) % Returns the scalar product of the vectors A and B. A and B must be vectors of the same length. transpose(A) % Returns the transpose of A +% 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 +median %median value +mean %mean value +std %standard deviation + ``` -- cgit v1.2.3 From c41efedd20ba6917912f66e12457975e3915aad9 Mon Sep 17 00:00:00 2001 From: Rafael Jegundo Date: Sat, 7 Sep 2013 23:07:38 +0100 Subject: added first version of git in PT-PT --- pt-pt/git-pt.html.markdown | 414 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 414 insertions(+) create mode 100644 pt-pt/git-pt.html.markdown diff --git a/pt-pt/git-pt.html.markdown b/pt-pt/git-pt.html.markdown new file mode 100644 index 00000000..213f1ad3 --- /dev/null +++ b/pt-pt/git-pt.html.markdown @@ -0,0 +1,414 @@ +--- +category: tool +tool: git +lang: pt-pt +filename: LearnGit.txt +contributors: + - ["Rafael Jegundo", "http://rafaeljegundo.github.io/"] +--- + +Git é um sistema distribuido de gestão para código fonte e controlo de versões. + +Funciona através de uma série de registos de estado do projecto e usa esse +registo para permitir funcionalidades de versionamento e gestão de código +fonte. + +## Conceitos de versionamento + +### O que é controlo de versões + +Controlo de versões (*source control*) é um processo de registo de alterações +a um ficheiro ou conjunto de ficheiros ao longo do tempo. + +### Controlo de versões: Centralizado VS Distribuido + +* Controlo de versões centralizado foca-se na sincronização, registo e *backup* +de ficheiros. +* Controlo de versões distribuido foca-se em partilhar alterações. Cada +alteração é associada a um *id* único. +* Sistemas distribuidos não têm estrutura definida. É possivel ter um sistema +centralizado ao estilo SVN usando git. + +[Informação adicional (EN)](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### Porquê usar git? + +* Permite trabalhar offline. +* Colaborar com outros é fácil! +* Criar *branches* é fácil! +* Fazer *merge* é fácil! +* Git é rápido. +* Git é flexivel. + +## Git - Arquitectura + + +### Repositório + +Um conjunto de ficheiros, directórios, registos históricos, *commits* e +referências. Pode ser imaginado 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 é constituido pelo directório .git e a *working tree* + +### Directório .git (componente do repositório) + +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) + +### *Working Tree* (componente do repositório) + +Isto é basicamente os directórios e ficheiros do repositório. É frequentemente +referido como o directório do projecto. + +### *Index* (componente do directório .git) + +O *Index* é a camada de interface no git. Consistente num elemento que separa +o directório do projecto do repositório git. Isto permite aos programadores um +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. +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! + +### *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 +automaticamente e passa a apontar para o commit mais recente. + +### *HEAD* e *head* (componentes do directório .git) + +*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 conceptuais (EN) + +* [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* + +Cria um repositório Git vazio. As definições, informação guardada e outros do +repositório git são guardados num directório (pasta) denominado ".git". + +```bash +$ git init +``` + +### *config* + +Permite configurar as definições, sejam as definições do repositório, sistema +ou configurações globais. + +```bash +# Imprime & Define Algumas Variáveis de Configuração Básicas (Global) +$ git config --global user.email +$ git config --global user.name + +$ 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) + +### help + +Para aceder rapidamente a um guia extremamente detalhada sobre cada comando. +Ou para dar apenas uma lembraça rápida de alguma semântica. + +```bash +# Ver rapidamente os comandos disponiveis +$ git help + +# Ver todos os comandos disponiveis +$ git help -a + +# Requerer *help* sobre um comando especifico - manual de utilizador +# git help +$ git help add +$ git help commit +$ git help init +``` + +### status + +Apresenta as diferenças entre o ficheiro *index* (no fundo a versão corrente +do repositório) e o *commit* da *HEAD* atual. + + +```bash +# Apresenta o *branch*, ficheiros não monitorizados, alterações e outras +# difereças +$ git status + +# Para aprender mais detalhes sobre git *status* +$ git help status +``` + +### add + +Adiciona ficheiros ao repositório corrente. Se os ficheiros novos não forem +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 +$ git add HelloWorld.java + +# adiciona um ficheiro num sub-directório +$ git add /path/to/file/HelloWorld.c + +# permite usar expressões regulares! +$ git add ./*.java +``` + +### branch + +Gere os *branches*. É possível ver, editar, criar e apagar branches com este +comando. + +```bash +# listar *branches* existentes e remotos +$ git branch -a + +# criar um novo *branch* +$ git branch myNewBranch + +# apagar um *branch* +$ git branch -d myBranch + +# alterar o nome de um *branch* +# git branch -m +$ git branch -m myBranchName myNewBranchName + +# editar a descrição de um *branch* +$ git branch myBranchName --edit-description +``` + +### checkout + +Atualiza todos os ficheiros no directório do projecto de forma a ficarem iguais +à versão do index ou do *branch* especificado. + +```bash +# Checkout de um repositório - por predefinição para o branch master +$ git checkout +# Checkout de um branch especifico +$ git checkout branchName +# Cria um novo branch e faz checkout para ele. +# Equivalente a: "git branch ; git checkout " +$ git checkout -b newBranch +``` + +### clone + +Clona ou copia um repositório existente para um novo directório. Também +adiciona *branches* de monitorização remota para cada *branch* no repositório +clonado o que permite enviar alterações para um *branch* remoto. + +```bash +# Clona learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +``` + +### commit + +Guarda o conteudo atual do index num novo *commit*. Este *commit* contém +as alterações feitas e a mensagem criada pelo utilizador. + +```bash +# commit com uma mensagem +$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" +``` + +### diff + +Apresenta as diferenças entre um ficheiro no repositório do projecto, *index* +e *commits* + +```bash +# Apresenta a diferença entre o directório atual e o index +$ git diff + +# Apresenta a diferença entre o index e os commits mais recentes +$ git diff --cached + +# Apresenta a diferença entre o directório atual e o commit mais recente +$ git diff HEAD +``` + +### grep + +Permite procurar facilmente num repositório + +Configurações opcionais: + +```bash +# Obrigado a Travis Jeffery por estas +# Define a apresentação de números de linha nos resultados do grep +$ git config --global grep.lineNumber true + +# Torna os resultados da pesquisa mais fáceis de ler, agrupando-os +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Pesquisa por "variableName" em todos os ficheiros de java +$ git grep 'variableName' -- '*.java' + +# Pesquisa por uma linha que contém "arrayListName" e "add" ou "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Google é teu amigo; para mais exemplos: +[Git Grep Ninja (EN)](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Apresenta commits do repositório. + +```bash +# Apresenta todos os commits +$ git log + +# Apresenta X commits +$ git log -n 10 + +# Apresenta apenas commits de merge +$ git log --merges +``` + +### merge + +"Merge" (junta) as alterações de commits externos com o *branch* atual. + +```bash +# Junta o branch especificado com o atual +$ git merge branchName + +# Para gerar sempre um commit ao juntar os branches +$ git merge --no-ff branchName +``` + +### mv + +Alterar o nome ou mover um ficheiro. + +```bash +# Alterar o nome de um ficheiro +$ git mv HelloWorld.c HelloNewWorld.c + +# Mover um ficheiro +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Forçar a alteração de nome ou mudança local +# "existingFile" já existe no directório, será sobre-escrito. +$ git mv -f myFile existingFile +``` + +### pull + +Puxa alterações de um repositório e junta-as com outro branch + +```bash +# Atualiza o repositório local, juntando as novas alterações +# do repositório remoto 'origin' e branch 'master' +# git pull +# git pull => aplica a predefinição => git pull origin master +$ git pull origin master + +# 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 + +Enviar e juntar alterações de um branch para o seu branch correspondente +num repositório remoto. + +```bash +# Envia e junta as alterações de um repositório local +# para um remoto denominado "origin" no branch "master". +# git push +# git push => aplica a predefinição => git push origin master +$ git push origin master +``` + +### rebase (cautela!) + +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 +# Faz Rebase de experimentBranch para master +# git rebase +$ git rebase master experimentBranch +``` + +[Additional Reading (EN).](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (cautela!) + +Restabelece a HEAD atual ao estado definido. Isto permite reverter *merges*, +*pulls*, *commits*, *adds* e outros. É um comando muito poderoso mas também +perigoso se não há certeza quanto ao que se está a fazer. + +```bash +# Restabelece a camada intermediária dr registo para o último +# commit (o directório fica sem alterações) +$ git reset + +# Restabelece a camada intermediária de registo para o último commit, e +# sobre-escreve o projecto atual +$ git reset --hard + +# Move a head do branch atual para o commit especificado, sem alterar o projecto. +# todas as alterações ainda existem no projecto +$ git reset 31f2bb1 + +# Inverte a head do branch atual para o commit especificado +# fazendo com que este esteja em sintonia com o directório do projecto +# Remove alterações não registadas e todos os commits após o commit especificado +$ git reset --hard 31f2bb1 +``` + +### rm + +O oposto de git add, git rm remove ficheiros do branch atual. + +```bash +# remove HelloWorld.c +$ git rm HelloWorld.c + +# Remove um ficheiro de um sub-directório +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## Informação complementar (EN) + +* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) + +* [git-scm - Video Tutorials](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) -- cgit v1.2.3 From 1f04c99ca4a06ea8a21b917a01174475292af1be Mon Sep 17 00:00:00 2001 From: Nathan Bouscal Date: Sun, 8 Sep 2013 04:24:37 -0400 Subject: Fix grammar in ruby-ecosystem.html.markdown --- ruby-ecosystem.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index c2a2087b..d186f712 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -121,9 +121,9 @@ dependency graph to resolve. # Testing -Testing is a large of ruby culture. Ruby comes with its own Unit-style testing -framework called minitest (Or TestUnit for ruby version 1.8.x). There are many -testing libraries with different goals. +Testing is a large part of ruby culture. Ruby comes with its own Unit-style +testing framework called minitest (Or TestUnit for ruby version 1.8.x). There +are many testing libraries with different goals. * TestUnit - Ruby 1.8's built-in "Unit-style" testing framework * minitest - Ruby 1.9/2.0's built-in testing framework -- cgit v1.2.3 From 26a633f0de9bc5657760839ad291d28f6b287873 Mon Sep 17 00:00:00 2001 From: FeepingCreature Date: Sun, 8 Sep 2013 13:09:24 +0200 Subject: Add documentation for Neat, my D1-lite. --- neat.html.markdown | 275 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 275 insertions(+) create mode 100644 neat.html.markdown diff --git a/neat.html.markdown b/neat.html.markdown new file mode 100644 index 00000000..0328a597 --- /dev/null +++ b/neat.html.markdown @@ -0,0 +1,275 @@ +--- + +language: neat +contributors: + - ["Feep", "https://github.com/FeepingCreature"] +filename: LearnNeat.nt + +--- + +Neat is basically a smaller version of D1 with some experimental syntax and a focus on terseness without losing the basic C-like syntax. + +[Read more here.](https://github.com/FeepingCreature/fcc/wiki) + +```D +// single line comments start with // +/* + multiline comments look like this +*/ +/+ + or this + /+ these can be nested too, same as D +/ ++/ + +// Module name. This has to match the filename/directory. +module neat; + +// Make names from another module visible in this one. +import std.file; +// You can import multiple things at once. +import std.math, std.util; +// You can even group up imports! +import std.(process, socket); + +// Global functions! +void foo() { } + +// Main function, same as in C. +// string[] == "array of strings". +// "string" is just an alias for char[], +void main(string[] args) { + // Call functions with "function expression". + writeln "Hello World"; + // You can do it like in C too... if you really want. + writeln ("Hello World"); + // Declare a variable with "type identifier" + string arg = ("Hello World"); + writeln arg; + // (expression, expression) forms a tuple. + // There are no one-value tuples though. + // So you can always use () in the mathematical sense. + // (string) arg; <- is an error + + /* + byte: 8 bit signed integer + char: 8 bit UTF-8 byte component. + short: 16 bit signed integer + int: 32 bit signed integer + long: 64 bit signed integer + + float: 32 bit floating point + double: 64 bit floating point + real: biggest native size floating point (80 bit on x86). + + bool: true or false + */ + int a = 5; + bool b = true; + // as in C, && and || are short-circuit evaluating. + b = b && false; + assert(b == false); + // "" are "format strings". So $variable will be substituted at runtime + // with a formatted version of the variable. + writeln "$a"; + // This will just print $a. + writeln `$a`; + // you can format expressions with $() + writeln "$(2+2)"; + // Note: there is no special syntax for characters. + char c = "a"; + // Cast values by using type: expression. + // There are three kinds of casts: + // casts that just specify conversions that would be happening automatically + // (implicit casts) + float f = float:5; + float f2 = 5; // would also work + // casts that require throwing away information - + // those must always be done explicitly + // (conversion casts) + int i = int:f; + // int i = f; // would not work! + // and, as a last attempt, casts that just reinterpret the raw data. + // Those only work if the types have the same size. + string s = "Hello World"; + // Arrays are (length, pointer) pairs. + // This is a tuple type. Tuple types are (type, type, type). + // The type of a tuple expression is a tuple type. (duh) + (int, char*) array = (int, char*): s; + // You can index arrays and tuples using the expression[index] syntax. + writeln "pointer is $(array[1]) and length is $(array[0])"; + // You can slice them using the expression[from .. to] syntax. + // Slicing an array makes another array. + writeln "$(s[0..5]) World"; + // Alias name = expression gives the expression a name. + // As opposed to a variable, aliases do not have an address + // and can not be assigned to. (Unless the expression is assignable) + alias range = 0 .. 5; + writeln "$(s[range]) World"; + // You can iterate over ranges. + for int i <- range { + write "$(s[i])"; + } + writeln " World"; + // Note that if "range" had been a variable, it would be 'empty' now! + // Range variables can only be iterated once. + // The syntax for iteration is "expression <- iterable". + // Lots of things are iterable. + for char c <- "Hello" { write "$c"; } + writeln " World"; + // For loops are "for test statement"; + alias test = char d <- "Hello"; + for test write "$d"; + writeln " World\t\x05"; // note: escapes work + // Pointers: function the same as in C, btw. The usual. + // Do note: the pointer star sticks with the TYPE, not the VARIABLE! + string* p; + assert(p == null); // default initializer + p = &s; + writeln "$(*p)"; + // Math operators are (almost) standard. + int x = 2 + 3 * 4 << 5; + // Note: XOR is "xor". ^ is reserved for exponentiation (once I implement that). + int y = 3 xor 5; + int z = 5; + assert(z++ == 5); + assert(++z == 7); + writeln "x $x y $y z $z"; + // As in D, ~ concatenates. + string hewo = "Hello " ~ "World"; + // == tests for equality, "is" tests for identity. + assert (hewo == s); + assert !(hewo is s); + // same as + assert (hewo !is s); + // You can do a C for loop too + // - but why would you want to? + for (int i = 0; i < 5; ++i) { } + // Otherwise, for and while are the same. + while int i <- 0..4 { + assert(i == 0); + break; // continue works too + } then assert(false); // if we hadn't break'd, this would run at the end + // This is the height of loopdom - the produce-test-consume loop. + do { + int i = 5; + } while (i == 5) { + assert(i == 5); + break; // otherwise we'd go back up to do { + } + + // This is a nested function. + // Nested functions can access the surrounding function. + string returnS() { return s; } + writeln returnS(); + + // Take the address of a function using & + // The type of a global function is ReturnType function(ParameterTypeTuple). + void function() foop = &foo; + + // Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple). + string delegate() returnSp = &returnS; + writeln returnSp(); + // Class member functions and struct member functions also fit into delegate variables. + // In general, delegates are functions that carry an additional context pointer. + // ("fat pointers" in C) + + // Allocate a "snapshot" with "new delegate". + // Snapshots are not closures! I used to call them closures too, + // but then my Haskell-using friends yelled at me so I had to stop. + // The difference is that snapshots "capture" their surrounding context + // when "new" is used. + // This allows things like this + int delegate(int) add(int a) { + int add_a(int b) { return a + b; } + // This does not work - the context of add_a becomes invalid + // when add returns. + // return &add_a; + // Instead: + return new &add_a; + } + int delegate(int) dg = add 2; + assert (dg(3) == 5); + // or + assert (((add 2) 3) == 5); + // or + assert (add 2 3 == 5); + // add can also be written as + int delegate(int) add2(int a) { + // this is an implicit, nameless nested function. + return new λ(int b) { return a + b; } + } + // or even + auto add3(int a) { return new λ(int b) -> a + b; } + // hahahaaa + auto add4 = λ(int a) -> new λ(int b) -> a + b; + assert(add4 2 3 == 5); + // If your keyboard doesn't have a λ (you poor sod) + // you can use \ too. + auto add5 = \(int a) -> new \(int b) -> a + b; + // Note! + auto nestfun = λ() { } // There is NO semicolon needed here! + // "}" can always substitute for "};". + // This provides syntactic consistency with built-in statements. + + + // This is a class. + // Note: almost all elements of Neat can be used on the module level + // or just as well inside a function. + class C { + int a; + void writeA() { writeln "$a"; } + // It's a nested class - it exists in the context of main(). + // so if you leave main(), any instances of C become invalid. + void writeS() { writeln "$s"; } + } + C cc = new C; + // c is a *reference* to C. Classes are always references. + cc.a = 5; // Always used for property access. + auto ccp = &cc; + (*ccp).a = 6; + // or just + ccp.a = 7; + cc.writeA(); + cc.writeS(); // to prove I'm not making things up + // Interfaces work same as in D, basically. Or Java. + interface E { void doE(); } + // Inheritance works same as in D, basically. Or Java. + class D : C, E { + override void writeA() { writeln "hahahahaha no"; } + override void doE() { writeln "eeeee"; } + // all classes inherit from Object. (toString is defined in Object) + override string toString() { return "I am a D"; } + } + C cd = new D; + // all methods are always virtual. + cd.writeA(); + E e = E:cd; // dynamic class cast! + e.doE(); + writeln "$e"; // all interfaces convert to Object implicitly. + + // Templates! + // Templates are parameterized namespaces, taking a type as a parameter. + template Templ(T) { + alias hi = 5, hii = 8; + // Templates always have to include something with the same name as the template + // - this will become the template's _value_. + // Static ifs are evaluated statically, at compile-time. + // Because of this, the test has to be a constant expression, + // or something that can be optimized to a constant. + static if (types-equal (T, int)) { + alias Templ = hi; + } else { + alias Templ = hii; + } + } + assert(Templ!int == 5); + assert(Templ!float == 8); +} +``` + +## Topics Not Covered + + * Extended iterator types and expressions + * Standard library + * Conditions (error handling) + * Macros -- cgit v1.2.3 From c38f2c1debf0828176712f6b347e5a7a5d73ffc0 Mon Sep 17 00:00:00 2001 From: FeepingCreature Date: Sun, 8 Sep 2013 13:10:41 +0200 Subject: Fix module filename; I misunderstood the directory layout there --- neat.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neat.html.markdown b/neat.html.markdown index 0328a597..db64f59f 100644 --- a/neat.html.markdown +++ b/neat.html.markdown @@ -22,7 +22,7 @@ Neat is basically a smaller version of D1 with some experimental syntax and a fo +/ // Module name. This has to match the filename/directory. -module neat; +module LearnNeat; // Make names from another module visible in this one. import std.file; -- cgit v1.2.3 From ff6cf1836481bded466bdbb4eb7765ad8424872c Mon Sep 17 00:00:00 2001 From: FeepingCreature Date: Sun, 8 Sep 2013 13:12:45 +0200 Subject: Amend cast doc to account for dynamic class casts --- neat.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neat.html.markdown b/neat.html.markdown index db64f59f..ecb255c2 100644 --- a/neat.html.markdown +++ b/neat.html.markdown @@ -83,7 +83,7 @@ void main(string[] args) { // (implicit casts) float f = float:5; float f2 = 5; // would also work - // casts that require throwing away information - + // casts that require throwing away information or complicated computation - // those must always be done explicitly // (conversion casts) int i = int:f; -- cgit v1.2.3 From ff24568b098b2233961408960ab30518acaebe32 Mon Sep 17 00:00:00 2001 From: FeepingCreature Date: Sun, 8 Sep 2013 13:15:38 +0200 Subject: Fix small syntax bug --- neat.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neat.html.markdown b/neat.html.markdown index ecb255c2..b7777cdc 100644 --- a/neat.html.markdown +++ b/neat.html.markdown @@ -223,7 +223,7 @@ void main(string[] args) { void writeS() { writeln "$s"; } } C cc = new C; - // c is a *reference* to C. Classes are always references. + // cc is a *reference* to C. Classes are always references. cc.a = 5; // Always used for property access. auto ccp = &cc; (*ccp).a = 6; -- cgit v1.2.3 From f5f3f2b3e5a6e3579d8f2217c96b5cd0d96298ee Mon Sep 17 00:00:00 2001 From: FeepingCreature Date: Sun, 8 Sep 2013 13:40:48 +0200 Subject: Document appender arrays and scope guards --- neat.html.markdown | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/neat.html.markdown b/neat.html.markdown index b7777cdc..6a319a7d 100644 --- a/neat.html.markdown +++ b/neat.html.markdown @@ -141,6 +141,30 @@ void main(string[] args) { assert !(hewo is s); // same as assert (hewo !is s); + + // Allocate arrays using "new array length" + int[] integers = new int[] 10; + assert(integers.length == 10); + assert(integers[0] == 0); // zero is default initializer + integers = integers ~ 5; // This allocates a new array! + assert(integers.length == 11); + + // This is an appender array. + // Instead of (length, pointer), it tracks (capacity, length, pointer). + // When you append to it, it will use the free capacity if it can. + // If it runs out of space, it reallocates - but it will free the old array automatically. + // This makes it convenient for building arrays. + int[auto~] appender; + appender ~= 2; + appender ~= 3; + appender.free(); // same as {mem.free(appender.ptr); appender = null;} + + // Scope variables are automatically freed at the end of the current scope. + scope int[auto~] someOtherAppender; + // This is the same as: + int[auto~] someOtherAppender2; + onExit { someOtherAppender2.free; } + // You can do a C for loop too // - but why would you want to? for (int i = 0; i < 5; ++i) { } -- cgit v1.2.3 From d22029e0d0e300c5fb4538748e5ed696eeb0241f Mon Sep 17 00:00:00 2001 From: Syl Zys Date: Sun, 8 Sep 2013 14:53:33 +0200 Subject: Added Python French translation --- fr-fr/python-fr.html.markdown | 491 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 491 insertions(+) create mode 100644 fr-fr/python-fr.html.markdown diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown new file mode 100644 index 00000000..84831772 --- /dev/null +++ b/fr-fr/python-fr.html.markdown @@ -0,0 +1,491 @@ +--- +langage: python + +contributeurs: + - ["Louie Dinh", "http://ldinh.ca"] + +traducteurs: + - ["Sylvain Zyssman", "https://github.com/sylzys"] + +fichier: learnpython.py + +--- + +Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de promgrammation les plus populaires. +Je suis tombé amoureux de Python de par la clarité de sa syntaxe. C'est pratiquement du pseudo-code exécutable. + +Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service] + +NB: Cet artice s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x +Vous pourrez bientôt trouver un article pour Python 3! + +```python +# Une ligne simple de commentaire commence par un dièse +""" Les lignes de commenatires multipes peut être écrite + en utilisant 3 '"', et sont souvent utilisées + pour commenter +""" + +#################################################### +## 1. Types Primaires et Opérateurs +#################################################### + +# Les nombres +3 #=> 3 + +# Les calculs produisent les résultats mathématiques escomptés +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# La division est un peu spéciale. C'est une division d' "int", et Python arrondi le résultat par défaut automatiquement. +5 / 2 #=> 2 + +# Pour corriger ce problème, on utilise les float. +2.0 # Voici un float +11.0 / 4.0 #=> 2.75 ahhh...beaucoup mieux + +# Forcer la priorité avec les parenthèses +(1 + 3) * 2 #=> 8 + +# Les valeurs booléenes sont de type primitif +True +False + +# Pour la négation, on utilise "not" +not True #=> False +not False #=> True + +# Pour l'égalité, == +1 == 1 #=> True +2 == 1 #=> False + +# L'inégalité est symbolisée par != +1 != 1 #=> False +2 != 1 #=> True + +# D'autres comparateurs +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# On peut enchaîner les comparateurs ! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Les chaînes de caractères sont créées avec " ou ' +"C'est une chaîne." +'C'est aussi une chaîne.' + +# On peut aussi les "additioner" ! +"Hello " + "world!" #=> "Hello world!" + +# Une chaîne peut être traiter comme une liste de caractères +"C'est une chaîne"[0] #=> 'C' + +# % peut être utilisé pour formatter des chaîne, comme ceci: +"%s can be %s" % ("strings", "interpolated") + +# Une nouvelle manière de formatter les chaînes de caractères est d'utiliser la méthode 'format' +# C'est la méthode à privilégier +"{0} peut être {1}".format("La chaîne", "formattée") +# On peut utiliser des mot-clés au lieu des chiffres. +"{name} veut manger des {food}".format(name="Bob", food="lasagnes") + +# None est un objet +None #=> None + +# Ne pas utiliser le symbole d'inégalité "==" pour comparer des objet à None +# Il faut utiliser "is" +"etc" is None #=> False +None is None #=> True + +# L'opérateur 'is' test l'identité de l'objet. +# Ce n'est pas très utilse avec les types primitifs, mais cela peut être très util +# lorsque l'on utilise des objets. + +# None, 0, et les chaînes de caractères vides valent False. +# Toutes les autres valeurs valent True +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Variables et Collections +#################################################### + +# Afficher, c'est facile +print "Je suis Python. Enchanté!" + + +# Il n'y a pas besoin de déclarer les variables avant de les assigner. +some_var = 5 # La convention veut que l'on utilise des minuscules_avec_underscores +some_var #=> 5 + +# Accéder à une variable non assignée lève une exception +# Voyez les structures de contrôle pour en apprendre plus sur la gestion des exceptions. +some_other_var # Lève une exception + +# 'if' peut être utilisé comme expression +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listes +li = [] +# On peut utiliser une liste pré-remplie. +other_li = [4, 5, 6] + +# On ajoute des éléments avec 'append' +li.append(1) #li contient [1] +li.append(2) #li contient [1, 2] +li.append(4) #li contient [1, 2, 4] +li.append(3) #li contient [1, 2, 4, 3] + +# Et on les supprime avec 'pop' +li.pop() #=> 3 et li contient [1, 2, 4] +# Remettons-le dans la liste +li.append(3) # li contient [1, 2, 4, 3] de nouveau. + +# On accède aux éléments d'une liste comme pour un tableau. +li[0] #=> 1 +# Le dernier élément +li[-1] #=> 3 + +# Accèder aux indes hors limite lève une exception +li[4] # Lève un 'IndexError' + +# On peut accèder à des rangs de valeurs avec la syntaxe "slice" +# (C'est un rang de type 'fermé/ouvert' pour les plus matheux) +li[1:3] #=> [2, 4] +# Ne pas spécifier de début de rang +li[2:] #=> [4, 3] +# Ne pas spécifier de fin de rang +li[:3] #=> [1, 2, 4] + +# Retirer un élément spécifique dee la lsite avec "del" +del li[2] # li contient [1, 2, 3] + +# On peut additionner des listes entre elles +li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li et other_li existent toujours à part entière + +# Concatener des listes avec "extend()" +li.extend(other_li) # li vaut maintenant [1, 2, 3, 4, 5, 6] + +# Vérifier l'existence d'un élément dans une liste avec "in" +1 in li #=> True + +# Récupérer la longueur avec "len()" +len(li) #=> 6 + + +# Les "tuples", sont comme des listes, mais sont immuables. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Lève un 'TypeError' + +# Mais vous pouvez faire tout ceci sur les tuples: +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Vous pouvez "dé-packager" les tupels (ou les listes) dans des variables +a, b, c = (1, 2, 3) # a vaut maintenant 1, b vaut maintenant 2 and c vaut maintenant 3 +# Sans parenthèses, un tuple est créé par défaut +d, e, f = 4, 5, 6 +# Voyez maintenant comme il est facile d'inverse 2 valeurs +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionaires +empty_dict = {} +# Un dictionnaire pré-rempli +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Trouver des valeurs avec [] +filled_dict["one"] #=> 1 + +# Récupérer toutes les clés sous forme de liste avec "keys()" +filled_dict.keys() #=> ["three", "two", "one"] +# Note - l'odre des clés du dictionnaire n'est pas garanti. +# Vos résultats peuvent différer de ceux ci-dessous. + +# Récupérer toutes les valeurs sous forme de liste avec "values()" +filled_dict.values() #=> [3, 2, 1] +# Note - Même remarque qu'au-dessus concernant l'ordre des valeurs. + +# Vérifier l'existence d'une clé dans le dictionnaire avec "in" +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Chercher une clé non existence lève une 'KeyError' +filled_dict["four"] # KeyError + +# Utiliser la méthode "get()" pour éviter 'KeyError' +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# La méthode get() prend un argument par défaut quand la valeur est inexistante +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# La méthode "setdefault()" permet d'ajouter de manière sécuris une paire clé-valeur dans le dictionnnaire +filled_dict.setdefault("five", 5) #filled_dict["five"] vaut 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] is toujours 5 + + +# Les sets stockent ... des sets +empty_set = set() +# On initialise un "set()" avec tout un tas de valeurs +some_set = set([1,2,2,3,4]) # some_set vaut maintenant set([1, 2, 3, 4]) + +# Depuis Python 2.7, {} peut être utilisé pour déclarer un 'set' +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Ajouter plus d'éléments au set +filled_set.add(5) # filled_set contient maintenant {1, 2, 3, 4, 5} + +# Intersection de sets avec & +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Union de sets avec | +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Différence de sets avec - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Vérifier l'existene d'une valeur dans un set avec "in" +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Structure de contrôle +#################################################### + +# Initialisons une variable +some_var = 5 + +# Voici une condition 'if'. L'indentation est significative en Python ! +# Affiche "some_var est inférieur à 10" +if some_var > 10: + print "some_var est supérieur à 10." +elif some_var < 10: # La clause elif est optionnelle + print "some_var iinférieur à 10." +else: # Optionnel également + print "some_var vaut 10." + + +""" +Les boucles "for" font des itérations sur les listes +Affiche: + chien : mammifère + chat : mammifère + souris : mammifère +""" +for animal in ["chien", "chat", "souris"]: + # On peut utiliser % pour l'interpolation des chaînes formattées + print "%s : mammifère" % animal + +""" +"range(number)" retourne une liste de nombres +de 0 au nombre donné +Affiche: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +Les boucles "while" boucle jusqu'à ce qu'une condition ne soit plus vraie +Affiche: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Raccourci pour x = x + 1 + +# Gérer les exceptions avec un bloc try/except + +# Fonctionne pour Python 2.6 et ultérieur: +try: + # Utiliser "raise" pour lever une exception + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass ne prend pas d'arguments. Généralement, on gère l'erreur ici. + + +#################################################### +## 4. Fonctions +#################################################### + +# Utiliser "def" pour créer une nouvelle fonction +def add(x, y): + print "x vaut %s et y vaur %s" % (x, y) + return x + y # Renvoi de valeur avec 'return' + +# Appeller une fonction avec des paramètres +add(5, 6) #=> Affichet "x is 5 et y vaut 6" et renvoie 11 + +# Une autre manière d'appeller une fonction, avec les arguments +add(y=6, x=5) # Les arguments peuvent venir dans n'importe quel ordre. + +# On peut définir une foncion qui prend un nombre variable de paramètres +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Ont peut également définir une fonction qui prend un nombrenumber of +# variable d'arguments +def keyword_args(**kwargs): + return kwargs + +# Appelons-là et voyons ce qu'il se passe +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# On peut faire les deux à la fois si on le souhaite +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) affiche: + (1, 2) + {"a": 3, "b": 4} +""" + +# En appellant les fonctions, on peut faire l'inverse des paramètres / arguments ! +# Utiliser * pour développer les paramètres, et ** pour développer les arguments +params = (1, 2, 3, 4) +args = {"a": 3, "b": 4} +all_the_args(*args) # equivaut à foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivaut à foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivaut à foo(1, 2, 3, 4, a=3, b=4) + +# Python a des fonctions de première classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Mais également des fonctions anonymes +(lambda x: x > 2)(3) #=> True + +# On trouve aussi des fonctions intégrées plus évoluées +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# On peut utiliser la syntaxe des liste pour construire les "maps" et les "filters" +[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 +#################################################### + +# Une classe hérite d'un objet +class Human(object): + + # L'attribut d'une classe. Il est partagé par toutes les instances de cette classe. + species = "H. sapiens" + + # Initialiseur basique + def __init__(self, name): + # Assigne le paramètre à l'attribut de l'instance de classe. + self.name = name + + # Une méthode de l'instance. Toutes les méthodes prennent "self" comme 1er paramètre. + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Une méthode de classe est partagée par toutes les instances. + # On les appelle avec le nom de la classe en premier paramètre + @classmethod + def get_species(cls): + return cls.species + + # Une méthode statique est appellée sans référence à une classe ou à une instance + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancier une classe +i = Human(name="Ian") +print i.say("hi") # Affiche "Ian: hi" + +j = Human("Joel") +print j.say("hello") #Affiche "Joel: hello" + +# Appeller notre méthode de classe +i.get_species() #=> "H. sapiens" + +# Changer les attributs partagés +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Appeller la méthode statique +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# On peut importer des modules +import math +print math.sqrt(16) #=> 4 + +# Et récupérer des fonctions spécifiques d'un module +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Récuperer toutes les fonctions d'un module +# Attention, ce n'est pas recommandé. +from math import * + +# On peut raccourcir le nom d'un module +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Les modules Python sont juste des fichiers Python ordinaires. +# On peut écrire ses propres modules et les importer. +# Le nom du module doit être le même que le nom du fichier. + +# On peut trouver quelle fonction et attributs déterminent un module +import math +dir(math) + + +``` + +## Prêt à aller plus loin? + +### En ligne gratuitement + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Format papier + +* [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 1b8a617b97f22fb9bfefee37ddad880f99f8fc7d Mon Sep 17 00:00:00 2001 From: Syl Zys Date: Sun, 8 Sep 2013 16:27:38 +0200 Subject: typo corrections --- fr-fr/python-fr.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 84831772..f8f907b4 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -11,8 +11,8 @@ fichier: learnpython.py --- -Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de promgrammation les plus populaires. -Je suis tombé amoureux de Python de par la clarité de sa syntaxe. C'est pratiquement du pseudo-code exécutable. +Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de programmation les plus populaires. +Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiquement du pseudo-code exécutable. Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service] @@ -21,9 +21,9 @@ Vous pourrez bientôt trouver un article pour Python 3! ```python # Une ligne simple de commentaire commence par un dièse -""" Les lignes de commenatires multipes peut être écrite - en utilisant 3 '"', et sont souvent utilisées - pour commenter +""" Les lignes de commenatires multipes peuvent être écrites + en utilisant 3 guillemets ("), et sont souvent utilisées + pour les commentaires """ #################################################### @@ -39,12 +39,12 @@ Vous pourrez bientôt trouver un article pour Python 3! 10 * 2 #=> 20 35 / 5 #=> 7 -# La division est un peu spéciale. C'est une division d' "int", et Python arrondi le résultat par défaut automatiquement. +# La division est un peu spéciale. C'est une division d'entiers, et Python arrondi le résultat par défaut automatiquement. 5 / 2 #=> 2 # Pour corriger ce problème, on utilise les float. 2.0 # Voici un float -11.0 / 4.0 #=> 2.75 ahhh...beaucoup mieux +11.0 / 4.0 #=> 2.75 ahhh... beaucoup mieux # Forcer la priorité avec les parenthèses (1 + 3) * 2 #=> 8 @@ -82,7 +82,7 @@ not False #=> True # On peut aussi les "additioner" ! "Hello " + "world!" #=> "Hello world!" -# Une chaîne peut être traiter comme une liste de caractères +# Une chaîne peut être traitée comme une liste de caractères "C'est une chaîne"[0] #=> 'C' # % peut être utilisé pour formatter des chaîne, comme ceci: -- cgit v1.2.3 From b466a86d9d293c0ddab7db089c31158a065b4cf1 Mon Sep 17 00:00:00 2001 From: Syl Zys Date: Sun, 8 Sep 2013 16:27:38 +0200 Subject: typo corrections, thanks to Nami-Doc for re-reading --- fr-fr/python-fr.html.markdown | 66 +++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 84831772..2f10e410 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -11,8 +11,8 @@ fichier: learnpython.py --- -Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de promgrammation les plus populaires. -Je suis tombé amoureux de Python de par la clarité de sa syntaxe. C'est pratiquement du pseudo-code exécutable. +Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de programmation les plus populaires. +Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiquement du pseudo-code exécutable. Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service] @@ -21,9 +21,9 @@ Vous pourrez bientôt trouver un article pour Python 3! ```python # Une ligne simple de commentaire commence par un dièse -""" Les lignes de commenatires multipes peut être écrite - en utilisant 3 '"', et sont souvent utilisées - pour commenter +""" Les lignes de commenatires multipes peuvent être écrites + en utilisant 3 guillemets ("), et sont souvent utilisées + pour les commentaires """ #################################################### @@ -39,12 +39,12 @@ Vous pourrez bientôt trouver un article pour Python 3! 10 * 2 #=> 20 35 / 5 #=> 7 -# La division est un peu spéciale. C'est une division d' "int", et Python arrondi le résultat par défaut automatiquement. +# La division est un peu spéciale. C'est une division d'entiers, et Python arrondi le résultat par défaut automatiquement. 5 / 2 #=> 2 # Pour corriger ce problème, on utilise les float. 2.0 # Voici un float -11.0 / 4.0 #=> 2.75 ahhh...beaucoup mieux +11.0 / 4.0 #=> 2.75 ahhh... beaucoup mieux # Forcer la priorité avec les parenthèses (1 + 3) * 2 #=> 8 @@ -82,13 +82,13 @@ not False #=> True # On peut aussi les "additioner" ! "Hello " + "world!" #=> "Hello world!" -# Une chaîne peut être traiter comme une liste de caractères +# Une chaîne peut être traitée comme une liste de caractères "C'est une chaîne"[0] #=> 'C' # % peut être utilisé pour formatter des chaîne, comme ceci: "%s can be %s" % ("strings", "interpolated") -# Une nouvelle manière de formatter les chaînes de caractères est d'utiliser la méthode 'format' +# Une autre manière de formatter les chaînes de caractères est d'utiliser la méthode 'format' # C'est la méthode à privilégier "{0} peut être {1}".format("La chaîne", "formattée") # On peut utiliser des mot-clés au lieu des chiffres. @@ -102,8 +102,8 @@ None #=> None "etc" is None #=> False None is None #=> True -# L'opérateur 'is' test l'identité de l'objet. -# Ce n'est pas très utilse avec les types primitifs, mais cela peut être très util +# L'opérateur 'is' teste l'identité de l'objet. +# Ce n'est pas très utilisé avec les types primitifs, mais cela peut être très utile # lorsque l'on utilise des objets. # None, 0, et les chaînes de caractères vides valent False. @@ -116,7 +116,7 @@ None is None #=> True ## 2. Variables et Collections #################################################### -# Afficher, c'est facile +# Afficher du texte, c'est facile print "Je suis Python. Enchanté!" @@ -133,7 +133,7 @@ some_other_var # Lève une exception # Listes li = [] -# On peut utiliser une liste pré-remplie. +# On peut remplir liste dès l'instanciation other_li = [4, 5, 6] # On ajoute des éléments avec 'append' @@ -147,29 +147,29 @@ li.pop() #=> 3 et li contient [1, 2, 4] # Remettons-le dans la liste li.append(3) # li contient [1, 2, 4, 3] de nouveau. -# On accède aux éléments d'une liste comme pour un tableau. +# On accède aux éléments d'une liste comme à ceux un tableau. li[0] #=> 1 # Le dernier élément li[-1] #=> 3 -# Accèder aux indes hors limite lève une exception +# Accèder aux indices hors limite lève une exception li[4] # Lève un 'IndexError' # On peut accèder à des rangs de valeurs avec la syntaxe "slice" # (C'est un rang de type 'fermé/ouvert' pour les plus matheux) li[1:3] #=> [2, 4] -# Ne pas spécifier de début de rang +# Sans spécifier de début de rang li[2:] #=> [4, 3] -# Ne pas spécifier de fin de rang +# Sans spécifier de fin de rang li[:3] #=> [1, 2, 4] -# Retirer un élément spécifique dee la lsite avec "del" +# Retirer un élément spécifique dee la liste avec "del" del li[2] # li contient [1, 2, 3] # On peut additionner des listes entre elles li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li et other_li existent toujours à part entière -# Concatener des listes avec "extend()" +# Concaténer des listes avec "extend()" li.extend(other_li) # li vaut maintenant [1, 2, 3, 4, 5, 6] # Vérifier l'existence d'un élément dans une liste avec "in" @@ -179,7 +179,7 @@ li.extend(other_li) # li vaut maintenant [1, 2, 3, 4, 5, 6] len(li) #=> 6 -# Les "tuples", sont comme des listes, mais sont immuables. +# Les "tuples" sont comme des listes, mais sont immuables. tup = (1, 2, 3) tup[0] #=> 1 tup[0] = 3 # Lève un 'TypeError' @@ -190,15 +190,15 @@ tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) tup[:2] #=> (1, 2) 2 in tup #=> True -# Vous pouvez "dé-packager" les tupels (ou les listes) dans des variables +# Vous pouvez "dé-packager" les tuples (ou les listes) dans des variables a, b, c = (1, 2, 3) # a vaut maintenant 1, b vaut maintenant 2 and c vaut maintenant 3 # Sans parenthèses, un tuple est créé par défaut d, e, f = 4, 5, 6 -# Voyez maintenant comme il est facile d'inverse 2 valeurs +# Voyez maintenant comme il est facile d'inverser 2 valeurs e, d = d, e # d is now 5 and e is now 4 -# Dictionaires +# Dictionnaires empty_dict = {} # Un dictionnaire pré-rempli filled_dict = {"one": 1, "two": 2, "three": 3} @@ -208,8 +208,8 @@ filled_dict["one"] #=> 1 # Récupérer toutes les clés sous forme de liste avec "keys()" filled_dict.keys() #=> ["three", "two", "one"] -# Note - l'odre des clés du dictionnaire n'est pas garanti. -# Vos résultats peuvent différer de ceux ci-dessous. +# Note - l'ordre des clés du dictionnaire n'est pas garanti. +# Vos résultats peuvent différer de ceux ci-dessus. # Récupérer toutes les valeurs sous forme de liste avec "values()" filled_dict.values() #=> [3, 2, 1] @@ -219,7 +219,7 @@ filled_dict.values() #=> [3, 2, 1] "one" in filled_dict #=> True 1 in filled_dict #=> False -# Chercher une clé non existence lève une 'KeyError' +# Chercher une clé non existante lève une 'KeyError' filled_dict["four"] # KeyError # Utiliser la méthode "get()" pour éviter 'KeyError' @@ -255,7 +255,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6} # Différence de sets avec - {1,2,3,4} - {2,3,5} #=> {1, 4} -# Vérifier l'existene d'une valeur dans un set avec "in" +# Vérifier l'existence d'une valeur dans un set avec "in" 2 in filled_set #=> True 10 in filled_set #=> False @@ -273,12 +273,12 @@ if some_var > 10: print "some_var est supérieur à 10." elif some_var < 10: # La clause elif est optionnelle print "some_var iinférieur à 10." -else: # Optionnel également +else: # La clause else également print "some_var vaut 10." """ -Les boucles "for" font des itérations sur les listes +Les boucles "for" permettent d'itérer sur les listes Affiche: chien : mammifère chat : mammifère @@ -301,7 +301,7 @@ for i in range(4): print i """ -Les boucles "while" boucle jusqu'à ce qu'une condition ne soit plus vraie +Les boucles "while" boucle jusqu'à ce que leur condition ne soit plus vraie Affiche: 0 1 @@ -345,7 +345,7 @@ def varargs(*args): varargs(1, 2, 3) #=> (1,2,3) -# Ont peut également définir une fonction qui prend un nombrenumber of +# On peut également définir une fonction qui prend un nombre # variable d'arguments def keyword_args(**kwargs): return kwargs @@ -395,10 +395,10 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] ## 5. Classes #################################################### -# Une classe hérite d'un objet +# Une classe est un objet class Human(object): - # L'attribut d'une classe. Il est partagé par toutes les instances de cette classe. + # Un attribut de classe. Il est partagé par toutes les instances de cette classe. species = "H. sapiens" # Initialiseur basique -- cgit v1.2.3 From 9cc1982c484e99adfb922733cb9c0fb5768b6a77 Mon Sep 17 00:00:00 2001 From: Matthew Johnston Date: Sun, 8 Sep 2013 11:46:08 -0500 Subject: Added module extension and inclusion examples Also added examples for callbacks made when modules are included and extended. --- ruby.html.markdown | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 80682682..b9ba83cb 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -403,4 +403,55 @@ end Human.bar # 0 Doctor.bar # nil +module ModuleExample + def foo + 'foo' + end +end + +# Including modules binds the methods to the object instance +# Extending modules binds the methods to the class instance + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' + +# Callbacks when including and extending a module are executed + +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' ``` -- cgit v1.2.3 From b392e48e712e791152856ad7e72d743122154032 Mon Sep 17 00:00:00 2001 From: Adrian Espinosa Date: Sun, 8 Sep 2013 19:43:37 +0200 Subject: Working on spanish translation --- es-es/go-es.html.markdown | 299 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 299 insertions(+) create mode 100644 es-es/go-es.html.markdown diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown new file mode 100644 index 00000000..5bc4844f --- /dev/null +++ b/es-es/go-es.html.markdown @@ -0,0 +1,299 @@ +--- +name: Go +category: language +language: Go +filename: learngo.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + +translators: + - ["Adrian Espinosa", "http://www.adrianespinosa.com"] + +--- + +Go fue creado por la necesidad de hacer el trabajo rápidamente. No es la última +tendencia en informática, pero es la forma nueva y más rápida de resolver probemas reales. + +Tiene conceptos familiares de lenguajes imperativos con tipado estático. +Es rápido compilando y rápido al ejecutar, añade una concurrencia fácil de entender para las CPUs de varios núcleos de hoy en día, y tiene características que ayudan con la programación a gran escala. +Go viene con una librería estándar muy buena y una comunidad entusiasta. + +```go +// Comentario de una sola línea +/* Comentario + multi línea */ + +// La cláusula package aparece al comienzo de cada archivo fuente. +// Main es un nombre especial que declara un ejecutable en vez de una librería. +package main + +// La declaración Import declara los paquetes de librerías referenciados en este archivo. +import ( + "fmt" // Un paquete en la librería estándar de Go + "net/http" // Sí, un servidor web! + "strconv" // Conversiones de cadenas +) + +// Definición de una función. Main es especial. Es el punto de entrada para el ejecutable. +// Te guste o no, Go utiliza llaves. +func main() { + // Println imprime una línea a stdout. + // Cualificalo con el nombre del paquete, fmt. + fmt.Println("Hello world!") + + // Llama a otra función de este paquete. + beyondHello() +} + +// Las funciones llevan parámetros entre paréntesis. +// Si no hay parámetros, los paréntesis siguen siendo obligatorios. +func beyondHello() { + var x int // Declaración de una variable. Las variables se deben declarar antes de // utilizarlas. + x = 3 // Asignación de variables. + // Declaración "corta" con := para inferir el tipo, declarar y asignar. + y := 4 + sum, prod := learnMultiple(x, y) // función devuelve dos valores + fmt.Println("sum:", sum, "prod:", prod) // simple salida + learnTypes() // < y minutes, learn more! +} + +// Las funciones pueden tener parámetros y (múltiples!) valores de retorno. +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // devolver dos valores +} + +// Algunos tipos incorporados y literales. +func learnTypes() { + // La declaración corta suele darte lo que quieres. + s := "Learn Go!" // tipo cadena + + s2 := ` Un tipo cadena "puro" puede incluir +saltos de línea.` // mismo tipo cadena + + // Literal no ASCII. Los fuentes de Go son UTF-8. + g := 'Σ' // tipo rune, un alias de uint32, alberga un punto unicode. + f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit + c := 3 + 4i // complex128, representado internamente por dos float64 + // Sintaxis Var con inicializadores. + var u uint = 7 // sin signo, pero la implementación depende del tamaño como en int + var pi float32 = 22. / 7 + + // Sintáxis de conversión con una declaración corta. + n := byte('\n') // byte es un alias de uint8 + + // Los Arrays tienen un tamaño fijo a la hora de compilar. + var a4 [4]int // un array de 4 ints, inicializados a 0 + a3 := [...]int{3, 1, 5} // un array de 3 ints, inicializados como se indica + + // Los Slices tienen tamaño dinámico. Los arrays y slices tienen sus ventajas + // y desventajas pero los casos de uso para los slices son más comunes. + s3 := []int{4, 5, 9} // Comparar con a3. No hay puntos suspensivos + s4 := make([]int, 4) // Asigna slices de 4 ints, inicializados a 0 + var d2 [][]float64 // solo declaración, sin asignación + bs := []byte("a slice") // sintaxis de conversión de tipo + + p, q := learnMemory() // declares p, q to be type pointer to int. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + + // Maps are a dynamically growable associative array type, like the + // hash or dictionary types of some other languages. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // Unused variables are an error in Go. + // The underbar lets you "use" a variable but discard its value. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Output of course counts as using a variable. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // back in the flow +} + +// Go is fully garbage collected. It has pointers but no pointer arithmetic. +// You can make a mistake with a nil pointer, but not by incrementing a pointer. +func learnMemory() (p, q *int) { + // Named return values p and q have type pointer to int. + p = new(int) // built-in function new allocates memory. + // The allocated int is initialized to 0, p is no longer nil. + s := make([]int, 20) // allocate 20 ints as a single block of memory + s[3] = 7 // assign one of them + r := -2 // declare another local variable + return &s[3], &r // & takes the address of an object. +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // If statements require brace brackets, and do not require parens. + if true { + fmt.Println("told ya") + } + // Formatting is standardized by the command line command "go fmt." + if false { + // pout + } else { + // gloat + } + // Use switch in preference to chained if statements. + x := 1 + switch x { + case 0: + case 1: + // cases don't "fall through" + case 2: + // unreached + } + // Like if, for doesn't use parens either. + for x := 0; x < 3; x++ { // ++ is a statement + fmt.Println("iteration", x) + } + // x == 1 here. + + // For is the only loop statement in Go, but it has alternate forms. + for { // infinite loop + break // just kidding + continue // unreached + } + // As with for, := in an if statement means to declare and assign y first, + // then test y > x. + if y := expensiveComputation(); y > x { + x = y + } + // Function literals are closures. + xBig := func() bool { + return x > 100 // references x declared above switch statement. + } + fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x) + x /= 1e5 // this makes it == 10 + fmt.Println("xBig:", xBig()) // false now + + // When you need it, you'll love it. + goto love +love: + + learnInterfaces() // Good stuff coming up! +} + +// Define Stringer as an interface type with one method, String. +type Stringer interface { + String() string +} + +// Define pair as a struct with two fields, ints named x and y. +type pair struct { + x, y int +} + +// Define a method on type pair. Pair now implements Stringer. +func (p pair) String() string { // p is called the "receiver" + // Sprintf is another public function in package fmt. + // Dot syntax references fields of p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // Brace syntax is a "struct literal." It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. + p := pair{3, 4} + fmt.Println(p.String()) // call String method of p, of type pair. + var i Stringer // declare i of interface type Stringer. + i = p // valid because pair implements Stringer + // Call String method of i, of type Stringer. Output same as above. + fmt.Println(i.String()) + + // Functions in the fmt package call the String method to ask an object + // for a printable representation of itself. + fmt.Println(p) // output same as above. Println calls String method. + fmt.Println(i) // output same as above + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" idiom used to tell if something worked or not. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. + fmt.Println("no one there") + } else { + fmt.Print(x) // x would be the value, if it were in the map. + } + // An error value communicates not just "ok" but more about the problem. + if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value + // prints "strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // We'll revisit interfaces a little later. Meanwhile, + learnConcurrency() +} + +// c is a channel, a concurrency-safe communication object. +func inc(i int, c chan int) { + c <- i + 1 // <- is the "send" operator when a channel appears on the left. +} + +// We'll use inc to increment some numbers concurrently. +func learnConcurrency() { + // Same make function used earlier to make a slice. Make allocates and + // initializes slices, maps, and channels. + c := make(chan int) + // Start three concurrent goroutines. Numbers will be incremented + // concurrently, perhaps in parallel if the machine is capable and + // properly configured. All three send to the same channel. + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) + // Read three results from the channel and print them out. + // There is no telling in what order the results will arrive! + fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. + + cs := make(chan string) // another channel, this one handles strings. + cc := make(chan chan string) // a channel of string channels. + go func() { c <- 84 }() // start a new goroutine just to send a value + go func() { cs <- "wordy" }() // again, for cs this time + // Select has syntax like a switch statement but each case involves + // a channel operation. It selects a case at random out of the cases + // that are ready to communicate. + select { + case i := <-c: // the value received can be assigned to a variable + fmt.Printf("it's a %T", i) + case <-cs: // or the value received can be discarded + fmt.Println("it's a string") + case <-cc: // empty channel, not ready for communication. + fmt.Println("didn't happen.") + } + // At this point a value was taken from either c or cs. One of the two + // goroutines started above has completed, the other will remain blocked. + + learnWebProgramming() // Go does it. You want to do it too. +} + +// A single function from package http starts a web server. +func learnWebProgramming() { + // ListenAndServe first parameter is TCP address to listen at. + // Second parameter is an interface, specifically http.Handler. + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // don't ignore errors +} + +// Make pair an http.Handler by implementing its only method, ServeHTTP. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Serve data with a method of http.ResponseWriter + w.Write([]byte("You learned Go in Y minutes!")) +} +``` + +## Further Reading + +The root of all things Go is the [official Go web site](http://golang.org/). +There you can follow the tutorial, play interactively, and read lots. + +The language definition itself is highly recommended. It's easy to read +and amazingly short (as language definitions go these days.) + +On the reading list for students of Go is the source code to the standard +library. Comprehensively documented, it demonstrates the best of readable +and understandable Go, Go style, and Go idioms. Click on a function name +in the documentation and the source code comes up! + -- cgit v1.2.3 From 4f0206f5aa373bf477bf88d62df720656d3aca2e Mon Sep 17 00:00:00 2001 From: Matthew Johnston Date: Sun, 8 Sep 2013 15:31:46 -0500 Subject: Fixed line wrapping --- php.html.markdown | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 0caa07b6..1952d833 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -107,7 +107,7 @@ echo 'This string ' . 'is concatenated'; /******************************** * Constants */ - + // A constant is defined by using define() // and can never be changed during runtime! @@ -143,7 +143,7 @@ echo $array[0]; // => "One" $array[] = 'Four'; // Remove element from array -unset($array[3]); +unset($array[3]); /******************************** * Output @@ -455,8 +455,10 @@ class MyClass // Static variables and their visibility public static $publicStaticVar = 'publicStatic'; - private static $privateStaticVar = 'privateStatic'; // Accessible within the class only - protected static $protectedStaticVar = 'protectedStatic'; // Accessible from the class and subclasses + // Accessible within the class only + private static $privateStaticVar = 'privateStatic'; + // Accessible from the class and subclasses + protected static $protectedStaticVar = 'protectedStatic'; // Properties must declare their visibility public $property = 'public'; @@ -476,14 +478,15 @@ class MyClass print 'MyClass'; } - //final keyword would make a function unoverridable + //final keyword would make a function unoverridable final function youCannotOverrideMe() { } /* -Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. -A property declared as static can not be accessed with an instantiated class object (though a static method can). + * Declaring class properties or methods as static makes them accessible without + * needing an instantiation of the class. A property declared as static can not + * be accessed with an instantiated class object (though a static method can). */ public static function myStaticMethod() @@ -674,10 +677,14 @@ $cls = new SomeOtherNamespace\MyClass(); ## More Information -Visit the [official PHP documentation](http://www.php.net/manual/) for reference and community input. +Visit the [official PHP documentation](http://www.php.net/manual/) for reference +and community input. -If you're interested in up-to-date best practices, visit [PHP The Right Way](http://www.phptherightway.com/). +If you're interested in up-to-date best practices, visit +[PHP The Right Way](http://www.phptherightway.com/). -If you're coming from a language with good package management, check out [Composer](http://getcomposer.org/). +If you're coming from a language with good package management, check out +[Composer](http://getcomposer.org/). -For common standards, visit the PHP Framework Interoperability Group's [PSR standards](https://github.com/php-fig/fig-standards). +For common standards, visit the PHP Framework Interoperability Group's +[PSR standards](https://github.com/php-fig/fig-standards). -- cgit v1.2.3 From 3ea52a10845e8e6a052443c12abdc012534c6210 Mon Sep 17 00:00:00 2001 From: Wesley Hill Date: Mon, 9 Sep 2013 01:30:43 +0100 Subject: corrected issue on floating point literals. --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 926a4a0d..1ed0ed58 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -80,7 +80,7 @@ int main (int argc, const char * argv[]) NSLog(@"%f", piFloat); NSNumber *piDoubleNumber = @3.1415926535; - piDouble = [piDoubleNumber doubleValue]; + double piDouble = [piDoubleNumber doubleValue]; NSLog(@"%f", piDouble); // BOOL literals -- cgit v1.2.3 From a933d419e07fd8af6effa89200b581e904c61679 Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 8 Sep 2013 21:52:47 -0700 Subject: Some fixes --- de-de/bash-de.html.markdown | 2 +- de-de/git-de.html.markdown | 2 +- de-de/javascript-de.html.markdown | 2 +- go.html.markdown | 2 +- zh-cn/go-zh.html.markdown | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index 9e3d7bc8..7b60d79f 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -1,4 +1,4 @@ ---- +--- category: tool tool: bash lang: de-de diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index 10deefd5..c7b6ad86 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -1,4 +1,4 @@ ---- +--- category: tool tool: git contributors: diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index d767815e..1855ebf2 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -1,4 +1,4 @@ ---- +--- language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] diff --git a/go.html.markdown b/go.html.markdown index 3a3800dd..6eb8d57d 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -1,4 +1,4 @@ ---- +--- name: Go category: language language: Go diff --git a/zh-cn/go-zh.html.markdown b/zh-cn/go-zh.html.markdown index 0af5bbe3..2cff089b 100644 --- a/zh-cn/go-zh.html.markdown +++ b/zh-cn/go-zh.html.markdown @@ -1,7 +1,7 @@ --- language: Go lang: zh-cn -filename: learngo.go +filename: learngo-cn.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["pantaovay", "https://github.com/pantaovay"] -- cgit v1.2.3 From 3cf89d514689ca8610c30171424b2ce1908c0465 Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 8 Sep 2013 22:05:15 -0700 Subject: Updated new contributions --- de-de/elixir-de.html.markdown | 3 ++- de-de/javascript-de.html.markdown | 1 + de-de/python-de.html.markdown | 1 + fr-fr/python-fr.html.markdown | 10 +++------- neat.html.markdown | 2 -- pt-br/erlang-pt.html.markdown | 1 + pt-br/go-pt.html.markdown | 2 +- pt-br/ruby-pt.html.markdown | 1 + pt-pt/git-pt.html.markdown | 2 ++ zh-cn/perl-cn.html.markdown | 3 ++- 10 files changed, 14 insertions(+), 12 deletions(-) diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown index 5f89e1f5..26f6168b 100644 --- a/de-de/elixir-de.html.markdown +++ b/de-de/elixir-de.html.markdown @@ -2,6 +2,7 @@ language: elixir contributors: - ["Joao Marques", "http://github.com/mrshankly"] +translators: - ["Gregor Große-Bölting", "http://www.ideen-und-soehne.de"] filename: learnelixir-de.ex --- @@ -414,4 +415,4 @@ self() #=> #PID<0.27.0> * [Getting started guide](http://elixir-lang.org/getting_started/1.html) auf der [elixir Website](http://elixir-lang.org) * [Elixir Documentation](http://elixir-lang.org/docs/master/) * ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) von Fred Hebert -* "Programming Erlang: Software for a Concurrent World" von Joe Armstrong \ No newline at end of file +* "Programming Erlang: Software for a Concurrent World" von Joe Armstrong diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index 1855ebf2..0418b2b6 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -2,6 +2,7 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] +translators: - ["ggb", "http://www.ideen-und-soehne.de"] filename: learnjavascript-de.js lang: de-de diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 7462d5f6..5ddb6f4b 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -2,6 +2,7 @@ language: python contributors: - ["Louie Dinh", "http://ldinh.ca"] +translators: - ["kultprok", "http:/www.kulturproktologie.de"] filename: learnpython-de.py lang: de-de diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 2f10e410..f9b98d41 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -1,14 +1,10 @@ --- langage: python - -contributeurs: +contributors: - ["Louie Dinh", "http://ldinh.ca"] - -traducteurs: +translators: - ["Sylvain Zyssman", "https://github.com/sylzys"] - -fichier: learnpython.py - +filename: learnpython-fr.py --- Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de programmation les plus populaires. diff --git a/neat.html.markdown b/neat.html.markdown index 6a319a7d..58c2224d 100644 --- a/neat.html.markdown +++ b/neat.html.markdown @@ -1,10 +1,8 @@ --- - language: neat contributors: - ["Feep", "https://github.com/FeepingCreature"] filename: LearnNeat.nt - --- Neat is basically a smaller version of D1 with some experimental syntax and a focus on terseness without losing the basic C-like syntax. diff --git a/pt-br/erlang-pt.html.markdown b/pt-br/erlang-pt.html.markdown index 6a86aafc..a81e5a1f 100644 --- a/pt-br/erlang-pt.html.markdown +++ b/pt-br/erlang-pt.html.markdown @@ -3,6 +3,7 @@ language: erlang filename: learnerlang-pt.erl contributors: - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] +translators: - ["Guilherme Heuser Prestes", "http://twitter.com/gprestes"] lang: pt-br --- diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown index 41a02c37..cca58b16 100644 --- a/pt-br/go-pt.html.markdown +++ b/pt-br/go-pt.html.markdown @@ -3,7 +3,7 @@ name: Go category: language language: Go filename: learngo-pt.go -lang: pt-pt +lang: pt-br contributors: - ["Sonia Keys", "https://github.com/soniakeys"] translators: diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 484bb0dd..a2f40c3b 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -4,6 +4,7 @@ lang: br-pt filename: learnruby.rb contributors: - ["Bruno Henrique - Garu", "http://garulab.com"] +translators: - ["Katyanna Moura", "https://twitter.com/amelie_kn"] --- diff --git a/pt-pt/git-pt.html.markdown b/pt-pt/git-pt.html.markdown index 213f1ad3..66cda07f 100644 --- a/pt-pt/git-pt.html.markdown +++ b/pt-pt/git-pt.html.markdown @@ -4,6 +4,8 @@ tool: git lang: pt-pt filename: LearnGit.txt contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: - ["Rafael Jegundo", "http://rafaeljegundo.github.io/"] --- diff --git a/zh-cn/perl-cn.html.markdown b/zh-cn/perl-cn.html.markdown index 8f99ccbf..5b0d6179 100644 --- a/zh-cn/perl-cn.html.markdown +++ b/zh-cn/perl-cn.html.markdown @@ -2,11 +2,12 @@ name: perl category: language language: perl -filename: learnperl.pl +filename: learnperl-cn.pl contributors: - ["Korjavin Ivan", "http://github.com/korjavin"] translators: - ["Yadong Wen", "https://github.com/yadongwen"] +lang: zh-cn --- Perl 5是一个功能强大、特性齐全的编程语言,有25年的历史。 -- cgit v1.2.3 From b28900b889c27f8500a44d9f9bcad5244f1f79bd Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 8 Sep 2013 22:52:09 -0700 Subject: Fixed up so it builds --- de-de/elixir-de.html.markdown | 2 +- fr-fr/python-fr.html.markdown | 8 +++++--- ko-kr/lua-kr.html.markdown | 3 --- matlab.html.markdown | 5 +---- neat.html.markdown | 2 +- ro-ro/python-ro.html.markdown | 3 ++- zh-cn/go-zh.html.markdown | 2 +- 7 files changed, 11 insertions(+), 14 deletions(-) diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown index 26f6168b..ecd74dcb 100644 --- a/de-de/elixir-de.html.markdown +++ b/de-de/elixir-de.html.markdown @@ -1,4 +1,4 @@ ---- +--- language: elixir contributors: - ["Joao Marques", "http://github.com/mrshankly"] diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index f9b98d41..2bf0afd0 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -1,10 +1,12 @@ --- -langage: python +language: python +filename: learnpython-fr.py contributors: - - ["Louie Dinh", "http://ldinh.ca"] + - ["Louie Dinh", "http://ldinh.ca"] translators: - ["Sylvain Zyssman", "https://github.com/sylzys"] -filename: learnpython-fr.py + - ["Nami-Doc", "https://github.com/Nami-Doc"] +lang: fr-fr --- Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de programmation les plus populaires. diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index c40d9ab0..862c47a7 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -361,9 +361,6 @@ local mod = require('mod') -- mod.lua 파일을 실행 -- require는 모듈을 포함시키는 표준화된 방법입니다. -- require는 다음과 같이 동작합니다: (캐싱돼 있지 않을 경우. 하단 참조) -local mod = (function () - -end)() -- mod.lua가 함수의 본문처럼 되므로 mod.lua 안의 지역 멤버는 -- 밖에서 볼 수 없습니다. diff --git a/matlab.html.markdown b/matlab.html.markdown index 3bcc4bbc..3c909153 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -10,10 +10,7 @@ If you have any feedback please feel free to reach me at [@the_ozzinator](https://twitter.com/the_ozzinator), or [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). -```Matlab - - - +```matlab % Comments start with a percent sign. %{ Multi line comments look diff --git a/neat.html.markdown b/neat.html.markdown index 58c2224d..e99d1e0e 100644 --- a/neat.html.markdown +++ b/neat.html.markdown @@ -9,7 +9,7 @@ Neat is basically a smaller version of D1 with some experimental syntax and a fo [Read more here.](https://github.com/FeepingCreature/fcc/wiki) -```D +```c // single line comments start with // /* multiline comments look like this diff --git a/ro-ro/python-ro.html.markdown b/ro-ro/python-ro.html.markdown index 36ea78ec..125ba2f4 100644 --- a/ro-ro/python-ro.html.markdown +++ b/ro-ro/python-ro.html.markdown @@ -3,8 +3,9 @@ language: python contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - - ["Ovidiu Ciule", "https://github.com/ociule"] lang: ro-ro filename: python-ro.html.markdown + - ["Ovidiu Ciule", "https://github.com/ociule"] filename: learnpython-ro.py +lang: ro-ro --- Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a devenit astăzi unul din diff --git a/zh-cn/go-zh.html.markdown b/zh-cn/go-zh.html.markdown index 2cff089b..7cc9c171 100644 --- a/zh-cn/go-zh.html.markdown +++ b/zh-cn/go-zh.html.markdown @@ -13,7 +13,7 @@ Go拥有命令式语言的静态类型,编译很快,执行也很快,同时 Go语言有非常棒的标准库,还有一个充满热情的社区。 -```Go +```go // 单行注释 /* 多行 注释 */ -- cgit v1.2.3 From 38ff402322c0fd4fefbd2277bfba982e4bb011de Mon Sep 17 00:00:00 2001 From: Adrian Espinosa Date: Mon, 9 Sep 2013 16:40:07 +0200 Subject: Half done through the translation I need moar time gosh >.< --- es-es/go-es.html.markdown | 89 ++++++++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 44 deletions(-) diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 5bc4844f..52f9fc5b 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -48,7 +48,8 @@ func main() { // Las funciones llevan parámetros entre paréntesis. // Si no hay parámetros, los paréntesis siguen siendo obligatorios. func beyondHello() { - var x int // Declaración de una variable. Las variables se deben declarar antes de // utilizarlas. + var x int // Declaración de una variable. Las variables se deben declarar antes de + // utilizarlas. x = 3 // Asignación de variables. // Declaración "corta" con := para inferir el tipo, declarar y asignar. y := 4 @@ -92,33 +93,33 @@ saltos de línea.` // mismo tipo cadena var d2 [][]float64 // solo declaración, sin asignación bs := []byte("a slice") // sintaxis de conversión de tipo - p, q := learnMemory() // declares p, q to be type pointer to int. - fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + p, q := learnMemory() // declara p, q para ser un tipo puntero a int. + fmt.Println(*p, *q) // * sigue un puntero. Esto imprime dos ints. - // Maps are a dynamically growable associative array type, like the - // hash or dictionary types of some other languages. + // Los Maps son arrays asociativos dinámicos, como los hash o diccionarios + // de otros lenguajes m := map[string]int{"three": 3, "four": 4} m["one"] = 1 - // Unused variables are an error in Go. - // The underbar lets you "use" a variable but discard its value. + // Las variables no utilizadas en Go producen error. + // El guión bajo permite "utilizar" una variable, pero descartar su valor. _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs - // Output of course counts as using a variable. + // Esto cuenta como utilización de variables. fmt.Println(s, c, a4, s3, d2, m) - learnFlowControl() // back in the flow + learnFlowControl() // vuelta al flujo } -// Go is fully garbage collected. It has pointers but no pointer arithmetic. -// You can make a mistake with a nil pointer, but not by incrementing a pointer. +// Go posee recolector de basura. Tiene puntero pero no aritmética de punteros. +// Puedes cometer un errores con un puntero nil, pero no incrementando un puntero. func learnMemory() (p, q *int) { - // Named return values p and q have type pointer to int. - p = new(int) // built-in function new allocates memory. - // The allocated int is initialized to 0, p is no longer nil. - s := make([]int, 20) // allocate 20 ints as a single block of memory - s[3] = 7 // assign one of them - r := -2 // declare another local variable - return &s[3], &r // & takes the address of an object. + // q y p tienen un tipo puntero a int. + p = new(int) // función incorporada que asigna memoria. + // La asignación de int se inicializa a 0, p ya no es nil. + s := make([]int, 20) // asigna 20 ints a un solo bloque de memoria. + s[3] = 7 // asignar uno de ellos + r := -2 // declarar otra variable local + return &s[3], &r // & toma la dirección de un objeto. } func expensiveComputation() int { @@ -126,69 +127,69 @@ func expensiveComputation() int { } func learnFlowControl() { - // If statements require brace brackets, and do not require parens. + // La declaración If requiere llaves, pero no paréntesis. if true { fmt.Println("told ya") } - // Formatting is standardized by the command line command "go fmt." + // El formato está estandarizado por el comando "go fmt." if false { // pout } else { // gloat } - // Use switch in preference to chained if statements. + // Utiliza switch preferiblemente para if encadenados. x := 1 switch x { case 0: case 1: - // cases don't "fall through" + // los cases no se mezclan, no requieren de "break" case 2: - // unreached + // no llega } - // Like if, for doesn't use parens either. - for x := 0; x < 3; x++ { // ++ is a statement + // Como if, for no utiliza paréntesis tampoco. + for x := 0; x < 3; x++ { // ++ es una sentencia fmt.Println("iteration", x) } - // x == 1 here. + // x == 1 aqui. - // For is the only loop statement in Go, but it has alternate forms. - for { // infinite loop - break // just kidding - continue // unreached + // For es la única sentencia de bucle en Go, pero tiene formas alternativas. + for { // bucle infinito + break // solo bromeaba! + continue // no llega } - // As with for, := in an if statement means to declare and assign y first, - // then test y > x. + // Como en for, := en una sentencia if significa declarar y asignar primero, + // luego comprobar y > x. if y := expensiveComputation(); y > x { x = y } - // Function literals are closures. + // Los literales de funciones son "closures". xBig := func() bool { - return x > 100 // references x declared above switch statement. + return x > 100 // referencia a x declarada encima de la sentencia switch. } - fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x) - x /= 1e5 // this makes it == 10 - fmt.Println("xBig:", xBig()) // false now + fmt.Println("xBig:", xBig()) // verdadero (la última vez asignamos 1e6 a x) + x /= 1e5 // esto lo hace == 10 + fmt.Println("xBig:", xBig()) // ahora es falso - // When you need it, you'll love it. + // Cuando lo necesites, te encantará. goto love love: - learnInterfaces() // Good stuff coming up! + learnInterfaces() // Buen material dentro de poco! } -// Define Stringer as an interface type with one method, String. +// Define Stringer como un tipo interfaz con un método, String. type Stringer interface { String() string } -// Define pair as a struct with two fields, ints named x and y. +// Define pair como un struct con dos campos int, x e y. type pair struct { x, y int } -// Define a method on type pair. Pair now implements Stringer. -func (p pair) String() string { // p is called the "receiver" - // Sprintf is another public function in package fmt. +// Define un método del tipo pair. Pair ahora implementa Stringer. +func (p pair) String() string { // p se llama "recibidor" + // Sprintf es otra función pública del paquete fmt. // Dot syntax references fields of p. return fmt.Sprintf("(%d, %d)", p.x, p.y) } -- cgit v1.2.3 From f9b2c181a3b6e5fe67c965f11addc8e5a907b2bd Mon Sep 17 00:00:00 2001 From: Adrian Espinosa Date: Tue, 10 Sep 2013 00:42:39 +0200 Subject: Go spanish translation. --- es-es/go-es.html.markdown | 122 +++++++++++++++++++++++----------------------- 1 file changed, 61 insertions(+), 61 deletions(-) diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 52f9fc5b..f2b069d6 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -8,11 +8,11 @@ contributors: translators: - ["Adrian Espinosa", "http://www.adrianespinosa.com"] - +lang: es-es --- Go fue creado por la necesidad de hacer el trabajo rápidamente. No es la última -tendencia en informática, pero es la forma nueva y más rápida de resolver probemas reales. +tendencia en informática, pero es la forma nueva y más rápida de resolver problemas reales. Tiene conceptos familiares de lenguajes imperativos con tipado estático. Es rápido compilando y rápido al ejecutar, añade una concurrencia fácil de entender para las CPUs de varios núcleos de hoy en día, y tiene características que ayudan con la programación a gran escala. @@ -190,111 +190,111 @@ type pair struct { // Define un método del tipo pair. Pair ahora implementa Stringer. func (p pair) String() string { // p se llama "recibidor" // Sprintf es otra función pública del paquete fmt. - // Dot syntax references fields of p. + // La sintaxis con punto referencia campos de p. return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { - // Brace syntax is a "struct literal." It evaluates to an initialized - // struct. The := syntax declares and initializes p to this struct. + // La sintaxis de llaves es un "literal struct". Evalúa a un struct + // inicializado. La sintaxis := declara e inicializa p a este struct. p := pair{3, 4} - fmt.Println(p.String()) // call String method of p, of type pair. - var i Stringer // declare i of interface type Stringer. - i = p // valid because pair implements Stringer - // Call String method of i, of type Stringer. Output same as above. + fmt.Println(p.String()) // llamar al método String de p, de tipo pair. + var i Stringer // declarar i como interfaz tipo Stringer. + i = p // válido porque pair implementa Stringer + // Llamar al metodo String de i, de tipo Stringer. Misma salida que arriba fmt.Println(i.String()) - // Functions in the fmt package call the String method to ask an object - // for a printable representation of itself. - fmt.Println(p) // output same as above. Println calls String method. - fmt.Println(i) // output same as above + // Las funciones en el paquete fmt llaman al método String para preguntar a un objeto + // por una versión imprimible de si mismo + fmt.Println(p) // salida igual que arriba. Println llama al método String. + fmt.Println(i) // salida igual que arriba. learnErrorHandling() } func learnErrorHandling() { - // ", ok" idiom used to tell if something worked or not. + // ", ok" forma utilizada para saber si algo funcionó o no. m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. + if x, ok := m[1]; !ok { // ok será falso porque 1 no está en el map. fmt.Println("no one there") } else { - fmt.Print(x) // x would be the value, if it were in the map. + fmt.Print(x) // x sería el valor, si estuviera en el map. } - // An error value communicates not just "ok" but more about the problem. - if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value - // prints "strconv.ParseInt: parsing "non-int": invalid syntax" + // Un valor de error comunica más información sobre el problema aparte de "ok". + if _, err := strconv.Atoi("non-int"); err != nil { // _ descarta el valor + // imprime "strconv.ParseInt: parsing "non-int": invalid syntax" fmt.Println(err) } - // We'll revisit interfaces a little later. Meanwhile, + // Revisarmeos las interfaces más tarde. Mientras tanto, learnConcurrency() } -// c is a channel, a concurrency-safe communication object. +// c es un canal, un objeto de comunicación de concurrencia segura. func inc(i int, c chan int) { - c <- i + 1 // <- is the "send" operator when a channel appears on the left. + c <- i + 1 // <- es el operador "enviar" cuando un canal aparece a la izquierda. } -// We'll use inc to increment some numbers concurrently. +// Utilizaremos inc para incrementar algunos números concurrentemente. func learnConcurrency() { - // Same make function used earlier to make a slice. Make allocates and - // initializes slices, maps, and channels. + // Misma función make utilizada antes para crear un slice. Make asigna e + // inicializa slices, maps, y channels. c := make(chan int) - // Start three concurrent goroutines. Numbers will be incremented - // concurrently, perhaps in parallel if the machine is capable and - // properly configured. All three send to the same channel. - go inc(0, c) // go is a statement that starts a new goroutine. + // Iniciar tres goroutines concurrentes. Los números serán incrementados + // concurrentemente, quizás en paralelo si la máquina es capaz y + // está correctamente configurada. Las tres envían al mismo channel. + go inc(0, c) // go es una sentencia que inicia una nueva goroutine. go inc(10, c) go inc(-805, c) - // Read three results from the channel and print them out. - // There is no telling in what order the results will arrive! - fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. - - cs := make(chan string) // another channel, this one handles strings. - cc := make(chan chan string) // a channel of string channels. - go func() { c <- 84 }() // start a new goroutine just to send a value - go func() { cs <- "wordy" }() // again, for cs this time - // Select has syntax like a switch statement but each case involves - // a channel operation. It selects a case at random out of the cases - // that are ready to communicate. + // Leer los tres resultados del channel e imprimirlos. + // No se puede saber en que orden llegarán los resultados! + fmt.Println(<-c, <-c, <-c) // channel a la derecha, <- es el operador "recibir". + + cs := make(chan string) // otro channel, este gestiona cadenas. + cc := make(chan chan string) // un channel de cadenas de channels. + go func() { c <- 84 }() // iniciar una nueva goroutine solo para enviar un valor. + go func() { cs <- "wordy" }() // otra vez, para cs en esta ocasión + // Select tiene una sintáxis parecida a la sentencia switch pero cada caso involucra + // una operacion de channels. Selecciona un caso de forma aleatoria de los casos + // que están listos para comunicarse. select { - case i := <-c: // the value received can be assigned to a variable + case i := <-c: // el valor recibido puede ser asignado a una variable fmt.Printf("it's a %T", i) - case <-cs: // or the value received can be discarded + case <-cs: // o el valor puede ser descartado fmt.Println("it's a string") - case <-cc: // empty channel, not ready for communication. + case <-cc: // channel vacío, no está listo para la comunicación. fmt.Println("didn't happen.") } - // At this point a value was taken from either c or cs. One of the two - // goroutines started above has completed, the other will remain blocked. + // En este punto un valor fue devuelvto de c o cs. Uno de las dos + // goroutines que se iniciaron se ha completado, la otrá permancerá bloqueada. - learnWebProgramming() // Go does it. You want to do it too. + learnWebProgramming() // Go lo hace. Tu también quieres hacerlo. } -// A single function from package http starts a web server. +// Una simple función del paquete http inicia un servidor web. func learnWebProgramming() { - // ListenAndServe first parameter is TCP address to listen at. - // Second parameter is an interface, specifically http.Handler. + // El primer parámetro de la direccinón TCP a la que escuchar. + // El segundo parámetro es una interfaz, concretamente http.Handler. err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // don't ignore errors + fmt.Println(err) // no ignorar errores } -// Make pair an http.Handler by implementing its only method, ServeHTTP. +// Haz pair un http.Handler implementando su único método, ServeHTTP. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Serve data with a method of http.ResponseWriter + // Servir datos con un método de http.ResponseWriter w.Write([]byte("You learned Go in Y minutes!")) } ``` -## Further Reading +## Para leer más -The root of all things Go is the [official Go web site](http://golang.org/). -There you can follow the tutorial, play interactively, and read lots. +La raíz de todas las cosas de Go es la [web oficial de Go](http://golang.org/). +Ahí puedes seguir el tutorial, jugar interactivamente y leer mucho. -The language definition itself is highly recommended. It's easy to read -and amazingly short (as language definitions go these days.) +La propia definición del lenguaje también está altamente recomendada. Es fácil de leer +e increíblemente corta (como otras definiciones de lenguajes hoy en día) -On the reading list for students of Go is the source code to the standard -library. Comprehensively documented, it demonstrates the best of readable -and understandable Go, Go style, and Go idioms. Click on a function name -in the documentation and the source code comes up! +En la lista de lectura de estudiantes de Go está el código fuente de la +librería estándar. Muy bien documentada, demuestra lo mejor de Go leíble, comprendible, +estilo Go y formas Go. Pincha en el nombre de una función en la documentación +y te aparecerá el código fuente! -- cgit v1.2.3 From 2ab5910d38224a2d529bcbf249b32018b5eceabd Mon Sep 17 00:00:00 2001 From: Adrian Espinosa Date: Tue, 10 Sep 2013 00:44:29 +0200 Subject: Spanish translation fix. --- es-es/go-es.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index f2b069d6..6f65a6ad 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -5,10 +5,11 @@ language: Go filename: learngo.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - translators: - ["Adrian Espinosa", "http://www.adrianespinosa.com"] lang: es-es + + --- Go fue creado por la necesidad de hacer el trabajo rápidamente. No es la última -- cgit v1.2.3 From 3f9ba06563c580c4795228a822475bf305d5b694 Mon Sep 17 00:00:00 2001 From: jeroenransijn Date: Wed, 11 Sep 2013 15:51:21 +0200 Subject: Note aboute setTimeout --- javascript.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index bc2a973a..859d61a9 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -219,6 +219,7 @@ function myFunction(){ // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000); +// Note: setTimeout isn't part of the JS language, but is provided by browsers and Node.js. // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. -- cgit v1.2.3 From 5d6866f39b0651925b72caea72d615587d606e04 Mon Sep 17 00:00:00 2001 From: Artem Medeusheyev Date: Thu, 12 Sep 2013 09:31:22 +0600 Subject: [go/ru-ru] russian translation for Go language --- ru-ru/go-ru.html.markdown | 305 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 305 insertions(+) create mode 100644 ru-ru/go-ru.html.markdown diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown new file mode 100644 index 00000000..16193ec8 --- /dev/null +++ b/ru-ru/go-ru.html.markdown @@ -0,0 +1,305 @@ +--- +name: Go +category: language +language: Go +filename: learngo-ru.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Artem Medeusheyev", "https://github.com/armed"] +lang: ru-ru +--- + +Go - это язык общего назначения, целью которого является удобство, простота, +конкуррентность. Это не тренд в компьютерных науках, а новейший и быстрый +способ решать насущные проблемы. + +Концепции Go схожи с другими императивными статически типизированными языками. +Быстро компилируются и быстро выполняются, имеет легкие в понимании конструкции +для создания масштабируемых и многопоточных программ. + +Имеет в наличии отличную стандартную библиотеку и большое комьюнити, полное +энтузиазтов. + +```go +// Однострочный комментарий +/* Многострочный + комментарий */ + +// Ключевое слово package присутствует в начале каждого файла. +// Main это специальное имя, обозначающее исполняемый файл, нежели библиотеку. +package main + +// Import предназначен для указания зависимостей этого файла. +import ( + "fmt" // Пакет в стандартной библиотеке Go + "net/http" // Да, это web server! + "strconv" // Конвертирование типов в строки и обратно +) + +// Объявление функции. Main это специальная функция, служащая точкой входа для +// исполняемой программы. Нравится вам или нет, но Go использует фигурные +// скобки. +func main() { + // Println выводит строку в stdout. + // В данном случае фигурирует вызов функции из пакета fmt. + fmt.Println("Hello world!") + + // Вызов другой функции из текущего пакета. + beyondHello() +} + +// Функции содержат входные параметры в круглых скобках. +// Если параметров нет, пустые скобки все равно обязательны. +func beyondHello() { + var x int // Переменные должны быть объявлены до их использования. + x = 3 // Присвоение значения переменной. + // Краткое определение := позволяет объявить перменную с автоматической + // подстановкой типа из значения. + y := 4 + sum, prod := learnMultiple(x, y) // функция возвращает два значения + fmt.Println("sum:", sum, "prod:", prod) // простой вывод + learnTypes() // < y minutes, learn more! +} + +// Функция имеющая входные параметры и возврат нескольких значений. +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // возврат двух результатов +} + +// Некотрые встроенные типы и литералы. +func learnTypes() { + // Краткое определение переменной говорит само за себя. + s := "Learn Go!" // тип string + + s2 := `"Чистый" строковой литерал +может содержать переносы строк` // тоже тип данных string + + // символ не из ASCII. Исходный код Go в кодировке UTF-8. + g := 'Σ' // тип rune, это алиас для типа uint32, содержит юникод символ + + f := 3.14195 // float64, 64-х битное число с плавающей точкой (IEEE-754) + c := 3 + 4i // complex128, внутри себя содержит два float64 + + // Синтаксис var с инициализациями + var u uint = 7 // беззнаковое, но размер зависит от реализации, как и у int + var pi float32 = 22. / 7 + + // Синтаксис приведения типа с кратким определением + n := byte('\n') // byte алиас для uint8 + + // Массивы (Array) имеют фиксированный размер на момент компиляции. + var a4 [4]int // массив из 4-х int, проинициализирован нулями + a3 := [...]int{3, 1, 5} // массив из 3-х int, ручная инициализация + + // Slice имеют динамическую длину. И массивы и slice-ы имеют каждый свои + // преимущества, но slice-ы используются гораздо чаще. + s3 := []int{4, 5, 9} // по сравнению с a3 тут нет троеточия + s4 := make([]int, 4) // выделение памяти для slice из 4-х int (нули) + var d2 [][]float64 // только объявление, память не выделяется + bs := []byte("a slice") // конвертирование строки в slice байтов + + p, q := learnMemory() // объявление p и q как указателей на int. + fmt.Println(*p, *q) // * извлекает указатель. Печатает два int-а. + + // Map как словарь или хеш теблица из других языков является динамически + // растущим ассоциативным массивом. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // Неиспользуемые переменные в Go являются ошибкой. + // Нижнее подчеркивание позволяет игнорировать такие переменные. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Вывод считается использованием переменной. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // идем далее +} + +// У Go есть полноценный сборщик мусора. В нем есть указатели но нет арифметики +// указатеей. Вы можете допустить ошибку с указателем на nil, но не с его +// инкрементацией. +func learnMemory() (p, q *int) { + // Именованные возвращаемые значения p и q являются указателями на int. + p = new(int) // встроенная функция new выделяет память. + // Выделенный int проинициализирован нулем, p больше не содержит nil. + s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов, + s[3] = 7 // назначение одному из них, + r := -2 // опредление еще одной локальной переменной, + return &s[3], &r // амперсанд обозначает получение адреса переменной. +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // If-ы всегда требуют наличине фигурных скобок, но круглые скобки + // необязательны. + if true { + fmt.Println("told ya") + } + // Форматирование кода стандартизировано утилитой "go fmt". + if false { + // все тлен + } else { + // жизнь прекрасна + } + // Использоване switch на замену нескольким if-else + x := 1 + switch x { + case 0: + case 1: + // case-ы в Go не проваливаются, т.е. break по умолчанию + case 2: + // не выполнится + } + // For, как и if не требует круглых скобок + for x := 0; x < 3; x++ { // ++ это операция + fmt.Println("итерация", x) + } + // тут x == 1. + + // For это единственный цикл в Go, но у него несколько форм. + for { // бесконечный цикл + break // не такой уж и бесконечный + continue // не выполнится + } + // Как и в for, := в if-е означает объявление и присвоение значения y, + // затем проверка y > x. + if y := expensiveComputation(); y > x { + x = y + } + // Функции являются замыканиями. + xBig := func() bool { + return x > 100 // ссылается на x, объявленый выше switch. + } + fmt.Println("xBig:", xBig()) // true (т.к. мы присвоили x = 1e6) + x /= 1e5 // тут х == 10 + fmt.Println("xBig:", xBig()) // теперь false + + // Метки, куда же без них, их все любят. + goto love +love: + + learnInterfaces() // О! Интерфейсы, идем далее. +} + +// Объявление Stringer как интерфейса с одним мметодом, String. +type Stringer interface { + String() string +} + +// Объявление pair как структуры с двумя полями x и y типа int. +type pair struct { + x, y int +} + +// Объявление метода для типа pair. Теперь pair реализует интерфейс Stringer. +func (p pair) String() string { // p в данном случае называют receiver-ом + // Sprintf - еще одна функция из пакета fmt. + // Обращение к полям p через точку. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // Синтаксис с фигурными скобками это "литерал структуры". Он возвращает + // проинициализированную структуру, а оператор := присваивает ее в p. + p := pair{3, 4} + fmt.Println(p.String()) // вызов метода String у p, типа pair. + var i Stringer // объявление i как типа с интерфейсом Stringer. + i = p // валидно, т.к. pair реализует Stringer. + // Вызов метода String у i, типа Stringer. Вывод такой же что и выше. + fmt.Println(i.String()) + + // Функции в пакете fmt вызывают метод String у объектов для получения + // строкового представления о них. + fmt.Println(p) // Вывод такой же что и выше. Println вызывает метод String. + fmt.Println(i) // тоже самое + + learnErrorHandling() +} + +func learnErrorHandling() { + // Идиома ", ok" служит для обозначения сработало что-то или нет. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok будет false, потому что 1 нет в map-е. + fmt.Println("тут никого") + } else { + fmt.Print(x) // x содержал бы значение, если бы 1 был в map-е. + } + // Идиома ", err" служит для обозначения была ли ошибка или нет. + if _, err := strconv.Atoi("non-int"); err != nil { // _ игнорирует значение + // выведет "strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // Мы еще обратимся к интерфейсам чуть позже, а пока... + learnConcurrency() +} + +// c это тип данных channel (канал), объект для конкуррентного взаимодействия. +func inc(i int, c chan int) { + c <- i + 1 // когда channel слева, <- являтся оператором "отправки". +} + +// Будем использовать функцию inc для конкуррентной инкрементации чисел. +func learnConcurrency() { + // Тот же make, что и в случае со slice. Он предназначен для выделения + // памяти и инициализации типов slice, map и channel. + c := make(chan int) + // Старт трех конкуррентных goroutine. Числа будут инкрементированы + // конкуррентно и, может быть параллельно, если машина правильно + // сконфигурирована и позволяет это делать. Все они будут отправлены в один + // и тот же канал. + go inc(0, c) // go начинает новую горутину. + go inc(10, c) + go inc(-805, c) + // Считывание всех трех результатов из канала и вывоод на экран. + // Нет никакой гарантии в каком порядке они будут выведены. + fmt.Println(<-c, <-c, <-c) // канал справа, <- обозначает "получение". + + cs := make(chan string) // другой канал, содержит строки. + cc := make(chan chan string) // канал каналов со строками. + go func() { c <- 84 }() // пуск новой горутины для отправки значения + go func() { cs <- "wordy" }() // еще раз, теперь для cs + // Select тоже что и switch, но работает с каналами. Он случайно выбирает + // готовый для взаимодействия канал. + select { + case i := <-c: // полученное значение можно присвоить переменной + fmt.Printf("это %T", i) + case <-cs: // либо значение можно игнорировать + fmt.Println("это строка") + case <-cc: // пустой канал, не готов для коммуникации. + fmt.Println("это не выполнится.") + } + // В этой точке значение будет получено из c или cs. Одна горутина будет + // завершена, другая останется заблокированной. + + learnWebProgramming() // Да, Go это может. +} + +// Всего одна функция из пакета http запускает web-сервер. +func learnWebProgramming() { + // У ListenAndServe первый параметр это TCP адрес, который нужно слушать. + // Второй параметр это интерфейс типа http.Handler. + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // не игнорируйте сообщения об ошибках +} + +// Реализация интерфейса http.Handler для pair, только один метод ServeHTTP. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Обработка запроса и отправка данных методом из http.ResponseWriter + w.Write([]byte("You learned Go in Y minutes!")) +} +``` + +## Что еще почитать + +Основа всех основ в Go это [официальный веб сайт](http://golang.org/). +Там можно пройти туториал, поиграться с интерактивной средой Go и почитать +объемную документацию. + +Для ознакомления рекомендуется почитать исходные коды [стандартной библиотеки +Go](http://golang.org/src/pkg/). Отлично задокументированая, она является +лучшим источником для чтения и понимания Go, его стиля и идиом. Либо можно, +кликнув на имени функции в [документации](http://golang.org/pkg/), перейти к ее +исходным кодам. -- cgit v1.2.3 From 1528dd4fbe680f26646be3af17d9fb5dce209dd0 Mon Sep 17 00:00:00 2001 From: JohnYangSam Date: Thu, 12 Sep 2013 02:01:52 -0700 Subject: Correct bash for...in loop example Removed the $ in the variable declaration of the for...in bash loop to correct the code. --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index 76c794c6..708131bd 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -82,7 +82,7 @@ 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 VARIABLE in x y z do echo "$VARIABLE" done -- cgit v1.2.3 From c515c37bd9889b07aa3fee73bbc7f5a2a32e0bb0 Mon Sep 17 00:00:00 2001 From: Adam Date: Thu, 12 Sep 2013 09:53:20 -0700 Subject: Fix c# es --- es-es/csharp-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/csharp-es.html.markdown b/es-es/csharp-es.html.markdown index 7d1a1201..ef26d8ce 100644 --- a/es-es/csharp-es.html.markdown +++ b/es-es/csharp-es.html.markdown @@ -6,6 +6,7 @@ contributors: translators: - ["Olfran Jiménez", "https://twitter.com/neslux"] filename: LearnCSharp-es.cs +lang: es-es --- C# es un lenguaje orientado a objetos elegante y de tipado seguro que -- cgit v1.2.3 From 9d1015232c1c5cf90ccc8d4807d8c4216a2406dc Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Fri, 13 Sep 2013 20:21:14 +0930 Subject: Wrapped setTimeout note to 80 chars --- javascript.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 859d61a9..2f742574 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -219,7 +219,8 @@ function myFunction(){ // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000); -// Note: setTimeout isn't part of the JS language, but is provided by browsers and Node.js. +// Note: setTimeout isn't part of the JS language, but is provided by browsers +// and Node.js. // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. -- cgit v1.2.3 From 18da2a424460760010377dfe985d8c57c07cb277 Mon Sep 17 00:00:00 2001 From: Madison Dickson Date: Fri, 13 Sep 2013 11:49:15 -0400 Subject: fixing language tag was also displaying incorrectly on the main site --- de-de/elixir-de.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown index ecd74dcb..f77f9b0c 100644 --- a/de-de/elixir-de.html.markdown +++ b/de-de/elixir-de.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Gregor Große-Bölting", "http://www.ideen-und-soehne.de"] filename: learnelixir-de.ex ++lang: de-de --- Elixir ist eine moderne, funktionale Sprache für die Erlang VM. Sie ist voll -- cgit v1.2.3 From 338862e732e82a45fbd8843d48492b4bd3121c0b Mon Sep 17 00:00:00 2001 From: Madison Dickson Date: Fri, 13 Sep 2013 11:58:46 -0400 Subject: Added '?' conditional logic example Also added myself as a contributor. --- java.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index a2fc3630..0dec51d1 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -3,6 +3,7 @@ language: java contributors: - ["Jake Prather", "http://github.com/JakeHP"] + - ["Madison Dickson", "http://github.com/mix3d"] filename: LearnJava.java --- @@ -245,6 +246,13 @@ public class LearnJava { break; } System.out.println("Switch Case Result: " + monthString); + + // Conditional Shorthand + // You can use the '?' operator for quick assignments or logic forks. + // Reads as "If (statement) is true, use , otherwise, use " + int foo = 5 + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Prints A, because the statement is true /////////////////////////////////////// -- cgit v1.2.3 From 1dd0e00f2249526520b047c6852d22a7ee2df7ad Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 13 Sep 2013 10:28:48 -0700 Subject: Fixed a bunch of headers --- csharp.html.markdown | 2 -- es-es/go-es.html.markdown | 2 +- ru-ru/clojure-ru.html.markdown | 1 + ru-ru/erlang-ru.html.markdown | 1 + ru-ru/go-ru.html.markdown | 1 + ru-ru/php-ru.html.markdown | 1 + ru-ru/python-ru.html.markdown | 2 ++ ru-ru/ruby-ru.html.markdown | 1 + 8 files changed, 8 insertions(+), 3 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 55de415d..d3adbd01 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -1,11 +1,9 @@ --- - language: c# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] filename: LearnCSharp.cs - --- C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 6f65a6ad..434f6713 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -6,7 +6,7 @@ filename: learngo.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] translators: - - ["Adrian Espinosa", "http://www.adrianespinosa.com"] + - ["Adrian Espinosa", "http://www.adrianespinosa.com"] lang: es-es diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown index e1d68e5a..2f508a00 100644 --- a/ru-ru/clojure-ru.html.markdown +++ b/ru-ru/clojure-ru.html.markdown @@ -3,6 +3,7 @@ language: clojure filename: learnclojure-ru.clj contributors: - ["Adam Bard", "http://adambard.com/"] +translators: - ["Alexey Pirogov", "http://twitter.com/alex_pir"] lang: ru-ru --- diff --git a/ru-ru/erlang-ru.html.markdown b/ru-ru/erlang-ru.html.markdown index 88d07c09..99ea79ee 100644 --- a/ru-ru/erlang-ru.html.markdown +++ b/ru-ru/erlang-ru.html.markdown @@ -2,6 +2,7 @@ language: erlang contributors: - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] +translators: - ["Nikita Kalashnikov", "https://root.yuuzukiyo.net/"] filename: learnerlang-ru.erl lang: ru-ru diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 16193ec8..f76ab920 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -5,6 +5,7 @@ language: Go filename: learngo-ru.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] +translators: - ["Artem Medeusheyev", "https://github.com/armed"] lang: ru-ru --- diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index 9133ecca..edcac4dd 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -3,6 +3,7 @@ language: php contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] +translators: - ["SlaF", "https://github.com/SlaF"] lang: ru-ru filename: learnphp-ru.php diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index 3f457bdc..df4a38a8 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -2,6 +2,8 @@ language: python lang: ru-ru contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: - ["Yury Timofeev", "http://twitter.com/gagar1n"] filename: learnpython-ru.py --- diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown index 0a8fbb09..ead681ef 100644 --- a/ru-ru/ruby-ru.html.markdown +++ b/ru-ru/ruby-ru.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Luke Holder", "http://twitter.com/lukeholder"] - ["Tristan Hume", "http://thume.ca/"] - ["Nick LaMuro", "https://github.com/NickLaMuro"] +translators: - ["Alexey Makarov", "https://github.com/Anakros"] --- -- cgit v1.2.3 From 937eddf44e7561802c4f09a29ca1891de984e679 Mon Sep 17 00:00:00 2001 From: Artem Medeusheyev Date: Sat, 14 Sep 2013 20:56:37 +0600 Subject: [go/ru-ru] typos and edits --- ru-ru/go-ru.html.markdown | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index f76ab920..8098f601 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -15,10 +15,10 @@ Go - это язык общего назначения, целью которо способ решать насущные проблемы. Концепции Go схожи с другими императивными статически типизированными языками. -Быстро компилируются и быстро выполняются, имеет легкие в понимании конструкции +Быстро компилируется и быстро исполняется, имеет легкие в понимании конструкции для создания масштабируемых и многопоточных программ. -Имеет в наличии отличную стандартную библиотеку и большое комьюнити, полное +Может похвастаться отличной стандартной библиотекой и большим комьюнити, полным энтузиазтов. ```go @@ -50,7 +50,7 @@ func main() { } // Функции содержат входные параметры в круглых скобках. -// Если параметров нет, пустые скобки все равно обязательны. +// Пустые скобки все равно обязательны, даже если параметров нет. func beyondHello() { var x int // Переменные должны быть объявлены до их использования. x = 3 // Присвоение значения переменной. @@ -102,11 +102,13 @@ func learnTypes() { p, q := learnMemory() // объявление p и q как указателей на int. fmt.Println(*p, *q) // * извлекает указатель. Печатает два int-а. - // Map как словарь или хеш теблица из других языков является динамически - // растущим ассоциативным массивом. + // Map как словарь или хеш теблица из других языков является ассоциативным + // массивом с динамически изменяемым размером. m := map[string]int{"three": 3, "four": 4} m["one"] = 1 + delete(m, "three") // встроенная функция, удаляет элемент из map-а. + // Неиспользуемые переменные в Go являются ошибкой. // Нижнее подчеркивание позволяет игнорировать такие переменные. _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs @@ -212,8 +214,8 @@ func learnInterfaces() { // Вызов метода String у i, типа Stringer. Вывод такой же что и выше. fmt.Println(i.String()) - // Функции в пакете fmt вызывают метод String у объектов для получения - // строкового представления о них. + // Функции в пакете fmt сами всегда вызывают метод String у объектов для + // получения строкового представления о них. fmt.Println(p) // Вывод такой же что и выше. Println вызывает метод String. fmt.Println(i) // тоже самое @@ -254,7 +256,7 @@ func learnConcurrency() { go inc(0, c) // go начинает новую горутину. go inc(10, c) go inc(-805, c) - // Считывание всех трех результатов из канала и вывоод на экран. + // Считывание всех трех результатов из канала и вывод на экран. // Нет никакой гарантии в каком порядке они будут выведены. fmt.Println(<-c, <-c, <-c) // канал справа, <- обозначает "получение". @@ -293,14 +295,14 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { } ``` -## Что еще почитать +## Что дальше Основа всех основ в Go это [официальный веб сайт](http://golang.org/). Там можно пройти туториал, поиграться с интерактивной средой Go и почитать объемную документацию. -Для ознакомления рекомендуется почитать исходные коды [стандартной библиотеки -Go](http://golang.org/src/pkg/). Отлично задокументированая, она является -лучшим источником для чтения и понимания Go, его стиля и идиом. Либо можно, -кликнув на имени функции в [документации](http://golang.org/pkg/), перейти к ее -исходным кодам. +Для живого ознакомления рекомендуется почитать исходные коды [стандартной +библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированая, она +является лучшим источником для чтения и понимания Go, его стиля и идиом. Либо +можно, кликнув на имени функции в [документации](http://golang.org/pkg/), +перейти к ее исходным кодам. -- cgit v1.2.3 From f7ef4e6f8fde6ab60473f7ba8fd0f9d656cb87b3 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sat, 14 Sep 2013 22:17:41 +0100 Subject: Extend and improve MATLAB article --- matlab.html.markdown | 198 +++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 144 insertions(+), 54 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 3c909153..e72a95ea 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -2,9 +2,11 @@ language: Matlab contributors: - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] + --- -Matlab stands for Matrix Laboratory. It is a powerful numerical computing language commonly used in engineering and mathematics. +MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. If you have any feedback please feel free to reach me at [@the_ozzinator](https://twitter.com/the_ozzinator), or @@ -18,13 +20,23 @@ something like this %} +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 +openvar('A') % Open variable in variable editor + clc % Erases the writing on your Command Window -who % Displays all variables in memory -diary % History of session +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 + +profile viewer % Open profiler + help command % Displays documentation for command in Command Window +doc command % Displays documentation for command in Help Window lookfor command % Searches for a given command @@ -38,6 +50,7 @@ myVariable = 4 % Notice Workspace pane shows newly created variable myVariable = 4; % Semi colon suppresses output to the Command Window 4 + 6 % ans = 10 8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 @@ -50,6 +63,12 @@ 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: +A > 5 +% for each element, if condition is true, that element is 1 in returned matrix +A[ A > 5 ] +% returns a vector containing the elements in A for which condition is true + % Strings a = 'MyString' length(a) % ans = 8 @@ -75,7 +94,7 @@ x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 % Matrices A = [1 2 3; 4 5 6; 7 8 9] -% Rows are seperated with a semi colon, each element is seperated with space or comma +% Rows are separated by a semicolon; elements are separated with space or comma % A = % 1 2 3 @@ -83,6 +102,10 @@ A = [1 2 3; 4 5 6; 7 8 9] % 7 8 9 A(2,3) % ans = 6, A(row, column) +A(6) % ans = 8 +% (implicitly concatenates columns into vector, then indexes into that) + + A(2,3) = 42 % Update row 2 col 3 with 42 % A = @@ -108,77 +131,125 @@ A(1,:) % All columns in row 1 % 1 2 3 -A(:, [3 1 2]) %Rearrange the columns of original matrix +[A ; A] % Concatenation of matrices (vertically) +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +[A , A] % Concatenation of matrices (horizontally) + +%ans = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + + + +A(:, [3 1 2]) % Rearrange the columns of original matrix %ans = % 3 1 2 % 42 4 5 % 9 7 8 -A(1, :) =[] %Delete the first row of the matrix - size(A) % ans = 3 3 -A' % Transpose the matrix +A(1, :) =[] % Delete the first row of the matrix -[A ; A] % Concatenation of matrices -%ans = +A' % Hermitian transpose the matrix +% (the transpose, followed by taking complex conjugate of each element) +transpose(A) % Transpose the matrix, without taking complex conjugate -% 1 2 3 -% 4 5 42 -% 7 8 9 -% 1 2 3 -% 4 5 42 -% 7 8 9 -%Element by Element Arithmetic VS Matrix Arithmetic +% Element by Element Arithmetic vs. Matrix Arithmetic A * B % Matrix multiplication A .* B % Multiple each element in A by its corresponding element in B -%Plotting -x = 0:.10:2*pi % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 -y = sin(x) +% Plotting +x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 +y = sin(x); plot(x,y) 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 +plot(x,y1,'-',x,y2,'--',x,y3,':'') % For multiple functions on one plot +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 + +scatter(x, y); % Scatter-plot +hist(x); % Histogram +z = sin(x); +plot3(x,y,z); % 3D line plot -% .mat files -% Save the variables in your Workspace +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 -%M-file Scripts -%A script file is an external file that contains a sequence of statements. -%Better than typing your code in the Command Window -%Have .m extensions +h = figure %C reate new figure object, with handle f +figure(h) %M akes the figure corresponding to handle h the current figure +% Properties can be set and changed through a figure handle +h = plot(x, y); +set(h, 'Color', 'r') +% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black +set(h, 'LineStyle', '--') + % '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line +get(h, 'LineStyle') -%M-file Functions -%Programs that accept inputs and return an output -%Have .m extensions -% double_input.m - naming your ,m file the same as you call it in the file is required + +% 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 function output = double_input(x) %double_input(x) returns twice the value of x output = 2*x; end double_input(6) % ans = 12 -%User input + +% 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 +% functions, and have access to both its workspace and their own workspace. + + +% User input a = input('Enter the value: ') -%Reading in data +% Reading in data fopen(filename) -%Output +% Output disp(a) % Print out the value of variable a disp('Hello World') % Print out a string -fprintf % More control display to Command Window +fprintf % Print to Command Window with more control -%Conditional statements +% Conditional statements if a > 15 disp('Greater than 15') elseif a == 23 @@ -187,7 +258,9 @@ else disp('neither condition met') end -%Looping +% Looping +% NB. looping over elements of a vector/matrix is slow! +% Where possible, use functions that act on whole vector/matrix at once for k = 1:5 disp(k) end @@ -197,8 +270,13 @@ while (k < 5) k = k + 1; end +% Timing code execution: 'toc' prints the time since 'tic' was called +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc -%Connecting to a MySQL Database +% Connecting to a MySQL Database dbname = 'database_name'; username = 'root'; password = 'root'; @@ -206,7 +284,7 @@ driver = 'com.mysql.jdbc.Driver'; dburl = ['jdbc:mysql://localhost:8889/' dbname]; javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ conn = database(dbname, username, password, driver, dburl); -sql = ['SELECT * from table_name where id = 22'] %Example sql statement +sql = ['SELECT * from table_name where id = 22'] % Example sql statement a = fetch(conn, sql) %a will contain your data @@ -228,14 +306,19 @@ ceil(x) floor(x) round(x) rem(x) -rand -randi +rand % Uniformly distributed pseudorandom numbers +randi % Uniformly distributed pseudorandom integers +randn % Normally distributed pseudorandom numbers % Common constants pi 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 + % Common matrix functions zeros(m,n) % m x n matrix of 0's ones(m,n) % m x n matrix of 1's @@ -243,30 +326,37 @@ diag(A) % Extracts the diagonal elements of a matrix eye(m,n) % Indentity matrix inv(A) % Inverse of matrix A det(A) % Determinant of A -eig(A) %Eigenvalues and eigenvectors of A +eig(A) % Eigenvalues and eigenvectors of A +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 -numel(A) %Number of elements in matrix +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 cross(A,B) % Returns the cross product of the vectors A and B -dot(A,B) % Returns the scalar product of the vectors A and B. A and B must be vectors of the same length. +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 % 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 -median %median value -mean %mean value -std %standard deviation - +max % largest component +min % smallest component +length % length of a vector +sort % sort in ascending order +sum % sum of elements +prod % product of elements +mode % modal value +median % median value +mean % mean value +std % standard deviation +perms(x) % list all permutations of elements of x ``` ## More on Matlab * The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* The official MATLAB Answers forum: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) + -- cgit v1.2.3 From 5bf3efe1652144648c4b8c0d3557180545d04cfa Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sun, 15 Sep 2013 01:41:27 +0100 Subject: Matlab: more plotting functions, anonymous functions, matrix factorisations, and other features. Fix some typos. --- matlab.html.markdown | 117 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 97 insertions(+), 20 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index e72a95ea..1e48618d 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -20,10 +20,17 @@ 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 @@ -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 @@ -63,7 +71,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 +177,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 +198,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' +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 +229,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 + +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 -h = plot(x, y); +% 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 +249,38 @@ set(h, 'LineStyle', '--') get(h, 'LineStyle') +% The function gcs returns a handle to the axes for the current figure +set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis + +% To creatw 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 +290,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 +317,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 +384,18 @@ 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 +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 +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) % Indentity 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 @@ -340,13 +412,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 +% Alternative forms for matrices +[L, U, P] = lu(A) % LU decomposition: PA = LU +[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 -- cgit v1.2.3 From 372e79a3fb3c6db8d350defae65d30f0a7f48663 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sun, 15 Sep 2013 01:42:13 +0100 Subject: Relabel a section to 'Matrix Factorisations --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 1e48618d..eaf50e8e 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -412,7 +412,7 @@ 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 -% Alternative forms for matrices +% Matrix Factorisations [L, U, P] = lu(A) % LU decomposition: PA = LU [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 -- cgit v1.2.3 From e0f9a4dab392c13df8c909eb4a58a81950c30e1a Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sun, 15 Sep 2013 01:48:02 +0100 Subject: Comment explaining LU decomposition --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index eaf50e8e..98d085da 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -413,7 +413,7 @@ 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, 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 -- cgit v1.2.3 From 28f0e163e2d4d5d8e55f484fef93190dda4e7593 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sun, 15 Sep 2013 02:53:32 +0100 Subject: Typos --- matlab.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 98d085da..e9874f21 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -249,10 +249,10 @@ set(h, 'LineStyle', '--') get(h, 'LineStyle') -% The function gcs returns a handle to the axes for the current figure +% 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 creatw a figure that contains several axes in tiled positions, use subplot +% 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 @@ -394,7 +394,7 @@ 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 A diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere -eye(m,n) % Indentity matrix +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 -- cgit v1.2.3 From a3476993b1d44ea033967f979dfa022f0fd72429 Mon Sep 17 00:00:00 2001 From: Arnel Bucio Date: Sun, 15 Sep 2013 14:15:53 +0800 Subject: Fix typo --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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; -- cgit v1.2.3 From 3eb4dbab9a4a6d9082f424289f982e8489138033 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sun, 15 Sep 2013 16:06:26 +0100 Subject: Typos --- matlab.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index e9874f21..27b00eba 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -199,7 +199,7 @@ 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 +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. @@ -403,7 +403,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 -- cgit v1.2.3 From 8782aded63b0b5c2b31d1aad150d02f362c4587e Mon Sep 17 00:00:00 2001 From: alswl Date: Wed, 18 Sep 2013 20:01:47 +0800 Subject: 33% --- zh-cn/r-cn.html.markdown | 153 ++++++++++++++--------------------------------- 1 file changed, 44 insertions(+), 109 deletions(-) diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown index 1bd83c60..d377703e 100644 --- a/zh-cn/r-cn.html.markdown +++ b/zh-cn/r-cn.html.markdown @@ -1,46 +1,28 @@ - -# Comments start with hashtags. # 评论以 # 开始 -# You can't make a multi-line comment per se, -# but you can stack multiple comments like so. -# 你不能在每一个se下执行多个注释, -# 但是你可以像这样把命注释内容堆叠起来. -# in Windows, hit COMMAND-ENTER to execute a line -# 在windows下,点击回车键来执行一条命令 +# R 语言原生不支持 多行注释 +# 但是你可以像这样来多行注释 + +# 在窗口里按回车键可以执行一条命令 ################################################################### -# Stuff you can do without understanding anything about programming -# 素材可以使那些不懂编程的人同样得心用手 +# 不用懂编程就可以开始动手了 ################################################################### -data() # Browse pre-loaded data sets -data() # 浏览预加载的数据集 -data(rivers) # Lengths of Major North American Rivers +data() # 浏览内建的数据集 data(rivers) # 北美主要河流的长度(数据集) -ls() # Notice that "rivers" appears in the workspace -ls() # 在工作站中查看”河流“文件夹是否出现 -head(rivers) # peek at the dataset -head(rivers) # 浏览数据集 +ls() # 在工作空间中查看「河流」是否出现 +head(rivers) # 撇一眼数据集 # 735 320 325 392 524 450 -length(rivers) # how many rivers were measured? +length(rivers) # 我们测量了多少条河流? # 141 -length(rivers) # 测量了多少条河流 summary(rivers) # Min. 1st Qu. Median Mean 3rd Qu. Max. # 135.0 310.0 425.0 591.2 680.0 3710.0 -#查看”河流“数据集的特征 -# 最小值. 1st Qu. 中位数 平均值 最大值 -# 135.0 310.0 425.0 591.2 680.0 3710.0 -stem(rivers) #stem-and-leaf plot (like a histogram) -stem(rivers) #茎叶图(一种类似于直方图的展现形式) - - - - +stem(rivers) # 茎叶图(一种类似于直方图的展现形式) +# # The decimal point is 2 digit(s) to the right of the | -# 小数点向|右边保留两位数字 # # 0 | 4 # 2 | 011223334555566667778888899900001111223333344455555666688888999 @@ -62,11 +44,10 @@ stem(rivers) #茎叶图(一种类似于直方图的展现形式) # 34 | # 36 | 1 -stem(log(rivers)) #Notice that the data are neither normal nor log-normal! Take that, Bell Curve fundamentalists. -stem(log(rivers)) #查看数据集的方式既不是标准形式,也不是取log后的结果! 看起来,是钟形曲线形式的基本数据集 + +stem(log(rivers)) # 查看数据集的方式既不是标准形式,也不是取log后的结果! 看起来,是钟形曲线形式的基本数据集 # The decimal point is 1 digit(s) to the left of the | -# 小数点向|左边保留一位数字 # # 48 | 1 # 50 | @@ -88,35 +69,26 @@ stem(log(rivers)) #查看数据集的方式既不是标准形式,也不是取l # 82 | 2 -hist(rivers, col="#333333", border="white", breaks=25) #play around with these parameters -hist(rivers, col="#333333", border="white", breaks=25) #给river做统计频数直方图,包含了这些参数(名称,颜色,边界,空白) -hist(log(rivers), col="#333333", border="white", breaks=25) #you'll do more plotting later -hist(log(rivers), col="#333333", border="white", breaks=25) #稍后你还可以做更多的绘图,统计频数直方图,包含了这些参数(river数据集的log值,颜色,边界,空白) -hist(rivers, col="#333333", border="white", breaks=25) #play around with these parameters -hist(rivers, col="#333333", border="white", breaks=25) #运行同济频数直方图的这些参数 +hist(rivers, col="#333333", border="white", breaks=25) # 试试用这些参数画画 (译者注:给 river 做统计频数直方图,包含了这些参数:数据源,颜色,边框,空格) +hist(log(rivers), col="#333333", border="white", breaks=25) #你还可以做更多式样的绘图 -#Here's another neat data set that comes pre-loaded. R has tons of these. data() -#这里还有其他一些简洁的数据集可以被提前加载。R语言包括大量这种类型的数据集 +# 还有其他一些简单的数据集可以被用来加载。R 语言包括了大量这种 data() data(discoveries) -#数据集(发现) plot(discoveries, col="#333333", lwd=3, xlab="Year", main="Number of important discoveries per year") -#绘图(发现,颜色负值,宽度负值,X轴名称,主题:Number of important discoveries per year) - +# 译者注:参数为(数据源,颜色,线条宽度,X 轴名称,标题) +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", main="Number of important discoveries per year") -#rather than leaving the default ordering (by year) we could also sort to see what's typical -#宁可舍弃也不执行排序(按照年份完成)我们可以分类来查看这是那些类型 -sort(discoveries) #给(发现)分类 +# 除了按照默认的年份排序,我们还可以排序来发现特征 +sort(discoveries) # [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 # [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 # [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 # [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 -stem(discoveries, scale=2) -#茎叶图(发现,在原来的基础上降尺度扩大两倍) -# +stem(discoveries, scale=2) # 译者注:茎叶图(数据,放大系数) +# # The decimal point is at the | -# 小数点在| # # 0 | 000000000 # 1 | 000000000000 @@ -133,32 +105,26 @@ stem(discoveries, scale=2) # 12 | 0 max(discoveries) -#最大值(发现) # 12 summary(discoveries) -#数据集特征(发现) # Min. 1st Qu. Median Mean 3rd Qu. Max. # 0.0 2.0 3.0 3.1 4.0 12.0 -#Basic statistical operations don't require any programming knowledge either #基本的统计学操作也不需要任何编程知识 -#roll a die a few times -#随机输出数据 +#随机生成数据 round(runif(7, min=.5, max=6.5)) -#round(产生均匀分布的随机数,进行四舍五入(7个, 最小值为0.5, max=6.5)) +# 译者注:runif 产生随机数,round 四舍五入 # 1 4 6 1 4 6 4 -#your numbers will differ from mine unless we set the same random.seed(31337) -#你输出的结果将会与我们给出的不同,除非我们设置了同样的随机种子 random.seed(31337) +# 你输出的结果会和我们给出的不同,除非我们设置了相同的随机种子 random.seed(31337) -#draw from a standard Gaussian 9 times -#从标准高斯函数中随机的提取9次结果 +#从标准高斯函数中随机生成 9 次 rnorm(9) # [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 # [7] -0.59975593 0.57629164 1.08455362 @@ -172,100 +138,69 @@ rnorm(9) ######################### -# Basic programming stuff -# 基本的编程素材 +# 基础编程 ######################### -# NUMBERS +# 数值 -# "numeric" means double-precision floating-point numbers #“数值”指的是双精度的浮点数 5 # 5 class(5) # "numeric" -#定义(5)为数值型变量 # "numeric" -5e4 # 50000 #handy when dealing with large,small,or variable orders of magnitude -#5×104次方 可以手写输入改变数量级的大小将变量扩大 -6.02e23 # Avogadro's number -#阿伏伽德罗常数 -1.6e-35 # Planck length -#布朗克长度 - -# long-storage integers are written with L -#长存储整数并用L书写 +5e4 # 50000 # 用科学技术法方便的处理极大值、极小值或者可变的量级 +6.02e23 # 阿伏伽德罗常数# +1.6e-35 # 布朗克长度 + +# 长整数并用 L 结尾 5L # 5 #输出5L class(5L) # "integer" -#(5L)的类型, 整数型 -# Try ?class for more information on the class() function -#可以自己试一试?用class()功能函数定义更多的信息 -# In fact, you can look up the documentation on `xyz` with ?xyz -#事实上,你可以找一些文件查阅“xyz”以及xyz的差别 -# or see the source for `xyz` by evaluating xyz -#或者通过评估xyz来查看“xyz”的来源 +# 可以自己试一试?用 class() 函数获取更多信息 +# 事实上,你可以找一些文件查阅 `xyz` 以及xyz的差别 +# `xyz` 用来查看源码实现,?xyz 用来看帮助 -# Arithmetic -#算法 +# 算法 10 + 66 # 76 53.2 - 4 # 49.2 2 * 2.0 # 4 3L / 4 # 0.75 3 %% 2 # 1 -# Weird number types -#超自然数的类型 +# 特殊数值类型 class(NaN) # "numeric" class(Inf) # "numeric" -class(-Inf) # "numeric" #used in for example integrate( dnorm(x), 3, Inf ) -- which obviates Z-score tables -#定义以上括号内的数均为数值型变量,利用实例中的整数(正态分布函数(X),3,Inf )消除Z轴列表 +class(-Inf) # "numeric" # 在以下场景中会用到 integrate( dnorm(x), 3, Inf ) -- 消除 Z 轴数据 -# but beware, NaN isn't the only weird type... -# 但要注意,NaN并不是仅有的超自然类型。。。 -class(NA) # see below -#定义(NA)下面的部分会理解 +# 但要注意,NaN 并不是唯一的特殊数值类型…… +class(NA) # 看上面 class(NULL) # NULL -#定义(NULL)无效的 -# SIMPLE LISTS -#简单的数据集 +# 简单列表 c(6, 8, 7, 5, 3, 0, 9) # 6 8 7 5 3 0 9 -#输出数值型向量(6 8 7 5 3 0 9) c('alef', 'bet', 'gimmel', 'dalet', 'he') -#输出字符型变量# "alef" "bet" "gimmel" "dalet" "he" c('Z', 'o', 'r', 'o') == "Zoro" # FALSE FALSE FALSE FALSE -#输出逻辑型变量FALSE FALSE FALSE FALSE -#some more nice built-ins -#一些优雅的内置功能 +# 一些优雅的内置功能 5:15 # 5 6 7 8 9 10 11 12 13 14 15 -#从5-15输出,以进度为1递增 seq(from=0, to=31337, by=1337) -#输出序列(从0到31337,以1337递增) # [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 # [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 letters -#字符型变量,26个 # [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" # [20] "t" "u" "v" "w" "x" "y" "z" month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" -#表示月份的变量 # Access the n'th element of a list with list.name[n] or sometimes list.name[[n]] -#访问数据集名字为[n]的第n个元素 - +# 使用 list.name[n] 来访问第 n 个列表元素,有时候需要使用 list.name[[n]] letters[18] # "r" -#访问其中的第18个变量 LETTERS[13] # "M" -#用大写访问其中的第13个变量 month.name[9] # "September" -#访问名字文件中第9个变量 c(6, 8, 7, 5, 3, 0, 9)[3] # 7 -#访问向量中的第三个变量 -- cgit v1.2.3 From 75a7261f7e22fb321c2646123b4f1981f835003c Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Wed, 18 Sep 2013 15:51:20 +0300 Subject: added latest updates from php-en --- tr-tr/php-tr.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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. -- cgit v1.2.3 From e9634e0741f6f25bcef5436b28f1d068ff48d0d9 Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Wed, 18 Sep 2013 16:18:29 +0300 Subject: objective-c translating to Turkish language --- tr-tr/objective-c-tr.html.markdown | 320 +++++++++++++++++++++++++++++++++++++ 1 file changed, 320 insertions(+) create mode 100644 tr-tr/objective-c-tr.html.markdown 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 +#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 +// { +// Üye değişken (member variable) tanımlaması; +// } +// -/+ (type) Method tanımlaması; +// @end +@interface MyClass : NSObject +{ + 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) -- cgit v1.2.3 From 6b9ac70e5efc9163fd2919b35559e9ea9d7d1703 Mon Sep 17 00:00:00 2001 From: alswl Date: Wed, 18 Sep 2013 21:26:38 +0800 Subject: transalted 50% --- zh-cn/r-cn.html.markdown | 156 +++++++++++++++++------------------------------ 1 file changed, 56 insertions(+), 100 deletions(-) diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown index d377703e..68867d92 100644 --- a/zh-cn/r-cn.html.markdown +++ b/zh-cn/r-cn.html.markdown @@ -18,8 +18,8 @@ head(rivers) # 撇一眼数据集 length(rivers) # 我们测量了多少条河流? # 141 summary(rivers) -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 135.0 310.0 425.0 591.2 680.0 3710.0 +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 stem(rivers) # 茎叶图(一种类似于直方图的展现形式) # # The decimal point is 2 digit(s) to the right of the | @@ -34,14 +34,14 @@ stem(rivers) # 茎叶图(一种类似于直方图的展现形式) # 14 | 56 # 16 | 7 # 18 | 9 -# 20 | +# 20 | # 22 | 25 # 24 | 3 -# 26 | -# 28 | -# 30 | -# 32 | -# 34 | +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | # 36 | 1 @@ -50,7 +50,7 @@ stem(log(rivers)) # 查看数据集的方式既不是标准形式,也不是取 # The decimal point is 1 digit(s) to the left of the | # # 48 | 1 -# 50 | +# 50 | # 52 | 15578 # 54 | 44571222466689 # 56 | 023334677000124455789 @@ -65,7 +65,7 @@ stem(log(rivers)) # 查看数据集的方式既不是标准形式,也不是取 # 74 | 84 # 76 | 56 # 78 | 4 -# 80 | +# 80 | # 82 | 2 @@ -101,15 +101,15 @@ stem(discoveries, scale=2) # 译者注:茎叶图(数据,放大系数) # 8 | 0 # 9 | 0 # 10 | 0 -# 11 | +# 11 | # 12 | 0 max(discoveries) # 12 summary(discoveries) -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 0.0 2.0 3.0 3.1 4.0 12.0 +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 @@ -151,7 +151,7 @@ class(5) # "numeric" 1.6e-35 # 布朗克长度 # 长整数并用 L 结尾 -5L # 5 +5L # 5 #输出5L class(5L) # "integer" @@ -178,7 +178,7 @@ class(NULL) # NULL # 简单列表 c(6, 8, 7, 5, 3, 0, 9) # 6 8 7 5 3 0 9 -c('alef', 'bet', 'gimmel', 'dalet', 'he') +c('alef', 'bet', 'gimmel', 'dalet', 'he') c('Z', 'o', 'r', 'o') == "Zoro" # FALSE FALSE FALSE FALSE # 一些优雅的内置功能 @@ -200,119 +200,80 @@ month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "D letters[18] # "r" LETTERS[13] # "M" month.name[9] # "September" -c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 -# CHARACTERS -#特性 -# There's no difference between strings and characters in R -# 字符串和字符在R语言中没有区别 +# 字符串 + +# 字符串和字符在 R 语言中没有区别 "Horatio" # "Horatio" -#字符输出"Horatio" class("Horatio") # "character" -#字符串输出("Horatio") # "character" substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " -#提取字符串("Fortuna multis dat nimis, nulli satis.", 第9个到15个之前并输出) gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." -#替换字符春,用ø替换u -# LOGICALS -#逻辑值 +# 逻辑值 -# booleans -#布尔运算 +# 布尔值 class(TRUE) # "logical" -#定义为真,逻辑型 class(FALSE) # "logical" -#定义为假,逻辑型 -# Behavior is normal -#表现的标准形式 +# 和我们预想的一样 TRUE == TRUE # TRUE TRUE == FALSE # FALSE FALSE != FALSE # FALSE FALSE != TRUE # TRUE -# Missing data (NA) is logical, too -#缺失数据也是逻辑型的 +# 缺失数据(NA)也是逻辑值 class(NA) # "logical" #定义NA为逻辑型 -# FACTORS -#因子 -# The factor class is for categorical data -#因子是分类数据的定义函数 -# which can be ordered (like childrens' grade levels) -#可以使有序的(就像儿童的等级水平) -# or unordered (like gender) -#也可以是无序的(就像性别) -levels(factor(c("female", "male", "male", "female", "NA", "female"))) # "female" "male" "NA" -#c("female", "male", "male", "female", "NA", "female")向量,变量是字符型,levels factor()因子的等级水平 +# 因子 +# 因子是为数据分类排序设计的(像是排序小朋友们的年级或性别) +levels(factor(c("female", "male", "male", "female", "NA", "female"))) # "female" "male" "NA" -factor(c("female", "female", "male", "NA", "female")) +factor(c("female", "female", "male", "NA", "female")) # female female male NA female # Levels: female male NA -data(infert) #Infertility after Spontaneous and Induced Abortion -#数据集(感染) 自然以及引产导致的不育症 +data(infert) # 自然以及引产导致的不育症 levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" -#等级(感染与教育程度) 输出 -# VARIABLES -#变量 +# 变量 -# Lots of way to assign stuff -#许多种方式用来分配素材 -x = 5 # this is possible -#x = 5可能的 -y <- "1" # this is preferred -#y <- "1" 优先级的 -TRUE -> z # this works but is weird -#输出真实的,存在一个超自然数满足条件 +# 有许多种方式用来赋值 +x = 5 # 这样可以 +y <- "1" # 更推荐这样 +TRUE -> z # 这样可行,但是很怪 -# We can use coerce variables to different classes -#我们还可以使用枪支变量去进行不同的定义 +#我们还可以使用强制转型 as.numeric(y) # 1 -#定义数值型 as.character(x) # "5" -#字符型 - -# LOOPS -#循环 +# 循环 -# We've got for loops -#循环语句 +# for 循环语句 for (i in 1:4) { print(i) } -#定义一个i,从1-4输出 -# We've got while loops -#我们可以获取循环结构 +# while 循环 a <- 10 while (a > 4) { cat(a, "...", sep = "") a <- a - 1 } -#把10负值为a,a<4,输出文件(a,"...",sep="" ),跳出继续下一个循环取a=a-1,如此循环,直到a=10终止 -# Keep in mind that for and while loops run slowly in R -#在R语言中牢记 for和它的循环结构 -# Operations on entire vectors (i.e. a whole row, a whole column) -#牢记矢量中附带的操作(例如,整行和整列) -# or apply()-type functions (we'll discuss later) are preferred -#或者优先使用()-函数,稍后会进行讨论 + +# 记住,在 R 语言中 for / while 循环都很慢 +# 建议使用 apply()(我们一会介绍)来错做一串数据(比如一列或者一行数据) # IF/ELSE -#判断分支 -# Again, pretty standard -#再一次,看这些优雅的标准 +# 再来看这些优雅的标准 if (4 > 3) { print("Huzzah! It worked!") } else { @@ -322,30 +283,25 @@ if (4 > 3) { # => # [1] "Huzzah! It worked!" -# FUNCTIONS -#功能函数 +# 函数 -# Defined like so: -#定义如下 +# 定义如下 jiggle <- function(x) { - x+ rnorm(x, sd=.1) #add in a bit of (controlled) noise + x + rnorm(x, sd=.1) #add in a bit of (controlled) noise return(x) } -#把功能函数x负值给jiggle, -# Called like any other R function: -jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 +# 和其他 R 语言函数一样调用 +jiggle(5) # 5±ε. 使用 set.seed(2716057) 后, jiggle(5)==5.005043 ######################### -# Fun with data: vectors, matrices, data frames, and arrays -# 数据参数:向量,矩阵,数据框,数组, +# 数据容器:vectors, matrices, data frames, and arrays ######################### -# ONE-DIMENSIONAL -#单维度 +# 单维度 # You can vectorize anything, so long as all components have the same type #你可以将任何东西矢量化,因此所有的组分都有相同的类型 -vec <- c(8, 9, 10, 11) +vec <- c(8, 9, 10, 11) vec # 8 9 10 11 # The class of a vector is the class of its components #矢量class表示这一组分的类型 @@ -423,10 +379,10 @@ t(mat) mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) mat2 # => -# [,1] [,2] -# [1,] "1" "dog" -# [2,] "2" "cat" -# [3,] "3" "bird" +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" # [4,] "4" "dog" class(mat2) # matrix #定义mat2矩阵 @@ -451,7 +407,7 @@ mat3 # TWO-DIMENSIONAL (DIFFERENT CLASSES) ##二维函数(不同的变量类型) -# For columns of different classes, use the data frame +# For columns of different classes, use the data frame 利用数组可以将不同类型放在一起 dat <- data.frame(c(5,2,1,4), c("dog", "cat", "bird", "dog")) #dat<-数据集(c(5,2,1,4), c("dog", "cat", "bird", "dog")) @@ -484,7 +440,7 @@ dat[,"number"] # 5 2 1 4 # You can make a two-dimensional table (sort of like a matrix) #你可以建立一个2维表格(类型和矩阵相似) array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) -#数组(c(c(1,2,4,5),c(8,9,3,6)),有前两个向量组成,2行4列 +#数组(c(c(1,2,4,5),c(8,9,3,6)),有前两个向量组成,2行4列 # => # [,1] [,2] [,3] [,4] # [1,] 1 4 8 3 @@ -540,7 +496,7 @@ mat #使用(X, MARGIN, FUN)将一个function功能函数根据其特征应用到矩阵x中 # over rows (MAR = 1) or columns (MAR = 2) #规定行列,其边界分别为1,2 -# That is, R does FUN to each row (or column) of X, much faster than a +# That is, R does FUN to each row (or column) of X, much faster than a #即就是,R定义一个function使每一行/列的x快于一个for或者while循环 # for or while loop would do apply(mat, MAR = 2, myFunc) -- cgit v1.2.3 From 3ff90ab9eb308b688480e6e3440b9e2c33d713e6 Mon Sep 17 00:00:00 2001 From: alswl Date: Wed, 18 Sep 2013 21:51:48 +0800 Subject: transalte 74% --- zh-cn/r-cn.html.markdown | 91 +++++++++++++++++------------------------------- 1 file changed, 31 insertions(+), 60 deletions(-) diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown index 68867d92..9a1414bb 100644 --- a/zh-cn/r-cn.html.markdown +++ b/zh-cn/r-cn.html.markdown @@ -299,42 +299,32 @@ jiggle(5) # 5±ε. 使用 set.seed(2716057) 后, jiggle(5)==5.005043 ######################### # 单维度 -# You can vectorize anything, so long as all components have the same type -#你可以将任何东西矢量化,因此所有的组分都有相同的类型 +# 你可以将目前我们学习到的任何类型矢量化,只要它们拥有相同的类型 vec <- c(8, 9, 10, 11) vec # 8 9 10 11 -# The class of a vector is the class of its components -#矢量class表示这一组分的类型 +# 矢量的类型是这一组数据元素的类型 class(vec) # "numeric" # If you vectorize items of different classes, weird coercions happen -#如果你强制的将不同类型的classes矢量化,会发生超自然形式的函数,例如都转变成数值型、字符型 +#如果你强制的将不同类型数值矢量化,会出现特殊值 c(TRUE, 4) # 1 4 c("dog", TRUE, 4) # "dog" "TRUE" "4" -# We ask for specific components like so (R starts counting from 1) -#我们可以找寻特定的组分,例如这个例子(R从1算起) +#我们这样来取内部数据,(R 的下标索引顺序 1 开始) vec[1] # 8 -# We can also search for the indices of specific components, -#我们也可以从这些特定组分中找寻这些指标 +# 我们可以根据条件查找特定数据 which(vec %% 2 == 0) # 1 3 -# or grab just the first or last entry in the vector -#抓取矢量中第1个和最后一个字符 +# 抓取矢量中第一个和最后一个字符 head(vec, 1) # 8 tail(vec, 1) # 11 -#如果指数结束或不存在即"goes over" 可以获得NA -# If an index "goes over" you'll get NA: +#如果下标溢出或不存会得到 NA vec[6] # NA -# You can find the length of your vector with length() -#你也可以找到矢量的长度 +# 你可以使用 length() 获取矢量的长度 length(vec) # 4 -# You can perform operations on entire vectors or subsets of vectors -#你可以将整个矢量或者子矢量集进行展示 +# 你可以直接操作矢量或者矢量的子集 vec * 4 # 16 20 24 28 -# vec[2:3] * 5 # 25 30 -# and there are many built-in functions to summarize vectors -#这里有许多内置的功能函数,并且可对矢量特征进行总结 +# 这里有许多内置的函数,来表现向量 mean(vec) # 9.5 var(vec) # 1.666667 sd(vec) # 1.290994 @@ -342,40 +332,32 @@ max(vec) # 11 min(vec) # 8 sum(vec) # 38 -# TWO-DIMENSIONAL (ALL ONE CLASS) -#二维函数 +# 二维(相同元素类型) -# You can make a matrix out of entries all of the same type like so: -#你可以建立矩阵,保证所有的变量形式相同 +#你可以为同样类型的变量建立矩阵 mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) -#建立mat矩阵,3行2列,从1到6排列,默认按列排布 mat # => # [,1] [,2] # [1,] 1 4 # [2,] 2 5 # [3,] 3 6 -# Unlike a vector, the class of a matrix is "matrix", no matter what's in it +# 和 vector 不一样的是,一个矩阵的类型真的是 「matrix」,而不是内部元素的类型 class(mat) # => "matrix" -# Ask for the first row -#访问第一行的字符 +# 访问第一行的字符 mat[1,] # 1 4 -# Perform operation on the first column -#优先输入第一列,分别×3输出 +# 操作第一行数据 3 * mat[,1] # 3 6 9 -# Ask for a specific cell -#访问特殊的单元,第3行第二列 +# 访问一个特定数据 mat[3,2] # 6 -# Transpose the whole matrix -#转置整个矩阵,变成2行3列 +# 转置整个矩阵(译者注:变成 2 行 3 列) t(mat) # => # [,1] [,2] [,3] # [1,] 1 2 3 # [2,] 4 5 6 -# cbind() sticks vectors together column-wise to make a matrix -把两个矩阵按列合并,形成新的矩阵 +# 使用 cbind() 函数把两个矩阵按列合并,形成新的矩阵 mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) mat2 # => @@ -385,36 +367,27 @@ mat2 # [3,] "3" "bird" # [4,] "4" "dog" class(mat2) # matrix -#定义mat2矩阵 # Again, note what happened! -#同样的注释 -# Because matrices must contain entries all of the same class, -#矩阵必须包含同样的形式 -# everything got converted to the character class -#每一个变量都可以转化成字符串形式 +# 注意 +# 因为矩阵内部元素必须包含同样的类型 +# 所以现在每一个元素都转化成字符串 c(class(mat2[,1]), class(mat2[,2])) -# rbind() sticks vectors together row-wise to make a matrix -#按行合并两个向量,建立新的矩阵 +# 按行合并两个向量,建立新的矩阵 mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) mat3 # => # [,1] [,2] [,3] [,4] # [1,] 1 2 4 5 # [2,] 6 7 0 4 -# Aah, everything of the same class. No coercions. Much better. +# 哈哈,数据类型都一样的,没有发生强制转换,生活真美好 -# TWO-DIMENSIONAL (DIFFERENT CLASSES) -##二维函数(不同的变量类型) +# 二维(不同的元素类型) -# For columns of different classes, use the data frame -利用数组可以将不同类型放在一起 +# 利用 data frame 可以将不同类型数据放在一起 dat <- data.frame(c(5,2,1,4), c("dog", "cat", "bird", "dog")) -#dat<-数据集(c(5,2,1,4), c("dog", "cat", "bird", "dog")) -names(dat) <- c("number", "species") # name the columns -#给每一个向量命名 +names(dat) <- c("number", "species") # 给数据列命名 class(dat) # "data.frame" -#建立数据集dat dat # => # number species @@ -425,18 +398,16 @@ dat class(dat$number) # "numeric" class(dat[,2]) # "factor" # The data.frame() function converts character vectors to factor vectors -#数据集,将字符特征转化为因子矢量 +# data.frame() 会将字符向量转换为 factor 向量 -# There are many twisty ways to subset data frames, all subtly unalike -#这里有许多种生成数据集的方法,所有的都很巧妙但又不相似 +# 有很多精妙的方法来获取 data frame 的子数据集 dat$number # 5 2 1 4 dat[,1] # 5 2 1 4 dat[,"number"] # 5 2 1 4 -# MULTI-DIMENSIONAL (ALL OF ONE CLASS) -#多维函数 -# Arrays creates n-dimensional tables -#利用数组创造一个n维的表格 +# 多维(相同元素类型) + +# 利用数组创造一个 n 维的表格 # You can make a two-dimensional table (sort of like a matrix) #你可以建立一个2维表格(类型和矩阵相似) array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) -- cgit v1.2.3 From f46b6cda6e88fad20e785e77ee0cd25e516dcc67 Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Wed, 18 Sep 2013 17:57:19 +0300 Subject: [brainfuck/tr] translating Brainfuck programming language to turkish --- tr-tr/brainfuck-tr.html.markdown | 86 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 tr-tr/brainfuck-tr.html.markdown diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/brainfuck-tr.html.markdown new file mode 100644 index 00000000..a6f6f078 --- /dev/null +++ b/tr-tr/brainfuck-tr.html.markdown @@ -0,0 +1,86 @@ +--- +language: brainfuck +filename: brainfuck-tr +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io"] +translators: + - ["Haydar KULEKCI", "http://scanf.info/"] +lang: tr-tr +--- + +Brainfuck 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 is represented by an array with 30,000 cells initialized to zero +and a data pointer pointing at the current cell. + +There are eight commands: ++ : 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. -- cgit v1.2.3 From 4ddcd660f8d08196c8628156d3e1bc0f1c785d97 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Wed, 18 Sep 2013 18:05:29 +0100 Subject: Explain difference between command and function syntax --- matlab.html.markdown | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 27b00eba..b8e552e2 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -37,8 +37,8 @@ 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 @@ -62,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 reveive output: +[V,D] = eig(A) % this has no equivalent in command form + + + % Logicals 1 > 5 % ans = 0 10 >= 10 % ans = 1 @@ -384,8 +395,10 @@ NaN inf % Solving matrix equations (if no solution, returns a least squares solution) +% 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 -- cgit v1.2.3 From c3fcedf70f1b607166be3e8ba64d0da25ccfddb0 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Wed, 18 Sep 2013 18:08:31 +0100 Subject: Fix typo - misspelt 'receive' --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index b8e552e2..15ff2303 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -68,7 +68,7 @@ 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 reveive output: +% literal text - cannot pass variable values. Also, can't receive output: [V,D] = eig(A) % this has no equivalent in command form -- cgit v1.2.3 From abb39e92d4bede85777e11c50fb97ae1bee4215f Mon Sep 17 00:00:00 2001 From: Francisco Gomez Date: Wed, 18 Sep 2013 11:58:59 -0700 Subject: Perl spanish translation. --- es-es/perl-es.html.markdown | 157 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 es-es/perl-es.html.markdown diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown new file mode 100644 index 00000000..b1327997 --- /dev/null +++ b/es-es/perl-es.html.markdown @@ -0,0 +1,157 @@ +--- +name: perl +category: language +language: perl +filename: learnperl-es.pl +contributors: + - ["Francisco Gomez", "http://github.com/frncscgmz"] +--- + +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` -- cgit v1.2.3 From de5a359faadffadbff1ccb19ad584ffb1c906796 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 19 Sep 2013 16:48:09 -0500 Subject: Edit wording of while loop in bash. --- bash.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 1473e669..2faa4988 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -53,10 +53,10 @@ else echo "And this is not" fi -# And the usual while loop: +# while loop: while [true] do - echo "put loop content here..." + echo "loop body here..." break done -- cgit v1.2.3 From f28d33fb187bc834e6e2956117039f9abe3b6d9b Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 19 Sep 2013 17:10:53 -0500 Subject: Edit wording on in c changes. --- c.html.markdown | 53 +++++++++++++++++++++++++---------------------------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index fd0b7964..89bfbe6d 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -39,7 +39,7 @@ Multi-line comments look like this. They work in C89 as well. //print formatting: "%d" // integer -"%3d" // minimum length of 3 digits for integer (right justifies text) +"%3d" // integer with minimum of length 3 digits (right justifies text) "%s" // string "%f" // float "%ld" // long @@ -51,7 +51,7 @@ Multi-line comments look like this. They work in C89 as well. "%o" // octal "%%" // prints % -// Constants: use #define keyword, no semicolon at end. +// Constants: #define (no semicolon at end) #define DAYS_IN_YEAR = 365 //enumeration constants are also ways to declare constants. @@ -62,7 +62,6 @@ enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; #include #include #include -#include // (File names between are headers from the C standard library.) // For your own headers, use double quotes instead of angle brackets: @@ -111,7 +110,7 @@ int main() { unsigned int ux_int; unsigned long long ux_long_long; - // chars inside single quotes '*' are integers in your character set. + // chars inside single quotes are integers in machine's character set. '0' //==> 48 on the ASCII character set. 'A' //==> 65 on the ASCII character set. @@ -226,20 +225,14 @@ int main() { 0 || 1; // => 1 (Logical or) 0 || 0; // => 0 - //Conditional expression ( ?: ) + //Conditional expression ( ? : ) int a, b, z; - z = (a > b) ? a : b; // z = max(a, b); + z = (a > b) ? a : b; // "if a > b return a, else return b." //Increment and decrement operators: - int j = 0; - char s[]; - int w = 0; - j++; //difference between postfix and prefix explained below - ++j; // in string example. - j--; - --j; s[j++]; //returns value of j to s THEN increments value of j. s[++j]; //increments value of j THEN returns value of j to s. + // same with j-- and --j // Bitwise operators! ~0x0F; // => 0xF0 (bitwise negation, "1's complement") @@ -267,12 +260,6 @@ int main() { printf("I print\n"); } - // Notes: - // Loops MUST always have a body. If no body is needed, do this: - for (i = 0; i <= 5; i++) { - ; // use semicolon to act as the body (null statement) - } - // While loops exist int ii = 0; while (ii < 10) { //ANY value not zero is true. @@ -297,6 +284,12 @@ int main() { printf("\n"); + // *****NOTES*****: + // Loops MUST always have a body. If no body is needed, do: + for (i = 0; i <= 5; i++) { + ; // use semicolon to act as the body (null statement) + } + // branching with multiple choices: switch() switch (some_integral_expression) { case 0: // labels need to be integral *constant* epxressions @@ -448,18 +441,20 @@ int add_two_ints(int x1, int x2) return x1 + x2; // Use return to return a value } -// Must declare a 'funtion prototype' before main() when creating functions -// in file. +// Must declare a 'funtion prototype' when creating functions before main() void getInt(char c); // function prototype -int main() { +int main() { // main function return 0; } void getInt(char w) { //parameter name does not need to match function prototype ; } -//if function takes no parameters, do: int getInt(void); for function prototype -// and for the function declaration: int getInt(void) {} -// this is to keep compatibility with older versions of C. + +//if function takes no parameters, do: +int getInt(void); for function prototype +// and for the function declaration: +int getInt(void) {} +// (this is to keep compatibility with older versions of C). /* Functions are call by value. So when a function is called, the arguments passed @@ -485,11 +480,13 @@ void str_reverse(char *str_in) } } +///////////////////////////////////// // Built in functions: +///////////////////////////////////// // from stdio.h: -int c = getchar(); //reads character from input. If input = hi, only h is read. -// getchar() can be stored into int or char. I am using int because -// char is not large enough to store EOF used below. +// getchar() +int c = getchar(); //reads character from input. +// If input = hi, 'h' is returned then next call, 'i' returned. while ((c = getchar()) != EOF) { // EOF constant "end of file". // Linux: CTRL+D, Windows: CTRL+X // must have () around getchar() as != is run before =. -- cgit v1.2.3 From 9e14fd6d364e9e33fcc5ad38c47dafd27e4e37ee Mon Sep 17 00:00:00 2001 From: Scott Feeney Date: Fri, 20 Sep 2013 01:25:36 -0400 Subject: Haskell: fix comment out of sync with code --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 -- cgit v1.2.3 From bc4fbec14d8d343aa2da7a3bcab97fcce71867b8 Mon Sep 17 00:00:00 2001 From: Adam Date: Thu, 19 Sep 2013 23:23:20 -0700 Subject: Updated perl-es --- es-es/perl-es.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown index b1327997..4f0c26c1 100644 --- a/es-es/perl-es.html.markdown +++ b/es-es/perl-es.html.markdown @@ -4,7 +4,10 @@ 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. -- cgit v1.2.3 From e555c285f253d125b2f33fee887ad9fb1ea8fb9d Mon Sep 17 00:00:00 2001 From: Joao Marques Date: Fri, 20 Sep 2013 08:40:39 +0100 Subject: Added pt-pt brainfuck translation. --- pt-pt/brainfuck-pt.html.markdown | 82 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 pt-pt/brainfuck-pt.html.markdown diff --git a/pt-pt/brainfuck-pt.html.markdown b/pt-pt/brainfuck-pt.html.markdown new file mode 100644 index 00000000..0ac97269 --- /dev/null +++ b/pt-pt/brainfuck-pt.html.markdown @@ -0,0 +1,82 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] + - ["Joao Marques", "http://github.com/mrshankly"] +--- + +Brainfuck (não capitalizado excepto no início de uma frase) é uma linguagem de +programação Turing-completa extremamente simples com apenas 8 comandos. + +``` +Qualquer caractere excepto "><+-.,[]" (não contar com as aspas) é ignorado. + +Brainfuck é representado por um vector com 30 000 células inicializadas a zero +e um ponteiro de dados que aponta para a célula actual. + +Existem 8 comandos: ++ : Incrementa o valor da célula actual em 1. +- : Decrementa o valor da célula actual 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 actual. (ex. 65 = 'A'). +, : Lê um único caractere para a célula actual. +[ : Se o valor da célula actual for zero, salta para o ] correspondente. + Caso contrário, passa para a instrução seguinte. +] : Se o valor da célula actual 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. + +Vejamos alguns programas básicos de 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. Incrementa-se o valor da célula #1 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 encontramo-nos 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, é então impresso o valor da célula #2. Ao valor +65 corresponde o caractere 'A' em ASCII, 'A' é então impresso para o 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, 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á a apontar 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: + +,[>+<-]>. + +Tenta descobrir o que este programa faz: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa lê dois números e multiplica-os. + +Basicamente o programa pede dois caracteres ao utilizador. 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. Contudo, 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. +``` + +Fica então explicado brainfuck. Simples, não? Por divertimento podes escrever os +teus próprios programas em brainfuck, ou então escrever um interpretador de +brainfuck noutra linguagem. O interpretador é relativamente fácil de se +implementar, mas se fores masoquista, tenta escrever um interpretador de +brainfuck… em brainfuck. -- cgit v1.2.3 From 40126e931c33f9302dc02f2ecc6f08767051410e Mon Sep 17 00:00:00 2001 From: Joao Marques Date: Fri, 20 Sep 2013 08:59:14 +0100 Subject: Fix header. --- pt-pt/brainfuck-pt.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pt-pt/brainfuck-pt.html.markdown b/pt-pt/brainfuck-pt.html.markdown index 0ac97269..60750de8 100644 --- a/pt-pt/brainfuck-pt.html.markdown +++ b/pt-pt/brainfuck-pt.html.markdown @@ -3,7 +3,9 @@ language: brainfuck contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: - ["Joao Marques", "http://github.com/mrshankly"] +lang: pt-pt --- Brainfuck (não capitalizado excepto no início de uma frase) é uma linguagem de -- cgit v1.2.3 From 8c00a882483fbc99922a54b94ae423c9bda8fc84 Mon Sep 17 00:00:00 2001 From: Tim Macfarlane Date: Fri, 20 Sep 2013 10:31:28 +0200 Subject: learn pogoscript --- pogo.html.markdown | 258 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 258 insertions(+) create mode 100644 pogo.html.markdown diff --git a/pogo.html.markdown b/pogo.html.markdown new file mode 100644 index 00000000..6c619e0b --- /dev/null +++ b/pogo.html.markdown @@ -0,0 +1,258 @@ +--- +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. + +# variables + +defining a variable + +``` +water temperature = 24 +``` + +re-assigning a variable after its definition + +``` +water temperature := 26 +``` + +## functions + +functions allow their parameters to be placed anywhere + +``` +temperature at (altitude) altitude = 32 - altitude / 100 +``` + +longer functions are just indented + +``` +temperature at (altitude) altitude := + if (altitude < 0) + water temperature + else + 32 - altitude / 100 +``` + +calling a function + +``` +current temperature = temperature at 3200 altitude +``` + +## objects and methods +this function constructs a new object + +``` +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) +} +``` + +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.' + +// Allen Ginsburg +``` + +interpolation + +``` +outlook = 'amazing!' +console.log "the weather tomorrow is going to be #(outlook)" +``` + +## regular expressions + +``` +r/(\d+)m/ +``` + +## 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) +``` + +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 () +``` + +# more on functions + +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 + +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 + +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 + +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)" +``` + +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! -- cgit v1.2.3 From 49b30c38e2741162bd1661e020fe80c80759dee3 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Fri, 20 Sep 2013 19:17:10 +0930 Subject: Add missing semicolon --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 2f742574..9adc0a6d 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -359,7 +359,7 @@ myObj.meaningOfLife; // = 43 // are given when they're created with that constructor and the new keyword. myConstructor.prototype = { getMyNumber: function(){ - return this.myNumber + return this.myNumber; } }; var myNewObj2 = new myConstructor(); -- cgit v1.2.3 From 750b2a2f21262fc011d5ee07362c667223d3de23 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Fri, 20 Sep 2013 19:22:00 +0930 Subject: [javascript] clarify constructor prototype example, as per #204 --- javascript.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index 9adc0a6d..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; } }; 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. -- cgit v1.2.3 From 1405dc6387ad95f0161e788a27340e02f3f82471 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Fri, 20 Sep 2013 19:32:58 +0930 Subject: [python] Clarify setdefault, as per #234 --- python.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index bad9a360..bbb493da 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -224,7 +224,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 @@ -282,9 +282,9 @@ prints: for animal in ["dog", "cat", "mouse"]: # You can use % to interpolate formatted strings 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 @@ -459,7 +459,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 -- cgit v1.2.3 From 6d8ffb19b4858d88fc33599aab279a849991c0d8 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Fri, 20 Sep 2013 19:33:39 +0930 Subject: [python] Fix typo in comment, as per #265 --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index bbb493da..ff6781da 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -235,7 +235,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} -- cgit v1.2.3 From b0ff6fad112076d91fac51a4050faa8aadc38e30 Mon Sep 17 00:00:00 2001 From: Tim Macfarlane Date: Fri, 20 Sep 2013 12:14:56 +0200 Subject: one big code block, plus some clarifications --- pogo.html.markdown | 198 +++++++++++++++++++---------------------------------- 1 file changed, 71 insertions(+), 127 deletions(-) diff --git a/pogo.html.markdown b/pogo.html.markdown index 6c619e0b..2e856825 100644 --- a/pogo.html.markdown +++ b/pogo.html.markdown @@ -7,48 +7,27 @@ 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. -# variables - -defining a variable - ``` +// defining a variable water temperature = 24 -``` -re-assigning a variable after its definition - -``` +// re-assigning a variable after its definition water temperature := 26 -``` - -## functions - -functions allow their parameters to be placed anywhere - -``` -temperature at (altitude) altitude = 32 - altitude / 100 -``` -longer functions are just indented +// functions allow their parameters to be placed anywhere +temperature at (a) altitude = 32 - a / 100 -``` -temperature at (altitude) altitude := - if (altitude < 0) +// longer functions are just indented +temperature at (a) altitude := + if (a < 0) water temperature else - 32 - altitude / 100 -``` + 32 - a / 100 -calling a function - -``` +// calling a function current temperature = temperature at 3200 altitude -``` - -## objects and methods -this function constructs a new object -``` +// this function constructs a new object with methods position (x, y) = { x = x y = y @@ -58,42 +37,32 @@ position (x, y) = { dy = self.y - p.y Math.sqrt (dx * dx + dy * dy) } -``` -calling methods +// `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 -``` +// as in JavaScript, objects are hashes too position.'x' == position.x == position.('x') -``` - -## arrays -``` +// arrays positions = [ position (1, 1) position (1, 2) position (1, 3) ] -``` - -indexing an array -``` +// indexing an array positions.0.y n = 2 positions.(n).y -``` -## strings - -``` +// 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. @@ -103,25 +72,17 @@ poem = 'Tail turned to red sunset on a juniper crown a lone magpie cawks. Sky reddens behind fir trees, larks twitter, sparrows cheep cheep cheep cheep cheep.' -// Allen Ginsburg -``` +// that's Allen Ginsburg -interpolation - -``` +// interpolation outlook = 'amazing!' console.log "the weather tomorrow is going to be #(outlook)" -``` - -## regular expressions - -``` -r/(\d+)m/ -``` -## operators +// regular expressions +r/(\d+)m/i +r/(\d+) degrees/mg -``` +// operators true @and true false @or true @not false @@ -130,44 +91,23 @@ false @or true 2 > 1 // plus all the javascript ones -``` - -to define your own -``` +// to define your own (p1) plus (p2) = position (p1.x + p2.x, p1.y + p2.y) -``` -can be called as an operator - -``` +// `plus` can be called as an operator position (1, 1) @plus position (0, 2) -``` - -or as a function - -``` +// or as a function (position (1, 1)) plus (position (0, 2)) -``` - -explicit return -``` +// explicit return (x) times (y) = return (x * y) -``` -new - -``` +// new now = @new Date () -``` - -# more on functions - -functions can take named optional arguments -``` +// functions can take named optional arguments spark (position, color: 'black', velocity: {x = 0, y = 0}) = { color = color position = position @@ -176,21 +116,16 @@ spark (position, color: 'black', velocity: {x = 0, y = 0}) = { red = spark (position 1 1, color: 'red') fast black = spark (position 1 1, velocity: {x = 10, y = 0}) -``` - -functions can unsplat arguments too -``` +// functions can unsplat arguments too log (messages, ...) = console.log (messages, ...) -``` -## blocks +// 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 -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 @@ -202,53 +137,62 @@ render each @(spark) into canvas context @(c) Math.PI * 2 ) ctx.stroke () -``` -## asynchronous calls +// asynchronous calls -Node.js includes the `fs` module for accessing the file system. -Let's list the contents of a directory +// 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()`. +// `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 +// 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 +// 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 -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 +// 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' + } -we don't wait for either of these calls to finish +// 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 -``` +// 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. -- cgit v1.2.3 From de36671ac194983a0b18d6a93b9f20f58f23be8f Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Fri, 20 Sep 2013 19:49:38 +0930 Subject: [python] Change to print function, as per #119 --- python.html.markdown | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index ff6781da..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. @@ -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,7 +283,7 @@ 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 @@ -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 -- cgit v1.2.3 From 609cc474c4f0a0a2b01bc3f1bf54918211bf8ddd Mon Sep 17 00:00:00 2001 From: Tim Macfarlane Date: Fri, 20 Sep 2013 12:43:05 +0200 Subject: added javascript highlighting --- pogo.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pogo.html.markdown b/pogo.html.markdown index 2e856825..60a83edd 100644 --- a/pogo.html.markdown +++ b/pogo.html.markdown @@ -7,7 +7,7 @@ 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 -- cgit v1.2.3 From 95faf8f5d2515c01c8eaae233291cc240ebb071d Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Fri, 20 Sep 2013 14:19:16 +0300 Subject: some updates on brainfuck/tr . i missed out "not capitalized except at the start of a sentence" about brainfuck --- tr-tr/brainfuck-tr.html.markdown | 57 ++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/brainfuck-tr.html.markdown index a6f6f078..baca4217 100644 --- a/tr-tr/brainfuck-tr.html.markdown +++ b/tr-tr/brainfuck-tr.html.markdown @@ -8,44 +8,45 @@ translators: lang: tr-tr --- -Brainfuck son derece minimal bir programlama dilidir. (Sadece 8 komut) ve -tamamen Turing'dir. +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 +"><+-.,[]" (tırnak işaretleri hariç) karakterleri dışındaki her karakter gözardı edilir. -Brainfuck is represented by an array with 30,000 cells initialized to zero -and a data pointer pointing at the current cell. +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. -There are eight commands: +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. +[ : 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. +] : 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. +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 +#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 +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. +#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. , [ > + < - ] > . @@ -53,14 +54,14 @@ yazdırıyoruz. 65 değerinin ASCII karşılığı 'A'dır. Ekrana 'A' yazılaca 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 +, 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ü +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 +Boşluk karakteri sadece okunabilirliği artırmak içindir. Aşağıdaki gibi de yazabilirsiniz. ,[>+<-]>. @@ -68,19 +69,19 @@ 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 +Ö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 +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. +İş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. -- cgit v1.2.3 From d3c5a723999b57774169e5cce28bebd3fc943cea Mon Sep 17 00:00:00 2001 From: JongChan Choi Date: Sat, 21 Sep 2013 04:17:53 +0900 Subject: fix typo --- brainfuck.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown index 9282381f..9cc7a937 100644 --- a/brainfuck.html.markdown +++ b/brainfuck.html.markdown @@ -53,25 +53,25 @@ 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 +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, we also increment cell #4, and then recopy cell #4 into cell #2. ``` -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. -- cgit v1.2.3 From 6eb210258d6c21a6634e1a459cd061a404ca78ba Mon Sep 17 00:00:00 2001 From: JongChan Choi Date: Sat, 21 Sep 2013 05:01:47 +0900 Subject: make explanation richer --- brainfuck.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown index 9cc7a937..27ac6921 100644 --- a/brainfuck.html.markdown +++ b/brainfuck.html.markdown @@ -67,8 +67,10 @@ 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, +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 -- cgit v1.2.3 From 09fe6eb5878d926196bc4bf23ec3dfae7aeeb81e Mon Sep 17 00:00:00 2001 From: JongChan Choi Date: Sat, 21 Sep 2013 05:14:20 +0900 Subject: add korean translation of brainfuck --- ko-kr/brainfuck-kr.html.markdown | 83 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 ko-kr/brainfuck-kr.html.markdown 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이 됩니다. +그럼 다시 바깥 루프를 돌 때에 안쪽의 루프를 돌지 않게 되는데, 이를 해결하려면 +네번째 칸의 값도 같이 증가시킨 다음, 그 값을 두번째 칸으로 옮기면 됩니다. +그러면 세번째 칸에 곱셈의 결과가 남습니다. +``` + +여기까지 브레인퍽이었습니다. 참 쉽죠? +재미삼아 브레인퍽 프로그램이나 다른 언어로 브레인퍽 인터프리터를 작성해보세요. +인터프리터 구현은 간단한 편인데, +사서 고생하는 것을 즐기는 편이라면 한 번 작성해보세요… 브레인퍽으로. -- cgit v1.2.3 From 2ef41199266fefc868dd28c3e0ac5dc55daf9d8f Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 20 Sep 2013 21:53:42 -0500 Subject: Fix typo for 'funtion prototype' --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index fd0b7964..68ef7f03 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -448,7 +448,7 @@ int add_two_ints(int x1, int x2) return x1 + x2; // Use return to return a value } -// Must declare a 'funtion prototype' before main() when creating functions +// Must declare a 'function prototype' before main() when creating functions // in file. void getInt(char c); // function prototype int main() { -- cgit v1.2.3 From 7c559d57a88143b0cbe7b16dbd071f0e07c83b32 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 20 Sep 2013 22:05:08 -0500 Subject: Move special characters to end of file --- c.html.markdown | 61 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 2a65d82c..9745ed9a 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -20,37 +20,6 @@ memory management and C will take you as far as you need to go. Multi-line comments look like this. They work in C89 as well. */ -//Special characters: -'\a' // alert (bell) character -'\n' // newline character -'\t' // tab character (left justifies text) -'\v' // vertical tab -'\f' // new page (formfeed) -'\r' // carriage return -'\b' // backspace character -'\0' // null character. Usually put at end of strings in C lang. - // hello\n\0. \0 used by convention to mark end of string. -'\\' // backspace -'\?' // question mark -'\'' // single quote -'\"' // double quote -'\xhh' // hexadecimal number. Example: '\xb' = vertical tab character -'\ooo' // octal number. Example: '\013' = vertical tab character - -//print formatting: -"%d" // integer -"%3d" // integer with minimum of length 3 digits (right justifies text) -"%s" // string -"%f" // float -"%ld" // long -"%3.2f" // minimum 3 digits left and 2 digits right decimal float -"%7.4s" // (can do with strings too) -"%c" // char -"%p" // pointer -"%x" // hexidecimal -"%o" // octal -"%%" // prints % - // Constants: #define (no semicolon at end) #define DAYS_IN_YEAR = 365 @@ -590,6 +559,36 @@ typedef void (*my_fnp_type)(char *); // ... // my_fnp_type f; +//Special characters: +'\a' // alert (bell) character +'\n' // newline character +'\t' // tab character (left justifies text) +'\v' // vertical tab +'\f' // new page (formfeed) +'\r' // carriage return +'\b' // backspace character +'\0' // null character. Usually put at end of strings in C lang. + // hello\n\0. \0 used by convention to mark end of string. +'\\' // backspace +'\?' // question mark +'\'' // single quote +'\"' // double quote +'\xhh' // hexadecimal number. Example: '\xb' = vertical tab character +'\ooo' // octal number. Example: '\013' = vertical tab character + +//print formatting: +"%d" // integer +"%3d" // integer with minimum of length 3 digits (right justifies text) +"%s" // string +"%f" // float +"%ld" // long +"%3.2f" // minimum 3 digits left and 2 digits right decimal float +"%7.4s" // (can do with strings too) +"%c" // char +"%p" // pointer +"%x" // hexidecimal +"%o" // octal +"%%" // prints % /////////////////////////////////////// // Order of Evaluation -- cgit v1.2.3 From 35909645f2dbfedc38b566ec9838c2202cd51e3c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 20 Sep 2013 22:13:10 -0500 Subject: Edit note on function prototypes. --- c.html.markdown | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 9745ed9a..df6cd036 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -41,6 +41,10 @@ enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; void function_1(); void function_2(); +// Must declare a 'function prototype' before main() when functions occur after +// your main() function. +int add_two_ints(int x1, int x2); // function prototype + // Your program's entry point is a function called // main with an integer return type. int main() { @@ -410,15 +414,6 @@ int add_two_ints(int x1, int x2) return x1 + x2; // Use return to return a value } -// Must declare a 'function prototype' before main() when creating functions -void getInt(char c); // function prototype -int main() { // main function - return 0; -} -void getInt(char w) { //parameter name does not need to match function prototype - ; -} - //if function takes no parameters, do: int getInt(void); for function prototype // and for the function declaration: -- cgit v1.2.3 From f471616ccb97e5fd32393f1f408394cfebe0d151 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 20 Sep 2013 22:16:01 -0500 Subject: Remove .orig file created during merge. --- c.html.markdown.orig | 641 --------------------------------------------------- 1 file changed, 641 deletions(-) delete mode 100644 c.html.markdown.orig diff --git a/c.html.markdown.orig b/c.html.markdown.orig deleted file mode 100644 index 47996cb2..00000000 --- a/c.html.markdown.orig +++ /dev/null @@ -1,641 +0,0 @@ ---- -language: c -filename: learnc.c -contributors: - - ["Adam Bard", "http://adambard.com/"] - - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - ---- - -Ah, C. Still **the** language of modern high-performance computing. - -C is the lowest-level language most programmers will ever use, but -it more than makes up for it with raw speed. Just be aware of its manual -memory management and C will take you as far as you need to go. - -```c -// Single-line comments start with // - only available in C99 and later. - -/* -Multi-line comments look like this. They work in C89 as well. -*/ - -//Special characters: -'\a' // alert (bell) character -'\n' // newline character -'\t' // tab character (left justifies text) -'\v' // vertical tab -'\f' // new page (formfeed) -'\r' // carriage return -'\b' // backspace character -'\0' // null character. Usually put at end of strings in C lang. - // hello\n\0. \0 used by convention to mark end of string. -'\\' // backspace -'\?' // question mark -'\'' // single quote -'\"' // double quote -'\xhh' // hexadecimal number. Example: '\xb' = vertical tab character -'\ooo' // octal number. Example: '\013' = vertical tab character - -//print formatting: -"%d" // integer -"%3d" // integer with minimum of length 3 digits (right justifies text) -"%s" // string -"%f" // float -"%ld" // long -"%3.2f" // minimum 3 digits left and 2 digits right decimal float -"%7.4s" // (can do with strings too) -"%c" // char -"%p" // pointer -"%x" // hexidecimal -"%o" // octal -"%%" // prints % - -// Constants: #define (no semicolon at end) -#define DAYS_IN_YEAR = 365 - -//enumeration constants are also ways to declare constants. -enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; -// MON gets 2 automatically, TUE gets 3, etc. - -// Import headers with #include -#include -#include -#include - -// (File names between are headers from the C standard library.) -// For your own headers, use double quotes instead of angle brackets: -#include "my_header.h" - -// Declare function signatures in advance in a .h file, or at the top of -// your .c file. -void function_1(); -void function_2(); - -// Your program's entry point is a function called -// main with an integer return type. -int main() { - // print output using printf, for "print formatted" - // %d is an integer, \n is a newline - printf("%d\n", 0); // => Prints 0 - // All statements must end with a semicolon - - /////////////////////////////////////// - // Types - /////////////////////////////////////// - - // ints are usually 4 bytes - int x_int = 0; - - // shorts are usually 2 bytes - short x_short = 0; - - // chars are guaranteed to be 1 byte - char x_char = 0; - char y_char = 'y'; // Char literals are quoted with '' - - // longs are often 4 to 8 bytes; long longs are guaranteed to be at least - // 64 bits - long x_long = 0; - long long x_long_long = 0; - - // floats are usually 32-bit floating point numbers - float x_float = 0.0; - - // doubles are usually 64-bit floating-point numbers - double x_double = 0.0; - - // Integral types may be unsigned. - unsigned short ux_short; - unsigned int ux_int; - unsigned long long ux_long_long; - - // chars inside single quotes are integers in machine's character set. - '0' //==> 48 on the ASCII character set. - 'A' //==> 65 on the ASCII character set. - - // sizeof(T) gives you the size of a variable with type T in bytes - // sizeof(obj) yields the size of the expression (variable, literal, etc.). - printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) - - - // If the argument of the `sizeof` operator an expression, then its argument - // is not evaluated (except VLAs (see below)). - // The value it yields in this case is a compile-time constant. - int a = 1; - size_t size = sizeof(a++); // a++ is not evaluated - printf("sizeof(a++) = %zu where a = %d\n", size, a); - // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) - - // Arrays must be initialized with a concrete size. - char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes - int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes - // (assuming 4-byte words) - - - // You can initialize an array to 0 thusly: - char my_array[20] = {0}; - - // Indexing an array is like other languages -- or, - // rather, other languages are like C - my_array[0]; // => 0 - - // Arrays are mutable; it's just memory! - my_array[1] = 2; - printf("%d\n", my_array[1]); // => 2 - - // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) - // can be declared as well. The size of such an array need not be a compile - // time constant: - printf("Enter the array size: "); // ask the user for an array size - char buf[0x100]; - fgets(buf, sizeof buf, stdin); - - // strtoul parses a string to an unsigned integer - size_t size = strtoul(buf, NULL, 10); - int var_length_array[size]; // declare the VLA - printf("sizeof array = %zu\n", sizeof var_length_array); - - // A possible outcome of this program may be: - // > Enter the array size: 10 - // > sizeof array = 40 - - // Strings are just arrays of chars terminated by a NUL (0x00) byte, - // represented in strings as the special character '\0'. - // (We don't have to include the NUL byte in string literals; the compiler - // inserts it at the end of the array for us.) - char a_string[20] = "This is a string"; - printf("%s\n", a_string); // %s formats a string - - printf("%d\n", a_string[16]); // => 0 - // i.e., byte #17 is 0 (as are 18, 19, and 20) - - // If we have characters between single quotes, that's a character literal. - // It's of type `int`, and *not* `char` (for historical reasons). - int cha = 'a'; // fine - char chb = 'a'; // fine too (implicit conversion from int to char) - - /////////////////////////////////////// - // Operators - /////////////////////////////////////// - - int i1 = 1, i2 = 2; // Shorthand for multiple declaration - float f1 = 1.0, f2 = 2.0; - - //more shorthands: - int a, b, c; - a = b = c = 0; - - // Arithmetic is straightforward - i1 + i2; // => 3 - i2 - i1; // => 1 - i2 * i1; // => 2 - i1 / i2; // => 0 (0.5, but truncated towards 0) - - f1 / f2; // => 0.5, plus or minus epsilon - // Floating-point numbers and calculations are not exact - - // Modulo is there as well - 11 % 3; // => 2 - - // Comparison operators are probably familiar, but - // there is no boolean type in c. We use ints instead. - // (Or _Bool or bool in C99.) - // 0 is false, anything else is true. (The comparison - // operators always yield 0 or 1.) - 3 == 2; // => 0 (false) - 3 != 2; // => 1 (true) - 3 > 2; // => 1 - 3 < 2; // => 0 - 2 <= 2; // => 1 - 2 >= 2; // => 1 - - // C is not Python - comparisons don't chain. - int a = 1; - // WRONG: - int between_0_and_2 = 0 < a < 2; - // Correct: - int between_0_and_2 = 0 < a && a < 2; - - // Logic works on ints - !3; // => 0 (Logical not) - !0; // => 1 - 1 && 1; // => 1 (Logical and) - 0 && 1; // => 0 - 0 || 1; // => 1 (Logical or) - 0 || 0; // => 0 - - //Conditional expression ( ? : ) - int a, b, z; - z = (a > b) ? a : b; // "if a > b return a, else return b." - - //Increment and decrement operators: - s[j++]; //returns value of j to s THEN increments value of j. - s[++j]; //increments value of j THEN returns value of j to s. - // same with j-- and --j - - // Bitwise operators! - ~0x0F; // => 0xF0 (bitwise negation, "1's complement") - 0x0F & 0xF0; // => 0x00 (bitwise AND) - 0x0F | 0xF0; // => 0xFF (bitwise OR) - 0x04 ^ 0x0F; // => 0x0B (bitwise XOR) - 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) - 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) - // - 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 - - /////////////////////////////////////// - // Control Structures - /////////////////////////////////////// - - if (0) { - printf("I am never run\n"); - } else if (0) { - printf("I am also never run\n"); - } else { - printf("I print\n"); - } - - // While loops exist - int ii = 0; - while (ii < 10) { //ANY value not zero is true. - printf("%d, ", ii++); // ii++ increments ii AFTER using it's current value. - } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - - printf("\n"); - - int kk = 0; - do { - printf("%d, ", kk); - } while (++kk < 10); // ++kk increments kk BEFORE using it's current value. - // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - - printf("\n"); - - // For loops too - int jj; - for (jj=0; jj < 10; jj++) { - printf("%d, ", jj); - } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - - printf("\n"); - - // *****NOTES*****: - // Loops MUST always have a body. If no body is needed, do: - for (i = 0; i <= 5; i++) { - ; // use semicolon to act as the body (null statement) - } - - // branching with multiple choices: switch() - switch (some_integral_expression) { - case 0: // labels need to be integral *constant* epxressions - do_stuff(); - break; // if you don't break, control flow falls over labels - case 1: - do_something_else(); - break; - default: - // if `some_integral_expression` didn't match any of the labels - fputs("error!\n", stderr); - exit(-1); - break; - } - - - /////////////////////////////////////// - // Typecasting - /////////////////////////////////////// - - // Every value in C has a type, but you can cast one value into another type - // if you want (with some constraints). - - int x_hex = 0x01; // You can assign vars with hex literals - - // Casting between types will attempt to preserve their numeric values - printf("%d\n", x_hex); // => Prints 1 - printf("%d\n", (short) x_hex); // => Prints 1 - printf("%d\n", (char) x_hex); // => Prints 1 - - // Types will overflow without warning - printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long) - - // For determining the max value of a `char`, a `signed char` and an `unisigned char`, - // respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from - - // Integral types can be cast to floating-point types, and vice-versa. - printf("%f\n", (float)100); // %f formats a float - printf("%lf\n", (double)100); // %lf formats a double - printf("%d\n", (char)100.0); - - /////////////////////////////////////// - // Pointers - /////////////////////////////////////// - - // A pointer is a variable declared to store a memory address. Its declaration will - // also tell you the type of data it points to. You can retrieve the memory address - // of your variables, then mess with them. - - int x = 0; - printf("%p\n", (void *)&x); // Use & to retrieve the address of a variable - // (%p formats an object pointer of type void *) - // => Prints some address in memory; - - - // Pointers start with * in their declaration - int *px, not_a_pointer; // px is a pointer to an int - px = &x; // Stores the address of x in px - printf("%p\n", (void *)px); // => Prints some address in memory - printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); - // => Prints "8, 4" on a typical 64-bit system - - // To retreive the value at the address a pointer is pointing to, - // put * in front to de-reference it. - // Note: yes, it may be confusing that '*' is used for _both_ declaring a - // pointer and dereferencing it. - printf("%d\n", *px); // => Prints 0, the value of x - - // You can also change the value the pointer is pointing to. - // We'll have to wrap the de-reference in parenthesis because - // ++ has a higher precedence than *. - (*px)++; // Increment the value px is pointing to by 1 - printf("%d\n", *px); // => Prints 1 - printf("%d\n", x); // => Prints 1 - - // Arrays are a good way to allocate a contiguous block of memory - int x_array[20]; //declares array of size 20 (cannot change size) - int xx; - for (xx = 0; xx < 20; xx++) { - x_array[xx] = 20 - xx; - } // Initialize x_array to 20, 19, 18,... 2, 1 - - // Declare a pointer of type int and initialize it to point to x_array - int* x_ptr = x_array; - // x_ptr now points to the first element in the array (the integer 20). - // This works because arrays often decay into pointers to their first element. - // For example, when an array is passed to a function or is assigned to a pointer, - // it decays into (implicitly converted to) a pointer. - // Exceptions: when the array is the argument of the `&` (address-od) operator: - int arr[10]; - int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`! - // It's of type "pointer to array" (of ten `int`s). - // or when the array is a string literal used for initializing a char array: - char arr[] = "foobarbazquirk"; - // or when it's the argument of the `sizeof` or `alignof` operator: - int arr[10]; - int *ptr = arr; // equivalent with int *ptr = &arr[0]; - printf("%zu %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8" - - - // Pointers are incremented and decremented based on their type - // (this is called pointer arithmetic) - printf("%d\n", *(x_ptr + 1)); // => Prints 19 - printf("%d\n", x_array[1]); // => Prints 19 - - // You can also dynamically allocate contiguous blocks of memory with the - // standard library function malloc, which takes one argument of type size_t - // representing the number of bytes to allocate (usually from the heap, although this - // may not be true on e. g. embedded systems - the C standard says nothing about it). - int *my_ptr = malloc(sizeof(*my_ptr) * 20); - for (xx = 0; xx < 20; xx++) { - *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx - } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) - - // Dereferencing memory that you haven't allocated gives - // "unpredictable results" - the program is said to invoke "undefined behavior" - printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash. - - // When you're done with a malloc'd block of memory, you need to free it, - // or else no one else can use it until your program terminates - // (this is called a "memory leak"): - free(my_ptr); - - // Strings are arrays of char, but they are usually represented as a - // pointer-to-char (which is a pointer to the first element of the array). - // It's good practice to use `const char *' when referring to a string literal, - // since string literals shall not be modified (i. e. "foo"[0] = 'a' is ILLEGAL.) - const char *my_str = "This is my very own string literal"; - printf("%c\n", *my_str); // => 'T' - - // This is not the case if the string is an array - // (potentially initialized with a string literal) - // that resides in writable memory, as in: - char foo[] = "foo"; - foo[0] = 'a'; // this is legal, foo now contains "aoo" - - function_1(); -} // end main function - -/////////////////////////////////////// -// Functions -/////////////////////////////////////// - -// Function declaration syntax: -// () - -int add_two_ints(int x1, int x2) -{ - return x1 + x2; // Use return to return a value -} - -<<<<<<< HEAD -// Must declare a 'function prototype' before main() when creating functions -// in file. -======= -// Must declare a 'funtion prototype' when creating functions before main() ->>>>>>> f28d33fb187bc834e6e2956117039f9abe3b6d9b -void getInt(char c); // function prototype -int main() { // main function - return 0; -} -void getInt(char w) { //parameter name does not need to match function prototype - ; -} - -//if function takes no parameters, do: -int getInt(void); for function prototype -// and for the function declaration: -int getInt(void) {} -// (this is to keep compatibility with older versions of C). - -/* -Functions are call by value. So when a function is called, the arguments passed -to the function are copies of original arguments (except arrays). Anything you -do to your arguments do not change the value of the actual argument where the -function was called. - -You can use pointers if you need to edit the original argument values. - -Example: in-place string reversal -*/ - -// A void function returns no value -void str_reverse(char *str_in) -{ - char tmp; - int ii = 0; - size_t len = strlen(str_in); // `strlen()` is part of the c standard library - for (ii = 0; ii < len / 2; ii++) { - tmp = str_in[ii]; - str_in[ii] = str_in[len - ii - 1]; // ii-th char from end - str_in[len - ii - 1] = tmp; - } -} - -///////////////////////////////////// -// Built in functions: -///////////////////////////////////// -// from stdio.h: -// getchar() -int c = getchar(); //reads character from input. -// If input = hi, 'h' is returned then next call, 'i' returned. -while ((c = getchar()) != EOF) { // EOF constant "end of file". - // Linux: CTRL+D, Windows: CTRL+X - // must have () around getchar() as != is run before =. - putchar(c); //prints character (without newline at end) - char c = getchar(); -} - -//if referring to external variables outside function, must use extern keyword. -int i = 0; -void testFunc() { - extern int i; //i here is now using external variable i -} - -/* -char c[] = "This is a test."; -str_reverse(c); -printf("%s\n", c); // => ".tset a si sihT" -*/ - -/////////////////////////////////////// -// User-defined types and structs -/////////////////////////////////////// - -// Typedefs can be used to create type aliases -typedef int my_type; -my_type my_type_var = 0; - -// Structs are just collections of data, the members are allocated sequentially, -// in the order they are written: -struct rectangle { - int width; - int height; -}; - -// It's not generally true that -// sizeof(struct rectangle) == sizeof(int) + sizeof(int) -// due to potential padding between the structure members (this is for alignment -// reasons). [1] - -void function_1() -{ - struct rectangle my_rec; - - // Access struct members with . - my_rec.width = 10; - my_rec.height = 20; - - // You can declare pointers to structs - struct rectangle *my_rec_ptr = &my_rec; - - // Use dereferencing to set struct pointer members... - (*my_rec_ptr).width = 30; - - // ... or even better: prefer the -> shorthand for the sake of readability - my_rec_ptr->height = 10; // Same as (*my_rec_ptr).height = 10; -} - -// You can apply a typedef to a struct for convenience -typedef struct rectangle rect; - -int area(rect r) -{ - return r.width * r.height; -} - -// if you have large structs, you can pass them "by pointer" to avoid copying -// the whole struct: -int area(const rect *r) -{ - return r->width * r->height; -} - -/////////////////////////////////////// -// Function pointers -/////////////////////////////////////// -/* -At runtime, functions are located at known memory addresses. Function pointers are -much like any other pointer (they just store a memory address), but can be used -to invoke functions directly, and to pass handlers (or callback functions) around. -However, definition syntax may be initially confusing. - -Example: use str_reverse from a pointer -*/ -void str_reverse_through_pointer(char *str_in) { - // Define a function pointer variable, named f. - void (*f)(char *); // Signature should exactly match the target function. - f = &str_reverse; // Assign the address for the actual function (determined at runtime) - // f = str_reverse; would work as well - functions decay into pointers, similar to arrays - (*f)(str_in); // Just calling the function through the pointer - // f(str_in); // That's an alternative but equally valid syntax for calling it. -} - -/* -As long as function signatures match, you can assign any function to the same pointer. -Function pointers are usually typedef'd for simplicity and readability, as follows: -*/ - -typedef void (*my_fnp_type)(char *); - -// Then used when declaring the actual pointer variable: -// ... -// my_fnp_type f; - - -/////////////////////////////////////// -// Order of Evaluation -/////////////////////////////////////// - -//---------------------------------------------------// -// Operators | Associativity // -//---------------------------------------------------// -// () [] -> . | left to right // -// ! ~ ++ -- + = *(type)sizeof | right to left // -// * / % | left to right // -// + - | left to right // -// << >> | left to right // -// < <= > >= | left to right // -// == != | left to right // -// & | left to right // -// ^ | left to right // -// | | left to right // -// && | left to right // -// || | left to right // -// ?: | right to left // -// = += -= *= /= %= &= ^= |= <<= >>= | right to left // -// , | left to right // -//---------------------------------------------------// - -``` - -## Further Reading - -Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) -It is *the* book about C, written by the creators of C. Be careful, though - it's ancient and it contains some -inaccuracies (well, ideas that are not considered good anymore) or now-changed practices. - -Another good resource is [Learn C the hard way](http://c.learncodethehardway.org/book/). - -If you have a question, read the [compl.lang.c Frequently Asked Questions](http://c-faq.com). - -It's very important to use proper spacing, indentation and to be consistent with your coding style in general. -Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the -[Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle). - -Other than that, Google is your friend. - -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member -- cgit v1.2.3 From ec7ee88698bf32bfe6e931865e94d2dac8f41c80 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 20 Sep 2013 22:19:07 -0500 Subject: Add to ? : example in C. --- c.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index df6cd036..f1e328cf 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -199,8 +199,10 @@ int main() { 0 || 0; // => 0 //Conditional expression ( ? : ) - int a, b, z; - z = (a > b) ? a : b; // "if a > b return a, else return b." + int a = 5; + int b = 10; + int z; + z = (a > b) ? a : b; // => 10 "if a > b return a, else return b." //Increment and decrement operators: s[j++]; //returns value of j to s THEN increments value of j. -- cgit v1.2.3 From 868be425a6602020f275404a8776d48f3d6d2715 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 20 Sep 2013 22:31:04 -0500 Subject: Add to notes on increment and decrement operators. --- c.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index f1e328cf..f67f6c4a 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -205,8 +205,11 @@ int main() { z = (a > b) ? a : b; // => 10 "if a > b return a, else return b." //Increment and decrement operators: - s[j++]; //returns value of j to s THEN increments value of j. - s[++j]; //increments value of j THEN returns value of j to s. + char *s = "iLoveC" + int j = 0; + s[j++]; // => "i" Returns value of j to s THEN increments value of j. + j = 0; + s[++j]; // => "L" Increments value of j THEN returns value of j to s. // same with j-- and --j // Bitwise operators! -- cgit v1.2.3 From 67cd987efa06141e5dac74f07fa8f561265c835a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 20 Sep 2013 22:33:19 -0500 Subject: Declare variable before empty for loop. --- c.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/c.html.markdown b/c.html.markdown index f67f6c4a..d075ea0e 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -264,6 +264,7 @@ int main() { // *****NOTES*****: // Loops MUST always have a body. If no body is needed, do: + int i; for (i = 0; i <= 5; i++) { ; // use semicolon to act as the body (null statement) } -- cgit v1.2.3 From 981cc871a4d4e5473e580dee8574a119ac8a9723 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 20 Sep 2013 22:37:40 -0500 Subject: Edit getchar() notes. --- c.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index d075ea0e..ee35cdd2 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -453,15 +453,14 @@ void str_reverse(char *str_in) ///////////////////////////////////// // Built in functions: ///////////////////////////////////// -// from stdio.h: -// getchar() -int c = getchar(); //reads character from input. +// from: #include +// ** getchar() ** +// int c = getchar(); //reads character from input. // If input = hi, 'h' is returned then next call, 'i' returned. while ((c = getchar()) != EOF) { // EOF constant "end of file". // Linux: CTRL+D, Windows: CTRL+X // must have () around getchar() as != is run before =. putchar(c); //prints character (without newline at end) - char c = getchar(); } //if referring to external variables outside function, must use extern keyword. -- cgit v1.2.3 From fceaa4a7cf0bcca54306ce6994f273f6b3710290 Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:05:14 -0400 Subject: added Decimal type example for C# --- csharp.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index d3adbd01..bb36d6ce 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -95,8 +95,12 @@ 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; -- cgit v1.2.3 From 81c0480780a600ef27071285e002e8ea78dc727c Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:23:24 -0400 Subject: corrected errors about the nullable types for C# --- csharp.html.markdown | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index bb36d6ce..16e3749e 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -107,7 +107,8 @@ namespace Learning // 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); @@ -142,14 +143,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 ? // ? = 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 + // ? is equivalent to writing Nullable + Nullable 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 -- cgit v1.2.3 From a2b14fcedfaa01d6dea7d7682b82fc5ddae9b84d Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:27:55 -0400 Subject: mentioned strings immutability and added details about var keyword (C#) --- csharp.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 16e3749e..c6394974 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -111,6 +111,9 @@ namespace Learning // 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); @@ -165,6 +168,8 @@ namespace Learning Console.WriteLine("Not nullable variable: " + notNullable); // Var - compiler will choose the most appropriate type based on value + // Please not 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; /////////////////////////////////////////////////// -- cgit v1.2.3 From dbfaa5ba52758cc826e710024f0be22404817e5c Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:29:03 -0400 Subject: typo (not instead of note) for C# doc --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index c6394974..2854a49b 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -168,7 +168,7 @@ namespace Learning Console.WriteLine("Not nullable variable: " + notNullable); // Var - compiler will choose the most appropriate type based on value - // Please not that this does not remove type safety. + // 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; -- cgit v1.2.3 From 41cf74fa53b1d315e2909e1ea62f4874727b578a Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:33:11 -0400 Subject: corrections for C# doc --- csharp.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 2854a49b..7239ca52 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -218,7 +218,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+) @@ -252,7 +252,6 @@ namespace Learning ~ Unary bitwise complement << Signed left shift >> Signed right shift - >>> Unsigned right shift & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR -- cgit v1.2.3 From 67b9af44925a66ac0dc278050bcaaa80fd50f21c Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:39:59 -0400 Subject: added details for the switch statement for C# --- csharp.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 7239ca52..dcbb30d1 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -343,6 +343,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; -- cgit v1.2.3 From 3b5e4837bda104ca6e23b65327f819953d1c1b2e Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:49:20 -0400 Subject: more details for the enums (C#) --- csharp.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index dcbb30d1..76af24af 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -359,7 +359,7 @@ namespace Learning /////////////////////////////////////// - // Converting Data Types And Typcasting + // Converting Data Types And Typecasting /////////////////////////////////////// // Converting data @@ -413,7 +413,7 @@ namespace Learning // Class Declaration Syntax: - // class { + // class { // //data fields, constructors, functions all inside. // //functions are called as methods in Java. // } @@ -428,11 +428,14 @@ 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 -- cgit v1.2.3 From 10bb7dbce413be31916c02b340b15f1a4e4a6a23 Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 16:00:08 -0400 Subject: various typos + added an example to declare an auto property (C#) --- csharp.html.markdown | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 76af24af..0c459bdb 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -441,7 +441,7 @@ namespace Learning // 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; @@ -486,7 +486,7 @@ namespace Learning // () // 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: // () @@ -501,13 +501,13 @@ 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; @@ -527,6 +527,11 @@ 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 @@ -552,7 +557,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. @@ -591,7 +596,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 -- cgit v1.2.3 From 758cd94b33dcfce89ab308c67725513184fb3c4b Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 16:07:43 -0400 Subject: added an example for the foreach loop in C# --- csharp.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 0c459bdb..e6a174c3 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -324,6 +324,17 @@ namespace Learning //Iterated 10 times, fooFor 0->9 } Console.WriteLine("fooFor Value: " + fooFor); + + // For Each Loop + // foreach loop structure => foreach( in ) + // The foreach loop loops over any object implementing IEnumerable or IEnumerable + // 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. -- cgit v1.2.3 From 71a62e642d2f31dcdc62aee9fd61ca6fa18d1c57 Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 16:11:45 -0400 Subject: breaking some lines (C#) --- csharp.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index e6a174c3..8b293534 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -328,7 +328,8 @@ namespace Learning // For Each Loop // foreach loop structure => foreach( in ) // The foreach loop loops over any object implementing IEnumerable or IEnumerable - // All the collection types (Array, List, Dictionary...) in the .Net framework implement one or both of these interfaces + // 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()) { @@ -518,7 +519,8 @@ namespace Learning gear = newValue; } - // Method parameters can have default 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; @@ -541,7 +543,8 @@ namespace Learning // 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: + // 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 -- cgit v1.2.3 From 6d5509e94b7e752e11285a86a2fe8f7f72e9f600 Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 16:16:04 -0400 Subject: added myself to the contributors (C#) --- csharp.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 8b293534..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 --- -- cgit v1.2.3 From c14586e8c3c285b34c20358fa97e44aeed356dde Mon Sep 17 00:00:00 2001 From: alexandre medeiros Date: Sun, 22 Sep 2013 01:06:35 -0300 Subject: add conditional execution info to bash --- bash.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 708131bd..41d0669e 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 --- @@ -51,6 +52,10 @@ else echo "And this is not" 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 )) -- cgit v1.2.3 From 9d0f731ad5c6e3e9ccda43651eb4f445fc8234f0 Mon Sep 17 00:00:00 2001 From: alexandre medeiros Date: Sun, 22 Sep 2013 01:29:05 -0300 Subject: Improve bash variable info --- bash.html.markdown | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 41d0669e..81565b6d 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -36,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?" -- cgit v1.2.3 From 9c8c0af0af1caef57f463c7c41e56ccc76f414d6 Mon Sep 17 00:00:00 2001 From: alexandre medeiros Date: Sun, 22 Sep 2013 11:04:24 -0300 Subject: add information about input, output, and error redirection --- bash.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 81565b6d..f281c1eb 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -86,6 +86,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. -- cgit v1.2.3 From 96055ac7a513fef69fd4323df465537b8df835c4 Mon Sep 17 00:00:00 2001 From: alexandre medeiros Date: Sun, 22 Sep 2013 11:09:28 -0300 Subject: better for description --- bash.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index f281c1eb..fe17e710 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -106,9 +106,10 @@ 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 -- cgit v1.2.3 From e1c34ca138cc1a978a85ba5062bed47219ac2d1c Mon Sep 17 00:00:00 2001 From: alexandre medeiros Date: Sun, 22 Sep 2013 11:20:10 -0300 Subject: improve if on bash --- bash.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index fe17e710..4a290358 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -59,11 +59,12 @@ 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 -- cgit v1.2.3 From 182eab60517e571931d7b928c28fb88a88fca894 Mon Sep 17 00:00:00 2001 From: alexandre medeiros Date: Sun, 22 Sep 2013 11:28:59 -0300 Subject: add function information for bash --- bash.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 4a290358..ed93d58b 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -115,4 +115,16 @@ 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 ``` -- cgit v1.2.3 From b3288dc9cd0e1bd39e0e6d41664b120ea2f2e02a Mon Sep 17 00:00:00 2001 From: alexandre medeiros Date: Sun, 22 Sep 2013 11:35:04 -0300 Subject: add useful commands --- bash.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index ed93d58b..4d80545e 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -127,4 +127,16 @@ foo () # 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 ``` -- cgit v1.2.3 From 86c2bafaa542f643fc8db15f3bd38dc92cfbe831 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Thu, 26 Sep 2013 15:38:48 -0400 Subject: improved first half of Julia tutorial: reworded comments, added a few new tips, fixed a bug or two. --- julia.html.markdown | 53 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index cf3a464b..e824bfcf 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -20,20 +20,20 @@ This is based on the current development version of Julia, as of June 29th, 2013 # Everything in Julia is a expression. -# You have numbers +# There are several basic types of numbers. 3 #=> 3 (Int64) 3.2 #=> 3.2 (Float64) 2 + 1im #=> 2 + 1im (Complex{Int64}) 2//3 #=> 2//3 (Rational{Int64}) -# Math is what you would expect +# All of the normal infix operators are available. 1 + 1 #=> 2 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7.0 +5 / 2 #=> 2.5 # dividing an Int by an Int always results in a Float +div(5, 2) #=> 2 # for a truncated result, use div 5 \ 35 #=> 7.0 -5 / 2 #=> 2.5 -div(5, 2) #=> 2 2 ^ 2 #=> 4 # power, not bitwise xor 12 % 10 #=> 2 @@ -77,11 +77,13 @@ false # Strings are created with " "This is a string." -# Character literals written with ' +# Character literals are written with ' 'a' -# A string can be treated like a list of characters +# A string can be indexed like an array of characters "This is a string"[1] #=> 'T' # Julia indexes from 1 +# However, this is will not work well for UTF8 strings, +# so iterating over strings is reccommended (map, for loops, etc). # $ can be used for string interpolation: "2 + 2 = $(2 + 2)" #=> "2 + 2 = 4" @@ -94,10 +96,10 @@ false ## 2. Variables and Collections #################################################### -# Printing is pretty easy +# Printing is easy println("I'm Julia. Nice to meet you!") -# No need to declare variables before assigning to them. +# You don't declare variables before assigning to them. some_var = 5 #=> 5 some_var #=> 5 @@ -108,12 +110,14 @@ catch e println(e) end -# Variable name start with a letter. You can use uppercase letters, digits, -# and exclamation points as well after the initial alphabetic character. +# Variable names start with a letter. +# After that, you can use letters, digits, underscores, and exclamation points. SomeOtherVar123! = 6 #=> 6 # You can also use unicode characters ☃ = 8 #=> 8 +# These are especially handy for mathematical notation +2 * π #=> 6.283185307179586 # A note on naming conventions in Julia: # @@ -158,6 +162,10 @@ a[1] #=> 1 # remember that Julia indexes from 1, not 0! # indexing expression a[end] #=> 6 +# we also have shift and unshift +shift!(a) #=> 1 and a is now [2,4,3,4,5,6] +unshift!(a,7) #=> [7,2,4,3,4,5,6] + # Function names that end in exclamations points indicate that they modify # their argument. arr = [5,4,6] #=> 3-element Int64 Array: [5,4,6] @@ -182,23 +190,24 @@ a = [1:5] #=> 5-element Int64 Array: [1,2,3,4,5] # You can look at ranges with slice syntax. a[1:3] #=> [1, 2, 3] a[2:] #=> [2, 3, 4, 5] +a[2:end] #=> [2, 3, 4, 5] -# Remove arbitrary elements from a list with splice! +# Remove elements from an array by index with splice! arr = [3,4,5] splice!(arr,2) #=> 4 ; arr is now [3,5] # Concatenate lists with append! b = [1,2,3] -append!(a,b) # Now a is [1, 3, 4, 5, 1, 2, 3] +append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] # Check for existence in a list with contains contains(a,1) #=> true # Examine the length with length -length(a) #=> 7 +length(a) #=> 8 # Tuples are immutable. -tup = (1, 2, 3) #=>(1,2,3) # an (Int64,Int64,Int64) tuple. +tup = (1, 2, 3) #=> (1,2,3) # an (Int64,Int64,Int64) tuple. tup[1] #=> 1 try: tup[0] = 3 #=> ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) @@ -214,17 +223,21 @@ contains(tup,2) #=> true # You can unpack tuples into variables a, b, c = (1, 2, 3) #=> (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 +# Tuples are created even if you leave out the parentheses d, e, f = 4, 5, 6 #=> (4,5,6) -# Now look how easy it is to swap two values +# A 1-element tuple is distinct from the value it contains +(1,) == 1 #=> false +(1) == 1 #=> true + +# Look how easy it is to swap two values e, d = d, e #=> (5,4) # d is now 5 and e is now 4 # Dictionaries store mappings empty_dict = Dict() #=> Dict{Any,Any}() -# Here is a prefilled dictionary +# You can create a dictionary using a literal filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] # => Dict{ASCIIString,Int64} @@ -247,19 +260,19 @@ contains(filled_dict, ("two", 3)) #=> false haskey(filled_dict, "one") #=> true haskey(filled_dict, 1) #=> false -# Trying to look up a non-existing key will raise an error +# Trying to look up a non-existant key will raise an error try filled_dict["four"] #=> ERROR: key not found: four in getindex at dict.jl:489 catch e println(e) end -# Use get method to avoid the error +# Use the get method to avoid that error by providing a default value # get(dictionary,key,default_value) get(filled_dict,"one",4) #=> 1 get(filled_dict,"four",4) #=> 4 -# Sets store sets +# Use Sets to represent collections of unordered, unique values empty_set = Set() #=> Set{Any}() # Initialize a set with a bunch of values filled_set = Set(1,2,2,3,4) #=> Set{Int64}(1,2,3,4) -- cgit v1.2.3 From c9587395d279c538f94e672b154e15f8b9f92e5b Mon Sep 17 00:00:00 2001 From: Matthieu Moquet Date: Sat, 28 Sep 2013 15:33:32 +0200 Subject: =?UTF-8?q?[Scala]=C2=A0Fix=20typo:=20forgotten=20dot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index b1b3ecbf..03c1ea76 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -374,7 +374,7 @@ import scala.collection.immutable._ import scala.collection.immutable.{List, Map} // Rename an import using '=>' -import scala.collection.immutable{ List => ImmutableList } +import scala.collection.immutable.{ List => ImmutableList } // Import all classes, except some. The following excludes Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} -- cgit v1.2.3 From 8b96638dc8555f3a85a8065435a7894671f514f7 Mon Sep 17 00:00:00 2001 From: Alexey Date: Sun, 29 Sep 2013 00:19:08 +0700 Subject: [ruby/ru-ru] Latest changes from English version && small changes in the translation --- ru-ru/ruby-ru.html.markdown | 99 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 84 insertions(+), 15 deletions(-) diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown index ead681ef..318e0e09 100644 --- a/ru-ru/ruby-ru.html.markdown +++ b/ru-ru/ruby-ru.html.markdown @@ -43,7 +43,7 @@ translators: # Логические величины -- это объекты nil # Здесь ничего нет -true # правда +true # истина false # ложь nil.class #=> NilClass @@ -79,7 +79,8 @@ false.class #=> FalseClass placeholder = "использовать интерполяцию строк" "Я могу #{placeholder}, когда создаю строку с двойными кавычками" -#=> "Я могу использовать интерполяцию строк, когда создаю строку с двойными кавычками" +#=> "Я могу использовать интерполяцию строк, +# когда создаю строку с двойными кавычками" # печатать в стандартный вывод @@ -107,10 +108,10 @@ path = '/bad/name/' # Идентификаторы (тоже объекты) # Идентификаторы -- это неизменяемые, многоразовые константы. -# Для каждого идентификатора (кроме текста) сохраняется цифровой хэш. При последующем -# использовании идентификатора, заместо создания нового объекта, будет найден уже -# существующий по цифровому хэшу. Они часто используются вместо строк -# для ускорения работы приложений +# Для каждого идентификатора (кроме текста) сохраняется цифровой хэш. +# При последующем использовании идентификатора, заместо создания нового объекта, +# будет найден уже существующий по цифровому хэшу. +# Они часто используются вместо строк для ускорения работы приложений :pending.class #=> Symbol @@ -178,15 +179,15 @@ new_hash.keys #=> [:defcon, :action] # Управление ходом выполнения (Управляющие структуры) if true - "if условие" + "Если истина" elsif false - "else if, условие" + "Иначе, если ложь (опционально)" else - "else, условие" + "Во всех других случаях" end for counter in 1..5 - puts "#итерация {counter}" + puts "итерация #{counter}" end #=> итерация 1 #=> итерация 2 @@ -197,10 +198,11 @@ end # Однако, никто не использует "for" для циклов. # Вместо него Вы должны использовать метод "each" вместе с блоком кода. # -# Блок кода -- это один из вариантов создания замыканий (лямбды, анонимные функции). +# Блок кода -- это один из вариантов создания замыканий (лямбды, +# анонимные функции). # Блок может только передаваться методу, сам по себе он существовать не может. # "for" не имеет своей области видимости и все переменные, объявленные в нём -# будут доступны отовсюду. "each" вместе с блоком создаёт свою область видимости. +# будут доступны отовсюду. "each" вместе с блоком создаёт свою область видимости # Метод "each" для диапазона значений запускает блок кода один раз # для каждого из значений диапазона @@ -219,7 +221,7 @@ end # Вы также можете ограничивать блоки фигурными скобками: (1..5).each {|counter| puts "итерация #{counter}"} -# Содержимое управляющих структур также можно перебирать используя "each": +# Содержимое структурных данных также можно перебирать используя "each": array.each do |element| puts "#{element} -- часть массива" end @@ -350,10 +352,27 @@ dwight.name #=> "Dwight K. Schrute" # Вызов метода класса Human.say("Hi") #=> "Hi" -# Класс тоже объект в Ruby. Потому класс может иметь переменные экземпляра. +# Область видимости переменной определяется тем, как мы даём имя переменной. +# Переменные, имя которых начинается с "$" имеют глобальную область видимости +$var = "I'm a global var" +defined? $var #=> "global-variable" + +# Переменная экземпляра класса, она видна только в экземпляре +@var = "I'm an instance var" +defined? @var #=> "instance-variable" + +# Переменная класса, видна для всех экземпляров этого класса и в самом классе +@@var = "I'm a class var" +defined? @@var #=> "class variable" + +# Имена переменных с большой буквы используются для создания констант +Var = "I'm a constant" +defined? Var #=> "constant" + +# Класс тоже объект в Ruby. Класс может иметь переменные экземпляра. # Переменная класса доступна в классе, его экземплярах и его потомках. -# Базовый класс +# Пример класса class Human @@foo = 0 @@ -396,4 +415,54 @@ end Human.bar # 0 Doctor.bar # nil +module ModuleExample + def foo + 'foo' + end +end + +# Включение модулей в класс добавляет их методы в экземпляр класса +# Или в сам класс, зависит только от метода подключения +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' + +# Коллбэки при подключении модуля + +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' ``` -- cgit v1.2.3 From bfd1293c4f9daa5ae3ce6dccc24b8b67c3113e07 Mon Sep 17 00:00:00 2001 From: alswl Date: Sun, 29 Sep 2013 23:09:45 +0800 Subject: translate to Chinese 100% --- zh-cn/r-cn.html.markdown | 121 +++++++++++++++++++++-------------------------- 1 file changed, 54 insertions(+), 67 deletions(-) diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown index 9a1414bb..bfb92ca9 100644 --- a/zh-cn/r-cn.html.markdown +++ b/zh-cn/r-cn.html.markdown @@ -1,3 +1,18 @@ +--- +language: R +contributors: + - ["e99n09", "http://github.com/e99n09"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] +translators: + - ["小柒", "http://weibo.com/u/2328126220"] + - ["alswl", "https://github.com/alswl"] +filename: learnr.r +--- + +R 是一门统计语言。它有很多数据分析和挖掘程序包。可以用来统计、分析和制图。 +你也可以在 LaTeX 文档中运行 `R` 命令。 + +```python # 评论以 # 开始 # R 语言原生不支持 多行注释 @@ -397,7 +412,6 @@ dat # 4 4 dog class(dat$number) # "numeric" class(dat[,2]) # "factor" -# The data.frame() function converts character vectors to factor vectors # data.frame() 会将字符向量转换为 factor 向量 # 有很多精妙的方法来获取 data frame 的子数据集 @@ -407,16 +421,14 @@ dat[,"number"] # 5 2 1 4 # 多维(相同元素类型) -# 利用数组创造一个 n 维的表格 +# 使用 arry 创造一个 n 维的表格 # You can make a two-dimensional table (sort of like a matrix) -#你可以建立一个2维表格(类型和矩阵相似) +# 你可以建立一个 2 维表格(有点像矩阵) array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) -#数组(c(c(1,2,4,5),c(8,9,3,6)),有前两个向量组成,2行4列 # => # [,1] [,2] [,3] [,4] # [1,] 1 4 8 3 # [2,] 2 5 9 6 -# You can use array to make three-dimensional matrices too #你也可以利用数组建立一个三维的矩阵 array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # => @@ -434,29 +446,25 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # [2,] 60 7 # [3,] 0 847 -# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES) #列表(多维的,不同类型的) -# Finally, R has lists (of vectors) -#R语言有列表的形式 +# R语言有列表的形式 list1 <- list(time = 1:40) -list1$price = c(rnorm(40,.5*list1$time,4)) # random +list1$price = c(rnorm(40,.5*list1$time,4)) # 随机 list1 # You can get items in the list like so -#你可以获得像上面列表的形式 +# 你可以这样获得列表的元素 list1$time # You can subset list items like vectors -#你也可以获取他们的子集,一种类似于矢量的形式 +# 你也可以和矢量一样获取他们的子集 list1$price[4] ######################### -# The apply() family of functions -#apply()函数家族的应用 +# apply()函数家族 ######################### -# Remember mat? -#输出mat矩阵 +# 还记得 mat 么? mat # => # [,1] [,2] @@ -464,90 +472,69 @@ mat # [2,] 2 5 # [3,] 3 6 # Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X -#使用(X, MARGIN, FUN)将一个function功能函数根据其特征应用到矩阵x中 -# over rows (MAR = 1) or columns (MAR = 2) -#规定行列,其边界分别为1,2 +# 使用(X, MARGIN, FUN)将函数 FUN 应用到矩阵 X 的行 (MAR = 1) 或者 列 (MAR = 2) # That is, R does FUN to each row (or column) of X, much faster than a -#即就是,R定义一个function使每一行/列的x快于一个for或者while循环 -# for or while loop would do +# R 在 X 的每一行/列使用 FUN,比循环要快很多 apply(mat, MAR = 2, myFunc) # => # [,1] [,2] # [1,] 3 15 # [2,] 7 19 # [3,] 11 23 -# Other functions: ?lapply, ?sapply -其他的功能函数, +# 还有其他家族函数 ?lapply, ?sapply -# Don't feel too intimidated; everyone agrees they are rather confusing -#不要被这些吓到,许多人在此都会容易混淆 -# The plyr package aims to replace (and improve upon!) the *apply() family. -#plyr程序包的作用是用来改进family函数家族 +# 不要被吓到,虽然许多人在此都被搞混 +# plyr 程序包的作用是用来改进 apply() 函数家族 install.packages("plyr") require(plyr) ?plyr ######################### -# Loading data +# 载入数据 ######################### -# "pets.csv" is a file on the internet -#"pets.csv" 是网上的一个文本 +# "pets.csv" 是网上的一个文本 pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") -#首先读取这个文本 pets -head(pets, 2) # first two rows -#显示前两行 -tail(pets, 1) # last row -#显示最后一行 - -# To save a data frame or matrix as a .csv file -#以.csv格式来保存数据集或者矩阵 -write.csv(pets, "pets2.csv") # to make a new .csv file -#输出新的文本pets2.csv +head(pets, 2) # 前两行 +tail(pets, 1) # 最后一行 + +# 以 .csv 格式来保存数据集或者矩阵 +write.csv(pets, "pets2.csv") # 保存到新的文件 pets2.csv # set working directory with setwd(), look it up with getwd() -#改变工作路径setwd(),查找工作路径getwd() +# 使用 setwd() 改变工作目录,使用 getwd() 查看当前工作目录 -# Try ?read.csv and ?write.csv for more information -#试着做一做以上学到的,或者运行更多的信息 +# 尝试使用 ?read.csv 和 ?write.csv 来查看更多信息 ######################### -# Plots -#画图 +# 画图 ######################### -# Scatterplots! -#散点图 -plot(list1$time, list1$price, main = "fake data") -#作图,横轴list1$time,纵轴list1$price,主题fake data -# Regressions! -#退回 -linearModel <- lm(price ~ time, data = list1) -# 线性模型,数据集为list1,以价格对时间做相关分析模型 -linearModel # outputs result of regression -#输出拟合结果,并退出 -# Plot regression line on existing plot -#将拟合结果展示在图上,颜色设为红色 +# 散点图 +plot(list1$time, list1$price, main = "fake data") # 译者注:横轴 list1$time,纵轴 wlist1$price,标题 fake data +# 回归图 +linearModel <- lm(price ~ time, data = list1) # 译者注:线性模型,数据集为list1,以价格对时间做相关分析模型 +linearModel # 拟合结果 +# 将拟合结果展示在图上,颜色设为红色 abline(linearModel, col = "red") -# Get a variety of nice diagnostics -#也可以获取各种各样漂亮的分析图 +# 也可以获取各种各样漂亮的分析图 plot(linearModel) -# Histograms! -#直方图 -hist(rpois(n = 10000, lambda = 5), col = "thistle") -#统计频数直方图() +# 直方图 +hist(rpois(n = 10000, lambda = 5), col = "thistle") # 译者注:统计频数直方图 -# Barplots! -#柱状图 +# 柱状图 barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) -#作图,柱的高度负值c(1,4,5,1,2),各个柱子的名称"red","blue","purple","green","yellow" -# Try the ggplot2 package for more and better graphics -#可以尝试着使用ggplot2程序包来美化图片 +# 可以尝试着使用 ggplot2 程序包来美化图片 install.packages("ggplot2") require(ggplot2) ?ggplot2 +``` + +## 获得 R +* 从 [http://www.r-project.org/](http://www.r-project.org/) 获得安装包和图形化界面 +* [RStudio](http://www.rstudio.com/ide/) 是另一个图形化界面 -- cgit v1.2.3 From f308445fe5a3b236880b95229ed180104faeaa25 Mon Sep 17 00:00:00 2001 From: alswl Date: Sun, 29 Sep 2013 23:10:25 +0800 Subject: dos2unix --- zh-cn/r-cn.html.markdown | 1080 +++++++++++++++++++++++----------------------- 1 file changed, 540 insertions(+), 540 deletions(-) diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown index bfb92ca9..8a542695 100644 --- a/zh-cn/r-cn.html.markdown +++ b/zh-cn/r-cn.html.markdown @@ -1,540 +1,540 @@ ---- -language: R -contributors: - - ["e99n09", "http://github.com/e99n09"] - - ["isomorphismes", "http://twitter.com/isomorphisms"] -translators: - - ["小柒", "http://weibo.com/u/2328126220"] - - ["alswl", "https://github.com/alswl"] -filename: learnr.r ---- - -R 是一门统计语言。它有很多数据分析和挖掘程序包。可以用来统计、分析和制图。 -你也可以在 LaTeX 文档中运行 `R` 命令。 - -```python -# 评论以 # 开始 - -# R 语言原生不支持 多行注释 -# 但是你可以像这样来多行注释 - -# 在窗口里按回车键可以执行一条命令 - - -################################################################### -# 不用懂编程就可以开始动手了 -################################################################### - -data() # 浏览内建的数据集 -data(rivers) # 北美主要河流的长度(数据集) -ls() # 在工作空间中查看「河流」是否出现 -head(rivers) # 撇一眼数据集 -# 735 320 325 392 524 450 -length(rivers) # 我们测量了多少条河流? -# 141 -summary(rivers) -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 135.0 310.0 425.0 591.2 680.0 3710.0 -stem(rivers) # 茎叶图(一种类似于直方图的展现形式) -# -# The decimal point is 2 digit(s) to the right of the | -# -# 0 | 4 -# 2 | 011223334555566667778888899900001111223333344455555666688888999 -# 4 | 111222333445566779001233344567 -# 6 | 000112233578012234468 -# 8 | 045790018 -# 10 | 04507 -# 12 | 1471 -# 14 | 56 -# 16 | 7 -# 18 | 9 -# 20 | -# 22 | 25 -# 24 | 3 -# 26 | -# 28 | -# 30 | -# 32 | -# 34 | -# 36 | 1 - - -stem(log(rivers)) # 查看数据集的方式既不是标准形式,也不是取log后的结果! 看起来,是钟形曲线形式的基本数据集 - -# The decimal point is 1 digit(s) to the left of the | -# -# 48 | 1 -# 50 | -# 52 | 15578 -# 54 | 44571222466689 -# 56 | 023334677000124455789 -# 58 | 00122366666999933445777 -# 60 | 122445567800133459 -# 62 | 112666799035 -# 64 | 00011334581257889 -# 66 | 003683579 -# 68 | 0019156 -# 70 | 079357 -# 72 | 89 -# 74 | 84 -# 76 | 56 -# 78 | 4 -# 80 | -# 82 | 2 - - -hist(rivers, col="#333333", border="white", breaks=25) # 试试用这些参数画画 (译者注:给 river 做统计频数直方图,包含了这些参数:数据源,颜色,边框,空格) -hist(log(rivers), col="#333333", border="white", breaks=25) #你还可以做更多式样的绘图 - -# 还有其他一些简单的数据集可以被用来加载。R 语言包括了大量这种 data() -data(discoveries) -plot(discoveries, col="#333333", lwd=3, xlab="Year", main="Number of important discoveries per year") -# 译者注:参数为(数据源,颜色,线条宽度,X 轴名称,标题) -plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", main="Number of important discoveries per year") - - -# 除了按照默认的年份排序,我们还可以排序来发现特征 -sort(discoveries) -# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 -# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 -# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 -# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 - -stem(discoveries, scale=2) # 译者注:茎叶图(数据,放大系数) -# -# The decimal point is at the | -# -# 0 | 000000000 -# 1 | 000000000000 -# 2 | 00000000000000000000000000 -# 3 | 00000000000000000000 -# 4 | 000000000000 -# 5 | 0000000 -# 6 | 000000 -# 7 | 0000 -# 8 | 0 -# 9 | 0 -# 10 | 0 -# 11 | -# 12 | 0 - -max(discoveries) -# 12 - -summary(discoveries) -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 0.0 2.0 3.0 3.1 4.0 12.0 - - - - -#基本的统计学操作也不需要任何编程知识 - -#随机生成数据 -round(runif(7, min=.5, max=6.5)) -# 译者注:runif 产生随机数,round 四舍五入 -# 1 4 6 1 4 6 4 - -# 你输出的结果会和我们给出的不同,除非我们设置了相同的随机种子 random.seed(31337) - - -#从标准高斯函数中随机生成 9 次 -rnorm(9) -# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 -# [7] -0.59975593 0.57629164 1.08455362 - - - - - - - - - -######################### -# 基础编程 -######################### - -# 数值 - -#“数值”指的是双精度的浮点数 -5 # 5 -class(5) # "numeric" -5e4 # 50000 # 用科学技术法方便的处理极大值、极小值或者可变的量级 -6.02e23 # 阿伏伽德罗常数# -1.6e-35 # 布朗克长度 - -# 长整数并用 L 结尾 -5L # 5 -#输出5L -class(5L) # "integer" - -# 可以自己试一试?用 class() 函数获取更多信息 -# 事实上,你可以找一些文件查阅 `xyz` 以及xyz的差别 -# `xyz` 用来查看源码实现,?xyz 用来看帮助 - -# 算法 -10 + 66 # 76 -53.2 - 4 # 49.2 -2 * 2.0 # 4 -3L / 4 # 0.75 -3 %% 2 # 1 - -# 特殊数值类型 -class(NaN) # "numeric" -class(Inf) # "numeric" -class(-Inf) # "numeric" # 在以下场景中会用到 integrate( dnorm(x), 3, Inf ) -- 消除 Z 轴数据 - -# 但要注意,NaN 并不是唯一的特殊数值类型…… -class(NA) # 看上面 -class(NULL) # NULL - - -# 简单列表 -c(6, 8, 7, 5, 3, 0, 9) # 6 8 7 5 3 0 9 -c('alef', 'bet', 'gimmel', 'dalet', 'he') -c('Z', 'o', 'r', 'o') == "Zoro" # FALSE FALSE FALSE FALSE - -# 一些优雅的内置功能 -5:15 # 5 6 7 8 9 10 11 12 13 14 15 - -seq(from=0, to=31337, by=1337) -# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 -# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 - -letters -# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" -# [20] "t" "u" "v" "w" "x" "y" "z" - -month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" - - -# Access the n'th element of a list with list.name[n] or sometimes list.name[[n]] -# 使用 list.name[n] 来访问第 n 个列表元素,有时候需要使用 list.name[[n]] -letters[18] # "r" -LETTERS[13] # "M" -month.name[9] # "September" -c(6, 8, 7, 5, 3, 0, 9)[3] # 7 - - - -# 字符串 - -# 字符串和字符在 R 语言中没有区别 -"Horatio" # "Horatio" -class("Horatio") # "character" -substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " -gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." - - - -# 逻辑值 - -# 布尔值 -class(TRUE) # "logical" -class(FALSE) # "logical" -# 和我们预想的一样 -TRUE == TRUE # TRUE -TRUE == FALSE # FALSE -FALSE != FALSE # FALSE -FALSE != TRUE # TRUE -# 缺失数据(NA)也是逻辑值 -class(NA) # "logical" -#定义NA为逻辑型 - - - -# 因子 -# 因子是为数据分类排序设计的(像是排序小朋友们的年级或性别) -levels(factor(c("female", "male", "male", "female", "NA", "female"))) # "female" "male" "NA" - -factor(c("female", "female", "male", "NA", "female")) -# female female male NA female -# Levels: female male NA - -data(infert) # 自然以及引产导致的不育症 -levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" - - - -# 变量 - -# 有许多种方式用来赋值 -x = 5 # 这样可以 -y <- "1" # 更推荐这样 -TRUE -> z # 这样可行,但是很怪 - -#我们还可以使用强制转型 -as.numeric(y) # 1 -as.character(x) # "5" - -# 循环 - -# for 循环语句 -for (i in 1:4) { - print(i) -} - -# while 循环 -a <- 10 -while (a > 4) { - cat(a, "...", sep = "") - a <- a - 1 -} - -# 记住,在 R 语言中 for / while 循环都很慢 -# 建议使用 apply()(我们一会介绍)来错做一串数据(比如一列或者一行数据) - -# IF/ELSE - -# 再来看这些优雅的标准 -if (4 > 3) { - print("Huzzah! It worked!") -} else { - print("Noooo! This is blatantly illogical!") -} - -# => -# [1] "Huzzah! It worked!" - -# 函数 - -# 定义如下 -jiggle <- function(x) { - x + rnorm(x, sd=.1) #add in a bit of (controlled) noise - return(x) -} - -# 和其他 R 语言函数一样调用 -jiggle(5) # 5±ε. 使用 set.seed(2716057) 后, jiggle(5)==5.005043 - -######################### -# 数据容器:vectors, matrices, data frames, and arrays -######################### - -# 单维度 -# 你可以将目前我们学习到的任何类型矢量化,只要它们拥有相同的类型 -vec <- c(8, 9, 10, 11) -vec # 8 9 10 11 -# 矢量的类型是这一组数据元素的类型 -class(vec) # "numeric" -# If you vectorize items of different classes, weird coercions happen -#如果你强制的将不同类型数值矢量化,会出现特殊值 -c(TRUE, 4) # 1 4 -c("dog", TRUE, 4) # "dog" "TRUE" "4" - -#我们这样来取内部数据,(R 的下标索引顺序 1 开始) -vec[1] # 8 -# 我们可以根据条件查找特定数据 -which(vec %% 2 == 0) # 1 3 -# 抓取矢量中第一个和最后一个字符 -head(vec, 1) # 8 -tail(vec, 1) # 11 -#如果下标溢出或不存会得到 NA -vec[6] # NA -# 你可以使用 length() 获取矢量的长度 -length(vec) # 4 - -# 你可以直接操作矢量或者矢量的子集 -vec * 4 # 16 20 24 28 -vec[2:3] * 5 # 25 30 -# 这里有许多内置的函数,来表现向量 -mean(vec) # 9.5 -var(vec) # 1.666667 -sd(vec) # 1.290994 -max(vec) # 11 -min(vec) # 8 -sum(vec) # 38 - -# 二维(相同元素类型) - -#你可以为同样类型的变量建立矩阵 -mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) -mat -# => -# [,1] [,2] -# [1,] 1 4 -# [2,] 2 5 -# [3,] 3 6 -# 和 vector 不一样的是,一个矩阵的类型真的是 「matrix」,而不是内部元素的类型 -class(mat) # => "matrix" -# 访问第一行的字符 -mat[1,] # 1 4 -# 操作第一行数据 -3 * mat[,1] # 3 6 9 -# 访问一个特定数据 -mat[3,2] # 6 -# 转置整个矩阵(译者注:变成 2 行 3 列) -t(mat) -# => -# [,1] [,2] [,3] -# [1,] 1 2 3 -# [2,] 4 5 6 - -# 使用 cbind() 函数把两个矩阵按列合并,形成新的矩阵 -mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) -mat2 -# => -# [,1] [,2] -# [1,] "1" "dog" -# [2,] "2" "cat" -# [3,] "3" "bird" -# [4,] "4" "dog" -class(mat2) # matrix -# Again, note what happened! -# 注意 -# 因为矩阵内部元素必须包含同样的类型 -# 所以现在每一个元素都转化成字符串 -c(class(mat2[,1]), class(mat2[,2])) - -# 按行合并两个向量,建立新的矩阵 -mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) -mat3 -# => -# [,1] [,2] [,3] [,4] -# [1,] 1 2 4 5 -# [2,] 6 7 0 4 -# 哈哈,数据类型都一样的,没有发生强制转换,生活真美好 - -# 二维(不同的元素类型) - -# 利用 data frame 可以将不同类型数据放在一起 -dat <- data.frame(c(5,2,1,4), c("dog", "cat", "bird", "dog")) -names(dat) <- c("number", "species") # 给数据列命名 -class(dat) # "data.frame" -dat -# => -# number species -# 1 5 dog -# 2 2 cat -# 3 1 bird -# 4 4 dog -class(dat$number) # "numeric" -class(dat[,2]) # "factor" -# data.frame() 会将字符向量转换为 factor 向量 - -# 有很多精妙的方法来获取 data frame 的子数据集 -dat$number # 5 2 1 4 -dat[,1] # 5 2 1 4 -dat[,"number"] # 5 2 1 4 - -# 多维(相同元素类型) - -# 使用 arry 创造一个 n 维的表格 -# You can make a two-dimensional table (sort of like a matrix) -# 你可以建立一个 2 维表格(有点像矩阵) -array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) -# => -# [,1] [,2] [,3] [,4] -# [1,] 1 4 8 3 -# [2,] 2 5 9 6 -#你也可以利用数组建立一个三维的矩阵 -array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) -# => -# , , 1 -# -# [,1] [,2] -# [1,] 2 8 -# [2,] 300 9 -# [3,] 4 0 -# -# , , 2 -# -# [,1] [,2] -# [1,] 5 66 -# [2,] 60 7 -# [3,] 0 847 - -#列表(多维的,不同类型的) - -# R语言有列表的形式 -list1 <- list(time = 1:40) -list1$price = c(rnorm(40,.5*list1$time,4)) # 随机 -list1 - -# You can get items in the list like so -# 你可以这样获得列表的元素 -list1$time -# You can subset list items like vectors -# 你也可以和矢量一样获取他们的子集 -list1$price[4] - -######################### -# apply()函数家族 -######################### - -# 还记得 mat 么? -mat -# => -# [,1] [,2] -# [1,] 1 4 -# [2,] 2 5 -# [3,] 3 6 -# Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X -# 使用(X, MARGIN, FUN)将函数 FUN 应用到矩阵 X 的行 (MAR = 1) 或者 列 (MAR = 2) -# That is, R does FUN to each row (or column) of X, much faster than a -# R 在 X 的每一行/列使用 FUN,比循环要快很多 -apply(mat, MAR = 2, myFunc) -# => -# [,1] [,2] -# [1,] 3 15 -# [2,] 7 19 -# [3,] 11 23 -# 还有其他家族函数 ?lapply, ?sapply - -# 不要被吓到,虽然许多人在此都被搞混 -# plyr 程序包的作用是用来改进 apply() 函数家族 - -install.packages("plyr") -require(plyr) -?plyr - -######################### -# 载入数据 -######################### - -# "pets.csv" 是网上的一个文本 -pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") -pets -head(pets, 2) # 前两行 -tail(pets, 1) # 最后一行 - -# 以 .csv 格式来保存数据集或者矩阵 -write.csv(pets, "pets2.csv") # 保存到新的文件 pets2.csv -# set working directory with setwd(), look it up with getwd() -# 使用 setwd() 改变工作目录,使用 getwd() 查看当前工作目录 - -# 尝试使用 ?read.csv 和 ?write.csv 来查看更多信息 - -######################### -# 画图 -######################### - -# 散点图 -plot(list1$time, list1$price, main = "fake data") # 译者注:横轴 list1$time,纵轴 wlist1$price,标题 fake data -# 回归图 -linearModel <- lm(price ~ time, data = list1) # 译者注:线性模型,数据集为list1,以价格对时间做相关分析模型 -linearModel # 拟合结果 -# 将拟合结果展示在图上,颜色设为红色 -abline(linearModel, col = "red") -# 也可以获取各种各样漂亮的分析图 -plot(linearModel) - -# 直方图 -hist(rpois(n = 10000, lambda = 5), col = "thistle") # 译者注:统计频数直方图 - -# 柱状图 -barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) - -# 可以尝试着使用 ggplot2 程序包来美化图片 -install.packages("ggplot2") -require(ggplot2) -?ggplot2 - -``` - -## 获得 R - -* 从 [http://www.r-project.org/](http://www.r-project.org/) 获得安装包和图形化界面 -* [RStudio](http://www.rstudio.com/ide/) 是另一个图形化界面 +--- +language: R +contributors: + - ["e99n09", "http://github.com/e99n09"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] +translators: + - ["小柒", "http://weibo.com/u/2328126220"] + - ["alswl", "https://github.com/alswl"] +filename: learnr.r +--- + +R 是一门统计语言。它有很多数据分析和挖掘程序包。可以用来统计、分析和制图。 +你也可以在 LaTeX 文档中运行 `R` 命令。 + +```python +# 评论以 # 开始 + +# R 语言原生不支持 多行注释 +# 但是你可以像这样来多行注释 + +# 在窗口里按回车键可以执行一条命令 + + +################################################################### +# 不用懂编程就可以开始动手了 +################################################################### + +data() # 浏览内建的数据集 +data(rivers) # 北美主要河流的长度(数据集) +ls() # 在工作空间中查看「河流」是否出现 +head(rivers) # 撇一眼数据集 +# 735 320 325 392 524 450 +length(rivers) # 我们测量了多少条河流? +# 141 +summary(rivers) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 +stem(rivers) # 茎叶图(一种类似于直方图的展现形式) +# +# The decimal point is 2 digit(s) to the right of the | +# +# 0 | 4 +# 2 | 011223334555566667778888899900001111223333344455555666688888999 +# 4 | 111222333445566779001233344567 +# 6 | 000112233578012234468 +# 8 | 045790018 +# 10 | 04507 +# 12 | 1471 +# 14 | 56 +# 16 | 7 +# 18 | 9 +# 20 | +# 22 | 25 +# 24 | 3 +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | +# 36 | 1 + + +stem(log(rivers)) # 查看数据集的方式既不是标准形式,也不是取log后的结果! 看起来,是钟形曲线形式的基本数据集 + +# The decimal point is 1 digit(s) to the left of the | +# +# 48 | 1 +# 50 | +# 52 | 15578 +# 54 | 44571222466689 +# 56 | 023334677000124455789 +# 58 | 00122366666999933445777 +# 60 | 122445567800133459 +# 62 | 112666799035 +# 64 | 00011334581257889 +# 66 | 003683579 +# 68 | 0019156 +# 70 | 079357 +# 72 | 89 +# 74 | 84 +# 76 | 56 +# 78 | 4 +# 80 | +# 82 | 2 + + +hist(rivers, col="#333333", border="white", breaks=25) # 试试用这些参数画画 (译者注:给 river 做统计频数直方图,包含了这些参数:数据源,颜色,边框,空格) +hist(log(rivers), col="#333333", border="white", breaks=25) #你还可以做更多式样的绘图 + +# 还有其他一些简单的数据集可以被用来加载。R 语言包括了大量这种 data() +data(discoveries) +plot(discoveries, col="#333333", lwd=3, xlab="Year", main="Number of important discoveries per year") +# 译者注:参数为(数据源,颜色,线条宽度,X 轴名称,标题) +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", main="Number of important discoveries per year") + + +# 除了按照默认的年份排序,我们还可以排序来发现特征 +sort(discoveries) +# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 +# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 +# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 +# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 + +stem(discoveries, scale=2) # 译者注:茎叶图(数据,放大系数) +# +# The decimal point is at the | +# +# 0 | 000000000 +# 1 | 000000000000 +# 2 | 00000000000000000000000000 +# 3 | 00000000000000000000 +# 4 | 000000000000 +# 5 | 0000000 +# 6 | 000000 +# 7 | 0000 +# 8 | 0 +# 9 | 0 +# 10 | 0 +# 11 | +# 12 | 0 + +max(discoveries) +# 12 + +summary(discoveries) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 + + + + +#基本的统计学操作也不需要任何编程知识 + +#随机生成数据 +round(runif(7, min=.5, max=6.5)) +# 译者注:runif 产生随机数,round 四舍五入 +# 1 4 6 1 4 6 4 + +# 你输出的结果会和我们给出的不同,除非我们设置了相同的随机种子 random.seed(31337) + + +#从标准高斯函数中随机生成 9 次 +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + + + + + + + +######################### +# 基础编程 +######################### + +# 数值 + +#“数值”指的是双精度的浮点数 +5 # 5 +class(5) # "numeric" +5e4 # 50000 # 用科学技术法方便的处理极大值、极小值或者可变的量级 +6.02e23 # 阿伏伽德罗常数# +1.6e-35 # 布朗克长度 + +# 长整数并用 L 结尾 +5L # 5 +#输出5L +class(5L) # "integer" + +# 可以自己试一试?用 class() 函数获取更多信息 +# 事实上,你可以找一些文件查阅 `xyz` 以及xyz的差别 +# `xyz` 用来查看源码实现,?xyz 用来看帮助 + +# 算法 +10 + 66 # 76 +53.2 - 4 # 49.2 +2 * 2.0 # 4 +3L / 4 # 0.75 +3 %% 2 # 1 + +# 特殊数值类型 +class(NaN) # "numeric" +class(Inf) # "numeric" +class(-Inf) # "numeric" # 在以下场景中会用到 integrate( dnorm(x), 3, Inf ) -- 消除 Z 轴数据 + +# 但要注意,NaN 并不是唯一的特殊数值类型…… +class(NA) # 看上面 +class(NULL) # NULL + + +# 简单列表 +c(6, 8, 7, 5, 3, 0, 9) # 6 8 7 5 3 0 9 +c('alef', 'bet', 'gimmel', 'dalet', 'he') +c('Z', 'o', 'r', 'o') == "Zoro" # FALSE FALSE FALSE FALSE + +# 一些优雅的内置功能 +5:15 # 5 6 7 8 9 10 11 12 13 14 15 + +seq(from=0, to=31337, by=1337) +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 + +letters +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" + +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" + + +# Access the n'th element of a list with list.name[n] or sometimes list.name[[n]] +# 使用 list.name[n] 来访问第 n 个列表元素,有时候需要使用 list.name[[n]] +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 + + + +# 字符串 + +# 字符串和字符在 R 语言中没有区别 +"Horatio" # "Horatio" +class("Horatio") # "character" +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." + + + +# 逻辑值 + +# 布尔值 +class(TRUE) # "logical" +class(FALSE) # "logical" +# 和我们预想的一样 +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE +# 缺失数据(NA)也是逻辑值 +class(NA) # "logical" +#定义NA为逻辑型 + + + +# 因子 +# 因子是为数据分类排序设计的(像是排序小朋友们的年级或性别) +levels(factor(c("female", "male", "male", "female", "NA", "female"))) # "female" "male" "NA" + +factor(c("female", "female", "male", "NA", "female")) +# female female male NA female +# Levels: female male NA + +data(infert) # 自然以及引产导致的不育症 +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + + + +# 变量 + +# 有许多种方式用来赋值 +x = 5 # 这样可以 +y <- "1" # 更推荐这样 +TRUE -> z # 这样可行,但是很怪 + +#我们还可以使用强制转型 +as.numeric(y) # 1 +as.character(x) # "5" + +# 循环 + +# for 循环语句 +for (i in 1:4) { + print(i) +} + +# while 循环 +a <- 10 +while (a > 4) { + cat(a, "...", sep = "") + a <- a - 1 +} + +# 记住,在 R 语言中 for / while 循环都很慢 +# 建议使用 apply()(我们一会介绍)来错做一串数据(比如一列或者一行数据) + +# IF/ELSE + +# 再来看这些优雅的标准 +if (4 > 3) { + print("Huzzah! It worked!") +} else { + print("Noooo! This is blatantly illogical!") +} + +# => +# [1] "Huzzah! It worked!" + +# 函数 + +# 定义如下 +jiggle <- function(x) { + x + rnorm(x, sd=.1) #add in a bit of (controlled) noise + return(x) +} + +# 和其他 R 语言函数一样调用 +jiggle(5) # 5±ε. 使用 set.seed(2716057) 后, jiggle(5)==5.005043 + +######################### +# 数据容器:vectors, matrices, data frames, and arrays +######################### + +# 单维度 +# 你可以将目前我们学习到的任何类型矢量化,只要它们拥有相同的类型 +vec <- c(8, 9, 10, 11) +vec # 8 9 10 11 +# 矢量的类型是这一组数据元素的类型 +class(vec) # "numeric" +# If you vectorize items of different classes, weird coercions happen +#如果你强制的将不同类型数值矢量化,会出现特殊值 +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" + +#我们这样来取内部数据,(R 的下标索引顺序 1 开始) +vec[1] # 8 +# 我们可以根据条件查找特定数据 +which(vec %% 2 == 0) # 1 3 +# 抓取矢量中第一个和最后一个字符 +head(vec, 1) # 8 +tail(vec, 1) # 11 +#如果下标溢出或不存会得到 NA +vec[6] # NA +# 你可以使用 length() 获取矢量的长度 +length(vec) # 4 + +# 你可以直接操作矢量或者矢量的子集 +vec * 4 # 16 20 24 28 +vec[2:3] * 5 # 25 30 +# 这里有许多内置的函数,来表现向量 +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 + +# 二维(相同元素类型) + +#你可以为同样类型的变量建立矩阵 +mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# 和 vector 不一样的是,一个矩阵的类型真的是 「matrix」,而不是内部元素的类型 +class(mat) # => "matrix" +# 访问第一行的字符 +mat[1,] # 1 4 +# 操作第一行数据 +3 * mat[,1] # 3 6 9 +# 访问一个特定数据 +mat[3,2] # 6 +# 转置整个矩阵(译者注:变成 2 行 3 列) +t(mat) +# => +# [,1] [,2] [,3] +# [1,] 1 2 3 +# [2,] 4 5 6 + +# 使用 cbind() 函数把两个矩阵按列合并,形成新的矩阵 +mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) +mat2 +# => +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" +# [4,] "4" "dog" +class(mat2) # matrix +# Again, note what happened! +# 注意 +# 因为矩阵内部元素必须包含同样的类型 +# 所以现在每一个元素都转化成字符串 +c(class(mat2[,1]), class(mat2[,2])) + +# 按行合并两个向量,建立新的矩阵 +mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 2 4 5 +# [2,] 6 7 0 4 +# 哈哈,数据类型都一样的,没有发生强制转换,生活真美好 + +# 二维(不同的元素类型) + +# 利用 data frame 可以将不同类型数据放在一起 +dat <- data.frame(c(5,2,1,4), c("dog", "cat", "bird", "dog")) +names(dat) <- c("number", "species") # 给数据列命名 +class(dat) # "data.frame" +dat +# => +# number species +# 1 5 dog +# 2 2 cat +# 3 1 bird +# 4 4 dog +class(dat$number) # "numeric" +class(dat[,2]) # "factor" +# data.frame() 会将字符向量转换为 factor 向量 + +# 有很多精妙的方法来获取 data frame 的子数据集 +dat$number # 5 2 1 4 +dat[,1] # 5 2 1 4 +dat[,"number"] # 5 2 1 4 + +# 多维(相同元素类型) + +# 使用 arry 创造一个 n 维的表格 +# You can make a two-dimensional table (sort of like a matrix) +# 你可以建立一个 2 维表格(有点像矩阵) +array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 4 8 3 +# [2,] 2 5 9 6 +#你也可以利用数组建立一个三维的矩阵 +array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +# => +# , , 1 +# +# [,1] [,2] +# [1,] 2 8 +# [2,] 300 9 +# [3,] 4 0 +# +# , , 2 +# +# [,1] [,2] +# [1,] 5 66 +# [2,] 60 7 +# [3,] 0 847 + +#列表(多维的,不同类型的) + +# R语言有列表的形式 +list1 <- list(time = 1:40) +list1$price = c(rnorm(40,.5*list1$time,4)) # 随机 +list1 + +# You can get items in the list like so +# 你可以这样获得列表的元素 +list1$time +# You can subset list items like vectors +# 你也可以和矢量一样获取他们的子集 +list1$price[4] + +######################### +# apply()函数家族 +######################### + +# 还记得 mat 么? +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X +# 使用(X, MARGIN, FUN)将函数 FUN 应用到矩阵 X 的行 (MAR = 1) 或者 列 (MAR = 2) +# That is, R does FUN to each row (or column) of X, much faster than a +# R 在 X 的每一行/列使用 FUN,比循环要快很多 +apply(mat, MAR = 2, myFunc) +# => +# [,1] [,2] +# [1,] 3 15 +# [2,] 7 19 +# [3,] 11 23 +# 还有其他家族函数 ?lapply, ?sapply + +# 不要被吓到,虽然许多人在此都被搞混 +# plyr 程序包的作用是用来改进 apply() 函数家族 + +install.packages("plyr") +require(plyr) +?plyr + +######################### +# 载入数据 +######################### + +# "pets.csv" 是网上的一个文本 +pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") +pets +head(pets, 2) # 前两行 +tail(pets, 1) # 最后一行 + +# 以 .csv 格式来保存数据集或者矩阵 +write.csv(pets, "pets2.csv") # 保存到新的文件 pets2.csv +# set working directory with setwd(), look it up with getwd() +# 使用 setwd() 改变工作目录,使用 getwd() 查看当前工作目录 + +# 尝试使用 ?read.csv 和 ?write.csv 来查看更多信息 + +######################### +# 画图 +######################### + +# 散点图 +plot(list1$time, list1$price, main = "fake data") # 译者注:横轴 list1$time,纵轴 wlist1$price,标题 fake data +# 回归图 +linearModel <- lm(price ~ time, data = list1) # 译者注:线性模型,数据集为list1,以价格对时间做相关分析模型 +linearModel # 拟合结果 +# 将拟合结果展示在图上,颜色设为红色 +abline(linearModel, col = "red") +# 也可以获取各种各样漂亮的分析图 +plot(linearModel) + +# 直方图 +hist(rpois(n = 10000, lambda = 5), col = "thistle") # 译者注:统计频数直方图 + +# 柱状图 +barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) + +# 可以尝试着使用 ggplot2 程序包来美化图片 +install.packages("ggplot2") +require(ggplot2) +?ggplot2 + +``` + +## 获得 R + +* 从 [http://www.r-project.org/](http://www.r-project.org/) 获得安装包和图形化界面 +* [RStudio](http://www.rstudio.com/ide/) 是另一个图形化界面 -- cgit v1.2.3 From 239595fc5929806b2f8c4d476d9bb383f8b0418e Mon Sep 17 00:00:00 2001 From: Marcin Wawrzyniak Date: Sun, 29 Sep 2013 18:15:16 +0100 Subject: ADD: "&" and "*" use cases in function parameters --- ruby.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index b9ba83cb..8723e18f 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -287,6 +287,18 @@ surround { puts 'hello world' } # } +# You can pass a block to a function +# "&" marks a reference to a passed block +def guests(&block) + block.call "some_argument" +end + +# You can pass a list of arguments, which will be converted into an array +# That's what splat operator ("*") is for +def guests(*array) + array.each { |guest| puts "#{guest}" } +end + # Define a class with the class keyword class Human -- cgit v1.2.3 From 97d15053e279bd247c7fd627fb857e89752a2384 Mon Sep 17 00:00:00 2001 From: Gustavo Rodrigues Date: Tue, 1 Oct 2013 09:10:27 -0300 Subject: Fixed comparisons section It was a mistake with `===` operator: `~=` is the equivalent for `==`, not `===` that is a more useful^([citation needed]) version of JS's `===`. --- livescript.html.markdown | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/livescript.html.markdown b/livescript.html.markdown index 8e11439b..5fd61f49 100644 --- a/livescript.html.markdown +++ b/livescript.html.markdown @@ -135,11 +135,19 @@ funRE = // 3 % 2 # => 1 -# Comparisons are mostly the same too, except that `==` and `===` are -# inverted. +# Comparisons are mostly the same too, except that `==` is the same as +# JS's `===`, where JS's `==` in LiveScript is `~=`, and `===` enables +# object and array comparisons, and also stricter comparisons: 2 == 2 # => true 2 == "2" # => false -2 === "2" # => true +2 ~= "2" # => true +2 === "2" # => false + +[1,2,3] == [1,2,3] # => false +[1,2,3] === [1,2,3] # => true + ++0 == -0 # => true ++0 === -0 # => false # Other relational operators include <, <=, > and >= -- cgit v1.2.3 From a91b4fd300d0fc66b5d5d9c29d86d8b4c4cb5464 Mon Sep 17 00:00:00 2001 From: Frederik Ring Date: Thu, 3 Oct 2013 20:02:16 +0200 Subject: be consistent with PascalCasing of constructors --- javascript.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index b15eae7c..6b6be34d 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -357,13 +357,13 @@ myObj.meaningOfLife; // = 43 // Constructors have a property called prototype. This is *not* the prototype of // 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 = { +MyConstructor.prototype = { myNumber: 5, getMyNumber: function(){ return this.myNumber; } }; -var myNewObj2 = new myConstructor(); +var myNewObj2 = new MyConstructor(); myNewObj2.getMyNumber(); // = 5 myNewObj2.myNumber = 6 myNewObj2.getMyNumber(); // = 6 -- cgit v1.2.3 From a6928aadc5e41df82fc5f49f803dd8225749dff3 Mon Sep 17 00:00:00 2001 From: Bastien Guerry Date: Thu, 3 Oct 2013 23:31:56 +0200 Subject: clojure.html.markdown: Fix typo --- clojure.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index a502a95c..35055602 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -63,7 +63,7 @@ and often automatically. ; If you want to create a literal list of data, use ' to stop it from ; being evaluated '(+ 1 2) ; => (+ 1 2) -; (shorthand for (quote (+ 1 2)) +; (shorthand for (quote (+ 1 2))) ; You can eval a quoted list (eval '(+ 1 2)) ; => 3 -- cgit v1.2.3 From 1fb3f1e67c3e7d6eb66db8052df806ae52824dce Mon Sep 17 00:00:00 2001 From: Bastien Guerry Date: Thu, 3 Oct 2013 23:31:56 +0200 Subject: clojure.html.markdown: Fix another typo --- clojure.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index 35055602..afd1c1fb 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -341,7 +341,7 @@ keymap ; => {:a 1, :b 2, :c 3} (swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1) (swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2) - ; Use '@' to dereference the atom and get the value +; Use '@' to dereference the atom and get the value my-atom ;=> Atom<#...> (Returns the Atom object) @my-atom ; => {:a 1 :b 2} -- cgit v1.2.3 From 626e963aa9edca53302562c5593a99fd8a002141 Mon Sep 17 00:00:00 2001 From: Bastien Guerry Date: Fri, 4 Oct 2013 11:18:47 +0200 Subject: Addfrench translation for the Clojure tutorial --- fr-fr/clojure-fr.html.markdown | 398 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 398 insertions(+) create mode 100644 fr-fr/clojure-fr.html.markdown diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown new file mode 100644 index 00000000..d3c5a67b --- /dev/null +++ b/fr-fr/clojure-fr.html.markdown @@ -0,0 +1,398 @@ +--- +language: clojure +filename: learnclojure-fr.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Bastien Guerry", "https://github.com/bzg"] +lang: fr-fr +--- + +Clojure est un langage de la famille des Lisp développé pour la machine +virtuelle Java. Ce langage insiste beaucoup plus sur la [programmation +fonctionnelle](https://fr.wikipedia.org/wiki/Programmation_fonctionnelle) pure +que Common Lisp, mais comprend plusieurs outils de gestion de la mémoire +transactionnelle +[STM](https://en.wikipedia.org/wiki/Software_transactional_memory) pour gérer +les changements d'états si besoin. + +Cette combinaison permet de gérer le parallélisme très simplement, et +souvent de façon automatique. + +(Vous avez besoin de Clojure 1.2 ou plus récent pour ce tutoriel.) + +```clojure +; Les commentaires commencent avec un point-virgule. + +; Clojure est composé de « formes », qui sont simplement des listes +; d'expressions entre parenthèses, séparées par une ou des espaces. +; +; L'interpréteur Clojure suppose que le premier élément est une fonction +; ou une macro, et que le reste contient des arguments. + +; Le premier appel dans un fichier doit être ns, pour définir +; l'espace de nom +(ns learnclojure) + +; D'autres d'exemples basiques: + +; str va créer une chaîne de caractères à partir de tous ses arguments +(str "Hello" " " "World") ; => "Hello World" + +; Les opérations mathématiques sont simples +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 + +; L'égalité est = +(= 1 1) ; => true +(= 2 1) ; => false + +; Vous avez aussi besoin de not pour la négation logique +(not true) ; => false + +; Les formes imbriquées fonctionnent comme on s'y attend +(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 + +; Types +;;;;;;;;;;;;; + +; Clojure utilise les types d'objets Java pour les booléens, les chaînes de +; caractères et les nombres. +; Utilisez `class` pour inspecter les types. +(class 1) ; Les nombres entiers littéraux sont java.lang.Long par défaut +(class 1.); Les flottants littéraux sont java.lang.Double +(class ""); Les chaînes sont toujours entourées de guillemets doubles, et sont java.lang.String +(class false) ; Les booléens sont java.lang.Boolean +(class nil); La valeur "null" est appelée nil + +; Si vous voulez créer une liste littérale de données, utilisez ' pour en +; empêcher son évaluation +'(+ 1 2) ; => (+ 1 2) +; (qui est un raccourci pour (quote (+ 1 2))) + +; Vous pouvez évaluer une liste "quotée": +(eval '(+ 1 2)) ; => 3 + +; Collections & séquences +;;;;;;;;;;;;;;;;;;;;;;;;; + +; Les listes sont des structures de données en listes chaînées, alors que les +; vecteurs reposent sur des tableaux. +; Les vecteurs et les listes sont des classes Java aussi ! +(class [1 2 3]); => clojure.lang.PersistentVector +(class '(1 2 3)); => clojure.lang.PersistentList + +; Une liste serait écrite comme (1 2 3), mais nous devons la quoter +; pour empêcher l'interpréteur de penser que c'est une fonction. +; Et (list 1 2 3) est la même chose que '(1 2 3) + +; Les "Collections" sont juste des groupes de données +; Les listes et les vecteurs sont tous deux des collections: +(coll? '(1 2 3)) ; => true +(coll? [1 2 3]) ; => true + +; Les "séquences" (seqs) sont des abstractions à partir de listes de données. +; Seules les listes sont elles-mêmes des séquences. +(seq? '(1 2 3)) ; => true +(seq? [1 2 3]) ; => false + +; Une séquence n'a besoin de fournir une entrée que lorsqu'on y accède. +; Donc, les séquences peuvent être "lazy" -- et définir une série infinie: +(range 4) ; => (0 1 2 3) +(range) ; => (0 1 2 3 4 ...) (une série infinie) +(take 4 (range)) ; (0 1 2 3) + +; Utilisez cons pour ajouter un item au début d'une liste ou d'un vecteur +(cons 4 [1 2 3]) ; => (4 1 2 3) +(cons 4 '(1 2 3)) ; => (4 1 2 3) + +; Conj ajoutera un item à une collection de la manière la plus efficace +; Pour les listes, conj ajoute l'item au début; pour les vecteurs, à la fin. +(conj [1 2 3] 4) ; => [1 2 3 4] +(conj '(1 2 3) 4) ; => (4 1 2 3) + +; Utilisez concat pour ajouter des listes ou vecteurs: +(concat [1 2] '(3 4)) ; => (1 2 3 4) + +; Utilisez filter, map pour interagir avec des collections +(map inc [1 2 3]) ; => (2 3 4) +(filter even? [1 2 3]) ; => (2) + +; Utilisez reduce pour les réduire +(reduce + [1 2 3 4]) +; = (+ (+ (+ 1 2) 3) 4) +; => 10 + +; Reduce peut aussi prendre un argument pour la valeur initiale +(reduce conj [] '(3 2 1)) +; = (conj (conj (conj [] 3) 2) 1) +; => [3 2 1] + +; Fonctions +;;;;;;;;;;;;;;;;;;;;; + +; Utilisez fn pour créer de nouvelles fonctions. +; Une fonction renvoie toujours sa dernière expression. +(fn [] "Hello World") ; => fn + +; (Vous devez ajouter des parenthèses pour l'appeler) +((fn [] "Hello World")) ; => "Hello World" + +; Vous pouvez créer une variable en utilisant def +(def x 1) +x ; => 1 + +; Assignez une fonction à une variable +(def hello-world (fn [] "Hello World")) +(hello-world) ; => "Hello World" + +; Vous pouvez raccourcir le procédé en utilisant defn +(defn hello-world [] "Hello World") + +; [] contient la liste des arguments de la fonction +(defn hello [name] + (str "Hello " name)) +(hello "Steve") ; => "Hello Steve" + +; Vous pouvez aussi utiliser ce raccourci pour créer des fonctions +(def hello2 #(str "Hello " %1)) +(hello2 "Fanny") ; => "Hello Fanny" + +; Vous pouvez avoir des fonctions multi-variadiques +(defn hello3 + ([] "Hello World") + ([name] (str "Hello " name))) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" + +; Les fonctions peuvent inclure des arguments supplémentaires dans une séquence +(defn count-args [& args] + (str "You passed " (count args) " args: " args)) +(count-args 1 2 3) ; => "Vous avez passé 3 args: (1 2 3)" + +; Vous pouvez combiner les arguments normaux et supplémentaires +(defn hello-count [name & args] + (str "Hello " name ", vous avez passé " (count args) " args supplémentaires")) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, vous avez passé 3 args supplémentaires" + + +; Maps +;;;;;;;;;;;;;;; + +; Les hashmaps et les arraymaps partagent une interface. Les hashmaps +; sont interrogés plus rapidement mais ne retiennent pas l'ordre des clefs. +(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap +(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap + +; Les array maps deviennent automatiquement des hashmaps pour la +; plupart des opérations si elles deviennent assez larges, donc vous +; n'avez pas à vous en faire. + +; Tous les types "hashables" sont acceptés comme clefs, mais en +; général on utilise des mots-clefs ("keywords") +; Les mots-clefs sont comme les chaînes de caractères mais en plus efficaces +(class :a) ; => clojure.lang.Keyword + +(def stringmap {"a" 1, "b" 2, "c" 3}) +stringmap ; => {"a" 1, "b" 2, "c" 3} + +(def keymap {:a 1, :b 2, :c 3}) +keymap ; => {:a 1, :c 3, :b 2} + +; Au passage, les virgules sont toujours traitées comme des espaces et +; ne font rien. + +; Sélectionnez une valeur dans une map en l'appelant comme fonction +(stringmap "a") ; => 1 +(keymap :a) ; => 1 + +; Les mots-clefs peuvent aussi être utilisés pour sélectionner leur +; valeur dans une map ! +(:b keymap) ; => 2 + +; N'essayez pas ça avec les chaînes de caractères +;("a" stringmap) +; => Exception: java.lang.String cannot be cast to clojure.lang.IFn + +; Sélectionner une clef absente renvoie nil +(stringmap "d") ; => nil + +; Use assoc to add new keys to hash-maps +(def newkeymap (assoc keymap :d 4)) +newkeymap ; => {:a 1, :b 2, :c 3, :d 4} + +; Mais souvenez-vous, les types en Clojure sont immuables ! +keymap ; => {:a 1, :b 2, :c 3} + +; Utilisez dissoc pour retirer des clefs +(dissoc keymap :a :b) ; => {:c 3} + +; Ensembles +;;;;;;;;;;;;;;; + +(class #{1 2 3}) ; => clojure.lang.PersistentHashSet +(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} + +; Ajoutez un élément avec conj +(conj #{1 2 3} 4) ; => #{1 2 3 4} + +; Retirez-en un avec disj +(disj #{1 2 3} 1) ; => #{2 3} + +; Testez la présence en utilisant l'ensemble comme une fonction +(#{1 2 3} 1) ; => 1 +(#{1 2 3} 4) ; => nil + +; Il y a encore d'autres fonctions dans l'espace de nom clojure.sets. + +; Formes utiles +;;;;;;;;;;;;;;; + +; Les constructions logiques en Clojure sont juste des macros, et +ressemblent à toutes les autres formes: +(if false "a" "b") ; => "b" +(if false "a") ; => nil + +; Utilisez let pour créer des assignations temporaires +(let [a 1 b 2] + (> a b)) ; => false + +; Groupez les énoncés ensemble avec do +(do + (print "Hello") + "World") ; => "World" (prints "Hello") + +; Les fonctions ont un do implicit +(defn print-and-say-hello [name] + (print "Saying hello to " name) + (str "Hello " name)) +(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") + +; De même pour let +(let [name "Urkel"] + (print "Saying hello to " name) + (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Modules +;;;;;;;;;;;;;;; + +; Utilisez "use" pour obtenir toutes les fonctions d'un module +(use 'clojure.set) + +; Maintenant nous pouvons utiliser les opération de set +(intersection #{1 2 3} #{2 3 4}) ; => #{2 3} +(difference #{1 2 3} #{2 3 4}) ; => #{1} + +; Vous pouvez aussi choisir un sous-ensemble de fonctions à importer +(use '[clojure.set :only [intersection]]) + +; Utilisez require pour importer un module +(require 'clojure.string) + +; Utilisez / pour appeler les fonctions d'un module +; Ici, le module est clojure.string et la fonction est blank? +(clojure.string/blank? "") ; => true + +; Vous pouvez associer un nom plus court au module au moment de l'importer +(require '[clojure.string :as str]) +(str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." +; (#"" dénote une expression régulière) + +; Vous pouvez utiliser require (et use, mais ne le faites pas) en +; appelant :require depuis un espace de noms. +; Dans ce cas-là, vous n'avez pas besoin de "quoter" vos modules: +(ns test + (:require + [clojure.string :as str] + [clojure.set :as set])) + +; Java +;;;;;;;;;;;;;;;;; + +; Java a une librairie standard énorme, donc vous voudrez apprendre à +; vous familiariser avec. + +; Utilisez import pour charger un module java +(import java.util.Date) + +; Vous pouvez importer depuis un ns aussi. +(ns test + (:import java.util.Date + java.util.Calendar)) + +; Utilisez les noms de classes avec "." à la fin pour créer une instance +(Date.) ; + +; Utilisez . pour invoquer des méthodes. Ou utilisez le raccourci ".method" +(. (Date.) getTime) ; +(.getTime (Date.)) ; exactement la même chose + +; Utilisez / pour appeler des méthodes statiques +(System/currentTimeMillis) ; (system est toujours présent) + +; Utilisez doto to rendre plus tolérable l'interaction avec des +; classes (mutables) +(import java.util.Calendar) +(doto (Calendar/getInstance) + (.set 2000 1 1 0 0 0) + .getTime) ; => Une classe Date. définie comme 2000-01-01 00:00:00 + +; STM +;;;;;;;;;;;;;;;;; + +; La mémoire logiciel transactionnelle ("Software Transactional Memory") +; est le mécanisme que Clojure utilise pour gérer les états persistents. +; Il y a plusieurs formes en Clojure qui utilisent cela. + +; L'atome est la plus simple. Passez-lui une valeur initiale +(def my-atom (atom {})) + +; Mettez à jour un atome avec swap!. +; swap! prend une fonction en argument et l'appelle avec la valeur +; actuelle de l'atome comme premier argument, et les autres arguments +; comme second argument. +(swap! my-atom assoc :a 1) ; Définit my-atom comme le résultat de (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Définit my-atom comme le résultat de (assoc {:a 1} :b 2) + +; Use '@' to dereference the atom and get the value +my-atom ;=> Atom<#...> (Renvoie l'objet Atom) +@my-atom ; => {:a 1 :b 2} + +; Voici un simple compteur utilisant un atome +(def counter (atom 0)) +(defn inc-counter [] + (swap! counter inc)) + +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) + +@counter ; => 5 + +; Les autres formes STM sont les refs et les agents. +; Refs: http://clojure.org/refs +; Agents: http://clojure.org/agents +``` + +### Lectures complémentaires + +C'est loin d'être exhaustif, mais assez pour vous permettre de continuer. + +Clojure.org propose de nombreux articles: +[http://clojure.org/](http://clojure.org/) + +Clojuredocs.org a de la documentation avec des exemples pour la +plupart des fonctions principales : +[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) + +4Clojure est une super manière d'augmenter vos compétences en Clojure et +en programmation fonctionnelle : +[http://www.4clojure.com/](http://www.4clojure.com/) + +Clojure-doc.org a pas mal d'article pour débuter : +[http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From 9a4721785cd51360472c329d1c9614fb6783d5e1 Mon Sep 17 00:00:00 2001 From: Bastien Guerry Date: Thu, 3 Oct 2013 23:40:38 +0200 Subject: clojure.html.markdown: Fix an error (s/value/key) --- clojure.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index afd1c1fb..779c28ae 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -205,7 +205,7 @@ keymap ; => {:a 1, :c 3, :b 2} ;("a" stringmap) ; => Exception: java.lang.String cannot be cast to clojure.lang.IFn -; Retrieving a non-present value returns nil +; Retrieving a non-present key returns nil (stringmap "d") ; => nil ; Use assoc to add new keys to hash-maps -- cgit v1.2.3 From 2c7fa291a34eb88380e9cf8c8e35a49e70114251 Mon Sep 17 00:00:00 2001 From: Christos Kontas Date: Fri, 4 Oct 2013 12:44:13 +0300 Subject: [Perl] Remove some redundant spaces --- perl.html.markdown | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index 18339dde..b04b76cd 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -131,13 +131,11 @@ sub logger { # Now we can use the subroutine just as any other built-in function: logger("We have a logger subroutine!"); - - ``` #### Using Perl modules -Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). A number of popular modules are included with the Perl distribution itself. +Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN (http://www.cpan.org/). A number of popular modules are included with the Perl distribution itself. perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use. -- cgit v1.2.3 From fba9728e46d46ab8d9c8b2ae02778d6bd1213837 Mon Sep 17 00:00:00 2001 From: Christos Kontas Date: Fri, 4 Oct 2013 12:46:28 +0300 Subject: [perl] Fix list with links at "Further Reading" --- perl.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index b04b76cd..ad9155e4 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -141,7 +141,7 @@ perlfaq contains questions and answers related to many common tasks, and often p #### Further Reading - - [perl-tutorial](http://perl-tutorial.org/) - - [Learn at www.perl.com](http://www.perl.org/learn.html) - - [perldoc](http://perldoc.perl.org/) - - and perl built-in : `perldoc perlintro` + - [perl-tutorial](http://perl-tutorial.org/) + - [Learn at www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - and perl built-in : `perldoc perlintro` -- cgit v1.2.3 From b2028c7f0c3087b34b601ab27e61cc59ae1e9a21 Mon Sep 17 00:00:00 2001 From: Christos Kontas Date: Fri, 4 Oct 2013 18:32:11 +0300 Subject: [bash] Fix some spell errors in comments --- bash.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 4d80545e..276bc31f 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -94,12 +94,12 @@ 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 $( ): +# Commands can be substituted within other commands using $( ): # The following command displays the number of files and directories in the # current directory. echo "There are $(ls | wc -l) items here." -# Bash uses a case statement that works similarily to switch in Java and C++: +# Bash uses a case statement that works similarly to switch in Java and C++: case "$VARIABLE" in #List patterns for the conditions you want to meet 0) echo "There is a zero.";; -- cgit v1.2.3 From 23c432f7af16851a6c889dcc0bff467440f82a18 Mon Sep 17 00:00:00 2001 From: Vinh Nguyen Date: Fri, 4 Oct 2013 23:18:05 +0700 Subject: add Git and Obj-C translation in Vietnamese language --- vi-vn/git-vi.html.markdown | 392 +++++++++++++++++++++++++++++++++++++ vi-vn/objective-c-vi.html.markdown | 318 ++++++++++++++++++++++++++++++ 2 files changed, 710 insertions(+) create mode 100644 vi-vn/git-vi.html.markdown create mode 100644 vi-vn/objective-c-vi.html.markdown diff --git a/vi-vn/git-vi.html.markdown b/vi-vn/git-vi.html.markdown new file mode 100644 index 00000000..77fec983 --- /dev/null +++ b/vi-vn/git-vi.html.markdown @@ -0,0 +1,392 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +filename: LearnGit-vi.txt +--- + +Git là một hệ quản lý mã nguồn và phiên bản phân tán (distributed version control and source code management system). + +Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, and nó hoạt động +với các snapshot đó để cung cấp cho bạn với chức năng đến phiên bản và +quản lý mã nguồn của bạn. + +## Khái Niệm Versioning + +### Version Control là gì? + +Version Control là một hệ thống ghi lại những thay đổi ở một tập tin, hay một nhóm các tập tin, theo thời gian. + +### Centralized Versioning VS Distributed Versioning + +* Quản lý phiên bản tập trung (Centralized Versioning) tập trung vào việc đồng bộ hóa, theo dõi, và lưu trữ tập tin. +* Quản lý phiên bản phân tán (Distributed Versioning) tập trung vào việc chia sẻ các thay đổi. Mỗi sự thay đổi có một mã định dạng (id) duy nhất. +* Các hệ phân tán không có cấu trúc định sẵn. Bạn có thể thay đổi một kiểu SVN, hệ phân tán, với git. + +[Thông tin thêm](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### Tại Sao Dùng Git? + +* Có thể hoạt động offline. +* Cộng tác với nhau rất dễ dàng! +* Phân nhánh dễ dàng! +* Trộn (Merging) +* Git nhanh. +* Git linh hoạt. + +## Kiến Trúc Git + + +### Repository + +Một nhóm các tập tin, thư mục, các ghi chép trong quá khứ, commit, và heads. Tưởng tượng nó như là một cấu trúc dữ liệu mã nguồn, +với thuộc tính mà một "nhân tố" mã nguồn cho bạn quyền truy cập đến lịch sử sửa đổi, và một số thứ khác. + +Một git repository bao gồm thư mục .git & tree đang làm việc. + +### Thư mục .git (thành phần của một repository) + +Thư mục .git chứa tất cả các cấu hình, log, nhánh, HEAD, và hơn nữa. +[Danh Sách Chi Tiết.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Tree Đang Làm (thành phần của một repository) + +Đây cơ bản là các thư mục và tập tin trong repository của bạn. Nó thường được tham chiếu +thư mục đang làm việc của bạn + +### Chỉ mục (thành phần của một thư mục .git) + +Chỉ mục của là một staging area trong git. Nó đơn giản là một lớp riêng biệt với tree đang làm việc của bạn +từ Git repository. Điều này cho nhà phát triền nhiều lựa chọn hơn trong việc xem xét những gì được gửi đến Git +repository. + +### Commit + +Một git commit là một snapshot của một nhóm các thay đổi, hoặc các thao tác Working Tree của bạn. +Ví dụ, nếu bạn thêm 5 tập tin, và xóa 2 tập tin khác, những thay đổi này sẽ được chứa trong +một commit (hoặc snapshot). Commit này có thể được đẩy đến các repo khác, hoặc không! + +### Nhánh + +Nhánh thực chất là một con trỏ đến commit mới nhất mà bạn vừa thực hiện. Khi bạn commit, +con trỏ này sẽ cập nhật tự động và trỏ đến commit mới nhất. + +### HEAD và head (thành phần của thư mục .git) + +HEAD là một con trỏ đến nhánh hiện tại. Một repo chỉ có một HEAD *đang hoạt động*. +head là một con trỏ đến bất kỳ commit nào. Một repo có thể có nhiều head. + +### Các Tài Nguyên Mang Tính Khái Niệm + +* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) +* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) + + +## Các Lệnh + + +### init + +Tạo một repo Git rỗng. Các cài đặt, thông tin lưu trữ... của Git +được lưu ở một thư mục tên là ".git". + +```bash +$ git init +``` + +### config + +Để chỉnh tùy chọn. Bất kể là cho repo, hay cho hệ thống, hay điều chỉnh +toàn cục (global) + + + +```bash +# In Ra & Và Gán Một Số Biến Tùy Chỉnh Cơ Bản (Toàn cục - Global) +$ git config --global user.email +$ git config --global user.name + +$ git config --global user.email "MyEmail@Zoho.com" +$ git config --global user.name "My Name" +``` + +[Tìm hiểu thêm về git config.](http://git-scm.com/docs/git-config) + +### help + +Để cho bạn lối truy cập nhanh đến một chỉ dẫn cực kỳ chi tiết của từng lệnh. Hoặc chỉ để +nhắc bạn một số cú pháp. + +```bash +# Xem nhanh các lệnh có sẵn +$ git help + +# Xem tất các các lệnh +$ git help -a + +# Lệnh help riêng biệt - tài liệu người dùng +# git help +$ git help add +$ git help commit +$ git help init +``` + +### status + +Để hiển thị sự khác nhau giữa tập tin index (cơ bản là repo đang làm việc) và HEAD commit +hiện tại. + + +```bash +# Sẽ hiển thị nhánh, các tập tin chưa track (chưa commit), các thay đổi và những khác biệt khác +$ git status + +# Để xem các "tid bits" về git status +$ git help status +``` + +### add + +Để thêm các tập vào tree/thư mục/repo hiện tại. Nếu bạn không `git add` các tập tin mới đến +tree/thư mục hiện tại, chúng sẽ không được kèm theo trong các commit! + +```bash +# thêm một file vào thư mục hiện tại +$ git add HelloWorld.java + +# thêm một file vào một thư mục khác +$ git add /path/to/file/HelloWorld.c + +# Hỗ trợ Regular Expression! +$ git add ./*.java +``` + +### branch + +Quản lý nhánh. Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này. + +```bash +# liệt kê các nhanh đang có và ở remote +$ git branch -a + +# tạo nhánh mới +$ git branch myNewBranch + +# xóa một nhánh +$ git branch -d myBranch + +# đặt tên lại một nhánh +# git branch -m +$ git branch -m myBranchName myNewBranchName + +# chỉnh sủa diễn giải của một nhánh +$ git branch myBranchName --edit-description +``` + +### checkout + +Cập nhật tất cả các file torng tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể. + +```bash +# Checkout (chuyển) một repo - mặc định là nhánh master +$ git checkout +# Checkout một nhánh cụ thể +$ git checkout branchName +# Tạo một nhánh mới và chuyển đến nó, tương tự: "git branch ; git checkout " +$ git checkout -b newBranch +``` + +### clone + +Nhân bản, hoặc sao chép, một repo hiện có thành một thư mục mới. Nó cũng thêm +các nhánh có remote-tracking cho mỗi nhánh trong một repo được nhân bản, mà +cho phép bạn push đến một nhánh remote. + +```bash +# Nhân bản learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +``` + +### commit + +Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một lời nhắn (ghi chú) tạo ra bởi người dùng. + +```bash +# commit với một ghi chú +$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" +``` + +### diff + +Hiển thị sự khác biệt giữa một file trong thư mục hiện tại, index và commits. + +```bash +# Hiển thị sự khác biệt giữa thư mục hiện tại và index +$ git diff + +# Hiển thị khác biệt giữa index và commit mới nhất. +$ git diff --cached + +# Hiển thị khác biệt giữa thư mục đang làm việc và commit mới nhất +$ git diff HEAD +``` + +### grep + +Cho phép bạn tìm kiếm nhanh một repo. + +Các tinh chỉnh tùy chọn: + +```bash +# Cảm ơn Travis Jeffery vì những lệnh này +# Đặt số của dòng được hiển thị trong kết quả tìm kiếm grep +$ git config --global grep.lineNumber true + +# Làm cho kết quả tìm kiếm dễ đọc hơn, bao gồm cả gom nhóm +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Tìm "variableName" trong tất cả các file Java +$ git grep 'variableName' -- '*.java' + +# Tìm một dòng mà có chứa "arrayListName" và, "add" hoặc "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Google để xem thêm các ví dụ +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Hiển thị các commit đến repo. + +```bash +# Hiện tất cả các commit +$ git log + +# Hiện X commit +$ git log -n 10 + +# Chỉ hiện các commit đã merge merge commits +$ git log --merges +``` + +### merge + +"Trộn" các thay đổi từ commit bên ngoài vào trong nhánh hiện tại. + +```bash +# Merge nhánh cụ thể vào nhánh hiện tại. +$ git merge branchName + +# Luôn khởi tạo một merge commit khi trộn (merge) +$ git merge --no-ff branchName +``` + +### mv + +Đặt lại tên hoặc di chuyển một file + +```bash +# Đặt lại tên một file +$ git mv HelloWorld.c HelloNewWorld.c + +# Di chuyển một file +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Buộc đặt lại tên hoặc di chuyển +# "existingFile" đã tồn tại trong thự mục, sẽ bị ghi đè +$ git mv -f myFile existingFile +``` + +### pull + +Kéo (tải) về từ một repo và merge nó vào nhánh khác. + +```bash +# Cập nhật repo cục bộ của bạn, bằng cách merge các thay đổi mới +# từ remote "origin" và nhánh "master". +# git pull +# git pull => hoàn toàn mặc định như => git pull origin master +$ git pull origin master + +# Merge các thay đổi từ nhánh remote và rebase +# các commit nhánh lên trên thư mục cục bộ, như: "git pull , git rebase " +$ git pull origin master --rebase +``` + +### push + +Đẩy và trộn (mege) các tay đổi từ một nhánh đế một remote & nhánh. + +```bash +# Push và merge các thay đổi từ repo cục bộ đến một +# remote tên là "origin" và nhánh "master". +# git push +# git push => hoàn toàn defaults to => git push origin master +$ git push origin master +``` + +### rebase (thận trọng) + +Lấy tất cả các thay đổi mà đã được commit trên một nhánh, và replay (?) chúng trên một nhánh khác. +*Không rebase các commit mà bạn đã push đến một repo công khai*. + +```bash +# Rebase experimentBranch lên master +# git rebase +$ git rebase master experimentBranch +``` + +[Đọc Thêm.](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (thận trọng) + +Thiết lập lạo HEAD hiện tại đến một trạng thái cụ thể. Điều này cho phép bạn làm lại các merges, +pulls, commits, thêm, and hơn nữa. Nó là một lệnh hay nhưng cũng nguy hiểm nếu bạn không +biết mình đang làm gì. + +```bash +# Thiết lập lại staging area, để trùng với commit mới nhất (để thư mục không thay đổi) +$ git reset + +# Thiết lập lại staging area, để trùng với commit mới nhất, và ghi đè lên thư mục hiện tại +$ git reset --hard + +# Di chuyển nhánh hiện tại đến một commit cụ thể (để thư mục không thay đổi) +# tất cả thay đổi vẫn duy trì trong thư mục. +$ git reset 31f2bb1 + +# Di chuyển nhánh hiện tại lùi về một commit cụ thể +# và làm cho thư mục hiện tại trùng (xóa các thay đổi chưa được commit và tất cả các commit +# sau một commit cụ thể). +$ git reset --hard 31f2bb1 +``` + +### rm + +Ngược lại với git add, git rm xóa file từ tree đang làm việc. + +```bash +# xóa HelloWorld.c +$ git rm HelloWorld.c + +# Xóa file từ thư mục khác +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## Thông tin thêm + +* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) + +* [git-scm - Video Tutorials](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown new file mode 100644 index 00000000..f6296ec0 --- /dev/null +++ b/vi-vn/objective-c-vi.html.markdown @@ -0,0 +1,318 @@ +--- + +language: Objective-C +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] +lang: vi-vi +filename: LearnObjectiveC-vi.m + +--- + +Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch. +Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C. + +```objective-c +// Chú thích dòng đơn bắt đầu với // + +/* +Chú thích đa dòng trông như thế này. +*/ + +// Nhập các headers của framework Foundation với cú pháp #import +#import +#import "MyClass.h" + +// Đầu vào chương trình của bạn là một hàm gọi là +// main với một kiểu trả về kiểu integer. +int main (int argc, const char * argv[]) +{ + // Tạo một autorelease pool để quản lý bộ nhớ vào chương trình + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + // Sử dụng hàm NSLog() để in ra các dòng lệnh vào console + NSLog(@"Hello World!"); // Print the string "Hello World!" + + /////////////////////////////////////// + // Kiểu & Biến (Types & Variables) + /////////////////////////////////////// + + // Khai báo số nguyên + int myPrimitive1 = 1; + long myPrimitive2 = 234554664565; + + // Khai báo đối tượng + // Đặt dấu nháy * vào trước tên biến cho khai báo đối tượng strong + MyClass *myObject1 = nil; // Strong + id myObject2 = nil; // Weak + // %@ là một đối tượng + // 'miêu tả' ('desciption') là thông lệ để trình bày giá trị của các Đối tượng + NSLog(@"%@ và %@", myObject1, [myObject2 description]); // In ra "(null) và (null)" + + // Chuỗi + NSString *worldString = @"World"; + NSLog(@"Hello %@!", worldString); // In ra "Hello World!" + + // Ký tự literals + NSNumber *theLetterZNumber = @'Z'; + char theLetterZ = [theLetterZNumber charValue]; + NSLog(@"%c", theLetterZ); + + // Số nguyên literals + 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); + + // Dấu phẩy động (floating point) literals + NSNumber *piFloatNumber = @3.141592654F; + float piFloat = [piFloatNumber floatValue]; + NSLog(@"%f", piFloat); + + NSNumber *piDoubleNumber = @3.1415926535; + double piDouble = [piDoubleNumber doubleValue]; + NSLog(@"%f", piDouble); + + // BOOL literals + NSNumber *yesNumber = @YES; + NSNumber *noNumber = @NO; + + // Đối tượng Mảng + NSArray *anArray = @[@1, @2, @3, @4]; + NSNumber *thirdNumber = anArray[2]; + NSLog(@"Third number = %@", thirdNumber); // In ra "Third number = 3" + + // Đối tượng Từ điển + NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSObject *valueObject = aDictionary[@"A Key"]; + NSLog(@"Đối tượng = %@", valueObject); // In ra "Object = (null)" + + /////////////////////////////////////// + // Toán Tử (Operators) + /////////////////////////////////////// + + // Các toán tử cũng hoạt động giống như ngôn ngữ C + // Ví dụ: + 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 dịch trái (bởi 1)) + + ///////////////////////////////////////////// + // Cấu Trúc Điều Khiển (Controls Structures) + ///////////////////////////////////////////// + + // Câu lệnh If-Else + if (NO) + { + NSLog(@"I am never run"); + } else if (0) + { + NSLog(@"I am also never run"); + } else + { + NSLog(@"I print"); + } + + // Câu lệnh Switch + switch (2) + { + case 0: + { + NSLog(@"I am never run"); + } break; + case 1: + { + NSLog(@"I am also never run"); + } break; + default: + { + NSLog(@"I print"); + } break; + } + + // Câu lệnh vòng lặp While + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++ tăng dần, sau khi sử dụng giá trị của nó. + } // => in ra "0," + // "1," + // "2," + // "3," + + // Câu lệnh vòng lặp For + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", jj); + } // => in ra "0," + // "1," + // "2," + // "3," + + // Câu lệnh Foreach + NSArray *values = @[@0, @1, @2, @3]; + for (NSNumber *value in values) + { + NSLog(@"%@,", value); + } // => in ra "0," + // "1," + // "2," + // "3," + + // Câu lệnh Try-Catch-Finally + @try + { + // Your statements here + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"Không Tìm Thấy Tập Tin trên Hệ Thống" userInfo:nil]; + } @catch (NSException * e) + { + NSLog(@"Exception: %@", e); + } @finally + { + NSLog(@"Finally"); + } // => in ra "Exception: Không Tìm Thấy Tập Tin trên Hệ Thống" + // "Finally" + + /////////////////////////////////////// + // Đối Tượng (Objects) + /////////////////////////////////////// + + // Tạo một thực thể đối tượng bằng cách phân vùng nhớ và khởi tạo đối tượng đó. + // Một đối tượng sẽ không thật sự hoạt động cho đến khi cả 2 bước alloc] init] được hoàn thành + MyClass *myObject = [[MyClass alloc] init]; + + // Mô hình lập trình hướng đối tượng của Objective-C dựa trên việc truyền thông điệp (message) + // và các thực thể đối tượng với nhau. + // Trong Objective-C một đối tượng không đơn thuần gọi phương thức; nó truyền thông điệp. + [myObject instanceMethodWithParameter:@"Steve Jobs"]; + + // Dọn dẹp vùng nhớ mà bạn đã dùng ở chương trình + [pool drain]; + + // Kết thúc chương trình + return 0; +} + +/////////////////////////////////////// +// Lớp và Hàm (Classes & Functions) +/////////////////////////////////////// + +// Khai báo lớp của bạn ở một tập tin header (MyClass.h): +// Cú pháp Khai Báo Lớp: +// @interface ClassName : ParentClassName +// { +// Khai báo biến thành viên; +// } +// -/+ (type) Khai báo method; +// @end +@interface MyClass : NSObject +{ + int count; + id data; + NSString *name; +} +// Ký hiệu (notation) tiện ích để tự động khởi tạo public getter và setter +@property int count; +@property (copy) NSString *name; // Sao chép đối tượng trong quá trình gán. +@property (readonly) id data; // Chỉ khai báo phương thức getter. + +// Phương thức ++/- (return type)methodSignature:(Parameter Type *)parameterName; + +// dấu '+' cho phương thức lớp ++ (NSString *)classMethod; + +// dấu '-' cho phương thức thực thể +- (NSString *)instanceMethodWithParameter:(NSString *)string; +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; + +@end + +// Thực thi các phương thức trong một tập tin thực thi (MyClass.m): + +@implementation MyClass + +// Gọi khi đối tượng được release +- (void)dealloc +{ +} + +// Phương thức khởi tạo (Constructors) là một cách để tạo các lớp +// Đây là phương thức khởi tạo mặc định được gọi khi đối tượng được khởi tạo +- (id)init +{ + if ((self = [super init])) + { + self.count = 1; + } + return self; +} + ++ (NSString *)classMethod +{ + return [[self alloc] init]; +} + +- (NSString *)instanceMethodWithParameter:(NSString *)string +{ + return @"New string"; +} + +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number +{ + return @42; +} + +// Các phương thức được khai báo vào MyProtocol +- (void)myProtocolMethod +{ + // câu lệnh +} + +@end + +/* + * Một protocol khai báo các phương thức mà có thể thực thi bởi bất kỳ lớp nào. + * Các protocol chính chúng không phải là các lớp. Chúng chỉ đơn giản là định ra giao diện (interface) + * mà các đối tượng khác có trách nhiệm sẽ thực thi. + */ +@protocol MyProtocol + - (void)myProtocolMethod; +@end + + + +``` +## Xem Thêm + ++ [Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) + ++ Apple Docs': + + [Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) + + + [Programming With Objective-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html) + + + [Object-Oriented Programming with Objective-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/OOP_ObjC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005149) + + + [Coding Guidelines for Cocoa](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html) + ++ [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From f400089013d99030e520c20735198273aed17b8e Mon Sep 17 00:00:00 2001 From: David Baumgartner <_davidbaumgartner@bluewin.ch> Date: Sun, 6 Oct 2013 21:44:48 +0200 Subject: Adding french translation of Haskell --- fr-fr/haskell.html.markdown | 428 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 428 insertions(+) create mode 100644 fr-fr/haskell.html.markdown diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown new file mode 100644 index 00000000..16c40554 --- /dev/null +++ b/fr-fr/haskell.html.markdown @@ -0,0 +1,428 @@ +--- +language: haskell +contributors: + - ["Adit Bhargava", "http://adit.io"] + - ["David Baumgartner", "http://davidbaumgartner.ch"] +--- + +Haskell a été conçu pour être un langage fonctionnel pur et maniable. Il est connu pour ses monades et son système de types, mais je continue d'y revenir pour son élégance. Pour moi, Haskell fait de la programmation une joie. + +```haskell +-- Un commentaire en une ligne commence avec deux tirets. +{- Un commentaire sur plusieurs lignes peut être contenu dans +un bloc de cette façon. +-} + +---------------------------------------------------- +-- 1. Types de données primitifs et opérateurs +---------------------------------------------------- + +-- Vous avez les nombres +3 -- 3 + +-- Les maths sont telles que vous vous y attendez +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- La division n'est pas entière par défaut +35 / 4 -- 8.75 + +-- division entière +35 `div` 4 -- 8 + +-- Les booléens sont primitifs +True +False + +-- Opérations avec les booléens +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- Dans les exemples plus hauts, `not`est une fonction qui prend une valeur +-- Haskell n'a pas besoin de parenthèses pour appeler une fonction... tous +-- les arguments sont juste listés après la fonction. Le schéma général est +-- donc: +-- func arg1 arg2 arg3... +-- Voyez la section sur les fonctions pour savoir comment écrire les vôtres. + +-- Caractères et chaînes de caractère +"Ceci est une chaîne de caractère." +'a' -- caractère +'Vous pouvez utiliser des apostrophes pour les chaînes de caractère.' -- erreur ! + +-- Les chaînes peuvent être concaténées +"Hello " ++ "world!" -- "Hello world!" + +-- Une chaîne de caractère est *réellement* une liste +"Ceci est une chaîne." !! 0 -- 'C' + + +---------------------------------------------------- +-- Lists and Tuples +---------------------------------------------------- + +-- Chaque élément d'une liste doit avoir le même type +-- les deux lignes suivantes sont semblables +[1, 2, 3, 4, 5] +[1..5] + +-- Il y a aussi des listes infinies en Haskell! +[1..] -- une liste de tous les nombres naturels + +-- Les listes infinies fonctionnent parce que Haskell a « l'évaluation +-- paresseuse ». Ça veut dire que Haskell n'évalue que ce qui a besoin +-- de l'être. Vous pouvez donc vous demander le 1000e élément de votre liste: + +[1..] !! 999 -- 1000 + +-- Et là, Haskell a évalué les éléments 1 à 1000 de la liste... mais le reste +-- de cette liste "infinie" n'existe pas encore! En fait, Haskell ne va jamais +-- le faire à moins qu'il en ait besoin. + +-- Adjoindre deux listes +[1..5] ++ [6..10] + +-- ajouter au début de la liste +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- l'indice d'une liste +[0..] !! 5 -- 5 + +-- d'autres opérations sur les listes +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +--liste en compréhension +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +--avec un conditionnel +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Chaque élément d'un tuple peut être d'un type différent, mais une +-- tuple a une longueur fixée. +-- Un tuple: +("haskell", 1) + +-- accéder aux éléments d'un tuple +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Functions +---------------------------------------------------- +-- Une simple fonction qui prend deux paramètres +add a b = a + b + +-- Notez que si vous utilisez ghci (l'interpréteur Haskell) +-- vous devrez utiliser `let`. Par exemple: +-- let add a b = a + b + +-- Utiliser une fonction +add 1 2 -- 3 + +-- Vous pouvez également mettre le nom de la fonction entre les +-- deux arguments avec des accents graves: +1 `add` 2 -- 3 + +-- Vous pouvez également définir des fonctions qui n'ont pas de +-- lettres! Ça vous laisse créer vos propres opérateurs! Voilà +-- un opérateur qui fait une division entière: +(//) a b = a `div` b +35 // 4 -- 8 + +-- Gardes: une façon pour créer des bifurcations de fonction +fib x + | x < 2 = x + | otherwise = fib (x - 1) + fib (x - 2) + +-- Le filtrage par motif est similaire. Là on a donné trois +-- définitions différents de `fib`. Haskell appellera automatiquement +-- la première fonction qui correspondra au motif de la valeur. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Filtrage par motif sur un tuple. +foo (x, y) = (x + 1, y + 2) + +-- Filtrage par motif sur des listes. Ici, `x` est le premier +-- élément de la liste, et `xs` le reste. On peut écrire notre +-- propre fonction `map`: +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Les fonctions anonymes sont créées avec des barres obliques +-- inverses, suivies de tous les arguments. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- Une utilisation de fold (appelée `inject` dans quelques autres +-- langages) avec comme paramètre une fonction anonyme. +-- `foldl1` veut dire fold left -- soit littéralement pli gauche. -- +-- et utilise la première valeur de la liste comme accumulateur. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Plus de fonctions +---------------------------------------------------- + +-- curryfaction: si vous n'appliquez pas tous les arguments à une +-- fonction, elle devient « curryfiée ». Ça veut dire qu'elle retourne +-- une fonction qui prend le reste des arguments. + +add a b = a + b +foo = add 10 -- foo est une fonction qui prend un nombre et y ajoute 10 +foo 5 -- 15 + +-- Une autre façon de l'écrire +foo = (+10) +foo 5 -- 15 + +-- Composition de fonctions +-- la fonction (.) enchaîne deux fonctions. +-- Par exemple, on a foo qui est une fonction qui prend une valeur, y ajoute +-- 10 et multiplie ce résultat par 5, et ensuite retourne la valeur finale. +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +-- fixation de priorité +-- Haskell a une autre fonction appelée `$`. Elle peut changer la priorité +-- de façon à ce que tout ce qu'il y a à sa gauche est calculé d'abord +-- et ensuite appliqué à tout ce qu'il y a à droite. Vous pouvez utiliser +-- `.` et `$` pour vous débarrasser de beaucoup de parenthèses: + +-- avant +(even (fib 7)) -- False + +-- ensuite +even . fib $ 7 -- False + +---------------------------------------------------- +-- 5. Signature de type +---------------------------------------------------- + +-- Haskell a un système de types très strict, et tout a un type. + +-- Quelques types simples: +5 :: Integer +"hello" :: String +True :: Bool + +-- Les fonctions ont des types également. +-- `not` prend un booléen et retourne un booléen. +-- not :: Bool -> Bool + +-- Voilà une fonction qui prend deux paramètres. +-- add :: Integer -> Integer -> Integer + +-- Quand vous définissez une valeur, une bonne pratique est d'écrire +-- son type explicitement +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Flux de contrôle et structures conditionnelles +---------------------------------------------------- + +-- structure conditionnelle if +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- les structures if peuvent être écrites sur plusieurs lignes +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- les structures case: Voilà comment vous pouvez analyser les arguments de +-- ligne de commande +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + + +-- Haskell n'a pas de boucles parce qu'il utilise la récursion. +-- `map` applique une fonction sur chaque élément d'une liste + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- vous pouvez créer une fonction `for` en utilisant `map` +for array func = map func array + +-- et l'utiliser +for [0..5] $ \i -> show i + +-- nous aurions pu l'écrire également ainsi +for [0..5] show + +-- vous pouvez utiliser foldl et foldr pour +-- réduire une liste +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- C'est donc la même chose que +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl évalue de gauche à droite, foldr +-- de droite à gauche +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Et c'est équivalent à +(2 * 3 + (2 * 2 + (2 * 1 + 4))) + +---------------------------------------------------- +-- 7. Types de données +---------------------------------------------------- + +-- Vous pouvez écrire vos propres types de données en Haskell + +data Couleur = Rouge | Bleu | Vert + +-- Et maintenant l'utiliser dans une fonction + + +say :: Couleur -> String +say Rouge = "Vous êtes Rouge!" +say Bleu = "Vous êtes Bleu!" +say Vert = "Vous êtes Vert!" + +-- Vos types peuvent également avoir des paramètres + +data Maybe a = Nothing | Just a + +-- Tous les exemples ci-dessous sont issus du type Maybe +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- Tandis que l'IO ne peut pas être totalement expliqué pleinement +-- sans que les monades ne le soient, il n'est pas difficile +-- d'expliquer suffisamment pour commencer. + +-- Quand un programme en Haskell est exécuté, la fonction `main` +-- est appelée. Il doit retourner une valeur de type `IO ()`. +-- Par exemple: + +main :: IO () +main = putStrLn $ "Bonjour, le ciel! " ++ (say Blue) +-- putStrLn a comme type String -> IO () + +-- Il est plus facile de faire IO si vous pouvez faire +-- votre programme en fonction String à String. La fonction +-- interact :: (String -> String) -> IO () +-- prend un texte, applique une fonction et affiche le résultat. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- Vous pouvez considérer qu'une valeur de type `IO ()` représente +-- une séquence d'actions que l'ordinateur exécute, un peu comme +-- dans un langage impératif. On peut utiliser la structure `do` +-- pour enchaîner des actions. Par exemple: + +sayHello :: IO () +sayHello = do + putStrLn "Quel est ton nom ?" + name <- getLine -- prend une ligne et assigne sa valeur à `name` + putStrLn $ "Salut, " ++ name + +-- Exercice: écrire votre propre version d'`interact` qui ne fait +-- que de lire une ligne d'entrée. + +-- Le code de `sayHello` ne sera jamais exécuté, cependant. La seule +-- action qui sera exécutée est la valeur de `main`. +-- Pour lancer `sayHello`, commentez l'ancienne définition de `main` +-- et remplacez-le par: +-- main = sayHello + +-- Essaions de mieux comprendre comment la fonction `getLine` que +-- nous venons d'utiliser. Son type est: +-- getLine :: IO String +-- vous pouvez considérer le type `IO a` comme un programme que +-- le programme va générer comme une valeur de type `a` quand +-- il sera exécuté. On peut l'enregistrer et la réutiliser en +-- utilisant `<-`. On peut aussi faire nos propres actions +-- de type `IO String`: + +action :: IO String +action = do + putStrLn "C'est une ligne. Heu" + input1 <- getLine + input2 <- getLine + -- Le type de la structure `do` est celui de sa dernière ligne. + -- `return` n'est pas un mot clef, mais simplement une fonction. + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- On peut maintenant l'utiliser comme on a utilisé `getLine` +-- tout à l'heure + +main'' = do + putStrLn "Je vais afficher deux lignes!" + result <- action + putStrLn result + putStrLn "C'était tout!" + +-- Le type `IO` est un exemple de « monade ». La façon dont Haskell une monade +-- pour faire de l'IO lui permet d'être purement fonctionnel. N'importe quelle +-- fonction qui interagit avec le « monde extérieur » (c'est à dire fait de l'IO) +-- devient marqué comme `IO` dans la signature de son type. Ça nous montre +-- quelles fonctions sont « pures » (n'interagissent pas avec le monde extérieur +-- ou ne changent pas d'état) et quelles fonctions ne le sont pas. + +-- C'est une fonctionnalité très puissante, car il est facile d'exécuter +-- des fonctions pures simultanément, donc, la concurrence en Haskell +-- est très facile. + + +---------------------------------------------------- +-- 9. Le REPL de Haskell +---------------------------------------------------- + +-- Lancer le REPL en tapant `ghci`. +-- Vous pouvez maintenant taper de code Haskell. +-- Toutes les nouvelles valeurs peuvent être crées +-- avec `let`: + +let foo = 5 + +-- Vous pouvez voir le type de n'importe quelle valeur avec `:t`: + +>:t foo +foo :: Integer + +-- Vous pouvez également des actions de type `IO ()` + +> sayHello +Quel est ton nom ? +Ami! +Salut, Ami! + +``` + +Et Haskell ne se limite pas à ça, on trouve encore par exemple les classes de types et les monades. Il y a beaucoup de raisons qui font que coder en Haskell est si *fun*. Je vous laisse avec un dernier exemple: une implémentation de quicksort: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell facile à installer. Téléchargez-le [ici](http://www.haskell.org/platform/). + +Vous pouvez trouver une approche beaucoup plus douce avec les excellents +[Learn you a Haskell](http://lyah.haskell.fr/) ou +[Real World Haskell (en)](http://book.realworldhaskell.org/). -- cgit v1.2.3 From fea0557241dd7d6c270ec05ba89d3c898676ac3e Mon Sep 17 00:00:00 2001 From: David Baumgartner <_davidbaumgartner@bluewin.ch> Date: Sun, 6 Oct 2013 22:25:47 +0200 Subject: Revert "Adding french translation of Haskell" This reverts commit f400089013d99030e520c20735198273aed17b8e. --- fr-fr/haskell.html.markdown | 428 -------------------------------------------- 1 file changed, 428 deletions(-) delete mode 100644 fr-fr/haskell.html.markdown diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown deleted file mode 100644 index 16c40554..00000000 --- a/fr-fr/haskell.html.markdown +++ /dev/null @@ -1,428 +0,0 @@ ---- -language: haskell -contributors: - - ["Adit Bhargava", "http://adit.io"] - - ["David Baumgartner", "http://davidbaumgartner.ch"] ---- - -Haskell a été conçu pour être un langage fonctionnel pur et maniable. Il est connu pour ses monades et son système de types, mais je continue d'y revenir pour son élégance. Pour moi, Haskell fait de la programmation une joie. - -```haskell --- Un commentaire en une ligne commence avec deux tirets. -{- Un commentaire sur plusieurs lignes peut être contenu dans -un bloc de cette façon. --} - ----------------------------------------------------- --- 1. Types de données primitifs et opérateurs ----------------------------------------------------- - --- Vous avez les nombres -3 -- 3 - --- Les maths sont telles que vous vous y attendez -1 + 1 -- 2 -8 - 1 -- 7 -10 * 2 -- 20 -35 / 5 -- 7.0 - --- La division n'est pas entière par défaut -35 / 4 -- 8.75 - --- division entière -35 `div` 4 -- 8 - --- Les booléens sont primitifs -True -False - --- Opérations avec les booléens -not True -- False -not False -- True -1 == 1 -- True -1 /= 1 -- False -1 < 10 -- True - --- Dans les exemples plus hauts, `not`est une fonction qui prend une valeur --- Haskell n'a pas besoin de parenthèses pour appeler une fonction... tous --- les arguments sont juste listés après la fonction. Le schéma général est --- donc: --- func arg1 arg2 arg3... --- Voyez la section sur les fonctions pour savoir comment écrire les vôtres. - --- Caractères et chaînes de caractère -"Ceci est une chaîne de caractère." -'a' -- caractère -'Vous pouvez utiliser des apostrophes pour les chaînes de caractère.' -- erreur ! - --- Les chaînes peuvent être concaténées -"Hello " ++ "world!" -- "Hello world!" - --- Une chaîne de caractère est *réellement* une liste -"Ceci est une chaîne." !! 0 -- 'C' - - ----------------------------------------------------- --- Lists and Tuples ----------------------------------------------------- - --- Chaque élément d'une liste doit avoir le même type --- les deux lignes suivantes sont semblables -[1, 2, 3, 4, 5] -[1..5] - --- Il y a aussi des listes infinies en Haskell! -[1..] -- une liste de tous les nombres naturels - --- Les listes infinies fonctionnent parce que Haskell a « l'évaluation --- paresseuse ». Ça veut dire que Haskell n'évalue que ce qui a besoin --- de l'être. Vous pouvez donc vous demander le 1000e élément de votre liste: - -[1..] !! 999 -- 1000 - --- Et là, Haskell a évalué les éléments 1 à 1000 de la liste... mais le reste --- de cette liste "infinie" n'existe pas encore! En fait, Haskell ne va jamais --- le faire à moins qu'il en ait besoin. - --- Adjoindre deux listes -[1..5] ++ [6..10] - --- ajouter au début de la liste -0:[1..5] -- [0, 1, 2, 3, 4, 5] - --- l'indice d'une liste -[0..] !! 5 -- 5 - --- d'autres opérations sur les listes -head [1..5] -- 1 -tail [1..5] -- [2, 3, 4, 5] -init [1..5] -- [1, 2, 3, 4] -last [1..5] -- 5 - ---liste en compréhension -[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] - ---avec un conditionnel -[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] - --- Chaque élément d'un tuple peut être d'un type différent, mais une --- tuple a une longueur fixée. --- Un tuple: -("haskell", 1) - --- accéder aux éléments d'un tuple -fst ("haskell", 1) -- "haskell" -snd ("haskell", 1) -- 1 - ----------------------------------------------------- --- 3. Functions ----------------------------------------------------- --- Une simple fonction qui prend deux paramètres -add a b = a + b - --- Notez que si vous utilisez ghci (l'interpréteur Haskell) --- vous devrez utiliser `let`. Par exemple: --- let add a b = a + b - --- Utiliser une fonction -add 1 2 -- 3 - --- Vous pouvez également mettre le nom de la fonction entre les --- deux arguments avec des accents graves: -1 `add` 2 -- 3 - --- Vous pouvez également définir des fonctions qui n'ont pas de --- lettres! Ça vous laisse créer vos propres opérateurs! Voilà --- un opérateur qui fait une division entière: -(//) a b = a `div` b -35 // 4 -- 8 - --- Gardes: une façon pour créer des bifurcations de fonction -fib x - | x < 2 = x - | otherwise = fib (x - 1) + fib (x - 2) - --- Le filtrage par motif est similaire. Là on a donné trois --- définitions différents de `fib`. Haskell appellera automatiquement --- la première fonction qui correspondra au motif de la valeur. -fib 1 = 1 -fib 2 = 2 -fib x = fib (x - 1) + fib (x - 2) - --- Filtrage par motif sur un tuple. -foo (x, y) = (x + 1, y + 2) - --- Filtrage par motif sur des listes. Ici, `x` est le premier --- élément de la liste, et `xs` le reste. On peut écrire notre --- propre fonction `map`: -myMap func [] = [] -myMap func (x:xs) = func x:(myMap func xs) - --- Les fonctions anonymes sont créées avec des barres obliques --- inverses, suivies de tous les arguments. -myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] - --- Une utilisation de fold (appelée `inject` dans quelques autres --- langages) avec comme paramètre une fonction anonyme. --- `foldl1` veut dire fold left -- soit littéralement pli gauche. -- --- et utilise la première valeur de la liste comme accumulateur. -foldl1 (\acc x -> acc + x) [1..5] -- 15 - ----------------------------------------------------- --- 4. Plus de fonctions ----------------------------------------------------- - --- curryfaction: si vous n'appliquez pas tous les arguments à une --- fonction, elle devient « curryfiée ». Ça veut dire qu'elle retourne --- une fonction qui prend le reste des arguments. - -add a b = a + b -foo = add 10 -- foo est une fonction qui prend un nombre et y ajoute 10 -foo 5 -- 15 - --- Une autre façon de l'écrire -foo = (+10) -foo 5 -- 15 - --- Composition de fonctions --- la fonction (.) enchaîne deux fonctions. --- Par exemple, on a foo qui est une fonction qui prend une valeur, y ajoute --- 10 et multiplie ce résultat par 5, et ensuite retourne la valeur finale. -foo = (*5) . (+10) - --- (5 + 10) * 5 = 75 -foo 5 -- 75 - --- fixation de priorité --- Haskell a une autre fonction appelée `$`. Elle peut changer la priorité --- de façon à ce que tout ce qu'il y a à sa gauche est calculé d'abord --- et ensuite appliqué à tout ce qu'il y a à droite. Vous pouvez utiliser --- `.` et `$` pour vous débarrasser de beaucoup de parenthèses: - --- avant -(even (fib 7)) -- False - --- ensuite -even . fib $ 7 -- False - ----------------------------------------------------- --- 5. Signature de type ----------------------------------------------------- - --- Haskell a un système de types très strict, et tout a un type. - --- Quelques types simples: -5 :: Integer -"hello" :: String -True :: Bool - --- Les fonctions ont des types également. --- `not` prend un booléen et retourne un booléen. --- not :: Bool -> Bool - --- Voilà une fonction qui prend deux paramètres. --- add :: Integer -> Integer -> Integer - --- Quand vous définissez une valeur, une bonne pratique est d'écrire --- son type explicitement -double :: Integer -> Integer -double x = x * 2 - ----------------------------------------------------- --- 6. Flux de contrôle et structures conditionnelles ----------------------------------------------------- - --- structure conditionnelle if -haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" - --- les structures if peuvent être écrites sur plusieurs lignes -haskell = if 1 == 1 - then "awesome" - else "awful" - --- les structures case: Voilà comment vous pouvez analyser les arguments de --- ligne de commande -case args of - "help" -> printHelp - "start" -> startProgram - _ -> putStrLn "bad args" - - --- Haskell n'a pas de boucles parce qu'il utilise la récursion. --- `map` applique une fonction sur chaque élément d'une liste - -map (*2) [1..5] -- [2, 4, 6, 8, 10] - --- vous pouvez créer une fonction `for` en utilisant `map` -for array func = map func array - --- et l'utiliser -for [0..5] $ \i -> show i - --- nous aurions pu l'écrire également ainsi -for [0..5] show - --- vous pouvez utiliser foldl et foldr pour --- réduire une liste --- foldl -foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 - --- C'est donc la même chose que -(2 * (2 * (2 * 4 + 1) + 2) + 3) - --- foldl évalue de gauche à droite, foldr --- de droite à gauche -foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 - --- Et c'est équivalent à -(2 * 3 + (2 * 2 + (2 * 1 + 4))) - ----------------------------------------------------- --- 7. Types de données ----------------------------------------------------- - --- Vous pouvez écrire vos propres types de données en Haskell - -data Couleur = Rouge | Bleu | Vert - --- Et maintenant l'utiliser dans une fonction - - -say :: Couleur -> String -say Rouge = "Vous êtes Rouge!" -say Bleu = "Vous êtes Bleu!" -say Vert = "Vous êtes Vert!" - --- Vos types peuvent également avoir des paramètres - -data Maybe a = Nothing | Just a - --- Tous les exemples ci-dessous sont issus du type Maybe -Just "hello" -- of type `Maybe String` -Just 1 -- of type `Maybe Int` -Nothing -- of type `Maybe a` for any `a` - ----------------------------------------------------- --- 8. Haskell IO ----------------------------------------------------- - --- Tandis que l'IO ne peut pas être totalement expliqué pleinement --- sans que les monades ne le soient, il n'est pas difficile --- d'expliquer suffisamment pour commencer. - --- Quand un programme en Haskell est exécuté, la fonction `main` --- est appelée. Il doit retourner une valeur de type `IO ()`. --- Par exemple: - -main :: IO () -main = putStrLn $ "Bonjour, le ciel! " ++ (say Blue) --- putStrLn a comme type String -> IO () - --- Il est plus facile de faire IO si vous pouvez faire --- votre programme en fonction String à String. La fonction --- interact :: (String -> String) -> IO () --- prend un texte, applique une fonction et affiche le résultat. - -countLines :: String -> String -countLines = show . length . lines - -main' = interact countLines - --- Vous pouvez considérer qu'une valeur de type `IO ()` représente --- une séquence d'actions que l'ordinateur exécute, un peu comme --- dans un langage impératif. On peut utiliser la structure `do` --- pour enchaîner des actions. Par exemple: - -sayHello :: IO () -sayHello = do - putStrLn "Quel est ton nom ?" - name <- getLine -- prend une ligne et assigne sa valeur à `name` - putStrLn $ "Salut, " ++ name - --- Exercice: écrire votre propre version d'`interact` qui ne fait --- que de lire une ligne d'entrée. - --- Le code de `sayHello` ne sera jamais exécuté, cependant. La seule --- action qui sera exécutée est la valeur de `main`. --- Pour lancer `sayHello`, commentez l'ancienne définition de `main` --- et remplacez-le par: --- main = sayHello - --- Essaions de mieux comprendre comment la fonction `getLine` que --- nous venons d'utiliser. Son type est: --- getLine :: IO String --- vous pouvez considérer le type `IO a` comme un programme que --- le programme va générer comme une valeur de type `a` quand --- il sera exécuté. On peut l'enregistrer et la réutiliser en --- utilisant `<-`. On peut aussi faire nos propres actions --- de type `IO String`: - -action :: IO String -action = do - putStrLn "C'est une ligne. Heu" - input1 <- getLine - input2 <- getLine - -- Le type de la structure `do` est celui de sa dernière ligne. - -- `return` n'est pas un mot clef, mais simplement une fonction. - return (input1 ++ "\n" ++ input2) -- return :: String -> IO String - --- On peut maintenant l'utiliser comme on a utilisé `getLine` --- tout à l'heure - -main'' = do - putStrLn "Je vais afficher deux lignes!" - result <- action - putStrLn result - putStrLn "C'était tout!" - --- Le type `IO` est un exemple de « monade ». La façon dont Haskell une monade --- pour faire de l'IO lui permet d'être purement fonctionnel. N'importe quelle --- fonction qui interagit avec le « monde extérieur » (c'est à dire fait de l'IO) --- devient marqué comme `IO` dans la signature de son type. Ça nous montre --- quelles fonctions sont « pures » (n'interagissent pas avec le monde extérieur --- ou ne changent pas d'état) et quelles fonctions ne le sont pas. - --- C'est une fonctionnalité très puissante, car il est facile d'exécuter --- des fonctions pures simultanément, donc, la concurrence en Haskell --- est très facile. - - ----------------------------------------------------- --- 9. Le REPL de Haskell ----------------------------------------------------- - --- Lancer le REPL en tapant `ghci`. --- Vous pouvez maintenant taper de code Haskell. --- Toutes les nouvelles valeurs peuvent être crées --- avec `let`: - -let foo = 5 - --- Vous pouvez voir le type de n'importe quelle valeur avec `:t`: - ->:t foo -foo :: Integer - --- Vous pouvez également des actions de type `IO ()` - -> sayHello -Quel est ton nom ? -Ami! -Salut, Ami! - -``` - -Et Haskell ne se limite pas à ça, on trouve encore par exemple les classes de types et les monades. Il y a beaucoup de raisons qui font que coder en Haskell est si *fun*. Je vous laisse avec un dernier exemple: une implémentation de quicksort: - -```haskell -qsort [] = [] -qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater - where lesser = filter (< p) xs - greater = filter (>= p) xs -``` - -Haskell facile à installer. Téléchargez-le [ici](http://www.haskell.org/platform/). - -Vous pouvez trouver une approche beaucoup plus douce avec les excellents -[Learn you a Haskell](http://lyah.haskell.fr/) ou -[Real World Haskell (en)](http://book.realworldhaskell.org/). -- cgit v1.2.3 From cc1c704b8aea62e50c596e54a88357820b1110c2 Mon Sep 17 00:00:00 2001 From: David Baumgartner <_davidbaumgartner@bluewin.ch> Date: Sun, 6 Oct 2013 22:28:53 +0200 Subject: Adding french translation of Haskell --- fr-fr/haskell.html.markdown | 429 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 429 insertions(+) create mode 100644 fr-fr/haskell.html.markdown diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown new file mode 100644 index 00000000..519bffd6 --- /dev/null +++ b/fr-fr/haskell.html.markdown @@ -0,0 +1,429 @@ +--- +language: haskell +contributors: + - ["Adit Bhargava", "http://adit.io"] + - ["David Baumgartner", "http://davidbaumgartner.ch"] +--- + +Haskell a été conçu pour être un langage fonctionnel pur et maniable. Il est connu pour ses monades et son système de types, mais je n'ai cesse d'y revenir pour son élégance. Pour moi, Haskell fait de la programmation une joie. + +```haskell +-- Un commentaire en une ligne commence avec deux tirets. +{- Un commentaire sur plusieurs lignes peut être contenu dans +un bloc de cette façon. +-} + +---------------------------------------------------- +-- 1. Types de données primitifs et opérateurs +---------------------------------------------------- + +-- Vous avez les nombres +3 -- 3 + +-- Les maths sont telles que vous vous y attendez +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- La division n'est pas entière par défaut +35 / 4 -- 8.75 + +-- division entière +35 `div` 4 -- 8 + +-- Les booléens sont primitifs +True +False + +-- Opérations avec les booléens +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- Dans les exemples plus hauts, `not` est une fonction qui prend une valeur. +-- Haskell n'a pas besoin de parenthèses pour appeler une fonction... tous +-- les arguments sont juste listés après la fonction. Le schéma général est +-- donc: +-- func arg1 arg2 arg3... +-- Voyez la section sur les fonctions pour savoir comment écrire les vôtres. + +-- Caractères et chaînes de caractère +"Ceci est une chaîne de caractère." +'a' -- caractère +'Vous pouvez utiliser des apostrophes pour les chaînes de caractère.' -- erreur ! + +-- Les chaînes peuvent être concaténées +"Hello " ++ "world!" -- "Hello world!" + +-- Une chaîne de caractère est *réellement* une liste +"Ceci est une chaîne." !! 0 -- 'C' + + +---------------------------------------------------- +-- Lists and Tuples +---------------------------------------------------- + +-- Chaque élément d'une liste doit avoir le même type. +-- les deux lignes suivantes sont semblables +[1, 2, 3, 4, 5] +[1..5] + +-- Il y a aussi des listes infinies en Haskell! +[1..] -- une liste de tous les nombres naturels + +-- Les listes infinies fonctionnent parce que Haskell a « l'évaluation +-- paresseuse ». Ça veut dire qu'il n'évalue que ce qui a besoin +-- de l'être. Vous pouvez donc vous demander le 1000e élément de votre liste +-- et il vous le donnera: + +[1..] !! 999 -- 1000 + +-- Et là, Haskell a évalué les éléments 1 à 1000 de la liste... mais le reste +-- de cette liste « infinie » n'existe pas encore! En fait, Haskell ne va jamais +-- le faire à moins qu'il le doive. + +-- Adjoindre deux listes +[1..5] ++ [6..10] + +-- ajouter au début de la liste +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- l'indice d'une liste +[0..] !! 5 -- 5 + +-- d'autres opérations sur les listes +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +--liste en compréhension +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +--avec un conditionnel +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Chaque élément d'un tuple peut être d'un type différent, mais un +-- tuple a une longueur fixée. +-- Un tuple: +("haskell", 1) + +-- accéder aux éléments d'un tuple +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Functions +---------------------------------------------------- +-- Une simple fonction qui prend deux paramètres +add a b = a + b + +-- Notez que si vous utilisez ghci (l'interpréteur Haskell) +-- vous devrez utiliser `let`. Par exemple: +-- let add a b = a + b + +-- Utiliser une fonction +add 1 2 -- 3 + +-- Vous pouvez également mettre le nom de la fonction entre les +-- deux arguments avec des accents graves: +1 `add` 2 -- 3 + +-- Vous pouvez également définir des fonctions qui n'ont pas de +-- lettres! Ça vous laisse créer vos propres opérateurs! Voilà +-- un opérateur qui fait une division entière: +(//) a b = a `div` b +35 // 4 -- 8 + +-- Gardes: une façon pour créer des bifurcations de fonction +fib x + | x < 2 = x + | otherwise = fib (x - 1) + fib (x - 2) + +-- Le filtrage par motif est similaire. Là on a donné trois +-- définitions différentes de `fib`. Haskell appellera automatiquement +-- la première fonction qui correspondra au motif de la valeur. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Filtrage par motif sur un tuple. +foo (x, y) = (x + 1, y + 2) + +-- Filtrage par motif sur des listes. Ici, `x` est le premier +-- élément de la liste, et `xs` le reste. On peut écrire notre +-- propre fonction `map`: +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Les fonctions anonymes sont créées avec des barres obliques +-- inverses, suivies de tous les arguments. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- Une utilisation de fold (appelée `inject` dans quelques autres +-- langages) avec comme paramètre une fonction anonyme. +-- `foldl1` veut dire fold left -- soit littéralement pli gauche -- +-- et utilise la première valeur de la liste comme accumulateur. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Plus de fonctions +---------------------------------------------------- + +-- curryfaction: si vous n'appliquez pas tous les arguments à une +-- fonction, elle devient « curryfiée ». Ça veut dire qu'elle retourne +-- une fonction qui prend le reste des arguments. + +add a b = a + b +foo = add 10 -- foo est une fonction qui prend un nombre et y ajoute 10 +foo 5 -- 15 + +-- Une autre façon de l'écrire +foo = (+10) +foo 5 -- 15 + +-- Composition de fonctions +-- la fonction (.) enchaîne deux fonctions. +-- Par exemple, on a foo qui est une fonction qui prend une valeur, y ajoute +-- 10 et multiplie ce résultat par 5, et ensuite retourne la valeur finale. +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +-- fixation de priorité +-- Haskell a une autre fonction appelée `$`. Elle peut changer la priorité +-- de sorte que tout ce qu'il y a à sa gauche est calculé d'abord et ensuite +-- appliqué à tout ce qu'il y a à droite. Vous pouvez utiliser `.` et `$` +-- pour vous débarrasser de beaucoup de parenthèses: + +-- avant +(even (fib 7)) -- False + +-- ensuite +even . fib $ 7 -- False + +---------------------------------------------------- +-- 5. Signature de type +---------------------------------------------------- + +-- Haskell a un système de types très strict; et en Haskell, tout a un type. + +-- Quelques types simples: +5 :: Integer +"hello" :: String +True :: Bool + +-- Les fonctions ont des types également. +-- `not` prend un booléen et retourne un booléen. +-- not :: Bool -> Bool + +-- Voilà une fonction qui prend deux paramètres. +-- add :: Integer -> Integer -> Integer + +-- Quand vous définissez une valeur, une bonne pratique est d'écrire +-- son type explicitement +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Flux de contrôle et structures conditionnelles +---------------------------------------------------- + +-- structure conditionnelle if +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- les structures if peuvent être écrites sur plusieurs lignes +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- les structures case: voilà comment vous pouvez analyser les arguments de +-- ligne de commande +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + + +-- Haskell n'a pas de boucles parce qu'il utilise la récursion. +-- `map` applique une fonction sur chaque élément d'une liste + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- vous pouvez créer une fonction `for` en utilisant `map` +for array func = map func array + +-- et l'utiliser +for [0..5] $ \i -> show i + +-- nous aurions pu l'écrire également ainsi +for [0..5] show + +-- vous pouvez utiliser foldl et foldr pour +-- réduire une liste +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- C'est donc la même chose que +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl évalue de gauche à droite, foldr +-- de droite à gauche +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Et c'est équivalent à +(2 * 3 + (2 * 2 + (2 * 1 + 4))) + +---------------------------------------------------- +-- 7. Types de données +---------------------------------------------------- + +-- Vous pouvez écrire vos propres types de données en Haskell + +data Couleur = Rouge | Bleu | Vert + +-- Et maintenant l'utiliser dans une fonction + + +say :: Couleur -> String +say Rouge = "Vous êtes Rouge!" +say Bleu = "Vous êtes Bleu!" +say Vert = "Vous êtes Vert!" + +-- Vos types peuvent également avoir des paramètres + +data Maybe a = Nothing | Just a + +-- Tous les exemples ci-dessous sont issus du type Maybe +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- Tandis que l'IO ne peut pas être totalement expliqué pleinement +-- sans que les monades ne le soient, il n'est pas difficile +-- d'expliquer suffisamment pour commencer. + +-- Quand un programme en Haskell est exécuté, la fonction `main` +-- est appelée. Il doit retourner une valeur de type `IO ()`. +-- Par exemple: + +main :: IO () +main = putStrLn $ "Bonjour, le ciel! " ++ (say Blue) +-- putStrLn a comme type String -> IO () + +-- La façon la plus simple pour faire de l'IO est de faire un programme +-- fonction de String vers String. La fonction +-- interact :: (String -> String) -> IO () +-- prend un texte, applique une fonction et affiche le résultat. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- Vous pouvez considérer qu'une valeur de type `IO ()` représente +-- une séquence d'actions que l'ordinateur exécute, un peu comme +-- dans un langage impératif. On peut utiliser la structure `do` +-- pour enchaîner des actions. Par exemple: + +sayHello :: IO () +sayHello = do + putStrLn "Quel est ton nom ?" + name <- getLine -- prend une ligne et assigne sa valeur à `name` + putStrLn $ "Salut, " ++ name + +-- Exercice: écrire votre propre version d'`interact` qui ne fait +-- que de lire une ligne d'entrée. + +-- Le code de `sayHello` ne sera jamais exécuté, cependant. La seule +-- action qui sera exécutée est la valeur de `main`. +-- Pour lancer `sayHello`, commentez l'ancienne définition de `main` +-- et remplacez-le par: +-- main = sayHello + +-- Essaions de mieux comprendre comment la fonction `getLine` que +-- nous venons d'utiliser. Son type est: +-- getLine :: IO String +-- vous pouvez considérer le type `IO a` comme un programme que +-- le programme va générer comme une valeur de type `a` quand +-- il sera exécuté. On peut l'enregistrer et la réutiliser en +-- utilisant `<-`. On peut aussi faire nos propres actions +-- de type `IO String`: + +action :: IO String +action = do + putStrLn "C'est une ligne. Heu" + input1 <- getLine + input2 <- getLine + -- Le type de la structure `do` est celui de sa dernière ligne. + -- `return` n'est pas un mot clef, mais simplement une fonction. + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- On peut maintenant l'utiliser comme on a utilisé `getLine` +-- tout à l'heure + +main'' = do + putStrLn "Je vais afficher deux lignes!" + result <- action + putStrLn result + putStrLn "C'était tout!" + +-- Le type `IO` est un exemple de « monade ». La façon dont Haskell utilise +-- une monade pour faire de l'IO lui permet d'être purement fonctionnel. N'importe +-- quelle fonction qui interagit avec le « monde extérieur » (c'est à dire fait de l'IO) +-- devient marqué comme `IO` dans la signature de son type. Ça nous montre +-- quelles fonctions sont « pures » (n'interagissent pas avec le monde extérieur +-- ou ne changent pas d'état) et quelles fonctions ne le sont pas. + +-- C'est une fonctionnalité très puissante, car il est facile d'exécuter +-- des fonctions pures simultanément, et donc la concurrence en Haskell +-- est très facile. + + +---------------------------------------------------- +-- 9. Le REPL de Haskell +---------------------------------------------------- + +-- Lancer le REPL en tapant `ghci`. +-- Vous pouvez maintenant taper du code Haskell. +-- Toutes les nouvelles valeurs peuvent être crées +-- avec `let`: + +let foo = 5 + +-- Vous pouvez voir le type de n'importe quelle valeur avec `:t`: + +>:t foo +foo :: Integer + +-- Vous pouvez également des actions de type `IO ()` + +> sayHello +Quel est ton nom ? +Ami! +Salut, Ami! + +``` + +Et Haskell ne se limite pas à ça, on trouve encore par exemple les classes de types et les monades. Il y a beaucoup de raisons qui font que coder en Haskell est si *fun*. Je vous laisse avec un dernier exemple: une implémentation de quicksort: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell facile à installer. Téléchargez-le [ici](http://www.haskell.org/platform/). + +Vous pouvez trouver une approche beaucoup plus douce avec les excellents +[Learn you a Haskell](http://lyah.haskell.fr/) ou +[Real World Haskell (en)](http://book.realworldhaskell.org/). -- cgit v1.2.3 From 2071148e1eb01848cb40d4ec4212a463e025fed9 Mon Sep 17 00:00:00 2001 From: "Benjamin R. Haskell" Date: Sun, 6 Oct 2013 22:40:06 -0400 Subject: Fixes language identification in elixir-de YAML frontmatter had a line that looks like it was mis-patched (started with a `+`). Removed the `+` so the translation is displayed in the right place. --- de-de/elixir-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown index f77f9b0c..29d5132d 100644 --- a/de-de/elixir-de.html.markdown +++ b/de-de/elixir-de.html.markdown @@ -5,7 +5,7 @@ contributors: translators: - ["Gregor Große-Bölting", "http://www.ideen-und-soehne.de"] filename: learnelixir-de.ex -+lang: de-de +lang: de-de --- Elixir ist eine moderne, funktionale Sprache für die Erlang VM. Sie ist voll -- cgit v1.2.3 From 2f4b2e319b54b72298661a35ff9985fee1ecbae0 Mon Sep 17 00:00:00 2001 From: Christos Kontas Date: Mon, 7 Oct 2013 17:48:30 +0300 Subject: [CommonLisp] fix typo error in comment --- common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index a672b682..dda60797 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -377,7 +377,7 @@ nil ; for false - and the empty list ;; 4. Equality ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Common Lisp has a sophisticated equality system. A couple are covered yere. +;; Common Lisp has a sophisticated equality system. A couple are covered here. ;; for numbers use `=' (= 3 3.0) ; => t -- cgit v1.2.3 From 8cbabf82b8ff938907ad6fc86327706668544c89 Mon Sep 17 00:00:00 2001 From: Craig Roddin Date: Mon, 7 Oct 2013 12:33:10 -0600 Subject: Fixed spelling of trig function "sin" --- lua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua.html.markdown b/lua.html.markdown index 369de908..27ce105b 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -125,7 +125,7 @@ f = function (x) return x * x end -- And so are these: local function g(x) return math.sin(x) end -local g = function(x) return math.xin(x) end +local g = function(x) return math.sin(x) end -- Equivalent to local function g(x)..., except referring -- to g in the function body won't work as expected. local g; g = function (x) return math.sin(x) end -- cgit v1.2.3 From 80e8200b55ae3d3c7e0dd3b4f363c2358470980b Mon Sep 17 00:00:00 2001 From: Christos Kontas Date: Tue, 8 Oct 2013 18:48:46 +0300 Subject: [git] Fix typo error in guide --- git.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index abe8e3a7..4b5e466e 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -40,7 +40,7 @@ Version control is a system that records changes to a file, or set of files, ove ### Repository -A set of files, directories, historical records, commits, and heads. Imagine it as a source code datastructure, +A set of files, directories, historical records, commits, and heads. Imagine it as a source code data structure, with the attribute that each source code "element" gives you access to its revision history, among other things. A git repository is comprised of the .git directory & working tree. -- cgit v1.2.3 From 925ded87809a5ae9f40a3c825324cb083eaba81e Mon Sep 17 00:00:00 2001 From: Christos Kontas Date: Tue, 8 Oct 2013 19:09:12 +0300 Subject: [java] Missing semi-colon at code example --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 0dec51d1..3d0cb1d7 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -250,7 +250,7 @@ public class LearnJava { // Conditional Shorthand // You can use the '?' operator for quick assignments or logic forks. // Reads as "If (statement) is true, use , otherwise, use " - int foo = 5 + int foo = 5; String bar = (foo < 10) ? "A" : "B"; System.out.println(bar); // Prints A, because the statement is true -- cgit v1.2.3 From a18773edbac72a994c57f44cb8d3644ebf701bc9 Mon Sep 17 00:00:00 2001 From: Guillermo Vaya Date: Wed, 9 Oct 2013 11:21:55 +0200 Subject: Correct relevant fix from issue #374 --- es-es/clojure-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/clojure-es.html.markdown b/es-es/clojure-es.html.markdown index 1ccdc50e..150d0bb2 100644 --- a/es-es/clojure-es.html.markdown +++ b/es-es/clojure-es.html.markdown @@ -70,7 +70,7 @@ y a menudo automáticamente. ; Si quieres crear una lista de datos, precedela con una comilla ; simple para evitar su evaluación '(+ 1 2) ; => (+ 1 2) -; (que es una abreviatura de (quote (+ 1 2)) +; (que es una abreviatura de (quote (+ 1 2)) ) ; Puedes evaluar una lista precedida por comilla con eval (eval '(+ 1 2)) ; => 3 -- cgit v1.2.3 From 9c0e7c548d3fb0cf655f282e36b1c24b21bba83b Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Thu, 10 Oct 2013 08:33:39 +1030 Subject: [javascript] Add bit about array mutability. Closes #381. --- javascript.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index 6b6be34d..97c5b712 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -142,6 +142,10 @@ var myArray = ["Hello", 45, true]; // Array indices start at zero. myArray[1]; // = 45 +// Arrays are mutable and of variable length. +myArray.push("World"); +myArray.length; // = 4 + // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; -- cgit v1.2.3 From c149c619da0f258c55bfb355e9d9e3b02dc880c2 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Thu, 10 Oct 2013 10:52:56 +1030 Subject: [javascript] Added note about ints --- javascript.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index 97c5b712..2ac98105 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -38,6 +38,8 @@ doStuff() // 1. Numbers, Strings and Operators // Javascript has one number type (which is a 64-bit IEEE 754 double). +// As with Lua, don't freak out about the lack of ints: doubles have a 52-bit +// mantissa, which is enough to store integers up to about 9✕10¹⁵ precisely. 3; // = 3 1.5; // = 1.5 -- cgit v1.2.3 From 200298c7691e0f0b78b7e879fcf7fc4909cea16a Mon Sep 17 00:00:00 2001 From: C-Duv Date: Fri, 11 Oct 2013 10:13:12 +0200 Subject: French translation typo in comments for slice syntax with omitted indexes Translation typo in comments for slice syntax with omitted indexes: "Omit the beginning" meant omit the beginning *of the list* (not the beginning of the range) "Omit the end" meant omit the end *of the list* (not the end of the range) --- fr-fr/python-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 2bf0afd0..9dbdafe1 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -156,9 +156,9 @@ li[4] # Lève un 'IndexError' # On peut accèder à des rangs de valeurs avec la syntaxe "slice" # (C'est un rang de type 'fermé/ouvert' pour les plus matheux) li[1:3] #=> [2, 4] -# Sans spécifier de début de rang +# Sans spécifier de fin de rang, on "saute" le début de la liste li[2:] #=> [4, 3] -# Sans spécifier de fin de rang +# Sans spécifier de début de rang, on "saute" la fin de la liste li[:3] #=> [1, 2, 4] # Retirer un élément spécifique dee la liste avec "del" -- cgit v1.2.3 From e0fbcf5b83f9dbc9185ef5b6e4d2fd2d35c4c915 Mon Sep 17 00:00:00 2001 From: Pablo Elices Date: Sat, 12 Oct 2013 17:56:51 +0200 Subject: Better translation. --- es-es/coffeescript-es.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/es-es/coffeescript-es.html.markdown b/es-es/coffeescript-es.html.markdown index 78bb9be5..6bf430e6 100644 --- a/es-es/coffeescript-es.html.markdown +++ b/es-es/coffeescript-es.html.markdown @@ -44,7 +44,7 @@ math = # "cube": function(x) { return x * square(x); } #} -# Símbolos: +# Número de argumentos variable: race = (winner, runners...) -> print winner, runners @@ -52,6 +52,6 @@ race = (winner, runners...) -> alert "I knew it!" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } -# Colecciones por comprensión: +# Listas: cubes = (math.cube num for num in list) #=> ... ``` -- cgit v1.2.3 From 3bfc820721618af1c1421e2858198bbc739ec70a Mon Sep 17 00:00:00 2001 From: alexandre medeiros Date: Sun, 13 Oct 2013 00:14:24 -0300 Subject: add another way to define functions to bash (fix #380) --- bash.html.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index 276bc31f..d208b957 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -117,7 +117,7 @@ done # You can also define functions # Definition: -foo () +function foo () { echo "Arguments work just like script arguments: $@" echo "And: $1 $2..." @@ -125,6 +125,13 @@ foo () return 0 } +# or simply +bar () +{ + echo "Another way to declare functions!" + return 0 +} + # Calling your function foo "My name is" $NAME -- cgit v1.2.3 From aa2506aa2a06b108794b7e624c5375c088285b6c Mon Sep 17 00:00:00 2001 From: David Baumgartner <_davidbaumgartner@bluewin.ch> Date: Wed, 16 Oct 2013 18:18:37 +0200 Subject: Applying corrections --- fr-fr/haskell.html.markdown | 97 +++++++++++++++++++++++---------------------- 1 file changed, 49 insertions(+), 48 deletions(-) diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown index 519bffd6..9d0cec99 100644 --- a/fr-fr/haskell.html.markdown +++ b/fr-fr/haskell.html.markdown @@ -2,7 +2,9 @@ language: haskell contributors: - ["Adit Bhargava", "http://adit.io"] - - ["David Baumgartner", "http://davidbaumgartner.ch"] +translators: + - ["David Baumgartner", "http://davidbaumgartner.ch"] +lang: fr-fr --- Haskell a été conçu pour être un langage fonctionnel pur et maniable. Il est connu pour ses monades et son système de types, mais je n'ai cesse d'y revenir pour son élégance. Pour moi, Haskell fait de la programmation une joie. @@ -20,7 +22,7 @@ un bloc de cette façon. -- Vous avez les nombres 3 -- 3 --- Les maths sont telles que vous vous y attendez +-- Les maths sont comme vous vous y attendez 1 + 1 -- 2 8 - 1 -- 7 10 * 2 -- 20 @@ -46,14 +48,14 @@ not False -- True -- Dans les exemples plus hauts, `not` est une fonction qui prend une valeur. -- Haskell n'a pas besoin de parenthèses pour appeler une fonction... tous -- les arguments sont juste listés après la fonction. Le schéma général est --- donc: +-- donc : -- func arg1 arg2 arg3... -- Voyez la section sur les fonctions pour savoir comment écrire les vôtres. -- Caractères et chaînes de caractère "Ceci est une chaîne de caractère." 'a' -- caractère -'Vous pouvez utiliser des apostrophes pour les chaînes de caractère.' -- erreur ! +'Vous ne pouvez pas utiliser des apostrophes pour les chaînes de caractère.' -- erreur ! -- Les chaînes peuvent être concaténées "Hello " ++ "world!" -- "Hello world!" @@ -63,27 +65,26 @@ not False -- True ---------------------------------------------------- --- Lists and Tuples +-- Listes et tuples ---------------------------------------------------- --- Chaque élément d'une liste doit avoir le même type. +-- Tous les éléments d'une liste doit avoir le même type. -- les deux lignes suivantes sont semblables [1, 2, 3, 4, 5] [1..5] --- Il y a aussi des listes infinies en Haskell! +-- Il y a aussi des listes infinies en Haskell ! [1..] -- une liste de tous les nombres naturels --- Les listes infinies fonctionnent parce que Haskell a « l'évaluation --- paresseuse ». Ça veut dire qu'il n'évalue que ce qui a besoin --- de l'être. Vous pouvez donc vous demander le 1000e élément de votre liste --- et il vous le donnera: +-- Les listes infinies fonctionnent parce que Haskell est « paresseux »: +-- ça veut dire qu'il n'évalue que ce qui a besoin de l'être. Vous pouvez +-- donc vous demander le 1000e élément de votre liste et il vous le donnera : [1..] !! 999 -- 1000 -- Et là, Haskell a évalué les éléments 1 à 1000 de la liste... mais le reste --- de cette liste « infinie » n'existe pas encore! En fait, Haskell ne va jamais --- le faire à moins qu'il le doive. +-- de cette liste « infinie » n'existe pas encore ! En fait, Haskell ne va jamais +-- le faire à moins qu'il ne le doive. -- Adjoindre deux listes [1..5] ++ [6..10] @@ -108,7 +109,7 @@ last [1..5] -- 5 -- Chaque élément d'un tuple peut être d'un type différent, mais un -- tuple a une longueur fixée. --- Un tuple: +-- Un tuple : ("haskell", 1) -- accéder aux éléments d'un tuple @@ -122,30 +123,30 @@ snd ("haskell", 1) -- 1 add a b = a + b -- Notez que si vous utilisez ghci (l'interpréteur Haskell) --- vous devrez utiliser `let`. Par exemple: +-- vous devrez utiliser `let`. Par exemple : -- let add a b = a + b -- Utiliser une fonction add 1 2 -- 3 -- Vous pouvez également mettre le nom de la fonction entre les --- deux arguments avec des accents graves: +-- deux arguments avec des accents graves : 1 `add` 2 -- 3 -- Vous pouvez également définir des fonctions qui n'ont pas de --- lettres! Ça vous laisse créer vos propres opérateurs! Voilà --- un opérateur qui fait une division entière: +-- lettres ! Ça vous laisse créer vos propres opérateurs ! Voilà +-- un opérateur qui fait une division entière : (//) a b = a `div` b 35 // 4 -- 8 --- Gardes: une façon pour créer des bifurcations de fonction +-- Gardes : Une façon de gérer la valeur de vos arguments en amont fib x | x < 2 = x | otherwise = fib (x - 1) + fib (x - 2) --- Le filtrage par motif est similaire. Là on a donné trois +-- Le filtrage par motif est similaire. Là, on a donné trois -- définitions différentes de `fib`. Haskell appellera automatiquement --- la première fonction qui correspondra au motif de la valeur. +-- la première fonction qui correspond au motif de la valeur. fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) @@ -155,7 +156,7 @@ foo (x, y) = (x + 1, y + 2) -- Filtrage par motif sur des listes. Ici, `x` est le premier -- élément de la liste, et `xs` le reste. On peut écrire notre --- propre fonction `map`: +-- propre fonction `map` : myMap func [] = [] myMap func (x:xs) = func x:(myMap func xs) @@ -173,7 +174,7 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15 -- 4. Plus de fonctions ---------------------------------------------------- --- curryfaction: si vous n'appliquez pas tous les arguments à une +-- curryfication : si vous n'appliquez pas tous les arguments à une -- fonction, elle devient « curryfiée ». Ça veut dire qu'elle retourne -- une fonction qui prend le reste des arguments. @@ -198,7 +199,7 @@ foo 5 -- 75 -- Haskell a une autre fonction appelée `$`. Elle peut changer la priorité -- de sorte que tout ce qu'il y a à sa gauche est calculé d'abord et ensuite -- appliqué à tout ce qu'il y a à droite. Vous pouvez utiliser `.` et `$` --- pour vous débarrasser de beaucoup de parenthèses: +-- pour vous débarrasser de beaucoup de parenthèses : -- avant (even (fib 7)) -- False @@ -210,22 +211,22 @@ even . fib $ 7 -- False -- 5. Signature de type ---------------------------------------------------- --- Haskell a un système de types très strict; et en Haskell, tout a un type. +-- Haskell a un système de types très strict : par exemple, tout a un type. --- Quelques types simples: +-- Quelques types simples : 5 :: Integer "hello" :: String True :: Bool --- Les fonctions ont des types également. +-- Les fonctions ont également des types. -- `not` prend un booléen et retourne un booléen. -- not :: Bool -> Bool -- Voilà une fonction qui prend deux paramètres. -- add :: Integer -> Integer -> Integer --- Quand vous définissez une valeur, une bonne pratique est d'écrire --- son type explicitement +-- Quand vous définissez une valeur (souvenez-vous, tout est valeur en +-- Haskell), une bonne pratique est d'écrire son type explicitement double :: Integer -> Integer double x = x * 2 @@ -241,7 +242,7 @@ haskell = if 1 == 1 then "awesome" else "awful" --- les structures case: voilà comment vous pouvez analyser les arguments de +-- les structures case : voilà comment vous pourriez analyser les arguments de -- ligne de commande case args of "help" -> printHelp @@ -290,9 +291,9 @@ data Couleur = Rouge | Bleu | Vert say :: Couleur -> String -say Rouge = "Vous êtes Rouge!" -say Bleu = "Vous êtes Bleu!" -say Vert = "Vous êtes Vert!" +say Rouge = "Vous êtes Rouge !" +say Bleu = "Vous êtes Bleu !" +say Vert = "Vous êtes Vert !" -- Vos types peuvent également avoir des paramètres @@ -313,10 +314,10 @@ Nothing -- of type `Maybe a` for any `a` -- Quand un programme en Haskell est exécuté, la fonction `main` -- est appelée. Il doit retourner une valeur de type `IO ()`. --- Par exemple: +-- Par exemple : main :: IO () -main = putStrLn $ "Bonjour, le ciel! " ++ (say Blue) +main = putStrLn $ "Bonjour, le ciel ! " ++ (say Blue) -- putStrLn a comme type String -> IO () -- La façon la plus simple pour faire de l'IO est de faire un programme @@ -332,7 +333,7 @@ main' = interact countLines -- Vous pouvez considérer qu'une valeur de type `IO ()` représente -- une séquence d'actions que l'ordinateur exécute, un peu comme -- dans un langage impératif. On peut utiliser la structure `do` --- pour enchaîner des actions. Par exemple: +-- pour enchaîner des actions. Par exemple : sayHello :: IO () sayHello = do @@ -340,23 +341,23 @@ sayHello = do name <- getLine -- prend une ligne et assigne sa valeur à `name` putStrLn $ "Salut, " ++ name --- Exercice: écrire votre propre version d'`interact` qui ne fait +-- Exercice : écrire votre propre version d'`interact` qui ne fait -- que de lire une ligne d'entrée. -- Le code de `sayHello` ne sera jamais exécuté, cependant. La seule -- action qui sera exécutée est la valeur de `main`. -- Pour lancer `sayHello`, commentez l'ancienne définition de `main` --- et remplacez-le par: +-- et remplacez-le par : -- main = sayHello -- Essaions de mieux comprendre comment la fonction `getLine` que --- nous venons d'utiliser. Son type est: +-- nous venons d'utiliser. Son type est : -- getLine :: IO String -- vous pouvez considérer le type `IO a` comme un programme que -- le programme va générer comme une valeur de type `a` quand -- il sera exécuté. On peut l'enregistrer et la réutiliser en -- utilisant `<-`. On peut aussi faire nos propres actions --- de type `IO String`: +-- de type `IO String` : action :: IO String action = do @@ -371,10 +372,10 @@ action = do -- tout à l'heure main'' = do - putStrLn "Je vais afficher deux lignes!" + putStrLn "Je vais afficher deux lignes !" result <- action putStrLn result - putStrLn "C'était tout!" + putStrLn "C'était tout !" -- Le type `IO` est un exemple de « monade ». La façon dont Haskell utilise -- une monade pour faire de l'IO lui permet d'être purement fonctionnel. N'importe @@ -395,25 +396,25 @@ main'' = do -- Lancer le REPL en tapant `ghci`. -- Vous pouvez maintenant taper du code Haskell. -- Toutes les nouvelles valeurs peuvent être crées --- avec `let`: +-- avec `let` : let foo = 5 --- Vous pouvez voir le type de n'importe quelle valeur avec `:t`: +-- Vous pouvez voir le type de n'importe quelle valeur avec `:t` : >:t foo foo :: Integer --- Vous pouvez également des actions de type `IO ()` +-- Vous pouvez également lancer des actions de type `IO ()` > sayHello Quel est ton nom ? -Ami! -Salut, Ami! +Ami +Salut, Ami ! ``` -Et Haskell ne se limite pas à ça, on trouve encore par exemple les classes de types et les monades. Il y a beaucoup de raisons qui font que coder en Haskell est si *fun*. Je vous laisse avec un dernier exemple: une implémentation de quicksort: +Et Haskell ne se limite pas à ça, on trouve encore par exemple les classes de types et les monades. Il y a beaucoup de raisons qui font que coder en Haskell est si *fun*. Je vous laisse avec un dernier exemple : une implémentation de quicksort : ```haskell qsort [] = [] -- cgit v1.2.3 From 7ec6479a3cbd5d50030492d3982e21a15410b21a Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Fri, 18 Oct 2013 18:33:42 -0500 Subject: Revised Julia in Y Minutes, until Types section. --- julia.html.markdown | 80 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 49 insertions(+), 31 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index e824bfcf..f8c2f6e7 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -274,22 +274,22 @@ get(filled_dict,"four",4) #=> 4 # Use Sets to represent collections of unordered, unique values empty_set = Set() #=> Set{Any}() -# Initialize a set with a bunch of values +# Initialize a set with values filled_set = Set(1,2,2,3,4) #=> Set{Int64}(1,2,3,4) -# Add more items to a set +# Add more values to a set add!(filled_set,5) #=> Set{Int64}(5,4,2,3,1) +# Check if the values are in the set +contains(filled_set,2) #=> true +contains(filled_set,10) #=> false + # There are functions for set intersection, union, and difference. other_set = Set(3, 4, 5, 6) #=> Set{Int64}(6,4,5,3) intersect(filled_set, other_set) #=> Set{Int64}(3,4,5) union(filled_set, other_set) #=> Set{Int64}(1,2,3,4,5,6) setdiff(Set(1,2,3,4),Set(2,3,5)) #=> Set{Int64}(1,4) -# Check for existence in a set with contains -contains(filled_set,2) #=> true -contains(filled_set,10) #=> false - #################################################### ## 3. Control Flow @@ -298,8 +298,7 @@ contains(filled_set,10) #=> false # Let's make a variable some_var = 5 -# Here is an if statement. Indentation is NOT meaningful in Julia. -# prints "some var is smaller than 10" +# Here is an if statement. Indentation is not meaningful in Julia. if some_var > 10 println("some_var is totally bigger than 10.") elseif some_var < 10 # This elseif clause is optional. @@ -307,44 +306,56 @@ elseif some_var < 10 # This elseif clause is optional. else # The else clause is optional too. println("some_var is indeed 10.") end +#=> prints "some var is smaller than 10" -# For loops iterate over iterables, such as ranges, lists, sets, dicts, strings. - +# For loops iterate over iterables. +# Iterable types include Range, Array, Set, Dict, and String. for animal=["dog", "cat", "mouse"] - # You can use $ to interpolate into strings println("$animal is a mammal") + # You can use $ to interpolate variables or expression into strings end # prints: # dog is a mammal # cat is a mammal # mouse is a mammal -# You can use in instead of =, if you want. +# You can use 'in' instead of '='. for animal in ["dog", "cat", "mouse"] println("$animal is a mammal") end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] - println("$(a[1]) is $(a[2])") + println("$(a[1]) is a $(a[2])") end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] - println("$k is $v") + println("$k is a $v") end - - -# While loops go until a condition is no longer met. # prints: -# 0 -# 1 -# 2 -# 3 +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# While loops loop while a condition is true x = 0 while x < 4 println(x) x += 1 # Shorthand for x = x + 1 end +# prints: +# 0 +# 1 +# 2 +# 3 # Handle exceptions with a try/except block try @@ -359,11 +370,14 @@ end ## 4. Functions #################################################### -# Use the keyword function to create new functions +# The keyword 'function' creates new functions +#function name(arglist) +# body... +#end function add(x, y) println("x is $x and y is $y") - # Functions implicitly return the value of their last statement + # Functions return the value of their last statement x + y end @@ -373,13 +387,16 @@ add(5, 6) #=> 11 after printing out "x is 5 and y is 6" # positional arguments function varargs(args...) return args + # use the keyword return to return anywhere in the function end +#=> varargs (generic function with 1 method) varargs(1,2,3) #=> (1,2,3) # The ... is called a splat. -# It can also be used in a fuction call -# to splat a list or tuple out to be the arguments +# We just used it in a function definition. +# It can also be used in a fuction call, +# where it will splat an Array or Tuple's contents into the argument list. Set([1,2,3]) #=> Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays Set([1,2,3]...) #=> Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) @@ -412,7 +429,7 @@ keyword_args(name2="ness") #=> ["name2"=>"ness","k1"=>4] keyword_args(k1="mine") #=> ["k1"=>"mine","name2"=>"hello"] keyword_args() #=> ["name2"=>"hello","k2"=>4] -# You can also do both at once +# You can combine all kinds of arguments in the same function function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") println("normal arg: $normal_arg") println("optional arg: $optional_positional_arg") @@ -433,12 +450,15 @@ function create_adder(x) return adder end -# or equivalently +# This is "stabby lambda syntax" for creating anonymous functions +(x -> x > 2)(3) #=> true + +# This function is identical to create_adder implementation above. function create_adder(x) y -> x + y end -# you can also name the internal function, if you want +# You can also name the internal function, if you want function create_adder(x) function adder(y) x + y @@ -449,14 +469,12 @@ end add_10 = create_adder(10) add_10(3) #=> 13 -# The first two inner functions above are anonymous functions -(x -> x > 2)(3) #=> true # There are built-in higher order functions map(add_10, [1,2,3]) #=> [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] -# We can use list comprehensions for nice maps and filters +# We can use list comprehensions for nicer maps [add_10(i) for i=[1, 2, 3]] #=> [11, 12, 13] [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -- cgit v1.2.3 From 364c367ff3de7d65d68c909316f805213de262d4 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Fri, 18 Oct 2013 23:48:02 -0500 Subject: Expanded Type and Multiple Dispatch sections, and added more dispatch examples. Also added link to mailing list. --- julia.html.markdown | 151 +++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 131 insertions(+), 20 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index f8c2f6e7..85aca49d 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -479,49 +479,104 @@ filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] #################################################### -## 5. Types and Multiple-Dispatch +## 5. Types #################################################### -# Type definition +# Julia has a type system. +# Every value has a type; variables do not have types themselves. +# You can use the `typeof` function to get the type of a value. +typeof(5) #=> Int64 + +# Types are first-class values +typeof(Int64) #=> DataType +typeof(DataType) #=> DataType +# DataType is the type that represents types, including itself. + +# Types are used for documentation, optimizations, and dispatch. +# They are not statically checked. + +# Users can define types +# They are like records or structs in other languages. +# New types are defined used the `type` keyword. + +# type Name +# field::OptionalType +# ... +# end type Tiger taillength::Float64 - coatcolor # no type annotation is implicitly Any + coatcolor # not including a type annotation is the same as `::Any` end -# default constructor is the properties in order -# so, Tiger(taillength,coatcolor) -# Type instantiation -tigger = Tiger(3.5,"orange") # the type doubles as the constructor function +# The default constructor's arguments are the properties +# of the tyep, in order the order they are listed in the definition +tigger = Tiger(3.5,"orange") #=> Tiger(3.5,"orange") + +# The type doubles as the constructor function for values of that type +sherekhan = typeof(tigger)(5.6,"fire") #=> Tiger(5.6,"fire") -# Abtract Types -abstract Cat # just a name and point in the type hierarchy +# These struct-style types are called concrete types +# They can be instantiated, but cannot have subtypes. +# The other kind of types is abstract types. -# * types defined with the type keyword are concrete types; they can be -# instantiated -# -# * types defined with the abstract keyword are abstract types; they can -# have subtypes. -# -# * each type has one supertype; a supertype can have zero or more subtypes. +# abstract Name +abstract Cat # just a name and point in the type hierarchy +# Abstract types cannot be instantiated, but can have subtypes. +# For example, Number is an abstract type +subtypes(Number) #=> 6-element Array{Any,1}: + # Complex{Float16} + # Complex{Float32} + # Complex{Float64} + # Complex{T<:Real} + # ImaginaryUnit + # Real +subtypes(Cat) #=> 0-element Array{Any,1} + +# Every type has a super type; use the `super` function to get it. +typeof(5) #=> Int64 +super(Int64) #=> Signed +super(Signed) #=> Real +super(Real) #=> Number +super(Number) #=> Any +super(super(Signed)) #=> Number +super(Any) #=> Any +# All of these type, except for Int64, are abstract. + +# <: is the subtyping operator type Lion <: Cat # Lion is a subtype of Cat mane_color roar::String end +# You can define more constructors for your type +# Just define a function of the same name as the type +# and call an existing constructor to get a value of the correct type +Lion(roar::String) = Lion("green",roar) +# This is an outer constructor because it's outside the type definition + type Panther <: Cat # Panther is also a subtype of Cat eye_color Panther() = new("green") # Panthers will only have this constructor, and no default constructor. end +# Using inner constructors, like Panter does, gives you control +# over how values of the type can be created. +# When possible, you should use outer constructors rather than inner ones. -# Multiple Dispatch +#################################################### +## 6. Multiple-Dispatch +#################################################### # In Julia, all named functions are generic functions # This means that they are built up from many small methods -# For example, let's make a function meow: +# Each constructor for Lion is a method of the generic function Lion. + +# For a non-constructor example, let's make a function meow: + +# Definitions for Lion, Panther, Tiger function meow(cat::Lion) - cat.roar # access properties using dot notation + cat.roar # access type properties using dot notation end function meow(cat::Panther) @@ -532,21 +587,76 @@ function meow(cat::Tiger) "rawwwr" end +# Testing the meow function meow(tigger) #=> "rawwr" meow(Lion("brown","ROAAR")) #=> "ROAAR" meow(Panther()) #=> "grrr" +# Review the local type hierarchy +issubtype(Tiger,Cat) #=> false +issubtype(Lion,Cat) #=> true +issubtype(Panther,Cat) #=> true + +# Defining a function that takes Cats function pet_cat(cat::Cat) println("The cat says $(meow(cat))") end +pet_cat(Lion("42")) #=> prints "The cat says 42" try pet_cat(tigger) #=> ERROR: no method pet_cat(Tiger,) catch e println(e) end -pet_cat(Lion(Panther(),"42")) #=> prints "The cat says 42" +# In OO languages, single dispatch is common; +# this means that the method is picked based on the type of the first argument. +# In Julia, all of the argument types contribute to selecting the best method. + +# Let's define a function with more arguments, so we can see the difference +function fight(t::Tiger,c::Cat) + println("The $(t.coatcolor) tiger wins!") +end +#=> fight (generic function with 1 method) + +fight(tigger,Panther()) #=> prints The orange tiger wins! +fight(tigger,Lion("ROAR")) #=> prints The orange tiger wins! + +# Let's change the behavior when the Cat is specifically a Lion +fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") +#=> fight (generic function with 2 methods) + +fight(tigger,Panther()) #=> prints The orange tiger wins! +fight(tigger,Lion("ROAR")) #=> prints The green-maned lion wins! + +# We don't need a Tiger in order to fight +fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +end +#=> fight (generic function with 3 methods) + +fight(Lion("balooga!"),Panther()) #=> prints The victorious cat says grrr +try + fight(Panther(),Lion("RAWR")) #=> ERROR: no method fight(Panther,Lion) +catch +end + +# Also let the cat go first +fight(c::Cat,l::Lion) = println("The cat beats the Lion") +#=> Warning: New definition +# fight(Cat,Lion) at none:1 +# is ambiguous with +# fight(Lion,Cat) at none:2. +# Make sure +# fight(Lion,Lion) +# is defined first. +#fight (generic function with 4 methods) + +# This warning is because it's unclear which fight will be called in: +fight(Lion("RAR"),Lion("brown","rarrr")) #=> prints The victorious cat says rarrr +# The result may be different in other versions of Julia + +fight(l::Lion,l2::Lion) = println("The lions come to a tie") +fight(Lion("RAR"),Lion("brown","rarrr")) #=> prints The lions come to a tie ``` @@ -554,3 +664,4 @@ pet_cat(Lion(Panther(),"42")) #=> prints "The cat says 42" You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) +The best place to get help with Julia is the (very friendly) [mailing list](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From d0e50426089263b4e629a44a1e4d4a30d6f276ae Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Fri, 18 Oct 2013 23:51:07 -0500 Subject: remove extraneous end --- julia.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 85aca49d..50ea6a80 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -631,7 +631,6 @@ fight(tigger,Lion("ROAR")) #=> prints The green-maned lion wins! # We don't need a Tiger in order to fight fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") -end #=> fight (generic function with 3 methods) fight(Lion("balooga!"),Panther()) #=> prints The victorious cat says grrr -- cgit v1.2.3 From 67472bb3911fefaaff2da458ee854d26c5a272b9 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Fri, 18 Oct 2013 23:58:33 -0500 Subject: updated method names (add! -> push!, contains -> in) --- julia.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 50ea6a80..741dfc92 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -201,7 +201,7 @@ b = [1,2,3] append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] # Check for existence in a list with contains -contains(a,1) #=> true +in(a,1) #=> true # Examine the length with length length(a) #=> 8 @@ -218,7 +218,7 @@ end # Many list functions also work on tuples length(tup) #=> 3 tup[1:2] #=> (1,2) -contains(tup,2) #=> true +in(tup,2) #=> true # You can unpack tuples into variables a, b, c = (1, 2, 3) #=> (1,2,3) # a is now 1, b is now 2 and c is now 3 @@ -255,8 +255,8 @@ values(filled_dict) # Note - Same as above regarding key ordering. # Check for existence of keys in a dictionary with contains, haskey -contains(filled_dict, ("one", 1)) #=> true -contains(filled_dict, ("two", 3)) #=> false +in(filled_dict, ("one", 1)) #=> true +in(filled_dict, ("two", 3)) #=> false haskey(filled_dict, "one") #=> true haskey(filled_dict, 1) #=> false @@ -278,11 +278,11 @@ empty_set = Set() #=> Set{Any}() filled_set = Set(1,2,2,3,4) #=> Set{Int64}(1,2,3,4) # Add more values to a set -add!(filled_set,5) #=> Set{Int64}(5,4,2,3,1) +push!(filled_set,5) #=> Set{Int64}(5,4,2,3,1) # Check if the values are in the set -contains(filled_set,2) #=> true -contains(filled_set,10) #=> false +in(filled_set,2) #=> true +in(filled_set,10) #=> false # There are functions for set intersection, union, and difference. other_set = Set(3, 4, 5, 6) #=> Set{Int64}(6,4,5,3) -- cgit v1.2.3 From 5e362f5f4fd77f162453146b8c24fe3855a041fd Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Fri, 18 Oct 2013 23:59:21 -0500 Subject: updated date --- julia.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 741dfc92..ad8a5741 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -8,7 +8,7 @@ filename: learnjulia.jl Julia is a new homoiconic functional language focused on technical computing. While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. -This is based on the current development version of Julia, as of June 29th, 2013. +This is based on the current development version of Julia, as of October 18th, 2013. ```ruby -- cgit v1.2.3 From 34aedd3fbb2223fe9258e13326273e1d04fc99b0 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Mon, 21 Oct 2013 09:39:45 -0500 Subject: Fix a couple forgotten references to `contains` in the comments --- julia.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index ad8a5741..4ebd50ff 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -200,7 +200,7 @@ splice!(arr,2) #=> 4 ; arr is now [3,5] b = [1,2,3] append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] -# Check for existence in a list with contains +# Check for existence in a list with in in(a,1) #=> true # Examine the length with length @@ -254,7 +254,7 @@ values(filled_dict) #=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Note - Same as above regarding key ordering. -# Check for existence of keys in a dictionary with contains, haskey +# Check for existence of keys in a dictionary with in, haskey in(filled_dict, ("one", 1)) #=> true in(filled_dict, ("two", 3)) #=> false haskey(filled_dict, "one") #=> true -- cgit v1.2.3 From 001093d53af262cdcae53a09f080a6105151bce0 Mon Sep 17 00:00:00 2001 From: Max Goldstein Date: Wed, 23 Oct 2013 15:19:55 -0400 Subject: Typo You don't need to credit me. --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 6b3c6e17..267b40af 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -11,7 +11,7 @@ makes coding a real joy for me. ```haskell -- Single line comments start with two dashes. {- Multiline comments can be enclosed -en a block like this. +in a block like this. -} ---------------------------------------------------- -- cgit v1.2.3 From 0cee5bd79af4deefe246dde09cdfcd44dca80558 Mon Sep 17 00:00:00 2001 From: Shaun McCarthy Date: Sat, 26 Oct 2013 14:34:39 -0400 Subject: Added Interesting Features (and fixed / cleaned up other code) Fixed syntax errors, made items more succinct, and added a section of interesting features in c# --- csharp.html.markdown | 583 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 354 insertions(+), 229 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 1471b833..f4c30b03 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -3,8 +3,8 @@ language: c# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] - - ["Melvyn Laïly", "http://x2a.yt"] -filename: LearnCSharp.cs + - ["Melvyn Laïly", "http://x2a.yt"] + - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] --- C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. @@ -23,7 +23,12 @@ Multi-line comments look like this // Specify namespaces application will be using using System; using System.Collections.Generic; - +using System.Data.Entity; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +using System.Net; +using System.Threading.Tasks; // defines scope to organize code into "packages" namespace Learning @@ -32,8 +37,8 @@ namespace Learning // you're allowed to do otherwise, but shouldn't for sanity. public class LearnCSharp { - // A console application must have a main method as an entry point - public static void Main(string[] args) + // BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before + public static void Syntax() { // Use Console.WriteLine to print lines Console.WriteLine("Hello World"); @@ -46,7 +51,6 @@ namespace Learning Console.Write("Hello "); Console.Write("World"); - /////////////////////////////////////////////////// // Types & Variables // @@ -61,140 +65,83 @@ namespace Learning // (0 <= byte <= 255) byte fooByte = 100; - // Short - Signed 16-bit integer - // (-32,768 <= short <= 32,767) + // Short - 16-bit integer + // Signed - (-32,768 <= short <= 32,767) + // Unsigned - (0 <= ushort <= 65,535) short fooShort = 10000; - - // Ushort - Unsigned 16-bit integer - // (0 <= ushort <= 65,535) ushort fooUshort = 10000; - // Integer - Signed 32-bit integer - // (-2,147,483,648 <= int <= 2,147,483,647) - int fooInt = 1; + // Integer - 32-bit integer + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) - // Uinteger - Unsigned 32-bit integer - // (0 <= uint <= 4,294,967,295) - uint fooUint = 1; - - // Long - Signed 64-bit integer - // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - long fooLong = 100000L; + // Long - 64-bit integer + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // Numbers default to being int or uint depending on size. // L is used to denote that this variable value is of type long or ulong - // anything without is treated as int or uint depending on size. - // Ulong - Unsigned 64-bit integer - // (0 <= ulong <= 18,446,744,073,709,551,615) - ulong fooUlong = 100000L; + // Double - Double-precision 64-bit IEEE 754 Floating Point + double fooDouble = 123.4; // Precision: 15-16 digits // Float - Single-precision 32-bit IEEE 754 Floating Point - // Precision: 7 digits - float fooFloat = 234.5f; - // f is used to denote that this variable value is of type float; - // otherwise it is treated as double. + float fooFloat = 234.5f; // Precision: 7 digits + // f is used to denote that this variable value is of type float - // 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; + // Decimal - a 128-bits data type, with more precision than other floating-point types, + // suited for financial and monetary calculations + decimal fooDecimal = 150.3m; // Boolean - true & false - bool fooBoolean = true; - bool barBoolean = false; + bool fooBoolean = true; // or false // Char - A single 16-bit Unicode character char fooChar = 'A'; // 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!"; + // a string is a reference type. That is, you can set it to null + string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; 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 + // 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'; + + // Compare strings with current culture, ignoring case + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // Formatting, based on sprintf string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); - Console.WriteLine(fooFormattedString); - // formatting dates + // Dates & Formatting DateTime fooDate = DateTime.Now; Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - // \n is an escaped character that starts a new line - string barString = "Printing on a new line?\nNo Problem!"; - Console.WriteLine(barString); - - // it can be written prettier by using the @ symbol + // You can split a string over two lines with the @ symbol. To escape " use "" string bazString = @"Here's some stuff - on a new line!"; - Console.WriteLine(bazString); - - // quotes need to be escaped - // use \" normally - string quotedString = "some \"quoted\" stuff"; - Console.WriteLine(quotedString); - - // use "" when strings start with @ - string quotedString2 = @"some MORE ""quoted"" stuff"; - Console.WriteLine(quotedString2); +on a new line! ""Wow!"", the masses cried"; // Use const or read-only to make a variable immutable // const values are calculated at compile time const int HOURS_I_WORK_PER_WEEK = 9001; - // Nullable types - // any value type (i.e. not a class) can be made nullable by suffixing a ? - // ? = - 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 - DateTime? nullableDate = null; - // The previous line would not have compiled without the '?' - // because DateTime is a value type - // ? is equivalent to writing Nullable - Nullable 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 - int notNullable = nullable ?? 0; - 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; - /////////////////////////////////////////////////// // Data Structures /////////////////////////////////////////////////// - Console.WriteLine("\n->Data Structures"); - // Arrays + // Arrays - zero indexed // The array size must be decided upon declaration // The format for declaring an array is follows: // [] = new []; int[] intArray = new int[10]; - string[] stringArray = new string[1]; - bool[] boolArray = new bool[100]; // Another way to declare & initialize an array int[] y = { 9000, 1000, 1337 }; // Indexing an array - Accessing an element Console.WriteLine("intArray @ 0: " + intArray[0]); - - // Arrays are zero-indexed and mutable. + // Arrays are mutable. intArray[1] = 1; - Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1 // Lists // Lists are used more frequently than arrays as they are more flexible @@ -202,28 +149,21 @@ namespace Learning // List = new List(); List intList = new List(); List stringList = new List(); - - // Another way to declare & initialize a list - List z = new List { 9000, 1000, 1337 }; - - // Indexing a list - Accessing an element - // Lists are zero-indexed and mutable. - Console.WriteLine("z @ 0: " + z[2]); + List z = new List { 9000, 1000, 1337 }; // intialize + // The <> are for templates - Check out the cool stuff section // Lists don't default to a value; // A value must be added before accessing the index intList.Add(1); Console.WriteLine("intList @ 0: " + intList[0]); - // Others data structures to check out: - // // Stack/Queue // Dictionary (an implementation of a hash map) + // HashSet // Read-only Collections // Tuple (.Net 4+) - /////////////////////////////////////// // Operators /////////////////////////////////////// @@ -232,10 +172,7 @@ namespace Learning int i1 = 1, i2 = 2; // Shorthand for multiple declarations // Arithmetic is straightforward - Console.WriteLine("1+2 = " + (i1 + i2)); // => 3 - Console.WriteLine("2-1 = " + (i2 - i1)); // => 1 - Console.WriteLine("2*1 = " + (i2 * i1)); // => 2 - Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // // Modulo Console.WriteLine("11%3 = " + (11 % 3)); // => 2 @@ -266,7 +203,6 @@ namespace Learning Console.WriteLine(i--); //i = 1. Post-Decrementation Console.WriteLine(--i); //i = 0. Pre-Decrementation - /////////////////////////////////////// // Control Structures /////////////////////////////////////// @@ -291,50 +227,37 @@ namespace Learning // A simple if/else can be written as follows // ? : string isTrue = (true) ? "True" : "False"; - Console.WriteLine("Ternary demo: " + isTrue); - // While loop int fooWhile = 0; while (fooWhile < 100) { - //Console.WriteLine(fooWhile); - //Increment the counter //Iterated 99 times, fooWhile 0->99 fooWhile++; } - Console.WriteLine("fooWhile Value: " + fooWhile); // Do While Loop int fooDoWhile = 0; do { - //Console.WriteLine(fooDoWhile); - //Increment the counter //Iterated 99 times, fooDoWhile 0->99 fooDoWhile++; } while (fooDoWhile < 100); - Console.WriteLine("fooDoWhile Value: " + fooDoWhile); - // For Loop - int fooFor; //for loop structure => for(; ; ) - for (fooFor = 0; fooFor < 10; fooFor++) + for (int fooFor = 0; fooFor < 10; fooFor++) { - //Console.WriteLine(fooFor); //Iterated 10 times, fooFor 0->9 } - Console.WriteLine("fooFor Value: " + fooFor); - - // For Each Loop + + // For Each Loop // foreach loop structure => foreach( in ) - // The foreach loop loops over any object implementing IEnumerable or IEnumerable - // 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) + // The foreach loop loops over any object implementing IEnumerable or IEnumerable + // 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 } @@ -356,20 +279,18 @@ 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; + // 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; } - Console.WriteLine("Switch Case Result: " + monthString); - /////////////////////////////////////// // Converting Data Types And Typecasting @@ -384,46 +305,227 @@ namespace Learning // try parse will default to type default on failure // in this case: 0 int tryInt; - int.TryParse("123", out tryInt); + if (int.TryParse("123", out tryInt)) // Funciton is boolean + Console.WriteLine(tryInt); // 123 // Convert Integer To String // Convert class has a number of methods to facilitate conversions Convert.ToString(123); + // or + tryInt.ToString(); + } - /////////////////////////////////////// - // Classes And Functions - /////////////////////////////////////// - - Console.WriteLine("\n->Classes & Functions"); - - // (definition of the Bicycle class follows) + /////////////////////////////////////// + // CLASSES - see definitions at end of file + /////////////////////////////////////// + public static void Classes() + { + // See Declaration of objects at end of file // Use new to instantiate a class Bicycle trek = new Bicycle(); // Call object methods - trek.speedUp(3); // You should always use setter and getter methods - trek.setCadence(100); + trek.SpeedUp(3); // You should always use setter and getter methods + trek.Cadence = 100; // ToString is a convention to display the value of this Object. - Console.WriteLine("trek info: " + trek.ToString()); - - // Instantiate another new Bicycle - Bicycle octo = new Bicycle(5, 10); - Console.WriteLine("octo info: " + octo.ToString()); + Console.WriteLine("trek info: " + trek.Info()); // Instantiate a new Penny Farthing PennyFarthing funbike = new PennyFarthing(1, 10); - Console.WriteLine("funbike info: " + funbike.ToString()); + Console.WriteLine("funbike info: " + funbike.Info()); Console.Read(); } // End main method + // CONSOLE ENTRY A console application must have a main method as an entry point + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // INTERESTING FEATURES + // + + // DEFAULT METHOD SIGNATURES + + public // Visibility + static // Allows for direct call on class without object + int // Return Type, + MethodSignatures( + int maxCount, // First variable, expects an int + int count = 0, // will default the value to 0 if not passed in + int another = 3, + params string[] otherParams // captures all other parameters passed to method + ) + { + return -1; + } + + // Methods can have the same name, as long as the signature is unique + public static void MethodSignature(string maxCount) + { + } + + // TEMPLATES + // The classes for TKey and TValue is specified by the user calling this function. + // This method emulates the SetDefault of Python + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // You can narrow down the objects that are passed in + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // We can iterate, since T is a IEnumerable + foreach (var item in toPrint) + // Item is an int + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // OPTIONAL PARAMETERS + MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); + MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + + // EXTENSION METHODS + int i = 3; + i.Print(); // Defined below + + // NULLABLE TYPES - great for database interaction / return values + // any value type (i.e. not a class) can be made nullable by suffixing a ? + // ? = + int? nullable = null; // short hand for Nullable + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // true if not null + + // ?? is syntactic sugar for specifying default value (coalesce) + // in case variable is null + int notNullable = nullable ?? 0; // 0 + + // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: + var magic = "magic is a string, at compile time, so you still get type safety"; + // magic = 9; will not work as magic is a string, not an int + + // TEMPLATES + var phonebook = new Dictionary() { + {"Sarah", "212 555 5555"} // Add some entries to the phone book + }; + + // Calling SETDEFAULT defined as a template above + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone + // nb, you don't need to specify the TKey and TValue since they can be + // derived implicitly + Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 + + // LAMBDA EXPRESSIONS - allow you to write code in line + Func square = (x) => x * x; // Last T item is the return value + Console.WriteLine(square(3)); // 9 + + // PARALLEL FRAMEWORK + // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary(); + + // Will spin up separate threads for each request, and join on them + // before going to the next step! + Parallel.ForEach(websites, + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads + website => + { + // Do something that takes a long time on the file + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // This won't happen till after all requests have been completed + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // DYNAMIC OBJECTS (great for working with other languages) + dynamic student = new ExpandoObject(); + student.FirstName = "First Name"; // No need to define class first! + + // You can even add methods (returns a string, and takes in a string) + student.Introduce = new Func( + (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE - almost all collections implement this, which gives you a lot of + // very useful Map / Filter / Reduce style methods + var bikes = new List(); + bikes.Sort(); // Sorts the array + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels + var result = bikes + .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable + + var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection + + // Create a list of IMPLICIT objects based on some parameters of the bike + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Hard to show here, but you get type ahead completion since the compiler can implicitly work + // out the types above! + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + // ASPARALLEL + // And this is where things get wicked - combines linq and parallel operations + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // this will happen in parallel! Threads will automagically be spun up and the + // results divvied amongst them! Amazing for large datasets when you have lots of + // cores + + // LINQ - maps a store to IQueryable objects, with delayed execution + // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document + var db = new BikeRespository(); + + // execution is delayed, which is great when querying a database + var fitler = db.Bikes.Where(b => b.HasTassles); // no query run + if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality + fitler = fitler.Where(b => b.IsBroken); // no query run + + var query = fitler + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // still no query run + + // Now the query runs, but opens a reader, so only populates are you iterate through + foreach (string bike in query) + Console.WriteLine(result); + + + + } } // End LearnCSharp class // You can include other classes in a .cs file + public static class Extensions + { + // EXTENSION FUNCTIONS + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } // Class Declaration Syntax: // class { @@ -434,64 +536,88 @@ namespace Learning public class Bicycle { // Bicycle's Fields/Variables - public int cadence; // Public: Can be accessed from anywhere - private int _speed; // Private: Only accessible from within the class - protected int gear; // Protected: Accessible from the class and subclasses - internal int wheels; // Internal: Accessible from within the assembly - string name; // Everything is private by default: Only accessible from within this class + public int Cadence // Public: Can be accessed from anywhere + { + get // get - define a method to retrieve the property + { + return _cadence; + } + set // set - define a method to set a proprety + { + _cadence = value; // Value is the value passed in to to the setter + } + } + private int _cadence; + + protected virtual int Gear // Protected: Accessible from the class and subclasses + { + get; // creates an auto property so you don't need a member field + set; + } + + internal int Wheels // Internal: Accessible from within the assembly + { + get; + private set; // You can set modifiers on the get/set methods + } + + int _speed; // Everything is private by default: Only accessible from within this class. + // can also use keyword privatee + public string Name { get; set; } // 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 + // 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 BikeBrand { AIST, BMC, - Electra=42, //you can explicitly set a value to a name + 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 declaring an enum type, we can declare the field of this type + public BikeBrand 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; // You can access them without a reference to any object: // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + static public int BicyclesCreated = 0; // readonly values are set at run time // they can only be assigned upon declaration or in a constructor - readonly bool hasCardsInSpokes = false; // read-only private + readonly bool _hasCardsInSpokes = false; // read-only private // Constructors are a way of creating classes // This is a default constructor - private Bicycle() + public Bicycle() { - gear = 1; - cadence = 50; + this.Gear = 1; // you can access mmebers of the object with the keyword this + Cadence = 50; // but you don't always need it _speed = 5; - name = "Bontrager"; - brand = Brand.AIST; - bicyclesCreated++; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; } // This is a specified constructor (it contains arguments) public Bicycle(int startCadence, int startSpeed, int startGear, - string name, bool hasCardsInSpokes, Brand brand) + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // calls base first { - this.gear = startGear; // "this" keyword denotes the current object - this.cadence = startCadence; - this._speed = startSpeed; - this.name = name; // it can be useful when there's a name conflict - this.hasCardsInSpokes = hasCardsInSpokes; - this.brand = brand; + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; } // Constructors can be chained - public Bicycle(int startCadence, int startSpeed, Brand brand) : - this(startCadence, startSpeed, 0, "big wheels", true) + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) { } @@ -501,27 +627,8 @@ namespace Learning // classes can implement getters and setters for their fields // or they can implement properties (this is the preferred way in C#) - // Method declaration syntax: - // () - public int GetCadence() - { - return cadence; - } - - // void methods require no return statement - public void SetCadence(int newValue) - { - cadence = newValue; - } - - // virtual keyword indicates this method can be overridden in a derived class - public virtual void SetGear(int newValue) - { - gear = newValue; - } - // Method parameters can have default values. - // In this case, methods can be called with these parameters omitted + // In this case, methods can be called with these parameters omitted public void SpeedUp(int increment = 1) { _speed += increment; @@ -541,12 +648,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; } + + // 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 @@ -558,13 +665,13 @@ namespace Learning } //Method to display the attribute values of this Object. - public override string ToString() + public virtual string Info() { - return "gear: " + gear + - " cadence: " + cadence + - " speed: " + _speed + - " name: " + name + - " cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") + + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + "\n------------------------------\n" ; } @@ -573,9 +680,10 @@ namespace Learning public static bool DidWeCreateEnoughBycles() { // Within a static method, we only can reference static class members - return bicyclesCreated > 9000; + return BicyclesCreated > 9000; } // If your class only needs static members, consider marking the class itself as static. + } // end class Bicycle // PennyFarthing is a subclass of Bicycle @@ -586,20 +694,27 @@ namespace Learning // calling parent constructor public PennyFarthing(int startCadence, int startSpeed) : - base(startCadence, startSpeed, 0, "PennyFarthing", true) + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) { } - public override void SetGear(int gear) + protected override int Gear { - gear = 0; + get + { + return 0; + } + set + { + throw new ArgumentException("You can't change gears on a PennyFarthing"); + } } - public override string ToString() + public override string Info() { string result = "PennyFarthing bicycle "; result += base.ToString(); // Calling the base version of the method - return reuslt; + return result; } } @@ -624,7 +739,7 @@ namespace Learning damage += meters; } - public void Broken + public bool Broken { get { @@ -632,24 +747,34 @@ namespace Learning } } } -} // End Namespace + /// + /// Used to connect to DB for LinqToSql example. + /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// + public class BikeRespository : DbSet + { + public BikeRespository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // End Namespace ``` ## Topics Not Covered * Flags * Attributes - * Generics (T), Delegates, Func, Actions, lambda expressions * Static properties * Exceptions, Abstraction - * LINQ * ASP.NET (Web Forms/MVC/WebMatrix) * Winforms * Windows Presentation Foundation (WPF) - - ## Further Reading * [DotNetPerls](http://www.dotnetperls.com) -- cgit v1.2.3 From eccc9e094832350842f16f3a7666aa633748098b Mon Sep 17 00:00:00 2001 From: Shaun McCarthy Date: Sat, 26 Oct 2013 15:27:53 -0400 Subject: Reanmed to Generics instead of templates --- csharp.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index f4c30b03..8c15b86f 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -150,7 +150,7 @@ on a new line! ""Wow!"", the masses cried"; List intList = new List(); List stringList = new List(); List z = new List { 9000, 1000, 1337 }; // intialize - // The <> are for templates - Check out the cool stuff section + // The <> are for generics - Check out the cool stuff section // Lists don't default to a value; // A value must be added before accessing the index @@ -369,7 +369,7 @@ on a new line! ""Wow!"", the masses cried"; { } - // TEMPLATES + // GENERICS // The classes for TKey and TValue is specified by the user calling this function. // This method emulates the SetDefault of Python public static TValue SetDefault( @@ -417,12 +417,13 @@ on a new line! ""Wow!"", the masses cried"; var magic = "magic is a string, at compile time, so you still get type safety"; // magic = 9; will not work as magic is a string, not an int - // TEMPLATES + // GENERICS + // var phonebook = new Dictionary() { {"Sarah", "212 555 5555"} // Add some entries to the phone book }; - // Calling SETDEFAULT defined as a template above + // Calling SETDEFAULT defined as a generic above Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone // nb, you don't need to specify the TKey and TValue since they can be // derived implicitly -- cgit v1.2.3 From 7ff3de74fe941a220e6fb3e3e3434d90d0d51cc6 Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 27 Oct 2013 22:17:56 -0700 Subject: Updates --- clojure.html.markdown | 2 +- csharp.html.markdown | 2 +- vi-vn/git-vi.html.markdown | 1 + vi-vn/objective-c-vi.html.markdown | 4 ++-- zh-cn/r-cn.html.markdown | 1 + 5 files changed, 6 insertions(+), 4 deletions(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index 779c28ae..7917ab08 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -376,5 +376,5 @@ Clojuredocs.org has documentation with examples for most core functions: 4Clojure is a great way to build your clojure/FP skills: [http://www.4clojure.com/](http://www.4clojure.com/) -Clojure-doc.org (yeah, really) has a number of getting started articles: +Clojure-doc.org (yes, really) has a number of getting started articles: [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/csharp.html.markdown b/csharp.html.markdown index 1471b833..ccc0ffad 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -3,7 +3,7 @@ language: c# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] - - ["Melvyn Laïly", "http://x2a.yt"] + - ["Melvyn Laïly", "http://x2a.yt"] filename: LearnCSharp.cs --- diff --git a/vi-vn/git-vi.html.markdown b/vi-vn/git-vi.html.markdown index 77fec983..bdb88204 100644 --- a/vi-vn/git-vi.html.markdown +++ b/vi-vn/git-vi.html.markdown @@ -4,6 +4,7 @@ tool: git contributors: - ["Jake Prather", "http://github.com/JakeHP"] filename: LearnGit-vi.txt +lang: vi-vn --- Git là một hệ quản lý mã nguồn và phiên bản phân tán (distributed version control and source code management system). diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown index f6296ec0..6d19ca02 100644 --- a/vi-vn/objective-c-vi.html.markdown +++ b/vi-vn/objective-c-vi.html.markdown @@ -4,7 +4,7 @@ language: Objective-C contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] -lang: vi-vi +lang: vi-vn filename: LearnObjectiveC-vi.m --- @@ -12,7 +12,7 @@ filename: LearnObjectiveC-vi.m Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch. Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C. -```objective-c +```cpp // Chú thích dòng đơn bắt đầu với // /* diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown index 8a542695..ed8c43b6 100644 --- a/zh-cn/r-cn.html.markdown +++ b/zh-cn/r-cn.html.markdown @@ -7,6 +7,7 @@ translators: - ["小柒", "http://weibo.com/u/2328126220"] - ["alswl", "https://github.com/alswl"] filename: learnr.r +lang: zh-cn --- R 是一门统计语言。它有很多数据分析和挖掘程序包。可以用来统计、分析和制图。 -- cgit v1.2.3 From 8ef0b6fc43492e051c30fe5d3f28c248e3630fde Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 27 Oct 2013 22:26:10 -0700 Subject: pointless change to test auto-deploy --- clojure.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index 7917ab08..779c28ae 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -376,5 +376,5 @@ Clojuredocs.org has documentation with examples for most core functions: 4Clojure is a great way to build your clojure/FP skills: [http://www.4clojure.com/](http://www.4clojure.com/) -Clojure-doc.org (yes, really) has a number of getting started articles: +Clojure-doc.org (yeah, really) has a number of getting started articles: [http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From 893766ed6fff6f7a5c38f019ae9c035bf3167d2b Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 27 Oct 2013 22:42:05 -0700 Subject: pointless change to test auto-deploy --- clojure.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index 779c28ae..7917ab08 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -376,5 +376,5 @@ Clojuredocs.org has documentation with examples for most core functions: 4Clojure is a great way to build your clojure/FP skills: [http://www.4clojure.com/](http://www.4clojure.com/) -Clojure-doc.org (yeah, really) has a number of getting started articles: +Clojure-doc.org (yes, really) has a number of getting started articles: [http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From 6c305c96d99ec625fb7db3d1fde4744ab2d567bd Mon Sep 17 00:00:00 2001 From: valipour Date: Mon, 28 Oct 2013 23:01:21 +0000 Subject: add farsi translation for javascript article --- fa-ir/javascript.html.markdown | 553 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 553 insertions(+) create mode 100644 fa-ir/javascript.html.markdown diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown new file mode 100644 index 00000000..07dec31a --- /dev/null +++ b/fa-ir/javascript.html.markdown @@ -0,0 +1,553 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] +filename: javascript.js +--- + +

+جاوااسکریپت توسط برندن ایش از شرکت NetScape در سال 1995 ساخته شد. در ابتدا به عنوان یک زبان اسکریپت‌نویسی در کنار جاوا (که برای موارد پیچیده تر در طراحی وب در نظر گرفته میشد) مورد استفاده بود، ولی در پی نفوذ بسیار گسترده آن در وب و همچنین پشتیبانی پیش-ساخته آن در مرورگر ها، امروزه به مراتب بیشتر از جاوا در برنامه نویسی سمت-کاربر در وب به کار برده میشود. +با این حال جاوااسکریپت فقط محدود به مرورگر های وب نمیشود. Node.js پروژه ایست که یک نسخه ی مستقل از اجراکننده ی موتور جاوااسکریپت V8 از گوگل کروم را در اختیار قرار میده که هر روزه درحال محبوب تر شدن نیز هست. +

+ +

+قدر دان نظرات سازنده شما هستم! شما میتوانید از طریق زیر با من تماس بگیرید: +

+ +[@adambrenecki](https://twitter.com/adambrenecki), or +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +

+// توضیحات همانند C هستند. توضیحات یک خطی با دو خط مورب شروع میشوند., +

+ +

+/* و توضیحات چند خطی با خط مورب-ستاره شروع، + و با ستاره-خط مورب ختم میشوند */ +

+ +```js +// Comments are like C. Single-line comments start with two slashes, +/* and multiline comments start with slash-star + and end with star-slash */ +``` +

+گزاره ها را میتوانید با نقطه ویرگول پایان دهید ; +

+```js +doStuff(); +``` +

+ولی لزومی به این کار نیست. نقطه ویرگول به صورت خودکار در نظر گرفته میشوند. +

+

+وقتی که خط جدیدی شروع میشود. مگر در موارد خاص. +

+```js +doStuff() +``` +

برای اینگه درگیر آن موارد خاص نشویم، در اینجا از اون ها

+

صرف نظر میکنیم.

+ +

1. اعداد، رشته ها و عملگرها

+ +

جاوااسکریپت فقط یک نوع عدد دارد و آن عدد اعشاری 64 بیتی IEEE 754 است.

+

نترسید! و نگران اعداد صحیح نباشید! این اعداد اعشاری دارای 54 بیت مانتیس هستند که قابلیت ذخیره ی

+

دقیق اعداد صحیح تا مقدار تقریبی 9x10¹⁵ را دارند.

+```js +3; // = 3 +1.5; // = 1.5 +``` +

+تمامی عملگر های محاسباتی آن طوری که انتظارش را دارید عمل خواهند کرد. +

+```js +1 + 1; // = 2 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 +``` +

و این حتی شامل تقسیم هم میشود.

+```js +5 / 2; // = 2.5 +``` +

عملگر های بیتی هم به همین شکل. وقتی از یک عملگر بیتی استفاده میکنید، عدد اعشاری شما

+

به عدد صحیح علامت دار *تا 32 بیت* تبدیل میشود.

+```js +1 << 2; // = 4 +``` +

عملیات داخل پرانتز تقدم بالاتری دارند.

+```js +(1 + 3) * 2; // = 8 +``` +

سه مقدار خاص وجود دارند که در واقع مقادیر عددی نیستند:

+```js +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0 +``` +

مقادیر بولی هم تعریف شده هستند:

+```js +true; +false; +``` +

رشته ها با آپستروف و یا گیومه تعریف میشوند.

+```js +'abc'; +"Hello, world"; +``` +

و منفی کردن شرط با علامت تعجب

+```js +!true; // = false +!false; // = true +``` +

تساوی دو مقدار با ==

+```js +1 == 1; // = true +2 == 1; // = false +``` +

و عدم تساوی با !=

+```js +1 != 1; // = false +2 != 1; // = true +``` +

و سایر عمیلات های مقایسه

+```js +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true +``` +

رشته ها با علامت جمع به یکدیگر متصل میشوند

+```js +"Hello " + "world!"; // = "Hello world!" +``` +

و با علامت برگتر و یا کوچکتر با یکدیگر مقایسه میشوند.

+```js +"a" < "b"; // = true +``` +

نوع متغیر برای عملیات مقایسه تطبیق داده میشود

+```js +"5" == 5; // = true +``` +

مگر اینکه از سه مساوی استفاده شود!

+```js +"5" === 5; // = false +``` +

با استفاده از charAt میتوانید به کارکتر های یک رشته دسترسی پیدا کنید.

+```js +"This is a string".charAt(0); +``` +

از null برای نشان دادن عمدی مقدار هیج استفاده میشود.

+

و از undefined برای نشان دادن اینکه در حال حاظر مقدار موجود نمی باشد، هرچند خود undefined یک مقدار محسوب میشود.

+```js +null; // used to indicate a deliberate non-value +undefined; // used to indicate a value is not currently present (although undefined + // is actually a value itself) +``` +

false, null, undefined, NaN, 0 و "" مقدار نادرست و هر چیز دیگر مقدار درست طلقی میشوند.

+

توجه داشته باشید که 0 نادرست و "0" درست طلقی میشوند حتی در عبارت 0=="0".

+ +

2. متغیر ها، آرایه ها و شئ ها

+ +

متغیر ها با کلید واژه var تعریف میشوند. اشیا در جاوااسکریپت دارای نوع پویا هستند،

+

بدین شکل که برای تعریف نیازی به مشخص کردن نوع متعیر نیست.

+

برای مقدار دهی از علامت مساوی استفاده میشود.

+```js +var someVar = 5; +``` + +

اگر کلید واژه var را قرار ندهید، هیچ خطایی دریافت نخواهید کرد...

+```js +someOtherVar = 10; +``` + +

در عوض متغیر شما در گستره ی کل برنامه تعریف شده خواهد بود.

+ +

متغیر هایی که تعریف شده ولی مقدار دهی نشوند، دارای مقدار undefined خواهند بود.

+```js +var someThirdVar; // = undefined +``` + +

برای اعمال عملگر های محاسباتی، میانبر هایی وجود دارند:

+```js +someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now +someVar *= 10; // now someVar is 100 +``` + +

حتی از این هم کوتاهتر برای اضافه یا کم کردن یک عدد با مقدار یک.

+```js +someVar++; // now someVar is 101 +someVar--; // back to 100 +``` + +

آرایه ها در واقع لیستی مرتب شده از مقادیر مختلف از هر نوعی هستند.

+```js +var myArray = ["Hello", 45, true]; +``` + +

به اعضای یک آرایه میتوان از طریق قرار دادن کروشه در جلوی نام آن دسترسی پیدا کرد.

+

نمایه ی آرایه از صفر شروع میشود.

+```js +myArray[1]; // = 45 +``` + +

آرایه ها ناپایدار و دارای طول قابل تغییر هستند

+```js +myArray.push("World"); +myArray.length; // = 4 +``` + +

در جاوااسکریپت، اشیاء چیزی شبیه دیکشنری و یا نقشه در زبان های دیگر هستند:

+

یک مجموعه ی نامرتب از جفت های کلید-مقدار.

+```js +var myObj = {key1: "Hello", key2: "World"}; +``` + +

کلید ها از نوع رشته هستند ولی در صورتی که مقدار معتبری برای اسم گزاری باشند نیازی به آوردن آنها درون گیومه نیست.

+```js +var myObj = {myKey: "myValue", "my other key": 4}; +``` + +

اعضای یک شئ را نیز میتوانید با استفاده از کروشه در مقابل نام آنها استخراج کنید.

+```js +myObj["my other key"]; // = 4 +``` + +

...و یا از طریق نقطه در صورتی که اسم عضو مورد نظر اسم معتبری برای اسم گزاری باشد.

+```js +myObj.myKey; // = "myValue" +``` + +

اشیاء ناپایدار و قابل اضافه کردن عضو جدید هستند.

+```js +myObj.myThirdKey = true; +``` + +

اگر سعی کنید عضوی را که وجود ندارد استخراج کنید، مقدار undefined را دریافت خواهید کرد.

+```js +myObj.myFourthKey; // = undefined +``` + +

3. منطق و ساختار کنترل

+ +

ساختار if به شکلی که انتظارش را دارید کار میکند.

+```js +var count = 1; +if (count == 3){ + // evaluated if count is 3 +} else if (count == 4) { + // evaluated if count is 4 +} else { + // evaluated if it's not either 3 or 4 +} +``` + +

و همینطور حلقه while

+```js +while (true) { + // An infinite loop! +} +``` + +

حلقه do-while شبیه while است با این تفاوت که حداقل یکبار اجرا میشود.

+```js +var input +do { + input = getInput(); +} while (!isValid(input)) +``` + +

حلقه for همانند زبان C و جاوا کار می کند.

+

مقدار دهی اولیه; شرط ادامه; چرخش حلقه

+```js +for (var i = 0; i < 5; i++){ + // will run 5 times +} +``` + +

عملگر && و || به ترتیب "و" و "یا" ی منطقی هستند.

+```js +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // colour is either red or blue +} +``` + +

از || همچنین میتوان برای تعیین مقدار پیشفرض استفاده کرد.

+```js +var name = otherName || "default"; +``` + +

4. توابع و مفاهیم گستره و بستار

+ +

توابع در جاوااسکریپت با استفاده از کلیدواژه ی function تعریف میشوند.

+```js +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" +``` + +

توابع در جاوااسکریپت نوعی شئ پایه محسوب میشوند، بنابر این می توانید آنها را به اشیاء مختلف

+

اضافه کنید و یا به عنوان پارامتر به توابع دیگر ارسال کنید.

+

- برای مثال وقتی که با یک رویداد کار میکنید.

+```js +function myFunction(){ + // this code will be called in 5 seconds' time +} +setTimeout(myFunction, 5000); +``` + +

توجه کنید که setTimeout تابعی تعریف شده در جاوااسکریپت نیست، ولی مرورگر ها و node.js از آن پشتیبانی میکنند.

+ + +

توابع نیازی به داشتن اسم ندارند. برای مثال وقتی تابعی را به تابعی دیگر ارسال میکنید

+

میتوانید آنرا به صورت بینام تعریف کنید.

+```js +setTimeout(function(){ + // this code will be called in 5 seconds' time +}, 5000); +``` + +

توابع دارای محدوده ی متغیر های خود هستند.

+

بر خلاف دیگر ساختار ها - مانند if

+```js +if (true){ + var i = 5; +} +i; // = 5 - not undefined as you'd expect in a block-scoped language +``` + +

به همین دلیل الگوی خاصی به نام "تابعی که بلافاصله صدا زده میشود" پدید آمده

+

تا از اضافه شدن متغیر های قسمتی از برنامه به گستره ی کلی برنامه جلوگیری شود.

+```js +(function(){ + var temporary = 5; + // We can access the global scope by assiging to the 'global object', which + // in a web browser is always 'window'. The global object may have a + // different name in non-browser environments such as Node.js. + window.permanent = 10; +})(); +temporary; // raises ReferenceError +permanent; // = 10 +``` + +

یکی از برترین ویژگی های جاوااسکریپت مفهومی با نام بستار است

+

بدین شکل که اگر تابعی درون تابع دیگری تعریف شود، تابع درونی به تمام متغیر های تابع خارجی دسترسی

+

خواهد داشت، حتی بعد از اینکه تابع خارجی به اتمام رسیده باشد.

+```js +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will + // exit immediately, and setTimeout will call inner afterwards. However, + // because inner is "closed over" sayHelloInFiveSeconds, inner still has + // access to the 'prompt' variable when it is finally called. +} +sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s +``` + +

5. دیگر اشیاء، سازنده ها و پیش‌نمونه ها

+ +

اشیاء میتوانند تابع داشته باشند.

+```js +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" +``` + +

وقتی تابع یک شی صدا زده می شود، تابع میتواند به سایر مقادیر درون آن شی

+

از طریق کلید واژه ی this دسترسی داشته باشد.

+```js +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" +``` + + +

اینکه مقدار this چه باشد بستگی به این دارد که تابع چگونه صدا زده شود

+

نه اینکه تابع کجا تعریف شده است.

+

بنابر این تابع بالا اگر بدین شکل صدا زده شود کار نخواهد کرد

+```js +var myFunc = myObj.myFunc; +myFunc(); // = undefined +``` + + +

به همین شکل، تابعی که در جای دیگر تعریف شده را میتوانید به یک شی الحاق کنید

+

و بدین ترتیب تابع میتواند به مقادیر درون شی از طریق this دسترسی پیدا کند.

+```js +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" +``` + + +

اگر تابعی با کلید new صدا زده شوند، شی جدیدی ایجاد شده و تابع در گستره ی آن صدا زده میشود.

+

توابعی که بدین شکل صدا زده شوند در واقع نقش سازنده را ایفا می کنند.

+```js +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 +``` + + +

تمامی اشیاء در جاوااسکریپت دارای یک پیش نمونه هستند

+

به شکلی که اگر تابع صدا زده شده بر روی شی مستقیما روی آن تعریف نشده باشد

+

اجرا کننده ی برنامه در لیست پیش نمونه به دنبال آن تابع خواهد گشت

+ +

برخی اجرا کننده های جاوااسکریپت به شما اجازه ی دسترسی به پیش نمونه های یک شی را از

+

طریق عضو جادویی __proto__ میدهند.

+

هرچند این به شناخت پیش نمونه ها کمک میکند ولی در حیطه ی جاوااسکریپت استاندارد قرار نمیگیرد.

+

در ادامه شکل استاندارد پیش نمونه ها مورد بررسی قرار میگیرند.

+```js +var myObj = { + myString: "Hello world!", +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 +``` + +

این موضوع در مورد توابع نیز صدق میکند.

+```js +myObj.myFunc(); // = "hello world!" +``` + + +

اگر عضو مورد نظر در پیش نمونه ی شی یافت نشود، پیش نمونه ی پیش نمونه جستجو شده و الی آخر

+```js +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true +``` + + +

توجه داشته باشید که پیش نمونه ها کپی نمی شوند و هر شی جدید به پیش نمونه موجود اشاره میکند

+

بدین ترتیب اگر تابعی به پیش نمونه اضافه شود تمامی اشیاء میتوانند به آن دسترسی پیدا کنند.

+```js +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 +``` + +

پیش تر اشاره شد که __proto__ راه استانداردی برای دسترسی به پیش نمونه نیست و هیچ استانداردی نیز برای دسترسی به پیش نمونه ی یک شی موجود پیش بینی نشده است

+

ولی دو راه برای ارائه پیش نمونه برای اشیاء جدید وجود دارد.

+ +

اولی وقتیست که از تابع Object.create استفاده میشود - که اخیرا به زبان اضافه شده است و بنابراین بر روی همه ی پیاده سازی های آن وجود ندارد.

+```js +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 +``` + + +

راه دوم - که همه جا قابل استفاده است - مربوط به سازنده ها می شود.

+

سازنده ها دارای عضوی با نام prototype هستند. این پیش نمونه ی خود سازنده نیست

+

بلکه پیش نمونه ایست که به تمامی اشیاء ساخته شده توسط این سازنده الحاق میشود.

+```js +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 +``` + + +

رشته ها و سایر سازنده های پیش ساخته ی زبان نیز دارای این ویژگی هستند.

+```js +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true +``` + + +

به جز این که این سازنده ها دقیقا مانند سازنده های دیگر نیستند.

+```js +typeof(myNumber); // = 'number' +typeof(myNumberObj); // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // This code won't execute, because 0 is falsy. +} +if (Number(0)){ + // This code *will* execute, because Number(0) is truthy. +} +``` + + +

ولی به هر حال هم اشیاء عادی و هم اشیاء پیش ساخته هر دو در داشتن پیش نمونه مشترک هستند

+

بنابر این شما میتوانید ویژگی و تابع جدیدی به رشته ها - به عنوان مثال - اضافه کنید.

+ + +

گاها به از این خاصیت با عنوان پلی فیل و برای اضافه کردن ویژگی های جدید به مجموعه ای از اشیاء فعلی زبان استفاده میشود

+

که کاربرد فراوانی در پشتیبانی از نسخه های قدیمیتر مرورگر ها دارد.

+```js +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" +``` + + +

برای مثال، پیشتر اشاره کردیم که Object.create در نسخه های جدید پشتیبانی نشده است

+

ولی میتوان آن را به صورت پلی فیل استفاده کرد.

+```js +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){}; + Constructor.prototype = proto; + // then use it to create a new, appropriately-prototyped object + return new Constructor(); + } +} +``` + +

منابع دیگر

+ +The [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) +

مرجعی بسیار خوب برای جاوااسکریپت به شکلی که در مرورگر ها مورد استفاده قرار گرفته است.

+

از آنجایی که این منبع یک ویکی میباشد همانطور که مطالب بیشتری یاد میگیرید میتوانید به دیگران نیز در یادگیری آن کمک کنید.

+ +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +

مشابه مطالبی که اینجا مطرح شده با جزییات بیشتر. در اینجا به شکل عمدی جاوااسکریپت فقط از دیدگاه زبان برنامه نویسی مورد بررسی قرار گرفته

+

در حالی که در این منبع میتوانید بیشتر از کاربرد آن در صفحات وب آشنایی پیدا کنید.

+[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) +

راهنمای دقیقی از قسمت های غیر ملموس زبان.

+ +

اضافه بر این در ویرایش این مقاله، قسمت هایی از سایت زیر مورد استفاده قرار گرفته است.

+Louie Dinh's Python tutorial on this site, and the [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +on the Mozilla Developer Network. -- cgit v1.2.3 From 58640037dfcf428f159277d932edbcffab10476e Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 28 Oct 2013 17:14:55 -0700 Subject: Add lang tag to farsi js translation --- fa-ir/javascript.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown index 07dec31a..64508e52 100644 --- a/fa-ir/javascript.html.markdown +++ b/fa-ir/javascript.html.markdown @@ -3,6 +3,7 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] filename: javascript.js +lang: fa-ir ---

-- cgit v1.2.3 From c31221067f40785569370dfa3c6db08b5ef3ede0 Mon Sep 17 00:00:00 2001 From: mvalipour Date: Tue, 29 Oct 2013 00:24:20 +0000 Subject: Update header for javascript in Farsi --- fa-ir/javascript.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown index 07dec31a..f1beae87 100644 --- a/fa-ir/javascript.html.markdown +++ b/fa-ir/javascript.html.markdown @@ -2,7 +2,10 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] +translators: + - ["Mohammad Valipour", "https://github.com/mvalipour"] filename: javascript.js +lang: fa-ir ---

-- cgit v1.2.3 From 39ec31efebd0772a86d1c62ca22a9c8bb500fa05 Mon Sep 17 00:00:00 2001 From: Abdala Cerqueira Date: Tue, 29 Oct 2013 11:07:56 -0300 Subject: Adding pt-br version to php --- pt-br/php-pt.html.markdown | 700 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 700 insertions(+) create mode 100644 pt-br/php-pt.html.markdown diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown new file mode 100644 index 00000000..344df43a --- /dev/null +++ b/pt-br/php-pt.html.markdown @@ -0,0 +1,700 @@ +--- +language: php +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Abdala Cerqueira", "http://abda.la"] + - ["Raquel Diniz", "http://twitter.com/raquelrdiniz"] +lang: pt-br +filename: learnphp-pt.php +--- + +Este documento descreve PHP 5+. + +```php + +Olá mundo novamente! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (um 0 denota um número octal) +$int4 = 0x0F; // => 15 (um 0x denota um literal hex) + +// Flutuantes - Floats (aka doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Excluir variável +unset($int1) + +// Aritmética +$soma = 1 + 1; // 2 +$diferenca = 2 - 1; // 1 +$produto = 2 * 2; // 4 +$quociente = 2 / 1; // 2 + +// Taquigrafia aritmética +$numero = 0; +$numero += 1; // Incrementa $number em 1 +echo $numero++; // Imprime 1 (incrementa após a avaliação) +echo ++$numero; // Imprime 3 (incrementa antes da avaliação) +$numero /= $float; // Divide e atribui o quociente de $numero + +// Strings podem ser colocadas entre aspas simples +$sgl_quotes = '$String'; // => '$String' + +// Evite o uso de aspas duplas, exceto para incorporar outras variáveis +$dbl_quotes = "Esta é uma $sgl_quotes."; // => 'Esta é uma $String.' + +// Os caracteres especiais só são escapados entre aspas duplas +$escapado = "Este contém um \t caractere tab."; +$naoescapado = 'Este contém somente a barra e o t: \t'; + +// Coloque uma variável entre chaves se necessário +$dinheiro = "Eu tenho $${numero} no banco."; + +// Desde o PHP 5.3, nowdocs podem ser usados para múltiplas linhas sem análise +$nowdoc = <<<'FIM' +múltiplas linhas +string +FIM; + +// Heredocs farão a análise +$heredoc = << 1, 'Dois' => 2, 'Tres' => 3); + +// PHP 5.4 introduziu uma nova sintaxe +$associativo = ['Um' => 1, 'Dois' => 2, 'Tres' => 3]; + +echo $associativo['Um']; // imprime 1 + +// Uma lista de literais atribui chaves inteiras implicitamente +$array = ['Um', 'Dois', 'Tres']; +echo $array[0]; // => "Um" + +// Adiciona um elemento no final do array +$array[] = 'Quatro'; + +// Remove um elemento do array +unset($array[3]); + +/******************************** + * Saída + */ + +echo('Olá Mundo!'); +// Imprime Olá Mundo! para stdout. +// Stdout é uma página web se executado em um navegador. + +print('Olá Mundo!'); // O mesmo que o echo + +// echo é atualmente um construtor de linguagem, então você pode +// remover os parênteses. +echo 'Olá Mundo!'; +print 'Olá Mundo!'; // O print também é + +$paragrafo = 'parágrafo'; + +echo 100; // Imprime valores escalares diretamente +echo $paragrafo; // ou variáveis + +// Se a abertura de tags curtas está configurada, ou sua versão do PHP é +// 5.4.0 ou maior, você pode usar a sintaxe de echo curto +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Despeja tipos e valores de variável para o stdout +var_dump($z); // imprime int(0) + +// Imprime variáveis para stdout em formato legível para humanos +print_r($array); // imprime: Array ( [0] => Um [1] => Dois [2] => Tres ) + +/******************************** + * Lógica + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert lança um aviso se o seu argumento não é verdadeiro + +// Estas comparações serão sempre verdadeiras, mesmo que os tipos +// não sejam os mesmos. +assert($a == $b); // igualdade +assert($c != $a); // desigualdade +assert($c <> $a); // alternativa para desigualdade +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// A seguir, só serão verdadeiras se os valores correspondem e são do mesmo tipo. +assert($c === $d); +assert($a !== $d); +assert(1 == '1'); +assert(1 !== '1'); + +// As variáveis podem ser convertidas entre tipos, dependendo da sua utilização. + +$inteiro = 1; +echo $inteiro + $inteiro; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (strings são coagidas para inteiros) + +$string = 'one'; +echo $string + $string; // => 0 +// Imprime 0 porque o operador + não pode fundir a string 'um' para um número + +// Tipo de fundição pode ser utilizado para tratar uma variável +// como um outro tipo + +$booleano = (boolean) 1; // => true + +$zero = 0; +$booleano = (boolean) $zero; // => false + +// Há também funções dedicadas para fundir a maioria dos tipos +$inteiro = 5; +$string = strval($inteiro); + +$var = null; // valor Null + + +/******************************** + * Estruturas de controle + */ + +if (true) { + print 'Eu fico impresso'; +} + +if (false) { + print 'Eu não\'t'; +} else { + print 'Eu fico impresso'; +} + +if (false) { + print 'Não fica impresso'; +} elseif(true) { + print 'Fica'; +} + +// operadores ternários +print (false ? 'Não fica impresso' : 'Fica'); + +$x = 0; +if ($x === '0') { + print 'Não imprime'; +} elseif($x == '1') { + print 'Não imprime'; +} else { + print 'Imprime'; +} + + + +// Esta sintaxe alternativa é útil para modelos (templates) +?> + + +Isto é exibido se o teste for verdadeiro. + +Isto é apresentado caso contrário. + + + 2, 'carro' => 4]; + +// Repetições foreach podem iterar sobre arrays +foreach ($rodas as $contador_rodas) { + echo $contador_rodas; +} // Imprime "24" + +echo "\n"; + +// Você pode iterar sobre as chaves, bem como os valores +foreach ($rodas as $veiculo => $contador_rodas) { + echo "O $veiculo tem $contador_rodas rodas"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Sai da repetição + } + echo $i++; +} // Imprime "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Ignora esta iteração da repetição + } + echo $i; +} // Imprime "0124" + + +/******************************** + * Functions + */ + +// Define a função com "function": +function minha_funcao () { + return 'Olá'; +} + +echo minha_funcao(); // => "Olá" + +// Um nome de função válido começa com uma letra ou sublinhado, +// seguido por qualquer quantidade de letras, números ou sublinhados. + +function adicionar($x, $y = 1) { // $y é opcional e o valor padrão é 1 + $resultado = $x + $y; + return $resultado; +} + +echo adicionar(4); // => 5 +echo adicionar(4, 2); // => 6 + +// $resultado não é acessível fora da função +// print $resultado; // Dá uma aviso. + +// Desde o PHP 5.3 você pode declarar funções anônimas +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Funções podem retornar funções +function bar ($x, $y) { + // Utilize 'use' para trazer variáveis de fora + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Imprime "A - B - C" + +// Você pode chamar funções nomeadas usando strings +$nome_funcao = 'add'; +echo $nome_funcao(1, 2); // => 3 +// Útil para dinamicamente determinar qual função será executada. +// Ou utilize call_user_func(callable $callback [, $parameter [, ... ]]); + +/******************************** + * Includes (Incluir) + */ + +propInstancia = $propInstancia; + } + + // Métodos são declarados como funções dentro de uma classe + public function meuMetodo() + { + print 'MinhaClasse'; + } + + //palavra-chave final faz uma função não poder ser sobrescrita + final function voceNaoPodeMeSobrescrever() + { + } + +/* + * Declarando propriedades ou métodos de classe como estáticos faz deles + * acessíveis sem precisar instanciar a classe. A propriedade declarada + * como estática não pode ser acessada com um objeto + * instanciado da classe (embora métodos estáticos possam). +*/ + + public static function meuMetodoEstatico() + { + print 'Eu sou estatico'; + } +} + +echo MinhaClasse::MINHA_CONST; // Imprime 'valor'; +echo MinhaClasse::$valorEstatico; // Imprime 'estatico'; +MinhaClasse::meuMetodoEstatico(); // Imprime 'Eu sou estatico'; + +// Instantiate classes using new +$minha_classe = new MinhaClasse('Uma propriedade de instância'); +// Os parênteses são opcionais, se não passar algum argumento. + +// Acesse membros da classe utilizando -> +echo $minha_classe->propriedade; // => "publica" +echo $minha_classe->instanceProp; // => "Uma propriedade de instância" +$minha_classe->meuMetodo(); // => "MinhaClasse" + + +// Estender classes usando "extends" +class MinhaOutraClasse extends MinhaClasse +{ + function imprimePropriedadeProtegida() + { + echo $this->prot; + } + + // Sobrescrever um método + function meuMetodo() + { + parent::meuMetodo(); + print ' > MinhaOutraClasse'; + } +} + +$minha_outra_classe = new MinhaOutraClasse('Propriedade de instância'); +$minha_outra_classe->imprimePropriedadeProtegida(); // => Prints "protegida" +$minha_outra_classe->myMethod(); // Prints "MinhaClasse > MinhaOutraClasse" + +final class VoceNaoPodeMeEstender +{ +} + +// Você pode usar "métodos mágicos" para criar getters e setters +class MinhaClasseMapa +{ + private $propriedade; + + public function __get($chave) + { + return $this->$chave; + } + + public function __set($chave, $valor) + { + $this->$chave = $valor; + } +} + +$x = new MinhaClasseMapa(); +echo $x->propriedade; // Irá usar o método __get() +$x->propriedade = 'Algo'; // Irá usar o método __set() + +// Classes podem ser abstratas (usando a palavra-chave abstract) ou +// implementar interfaces (usando a palavra-chave implements). +// Uma interface é declarada com a palavra-chave interface. + +interface InterfaceUm +{ + public function fazAlgo(); +} + +interface InterfaceDois +{ + public function fazOutraCoisa(); +} + +// interfaces podem ser estendidas +interface InterfaceTres extends InterfaceDois +{ + public function fazOutroContrato(); +} + +abstract class MinhaClasseAbstrata implements InterfaceUm +{ + public $x = 'fazAlgo'; +} + +class MinhaClasseConcreta extends MinhaClasseAbstrata implements InterfaceDois +{ + public function fazAlgo() + { + echo $x; + } + + public function fazOutraCoisa() + { + echo 'fazOutraCoisa'; + } +} + + +// Classes podem implementar mais de uma interface +class UmaOutraClasse implements InterfaceUm, InterfaceDois +{ + public function fazAlgo() + { + echo 'fazAlgo'; + } + + public function fazOutraCoisa() + { + echo 'fazOutraCoisa'; + } +} + + +/******************************** + * Traits (Traços) + */ + +// Traits estão disponíveis a partir de PHP 5.4.0 e +// são declarados usando "trait" + +trait MeuTraco +{ + public function meuMetodoDeTraco() + { + print 'Eu tenho MeuTraco'; + } +} + +class MinhaClasseTracada +{ + use MeuTraco; +} + +$cls = new MinhaClasseTracada(); +$cls->meuMetodoDeTraco(); // Imprime "Eu tenho MeuTraco" + + +/******************************** + * Namespaces (Espaço nominal) + */ + +// Esta seção é separada porque a declaração de espaços nominais +// deve ser a primeira instrução em um arquivo. Vamos fingir, aqui não é o caso + + Date: Tue, 29 Oct 2013 21:06:39 +0000 Subject: add Farsi translation for brainfuck -- partial --- fa-ir/brainfuck.html.markdown | 80 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 fa-ir/brainfuck.html.markdown diff --git a/fa-ir/brainfuck.html.markdown b/fa-ir/brainfuck.html.markdown new file mode 100644 index 00000000..133e664f --- /dev/null +++ b/fa-ir/brainfuck.html.markdown @@ -0,0 +1,80 @@ +--- +language: brainfuck +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] +lang: fa-ir +--- + +برین فاک زبان برنامه نویسی تورینگ کامل بی نهایت ساده ایست که دارای فقط هشت +دستور است. + +هر کارکتری به جر کارکتر های زیر در این زبان در نظر گرفته نمیشود. + +`>` `<` `+` `-` `.` `,` `[` `]` + +برین فاک به صورت یک آرایه ی سی هزار خانه ای کار میکند که در ابتدا تمامی خانه های آن صفر هستند. +همچنین یک اشاره گر در این برنامه به خانه ی فعلی اشاره میکند. + +در زیر هشت دستور این زبان شرح داده شده است: + +`+` : یک عدد به خانه ی فعلی اضافه می کند. +`-` : یک عدد از خانه ی فعلی کم می کند. +`>` : اشاره گر به خانه ی بعدی میرود -- به راست +`<` : اشاره گر به خانه ی قبلی میرود -- به چپ +`.` : کارکتر اسکی معادل مقدار خانه ی فعلی را چاپ میکند. -- به عنوان مثال 65 برای A +`,` : یک کارکتر را از ورودی خوانده و مقدار آن را در خانه ی فعلی زخیره میکند. +`[` : اگر مقدار خانه ی فعلی صفر باشد به محل بسته شدن کروشه جهش میکند. -- و از همه ی دستور های بین آن صرف نظر میشود. +در غیر این صورت به دستور بعدی میرود. +`]` : اگر مقدار خانه ی فعلی صفر باشد به خانه ی بعدی و در غیر این صورت به محل باز شدن کروشه جهش می کند. -- به عقب + +دو علامت کروشه امکان ایجاد حلقه را فراهم میکنند. + +در اینجا یک برنامه ی ساره برین فاک را مشاهده میکنید. + +``` +++++++ [ > ++++++++++ < - ] > +++++ . +``` + +این برنامه کارکتر A را بر روی خروجی چاپ میکند. +در این برنامه خانه ی اول به عنوان متغیر حلقه و خانه ی دوم برای مقدار عددی A +ابتدا عدد شش در خانه ی اول ایجاد شده. سپس برنامه وارد یک حلقه میشود که در هر بار +تکرار آن اشاره گر به خانه ی دوم رفته و ده بار به خانه ی فعلی اضافه می کند. +-- و در انتهای حلقه به خانه ی اول برگشته تا حلقه کنترل شود +بعد از اتمام حلقه به خانه ی دوم میرود و پنج بار به این خانه اضافه کرده و سپس آنرا چاپ میکند. + +``` +, [ > + < - ] > . +``` + +در این برنامه ابتدا یک +This program reads a character from the user input and copies the character into +cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, +move back to cell #1, and decrement the value at cell #1. This continues on +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 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. 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 +language. The interpreter is fairly simple to implement, but if you're a +masochist, try writing a brainfuck interpreter… in brainfuck. -- cgit v1.2.3 From 1f0d7a02a17e0d21fd34580f76bd442036182c35 Mon Sep 17 00:00:00 2001 From: valipour Date: Tue, 29 Oct 2013 23:40:24 +0000 Subject: complete Farsi translation for brainfuck --- fa-ir/brainfuck.html.markdown | 93 ++++++++++++++++++++++--------------------- 1 file changed, 47 insertions(+), 46 deletions(-) diff --git a/fa-ir/brainfuck.html.markdown b/fa-ir/brainfuck.html.markdown index 133e664f..ef2bcba3 100644 --- a/fa-ir/brainfuck.html.markdown +++ b/fa-ir/brainfuck.html.markdown @@ -5,76 +5,77 @@ contributors: lang: fa-ir --- -برین فاک زبان برنامه نویسی تورینگ کامل بی نهایت ساده ایست که دارای فقط هشت -دستور است. +

برین فاک زبان برنامه نویسی تورینگ کامل بی نهایت ساده ایست که دارای فقط هشت

+

دستور است.

+ +

هر کارکتری به جر کارکتر های زیر در این زبان در نظر گرفته نمیشود.

-هر کارکتری به جر کارکتر های زیر در این زبان در نظر گرفته نمیشود. `>` `<` `+` `-` `.` `,` `[` `]` -برین فاک به صورت یک آرایه ی سی هزار خانه ای کار میکند که در ابتدا تمامی خانه های آن صفر هستند. -همچنین یک اشاره گر در این برنامه به خانه ی فعلی اشاره میکند. +

برین فاک به صورت یک آرایه ی سی هزار خانه ای کار میکند که در ابتدا تمامی خانه های آن صفر هستند.

+

همچنین یک اشاره گر در این برنامه به خانه ی فعلی اشاره میکند.

-در زیر هشت دستور این زبان شرح داده شده است: +

در زیر هشت دستور این زبان شرح داده شده است:

-`+` : یک عدد به خانه ی فعلی اضافه می کند. -`-` : یک عدد از خانه ی فعلی کم می کند. -`>` : اشاره گر به خانه ی بعدی میرود -- به راست -`<` : اشاره گر به خانه ی قبلی میرود -- به چپ -`.` : کارکتر اسکی معادل مقدار خانه ی فعلی را چاپ میکند. -- به عنوان مثال 65 برای A -`,` : یک کارکتر را از ورودی خوانده و مقدار آن را در خانه ی فعلی زخیره میکند. -`[` : اگر مقدار خانه ی فعلی صفر باشد به محل بسته شدن کروشه جهش میکند. -- و از همه ی دستور های بین آن صرف نظر میشود. -در غیر این صورت به دستور بعدی میرود. -`]` : اگر مقدار خانه ی فعلی صفر باشد به خانه ی بعدی و در غیر این صورت به محل باز شدن کروشه جهش می کند. -- به عقب +

`+` : یک عدد به خانه ی فعلی اضافه می کند. +

`-` : یک عدد از خانه ی فعلی کم می کند.

+

`>` : اشاره گر به خانه ی بعدی میرود -- به راست

+

`<` : اشاره گر به خانه ی قبلی میرود -- به چپ

+

`.` : کارکتر اسکی معادل مقدار خانه ی فعلی را چاپ میکند. -- به عنوان مثال 65 برای A

+

`,` : یک کارکتر را از ورودی خوانده و مقدار آن را در خانه ی فعلی زخیره میکند.

+

`[` : اگر مقدار خانه ی فعلی صفر باشد به محل بسته شدن کروشه جهش میکند. -- و از همه ی دستور های بین آن صرف نظر میشود.

+

در غیر این صورت به دستور بعدی میرود.

+

`]` : اگر مقدار خانه ی فعلی صفر باشد به خانه ی بعدی و در غیر این صورت به محل باز شدن کروشه جهش می کند. -- به عقب

-دو علامت کروشه امکان ایجاد حلقه را فراهم میکنند. +

دو علامت کروشه امکان ایجاد حلقه را فراهم میکنند.

-در اینجا یک برنامه ی ساره برین فاک را مشاهده میکنید. +

در اینجا یک برنامه ی ساره برین فاک را مشاهده میکنید.

``` ++++++ [ > ++++++++++ < - ] > +++++ . ``` -این برنامه کارکتر A را بر روی خروجی چاپ میکند. -در این برنامه خانه ی اول به عنوان متغیر حلقه و خانه ی دوم برای مقدار عددی A -ابتدا عدد شش در خانه ی اول ایجاد شده. سپس برنامه وارد یک حلقه میشود که در هر بار -تکرار آن اشاره گر به خانه ی دوم رفته و ده بار به خانه ی فعلی اضافه می کند. --- و در انتهای حلقه به خانه ی اول برگشته تا حلقه کنترل شود -بعد از اتمام حلقه به خانه ی دوم میرود و پنج بار به این خانه اضافه کرده و سپس آنرا چاپ میکند. +

این برنامه کارکتر A را بر روی خروجی چاپ میکند.

+

در این برنامه خانه ی اول به عنوان متغیر حلقه و خانه ی دوم برای مقدار عددی A

+

ابتدا عدد شش در خانه ی اول ایجاد شده. سپس برنامه وارد یک حلقه میشود که در هر بار

+

تکرار آن اشاره گر به خانه ی دوم رفته و ده بار به خانه ی فعلی اضافه می کند.

+

-- و در انتهای حلقه به خانه ی اول برگشته تا حلقه کنترل شود

+

بعد از اتمام حلقه به خانه ی دوم میرود و پنج بار به این خانه اضافه کرده و سپس آنرا چاپ میکند.

``` , [ > + < - ] > . ``` -در این برنامه ابتدا یک -This program reads a character from the user input and copies the character into -cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, -move back to cell #1, and decrement the value at cell #1. This continues on -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 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. 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. -``` +

ابتدا دو عدد از ورودی خوانده می شوند. سپس حلقه ی بیرونی بر روی خانه شماره یک شروع میشود.

+

و درون آن حلقه ی دیگری بر روی خانه ی دوم شروع میشود که خانه ی 3 را زیاد میکند.

+

ولی مشکلی که در اینجا به وجود می آید اینست که در پایان حلقه ی دوم مقدار خانه ی 2 صفر شده

+

و مقدار اولیه ی آن از دست رفته است. برای حل این مشکل خانه ی شماره چهار هم زیاد میشود

+

و در پایان حلقه مقدار آن به خانه 2 کپی میشود.

+

در پایان خانه ی شماره 2 حاوی حاصلضرب خواهد بود.

+ +
-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. +

و این همه ی برین فاک بود! خیلی ساده برای یادگیری ولی سنگین برای به کار بردن.

+

حال می توانید برای تفریح مشغول نوشتن برنامه ی های مختلف با آن شوید.

+

و یا یک اجرا کننده برین فاک را با یک زبان دیگر پیاده سازی کنید.

+

و یا اگر خیلی دوست داشتید یک اجرا کننده ی برین فاک با برین فاک بنویسید!!

-- cgit v1.2.3 From cba64739f5e61f8fb524dc1cc88cbb31920d2b86 Mon Sep 17 00:00:00 2001 From: Steven Senatori Date: Sat, 2 Nov 2013 16:50:29 -0700 Subject: Deleted some bad syntax and tweaked an explanation for clarity --- javascript.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 2ac98105..36aad102 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -306,8 +306,8 @@ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" // When you call a function with the new keyword, a new object is created, and -// made available to the function via this. Functions designed to be called -// like this are called constructors. +// made available to the function via the this keyword. Functions designed to be called +// like that are called constructors. var MyConstructor = function(){ this.myNumber = 5; @@ -323,14 +323,14 @@ myNewObj.myNumber; // = 5 // property __proto__. While this is useful for explaining prototypes it's not // part of the standard; we'll get to standard ways of using prototypes later. var myObj = { - myString: "Hello world!", + myString: "Hello world!" }; var myPrototype = { meaningOfLife: 42, myFunc: function(){ return this.myString.toLowerCase() } -}; + myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 -- cgit v1.2.3 From 34b0264620c540bcdc451c96996ff5a38a6d26db Mon Sep 17 00:00:00 2001 From: Steven Senatori Date: Sat, 2 Nov 2013 17:30:36 -0700 Subject: fixing one of my corrections, no idea why I delted the }; on line 333 previously...sorry --- javascript.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index 36aad102..2d665e67 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -330,6 +330,7 @@ var myPrototype = { myFunc: function(){ return this.myString.toLowerCase() } +}; myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 -- cgit v1.2.3 From 9f0ae279d83a41bec3c9998c5245c46908942873 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Tue, 5 Nov 2013 12:47:58 +1030 Subject: [javascript/en] Enforce 80-char line width --- javascript.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 2d665e67..b6d4c8b7 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -107,10 +107,10 @@ false; // There's also null and undefined null; // used to indicate a deliberate non-value -undefined; // used to indicate a value is not currently present (although undefined - // is actually a value itself) +undefined; // used to indicate a value is not currently present (although + // undefined is actually a value itself) -// false, null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. +// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. // Note that 0 is falsy and "0" is truthy, even though 0 == "0". /////////////////////////////////// @@ -306,8 +306,8 @@ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" // When you call a function with the new keyword, a new object is created, and -// made available to the function via the this keyword. Functions designed to be called -// like that are called constructors. +// made available to the function via the this keyword. Functions designed to be +// called like that are called constructors. var MyConstructor = function(){ this.myNumber = 5; -- cgit v1.2.3 From 2a60ecbb8d5d6a22fe5df3aa1efa8f1314da9326 Mon Sep 17 00:00:00 2001 From: supernullset Date: Mon, 4 Nov 2013 19:21:17 -0800 Subject: Update syntax for `in` calls The call was flipped from how it is in the current documentation: http://docs.julialang.org/en/latest/stdlib/base/#Base.in --- julia.html.markdown | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 4ebd50ff..c3d2195b 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -100,7 +100,7 @@ false println("I'm Julia. Nice to meet you!") # You don't declare variables before assigning to them. -some_var = 5 #=> 5 +some_var = 5 #=> 5 some_var #=> 5 # Accessing a previously unassigned variable is an error @@ -201,7 +201,7 @@ b = [1,2,3] append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] # Check for existence in a list with in -in(a,1) #=> true +in(1, a) #=> true # Examine the length with length length(a) #=> 8 @@ -218,7 +218,7 @@ end # Many list functions also work on tuples length(tup) #=> 3 tup[1:2] #=> (1,2) -in(tup,2) #=> true +in(2, tup) #=> true # You can unpack tuples into variables a, b, c = (1, 2, 3) #=> (1,2,3) # a is now 1, b is now 2 and c is now 3 @@ -249,14 +249,14 @@ keys(filled_dict) #=> KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Note - dictionary keys are not sorted or in the order you inserted them. -# Get all values +# Get all values values(filled_dict) #=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Note - Same as above regarding key ordering. # Check for existence of keys in a dictionary with in, haskey -in(filled_dict, ("one", 1)) #=> true -in(filled_dict, ("two", 3)) #=> false +in(("one", 1), filled_dict) #=> true +in(("two", 3), filled_dict) #=> false haskey(filled_dict, "one") #=> true haskey(filled_dict, 1) #=> false @@ -281,8 +281,8 @@ filled_set = Set(1,2,2,3,4) #=> Set{Int64}(1,2,3,4) push!(filled_set,5) #=> Set{Int64}(5,4,2,3,1) # Check if the values are in the set -in(filled_set,2) #=> true -in(filled_set,10) #=> false +in(2, filled_set) #=> true +in(10, filled_set) #=> false # There are functions for set intersection, union, and difference. other_set = Set(3, 4, 5, 6) #=> Set{Int64}(6,4,5,3) @@ -396,7 +396,7 @@ varargs(1,2,3) #=> (1,2,3) # The ... is called a splat. # We just used it in a function definition. # It can also be used in a fuction call, -# where it will splat an Array or Tuple's contents into the argument list. +# where it will splat an Array or Tuple's contents into the argument list. Set([1,2,3]) #=> Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays Set([1,2,3]...) #=> Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) @@ -423,7 +423,7 @@ end # You can define functions that take keyword arguments function keyword_args(;k1=4,name2="hello") # note the ; return ["k1"=>k1,"name2"=>name2] -end +end keyword_args(name2="ness") #=> ["name2"=>"ness","k1"=>4] keyword_args(k1="mine") #=> ["k1"=>"mine","name2"=>"hello"] @@ -511,7 +511,7 @@ end # The default constructor's arguments are the properties # of the tyep, in order the order they are listed in the definition tigger = Tiger(3.5,"orange") #=> Tiger(3.5,"orange") - + # The type doubles as the constructor function for values of that type sherekhan = typeof(tigger)(5.6,"fire") #=> Tiger(5.6,"fire") @@ -529,8 +529,8 @@ subtypes(Number) #=> 6-element Array{Any,1}: # Complex{Float32} # Complex{Float64} # Complex{T<:Real} - # ImaginaryUnit - # Real + # ImaginaryUnit + # Real subtypes(Cat) #=> 0-element Array{Any,1} # Every type has a super type; use the `super` function to get it. @@ -565,7 +565,7 @@ end # When possible, you should use outer constructors rather than inner ones. #################################################### -## 6. Multiple-Dispatch +## 6. Multiple-Dispatch #################################################### # In Julia, all named functions are generic functions @@ -641,11 +641,11 @@ end # Also let the cat go first fight(c::Cat,l::Lion) = println("The cat beats the Lion") -#=> Warning: New definition +#=> Warning: New definition # fight(Cat,Lion) at none:1 -# is ambiguous with +# is ambiguous with # fight(Lion,Cat) at none:2. -# Make sure +# Make sure # fight(Lion,Lion) # is defined first. #fight (generic function with 4 methods) -- cgit v1.2.3 From a72bcacba5ee50061099a136f035f65989124665 Mon Sep 17 00:00:00 2001 From: Raul Brito Date: Sat, 9 Nov 2013 19:29:14 +0100 Subject: fix typo --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index 226eefff..c3317d59 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -11,7 +11,7 @@ This document describes PHP 5+. ```php Date: Sun, 10 Nov 2013 18:37:34 +0000 Subject: add css article in english --- css.html.markdown | 332 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 332 insertions(+) create mode 100644 css.html.markdown diff --git a/css.html.markdown b/css.html.markdown new file mode 100644 index 00000000..0c1908c8 --- /dev/null +++ b/css.html.markdown @@ -0,0 +1,332 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] +--- + +In early days of web there was no visual elements, just pure text. But with the further development of browser fully visual web pages also became common. CSS is the standard language that exists to keep the separation between the content (HTML) and the look-and-feel of web pages. + +In short, what CSS does is to provide a syntax that enables you to target different elements on an HTML page and assign different visual properties to them. + +Like any other language, CSS has many versions. Here we focus on CSS2.0 which is not the most recent but the most widely supported and compatible version. + +## Selectors + +```css +/* let's stick to the tradition and show how comments are made first! */ + +/* Generally, the primary statement in CSS is very simple */ +selector { property: value; /* more properties...*/ } + +/* the selector is used to target an element on page. + +You can target all elments on the page! */ +* { color:red; } + +/* +Given an element like this on the page: + +
+*/ + +/* you can target it by it's class name */ +.some-class { } + +/*or by both classes! */ +.some-class.class2 { } + +/* or by it's tag name */ +div { } + +/* or it's id */ +#someId { } + +/* or by the fact that it has an attribute! */ +[attr] { font-size:smaller; } + +/* or that the attribute has a specific value */ +[attr='value'] { font-size:smaller; } + +/* start with a value*/ +[attr^'val'] { font-size:smaller; } + +/* or ends with */ +[attr$='ue'] { font-size:smaller; } + +/* or even contains a value */ +[attr~='lu'] { font-size:smaller; } + + +/* and more importantly you can combine these together -- there shouldn't be any space between different parts because that makes it to have another meaning.*/ +div.some-class[attr$='ue'] { } + +/* you can also select an element based on how it's parent is.*/ + +/*an element which is direct child of an element (selected the same way) */ +div.some-parent > .class-name {} + +/* or any of it's parents in the tree */ +/* the following basically means any element that has class "class-name" and is child of a div with class name "some-parent" IN ANY DEPTH */ +div.some-parent .class-name {} + +/* warning: the same selector wihout space has another meaning. can you say what? */ +div.some-parent.class-name {} + +/* you also might choose to select an element based on it's direct previous sibling */ +.i-am-before + .this-element { } + +/*or any sibling before this */ +.i-am-any-before ~ .this-element {} + +/* There are some pseudo classes that allows you to select an element based on it's page behaviour (rather than page structure) */ + +/* for example for when an element is hovered */ +:hover {} + +/* or a visited link*/ +:visited {} + +/* or not visited link*/ +:link {} + +/* or an input element which is focused */ +:focus {} + +``` + +## Properties + +```css +/*## Units +can be like : + +- 50%: in percent +- 2em: two times the current font-size +- 20px: in pixels +- 20pt: in point +- 2cm: centimeter +- 20mm: millimeter +- 2in: inches + +*/ + +/* ## Colors + +#F6E -- can be in short hex +#F262E2 -- or in long hex format +red or tomato -- can be a named color +rgb(255, 255, 255) -- in rgb +rgb(10%, 20%, 50%) -- in rgb percent + +*/ + +/* ## Font */ +selector { + font-style: italic; /* or normal */ + font-weight: bold; /* or normal, lighter or a number between 100 and 900*/ + font-size: 2em; /* see units */ + font-family: Verdana, Arial; /* if the first one is not supported the second one is taken.*/ +} + +/* you can set all in one declaration. */ +selector { font: bold italic 12px Consolas; } + +/*## Background */ +selector { + background-color: red; /* see colors */ + background-image: url(/path/cat.jpg); + background-repeat: no-repaet; /* or repeat or repeat-x or repeat-y */ + background-attachment: scroll; /* or fixed */ + background-position: 10px 20px; /* or center, top, bottom, left, right */ +} + +/* again you can set all in one declaratio */ +selector { background: red url(image.jpg) no-repeat center top fixed; } + +/*## Box model + +All elements (other than inline elements like span) follow a box model +that consists of the following components. + + --------------- + margin + --------------- + border + --------------- + padding + --------------- +| margin | border | padding | [width/height] | padding | border | margin + --------------- + padding + --------------- + border + --------------- + margin + --------------- + +of these components all except margin add to the dimention of the element. + +e.g. border-left: 10px; width: 100px; border-left: 2px; padding-left:5px; + => effective width of the element 117px (given all right components are zero) + +*/ +selector { + width: 100px; + height: 100px; + + padding-top:10px; + padding-bottom:10px; + padding-left:10px; + padding-right:10px; + + margin-top:10px; + margin-bottom:10px; + margin-left:10px; + margin-right:10px; + + border-top:10px; + border-bottom:10px; + border-left:10px; + border-right:10px; +} + +/* again you can use shorthands + +for padding, margin and border the order is: +[top] [right] [bottom] [left]*/ +selector { + padding: 10px 8px 6px 5px; + /* same for margin and border*/ +} + +/* a shorter one! +[top and bottom] [left and right] */ +selector { + padding: 6px 5px; + /* same for margin and border*/ +} + +/* and even shorter! +[all sides] */ +selector { + padding: 6px; + /* same for margin and border*/ +} + +/*## Positioning + +elements are normally following the page flow based on where in the markup they are. + +some tags like `div` or `p` are full-width and the rest are inline by default. + +but all elements can have their layout changed*/ +selelctor { + display: inline; /* inline-block, block, table-cell, et.*/ +} + +/* elements can be absolutely positioned -- which means they won't follow the page flow and will be independently positioned on the screen. */ +selector { position:absolute; left: 200px; top:10px; /* or right:10px; bottom:10px; */ } + +/* in this case the elements top left will be alighned with the page body. + +but if you want it to be relative to an earlier parent.*/ +parent-selector { position:relative; } + +/* if you want to have the same thing but moving with scroll: */ +selector { position:fixed; left: 200px; top:10px; /* or right:10px; bottom:10px; */ } + +/* when elements appear on the same absolute position. the latest one in the markup appears on top. + +unless...*/ +selector { z-index: 2; /* or any number higher than others' */ } + +/* if you wish your element to follow the markup layout (not absolutely positioned) but floated to a side in it's parent:*/ +selector { float: left; /* or right */ } + +/*## Lists + +you can also control how the lists appear on the screen:*/ + +selector { + list-style-type: circle; /* disc | square | decimal | etc... */ + list-style-position: inside; /* or outside */ + list-style-image: url(path/image.jpg); +} + +/*as always this can be shorthanded */ + +selector { list-tyle: disc inside url(...); } + + +``` + +## Usage + +Save any CSS you want in a file with extension `.css`. + +```markup + + + + + + + +
+
+ +``` + +## Precedence + +As you noticed an element may be targetted by more than one selector. and may have a property set on it in more than one. In these cases, one of the rules takes precedence over others. + +Given the following CSS: +```css +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +and the following markdown: +```markdown +

+

+``` + +The precedence of style is as followed: +Note that the precedence is for each **property** in the style and not for the entire block. + +* `E` has the highest precedence because of the keyword `!important`. It is recommended to avoid this unless it is strictly necessary to use. +* `F` is the next because it is inline style. +* `A` is the next because is more "specific" that anything else. more specific = more specifiers. here 3 specifiers: 1 tagname `p` + class name `class1` + 1 attribute `attr='value'` +* `C` is the next. although it has the same specificness as `B` but it appears after that. +* Then is `B` +* and lastly is `D`. + +## Compatibility + +Most of the features in CSS2 (and gradually in CSS3) are compatible across all browsers and devices. But it's always vital to have in mind the compatiblity of what you use in CSS with your target browsers. + +[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. + +## Further Reading + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) + -- cgit v1.2.3 From 855afcfc2230d38a4018630dc454226a8eee5272 Mon Sep 17 00:00:00 2001 From: victormelo Date: Sun, 10 Nov 2013 16:23:52 -0300 Subject: [java/pt-br] java translated to pt-br --- pt-br/java-pt.html.markdown | 435 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 435 insertions(+) create mode 100644 pt-br/java-pt.html.markdown diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown new file mode 100644 index 00000000..f922f6d9 --- /dev/null +++ b/pt-br/java-pt.html.markdown @@ -0,0 +1,435 @@ +--- + +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Madison Dickson", "http://github.com/mix3d"] + translators: + - ["Victor Kléber Santos L. Melo", "http://victormelo.com.br/blog"] + - ["Renê Douglas N. de Morais", "rene.douglas.bsi@gmail.com"] +lang: pt-br +filename: LearnJava.java + +--- + +Java é uma linguagem de programação de propósito geral, concorrente, baseada em classes e orientada a objetos. +[Leia mais aqui](http://docs.oracle.com/javase/tutorial/java/index.html) + +```java +// Comentários de uma linha começam com // +/* +Comentários de várias linhas são feitos dessa forma. +*/ +/** +Comentários JavaDoc são feitos assim. São usados para descrever a Classe ou os atributos da Classe. +*/ + +// Importa a classe ArrayList que está dentro do pacote java.util +import java.util.ArrayList; +// Importa todas as classes que estão dentro do pacote java.security +import java.security.*; + +// Cada arquivo .java contém uma classe pública, com o mesmo nome do arquivo. +public class LearnJava { + + // Um programa precisa ter um método main como um ponto de entrada. + public static void main (String[] args) { + + // O System.out.println é usado para imprimir no console + System.out.println("Olá Mundo!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Para imprimir sem inserir uma nova lina, use o System.out.print + System.out.print("Olá "); + System.out.print("Mundo"); + + + /////////////////////////////////////// + // Tipos & Variáveis + /////////////////////////////////////// + + // Declara-se variáveis usando [ + // Byte - inteiro de 8 bits com sinal complementado a dois + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - inteiro de 16 bits com sinal complementado a dois + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - inteiro de 32 bits com sinal complementado a dois + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - inteiro de 64 bits com sinal complementado a dois + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L é usado para indicar que o valor da variável é do tipo Long; + // sem o L, tudo é tratado como inteiro por padrão. + + // Nota: Java não tem tipos sem sinal + + // Float - Ponto Flutuante 32-bits, de precisão simples no padrão IEEE 754 + float fooFloat = 234.5f; + // f é usado para indicar que o valor da variável é do tipo float; + // caso contrário, ela é tratada como double. + + // Double - Ponto Flutuante 64-bits, de precisão dupla no padrão IEEE 754 + double fooDouble = 123.4; + + // Boolean - true & false + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - Um caractere Unicode de 16 bits + char fooChar = 'A'; + + // Usa-se o final para fazer com que a variável seja imutável. + final int HORAS_QUE_TRABALHEI_POR_SEMANA = 9001; + + // Strings + String fooString = "Aqui está minha String!"; + + // \n é um caractere de escape que inicia uma nova linha + String barString = "Imprimir em uma nova linha?\nSem problemas!"; + // \t é um caractere de escape que adiciona um caractere de tabulação + String bazString = "Você quer adicionar tabulação?\tSem problemas!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Arrays + //O tamanho do array precisa ser determinado na sua declaração + //O formato para declarar um array é: + // [] = new []; + int [] intArray = new int[10]; + String [] stringArray = new String[1]; + boolean [] booleanArray = new boolean[100]; + + // Outra maneira de declarar e inicializar um array + int [] y = {9000, 1000, 1337}; + + // Indexando um array - Acessando um elemento + System.out.println("intArray no índice 0: " + intArray[0]); + + // O primeiro termo de um array é o 0 e eles são mutáveis. + intArray[1] = 1; + System.out.println("intArray no índice 1: " + intArray[1]); // => 1 + + // Outras estruturas que devem ser vistas + // ArrayLists - São parecidos com os arrays, porém oferecem mais funcionalidades + // e o tamanho é mutável. + // LinkedLists + // Maps + // HashMaps + + /////////////////////////////////////// + // Operadores + /////////////////////////////////////// + System.out.println("\n->Operadores"); + + int i1 = 1, i2 = 2; // Forma abreviada de escrever múltiplas declarações. + + // Aritmética é feita da forma convencional + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 arredondado para baixo) + + // Módulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Operadores de comparação + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Operadores bit-a-bit! + /* + ~ Complemento de um + << Deslocamento a esquerda com sinal + >> Deslocamento a direita com sinal + >>> Deslocamento a direita sem sinal + & E bit-a-bit + | OU bit-a-bit + ^ OU exclusivo bit-a-bit + */ + + // Incrementações + int i = 0; + System.out.println("\n->Inc/Dec-rementação"); + System.out.println(i++); //i = 1. Pós-Incrementação + System.out.println(++i); //i = 2. Pre-Incrementação + System.out.println(i--); //i = 1. Pós-Decrementação + System.out.println(--i); //i = 0. Pre-Decrementação + + /////////////////////////////////////// + // Estruturas de Controle + /////////////////////////////////////// + System.out.println("\n->Estruturas de Controle"); + + // Os comandos If são parecidos com o da linguagem C + int j = 10; + if (j == 10){ + System.out.println("Eu serei impresso"); + } else if (j > 10) { + System.out.println("Eu não"); + } else { + System.out.println("Eu também não"); + } + + // O Loop While + int fooWhile = 0; + while(fooWhile < 100) + { + //System.out.println(fooWhile); + //Incrementando o contador + //Iteração feita 99 vezes, fooWhile 0->99 + fooWhile++; + } + System.out.println("Valor do fooWhile: " + fooWhile); + + // O Loop Do While + int fooDoWhile = 0; + do + { + //System.out.println(fooDoWhile); + //Incrementando o contador + //Iteração feita 99 vezes, fooDoWhile 0->99 + fooDoWhile++; + }while(fooDoWhile < 100); + System.out.println("Valor do fooDoWhile: " + fooDoWhile); + + // O Loop For + int fooFor; + //estrutura do loop for => for(; ; ) + for(fooFor=0; fooFor<10; fooFor++){ + //System.out.println(fooFor); + //Iteração feita 10 vezes, fooFor 0->9 + } + System.out.println("Valor do fooFor: " + fooFor); + + // O Loop For Each + // Itera automaticamente por um array ou lista de objetos. + int[] fooList = {1,2,3,4,5,6,7,8,9}; + //estrutura do loop for each => for( : ) + //lê-se: para cada objeto no array + //nota: o tipo do objeto deve ser o mesmo do array. + + for( int bar : fooList ){ + //System.out.println(bar); + //Itera 9 vezes e imprime 1-9 em novas linhas + } + + // Switch + // Um switch funciona com os tipos de dados: byte, short, char e int + // Ele também funciona com tipos enumerados (vistos em tipos Enum) + // como também a classe String e algumas outras classes especiais + // tipos primitivos: Character, Byte, Short e Integer + int mes = 3; + String mesString; + switch (mes){ + case 1: + mesString = "Janeiro"; + break; + case 2: + mesString = "Fevereiro"; + break; + case 3: + mesString = "Março"; + break; + default: + mesString = "Algum outro mês"; + break; + } + System.out.println("Resultado do Switch: " + mesString); + + // Condição de forma abreviada. + // Você pode usar o operador '?' para atribuições rápidas ou decisões lógicas. + // Lê-se "Se (declaração) é verdadeira, use + // caso contrário, use ". + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); //Imprime A, pois a condição é verdadeira. + + + /////////////////////////////////////// + // Convertendo tipos de dados e Casting + /////////////////////////////////////// + + //Conversão de Dados + + //Convertendo String para Inteiro. + Integer.parseInt("123");//retorna uma versão inteira de "123". + + //Convertendo Inteiro para String + Integer.toString(123);//retorna uma versão String de 123. + + // Para outras conversões confira as seguintes classes + // Double + // Long + // String + + // Casting + // Você pode também converter objetos java, há vários detalhes e + // lida com alguns conceitos intermediários + // Dê uma olhada no link: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Classes e Métodos + /////////////////////////////////////// + + System.out.println("\n->Classes e Métodos"); + + // (segue a definição da classe Bicicleta) + + // Use o new para instanciar uma classe + Bicicleta caloi = new Bicicleta(); // Objeto caloi criado. + + // Chame os métodos do objeto + caloi.aumentarVelocidade(3); // Você deve sempre usar métodos para modificar variáveis + caloi.setRitmo(100); + + // toString é uma convenção para mostrar o valor deste objeto. + System.out.println("informações de caloi: " + caloi.toString()); + + } // Fim do método main +} // Fim da classe LearnJava + + +// Você pode incluir outras classes que não são públicas num arquivo .java + + +// Sintaxe de declaração de Classe. +// class { +// // atributos, construtores e todos os métodos. +// // funções são chamadas de métodos em Java. +// } + +class Bicicleta { + + // Atributos/Variáveis da classe Bicicleta. + public int ritmo; // Public: Pode ser acessada em qualquer lugar. + private int velocidade; // Private: Apenas acessível a classe. + protected int catraca; // Protected: Acessível a classe e suas subclasses. + String nome; // default: Apenas acessível ao pacote. + + // Construtores são uma forma de criação de classes + // Este é o construtor padrão. + public Bicicleta() { + catraca = 1; + ritmo = 50; + velocidade = 5; + nome = "Bontrager"; + } + + // Este é um construtor específico (ele contém argumentos). + public Bicicleta (int ritmoInicial, int velocidadeInicial, int catracaInicial, String nome) { + this.catraca = catracaInicial; + this.ritmo = ritmoInicial; + this.velocidade = velocidadeInicial; + this.nome = nome; + } + + // Sintaxe de um método: + // () // + + // Classes em Java costumam implementar métodos getters e setters para seus campos. + + // Sintaxe de declaração de métodos + // () // + public int getRitmo() { + return ritmo; + } + + // Métodos do tipo void não requerem declaração de retorno. + public void setRitmo(int novoValor) { + ritmo = novoValor; + } + + public void setEquipamento(int novoValor) { + catraca = novoValor; + } + + public void aumentarVelocidade(int incremento) { + velocidade += incremento; + } + + public void diminuirVelocidade(int decremento) { + velocidade -= decremento; + } + + public void setNome(String novoNome) { + nome = novoNome; + } + + public String getNome() { + return nome; // retorna um dado do tipo String. + } + + //Método para mostrar os valores dos atributos deste objeto. + @Override + public String toString() { + return "catraca: " + catraca + + " ritmo: " + ritmo + + " velocidade: " + velocidade + + " nome: " + nome; + } +} // fim classe Bicicleta + +// Velocipede é uma subclasse de bicicleta. +class Velocipede extends Bicicleta { + // (Velocípedes são bicicletas com rodas dianteiras grandes + // Elas não possuem catraca.) + + public Velocipede(int ritmoInicial, int velocidadeInicial){ + // Chame o construtor do pai (construtor de Bicicleta) com o comando super. + super(ritmoInicial, velocidadeInicial, 0, "PennyFarthing"); + } + + // Você pode marcar um método que você está substituindo com uma @annotation + // Para aprender mais sobre o que são as annotations e sua finalidade + // dê uma olhada em: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setEquipamento(int catraca) { + catraca = 0; + } + +} + +``` + +## Leitura Recomendada + +Os links fornecidos aqui abaixo são apenas para ter uma compreensão do tema, use o Google e encontre exemplos específicos. + +Outros tópicos para pesquisar: + +* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Modificadores de acesso do Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Herança](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polimorfismo](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstração](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceções](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Tipos Genéricos](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Conversões de código Java](http://www.oracle.com/technetwork/java/codeconv-138413.html) + +Livros: + +* [Use a cabeça, Java] (http://www.headfirstlabs.com/books/hfjava/) -- cgit v1.2.3 From b5409e78f8ff6c47b3f1a39023aeb4f11bca1d9f Mon Sep 17 00:00:00 2001 From: valipour Date: Sun, 10 Nov 2013 20:59:18 +0000 Subject: fix some issues in CSS english --- css.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index 0c1908c8..290f1ea3 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -48,7 +48,7 @@ div { } [attr='value'] { font-size:smaller; } /* start with a value*/ -[attr^'val'] { font-size:smaller; } +[attr^='val'] { font-size:smaller; } /* or ends with */ [attr$='ue'] { font-size:smaller; } @@ -164,10 +164,10 @@ that consists of the following components. margin --------------- -of these components all except margin add to the dimention of the element. +of these components all except margin add to the dimension of the element. -e.g. border-left: 10px; width: 100px; border-left: 2px; padding-left:5px; - => effective width of the element 117px (given all right components are zero) +e.g. padding-left: 10px; width: 100px; border-left: 2px; + => effective width of the element 112px (given all -right components are zero) */ selector { -- cgit v1.2.3 From 11924a8c180e134de470b849445ca0fdffe506e0 Mon Sep 17 00:00:00 2001 From: valipour Date: Sun, 10 Nov 2013 21:09:31 +0000 Subject: add more clarification to border and fix max 80 character line --- css.html.markdown | 84 ++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 61 insertions(+), 23 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index 290f1ea3..e421e1b1 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -4,11 +4,16 @@ contributors: - ["Mohammad Valipour", "https://github.com/mvalipour"] --- -In early days of web there was no visual elements, just pure text. But with the further development of browser fully visual web pages also became common. CSS is the standard language that exists to keep the separation between the content (HTML) and the look-and-feel of web pages. +In early days of web there was no visual elements, just pure text. But with the +further development of browser fully visual web pages also became common. +CSS is the standard language that exists to keep the separation between +the content (HTML) and the look-and-feel of web pages. -In short, what CSS does is to provide a syntax that enables you to target different elements on an HTML page and assign different visual properties to them. +In short, what CSS does is to provide a syntax that enables you to target +different elements on an HTML page and assign different visual properties to them. -Like any other language, CSS has many versions. Here we focus on CSS2.0 which is not the most recent but the most widely supported and compatible version. +Like any other language, CSS has many versions. Here we focus on CSS2.0 +which is not the most recent but the most widely supported and compatible version. ## Selectors @@ -57,7 +62,9 @@ div { } [attr~='lu'] { font-size:smaller; } -/* and more importantly you can combine these together -- there shouldn't be any space between different parts because that makes it to have another meaning.*/ +/* and more importantly you can combine these together -- there shouldn't be +any space between different parts because that makes it to have another +meaning.*/ div.some-class[attr$='ue'] { } /* you can also select an element based on how it's parent is.*/ @@ -66,19 +73,23 @@ div.some-class[attr$='ue'] { } div.some-parent > .class-name {} /* or any of it's parents in the tree */ -/* the following basically means any element that has class "class-name" and is child of a div with class name "some-parent" IN ANY DEPTH */ +/* the following basically means any element that has class "class-name" +and is child of a div with class name "some-parent" IN ANY DEPTH */ div.some-parent .class-name {} -/* warning: the same selector wihout space has another meaning. can you say what? */ +/* warning: the same selector wihout space has another meaning. +can you say what? */ div.some-parent.class-name {} -/* you also might choose to select an element based on it's direct previous sibling */ +/* you also might choose to select an element based on it's direct +previous sibling */ .i-am-before + .this-element { } /*or any sibling before this */ .i-am-any-before ~ .this-element {} -/* There are some pseudo classes that allows you to select an element based on it's page behaviour (rather than page structure) */ +/* There are some pseudo classes that allows you to select an element +based on it's page behaviour (rather than page structure) */ /* for example for when an element is hovered */ :hover {} @@ -184,10 +195,10 @@ selector { margin-left:10px; margin-right:10px; - border-top:10px; - border-bottom:10px; - border-left:10px; - border-right:10px; + border-top:10px solid red; + border-bottom:10px solid red; + border-left:10px solid red; + border-right:10px solid red; } /* again you can use shorthands @@ -213,6 +224,19 @@ selector { /* same for margin and border*/ } +/* border has three components that can be specified separately */ +selector { + border-left-style: solid; /* or dotted or dashed*/ + border-left-color: red; + border-left-width: 1px; +} + +/* this breakdown can also be done when the shorthand is used. */ +selector { + border-style: solid; + /* ... */ +} + /*## Positioning elements are normally following the page flow based on where in the markup they are. @@ -224,7 +248,8 @@ selelctor { display: inline; /* inline-block, block, table-cell, et.*/ } -/* elements can be absolutely positioned -- which means they won't follow the page flow and will be independently positioned on the screen. */ +/* elements can be absolutely positioned -- which means they won't follow +the page flow and will be independently positioned on the screen. */ selector { position:absolute; left: 200px; top:10px; /* or right:10px; bottom:10px; */ } /* in this case the elements top left will be alighned with the page body. @@ -235,12 +260,14 @@ parent-selector { position:relative; } /* if you want to have the same thing but moving with scroll: */ selector { position:fixed; left: 200px; top:10px; /* or right:10px; bottom:10px; */ } -/* when elements appear on the same absolute position. the latest one in the markup appears on top. +/* when elements appear on the same absolute position. +the latest one in the markup appears on top. unless...*/ selector { z-index: 2; /* or any number higher than others' */ } -/* if you wish your element to follow the markup layout (not absolutely positioned) but floated to a side in it's parent:*/ +/* if you wish your element to follow the markup layout (not absolutely positioned) +but floated to a side in it's parent:*/ selector { float: left; /* or right */ } /*## Lists @@ -268,12 +295,14 @@ Save any CSS you want in a file with extension `.css`. - + - +
@@ -281,7 +310,9 @@ Save any CSS you want in a file with extension `.css`. ## Precedence -As you noticed an element may be targetted by more than one selector. and may have a property set on it in more than one. In these cases, one of the rules takes precedence over others. +As you noticed an element may be targetted by more than one selector. +and may have a property set on it in more than one. +In these cases, one of the rules takes precedence over others. Given the following CSS: ```css @@ -309,18 +340,25 @@ and the following markdown: ``` The precedence of style is as followed: -Note that the precedence is for each **property** in the style and not for the entire block. +Note that the precedence is for each **property** in the style and +not for the entire block. -* `E` has the highest precedence because of the keyword `!important`. It is recommended to avoid this unless it is strictly necessary to use. +* `E` has the highest precedence because of the keyword `!important`. + It is recommended to avoid this unless it is strictly necessary to use. * `F` is the next because it is inline style. -* `A` is the next because is more "specific" that anything else. more specific = more specifiers. here 3 specifiers: 1 tagname `p` + class name `class1` + 1 attribute `attr='value'` -* `C` is the next. although it has the same specificness as `B` but it appears after that. +* `A` is the next because is more "specific" that anything else. + more specific = more specifiers. here 3 specifiers: 1 tagname `p` + + class name `class1` + 1 attribute `attr='value'` +* `C` is the next. although it has the same specificness as `B` + but it appears after that. * Then is `B` * and lastly is `D`. ## Compatibility -Most of the features in CSS2 (and gradually in CSS3) are compatible across all browsers and devices. But it's always vital to have in mind the compatiblity of what you use in CSS with your target browsers. +Most of the features in CSS2 (and gradually in CSS3) are compatible across +all browsers and devices. But it's always vital to have in mind the compatiblity +of what you use in CSS with your target browsers. [QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. -- cgit v1.2.3 From 5111009611d6c8ff2b177514bf69caf5fd2a6c51 Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 10 Nov 2013 14:35:26 -0800 Subject: Fix java pt-br frontmatter --- pt-br/java-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index f922f6d9..e8d5a538 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -4,9 +4,9 @@ language: java contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Madison Dickson", "http://github.com/mix3d"] - translators: +translators: - ["Victor Kléber Santos L. Melo", "http://victormelo.com.br/blog"] - - ["Renê Douglas N. de Morais", "rene.douglas.bsi@gmail.com"] + - ["Renê Douglas N. de Morais", "mailto:rene.douglas.bsi@gmail.com"] lang: pt-br filename: LearnJava.java -- cgit v1.2.3 From eb8afb2ff27e3dba477f9ab7257d4b13e55718b1 Mon Sep 17 00:00:00 2001 From: Amin Bandali Date: Mon, 11 Nov 2013 23:17:34 -0500 Subject: reverting a list using slices --- python.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 08e68407..50c4e63f 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -2,6 +2,7 @@ language: python contributors: - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] filename: learnpython.py --- @@ -159,6 +160,8 @@ li[1:3] #=> [2, 4] li[2:] #=> [4, 3] # Omit the end li[:3] #=> [1, 2, 4] +# Revert the list +li[::-1] #=> [3, 4, 2, 1] # Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] -- cgit v1.2.3 From 31f59a366cbe2f9030a89b9ac62e5cc0db383718 Mon Sep 17 00:00:00 2001 From: ins429 Date: Wed, 13 Nov 2013 00:15:06 -0800 Subject: better translation --- ko-kr/brainfuck-kr.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ko-kr/brainfuck-kr.html.markdown b/ko-kr/brainfuck-kr.html.markdown index 661fcfea..c2e4341f 100644 --- a/ko-kr/brainfuck-kr.html.markdown +++ b/ko-kr/brainfuck-kr.html.markdown @@ -5,10 +5,11 @@ contributors: - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["JongChan Choi", "http://0xABCDEF.com/"] + - ["Peter Lee", "http://peterjlee.com/"] lang: ko-kr --- -Brainfuck(f는 대문자로 적지 않습니다)은 +Brainfuck(문장을 시작하는 단어가 아닌이상 첫글자는 대문자를 사용하지 않습니다)은 여덟가지 명령어만으로 튜링-완전한 최소주의 프로그래밍 언어입니다. ``` -- cgit v1.2.3 From 8121793f32c36b6727474c6d41f31c27cea2ebf0 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sat, 16 Nov 2013 19:40:06 +1030 Subject: Fix errors specified in #410. --- java.html.markdown | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 3d0cb1d7..b4624d5e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -26,7 +26,8 @@ import java.util.ArrayList; // Import all classes inside of java.security package import java.security.*; -// Each .java file contains one public class, with the same name as the file. +// Each .java file contains one outer-level public class, with the same name as +// the file. public class LearnJava { // A program must have a main method as an entry point @@ -84,7 +85,7 @@ public class LearnJava { // Char - A single 16-bit Unicode character char fooChar = 'A'; - // Use final to make a variable immutable + // final variables can't be reassigned to another object final int HOURS_I_WORK_PER_WEEK = 9001; // Strings @@ -99,7 +100,7 @@ public class LearnJava { System.out.println(bazString); // Arrays - //The array size must be decided upon declaration + //The array size must be decided upon instantiation //The format for declaring an array is follows: // [] = new []; int [] intArray = new int[10]; @@ -161,10 +162,13 @@ public class LearnJava { // Incrementations int i = 0; System.out.println("\n->Inc/Dec-rementation"); - System.out.println(i++); //i = 1. Post-Incrementation - System.out.println(++i); //i = 2. Pre-Incrementation - System.out.println(i--); //i = 1. Post-Decrementation - System.out.println(--i); //i = 0. Pre-Decrementation + // The ++ and -- operators increment and decrement by 1 respectively. + // If they are placed before the variable, they increment then return; + // after the variable they return then increment. + System.out.println(i++); //i = 1, prints 0 (post-increment) + System.out.println(++i); //i = 2, prints 2 (pre-increment) + System.out.println(i--); //i = 1, prints 2 (post-decrement) + System.out.println(--i); //i = 0, prints 0 (pre-decrement) /////////////////////////////////////// // Control Structures @@ -211,19 +215,19 @@ public class LearnJava { //Iterated 10 times, fooFor 0->9 } System.out.println("fooFor Value: " + fooFor); - + // For Each Loop // An automatic iteration through an array or list of objects. int[] fooList = {1,2,3,4,5,6,7,8,9}; //for each loop structure => for( : ) //reads as: for each object in the array //note: the object type must match the array. - + for( int bar : fooList ){ //System.out.println(bar); //Iterates 9 times and prints 1-9 on new lines } - + // Switch Case // A switch works with the byte, short, char, and int data types. // It also works with enumerated types (discussed in Enum Types), @@ -246,7 +250,7 @@ public class LearnJava { break; } System.out.println("Switch Case Result: " + monthString); - + // Conditional Shorthand // You can use the '?' operator for quick assignments or logic forks. // Reads as "If (statement) is true, use , otherwise, use " @@ -294,14 +298,14 @@ public class LearnJava { trek.speedUp(3); // You should always use setter and getter methods trek.setCadence(100); - // toString is a convention to display the value of this Object. + // toString returns this Object's string representation. System.out.println("trek info: " + trek.toString()); } // End main method } // End LearnJava class -// You can include other, non-public classes in a .java file +// You can include other, non-public outer-level classes in a .java file // Class Declaration Syntax: @@ -319,7 +323,7 @@ class Bicycle { String name; // default: Only accessible from within this package // Constructors are a way of creating classes - // This is a default constructor + // This is a constructor public Bicycle() { gear = 1; cadence = 50; @@ -327,7 +331,7 @@ class Bicycle { name = "Bontrager"; } - // This is a specified constructor (it contains arguments) + // This is a constructor that takes arguments public Bicycle(int startCadence, int startSpeed, int startGear, String name) { this.gear = startGear; this.cadence = startCadence; -- cgit v1.2.3 From ed09da6cdd4092e72e0fb094773103f814cb3279 Mon Sep 17 00:00:00 2001 From: Andrew Popov Date: Sun, 17 Nov 2013 04:51:34 +0400 Subject: [c/ru] translate c manual to russian --- ru-ru/c-ru.html.markdown | 506 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 506 insertions(+) create mode 100644 ru-ru/c-ru.html.markdown diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown new file mode 100644 index 00000000..80f79ffd --- /dev/null +++ b/ru-ru/c-ru.html.markdown @@ -0,0 +1,506 @@ +--- +language: c +filename: learnc.c +contributors: + - ["Adam Bard", "http://adambard.com/"] + - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] +translators: + - ["Evlogy Sutormin", "http://evlogii.com"] +lang: ru-ru +--- + +Что ж, Си всё ещё является лидером среди современных высокопроизводительных языков. + +Для большинствоа программистов, Си – это самый низкоуровневый язык на котором они когда-либо писали, +но этот язык даёт больше, чем просто повышение производительности. +Держите это руководство в памяти и вы сможете использовать Си максимально эффективно. + +```c +// Однострочный комментарий начинается с // - доступно только после С99. + +/* +Многострочный комментарий выглядит так. Работает начиная с С89. +*/ + +// Импорт файлов происходит с помощью **#include** +#include +#include +#include + +// Файлы <в угловых скобочках> будут подключаться из стандартной библиотеки. +// Свои файлы необходимо подключать с помощью "двойных кавычек". +#include "my_header.h" + +// Объявление функций должно происходить в .h файлах или вверху .c файла. +void function_1(); +void function_2(); + +// Точка входа в программу – это функция main. +int main() { + // для форматированного вывода в консоль используется printf + // %d – означает, что будем выводить целое число, \n переводит указатель вывода + // на новую строчку + printf("%d\n", 0); // => напечатает "0" + // Каждый оператор заканчивается точкой с запятой. + + /////////////////////////////////////// + // Типы + /////////////////////////////////////// + + // int обычно имеет длину 4 байта + int x_int = 0; + + // shorts обычно имеет длину 2 байта + short x_short = 0; + + // chars гарантированно имеет длину 1 байта + char x_char = 0; + char y_char = 'y'; // Символьные литералы заключаются в кавычки '' + + // long как правило занимает от 4 до 8 байт + // long long занимает как минимум 64 бита + long x_long = 0; + long long x_long_long = 0; + + // float это 32-битное число с плавающей точкой + float x_float = 0.0; + + // double это 64-битное число с плавающей точкой + double x_double = 0.0; + + // Целые типы могут быть беззнаковыми. + unsigned short ux_short; + unsigned int ux_int; + unsigned long long ux_long_long; + + // sizeof(T) возвращает размер переменной типа Т в байтах. + // sizeof(obj) возвращает размер объекта obj в байтах. + printf("%zu\n", sizeof(int)); // => 4 (на большинстве машин int занимает 4 байта) + + // Если аргуметом sizeof будет выражение, то этот аргумент вычисляется + // ещё во время компиляции кода (кроме динамических массивов). + int a = 1; + // size_t это беззнаковый целый тип который использует как минимум 2 байта + // для записи размера объекта + size_t size = sizeof(a++); // a++ считается во время компиляции + printf("sizeof(a++) = %zu, где a = %d\n", size, a); + // выведет строку "sizeof(a++) = 4, где a = 1" (на 32-битной архитектуре) + + // Можно задать размер массива при объявлении. + char my_char_array[20]; // Этот массив занимает 1 * 20 = 20 байт + int my_int_array[20]; // Этот массив занимает 4 * 20 = 80 байт (сумма 4-битных слов) + + // Можно обнулить массив при объявлении. + char my_array[20] = {0}; + + // Индексация массива происходит также как и в других Си-подобных языках. + my_array[0]; // => 0 + + // Массивы изменяемы. Это просто память как и другие переменные. + my_array[1] = 2; + printf("%d\n", my_array[1]); // => 2 + + // В C99 (а также опционально в C11), массив может быть объявлен динамически. + // Размер массива не обязательно должен быть рассчитан на этапе компиляции. + printf("Enter the array size: "); // спрашиваем юзера размер массива + char buf[0x100]; + fgets(buf, sizeof buf, stdin); + size_t size = strtoul(buf, NULL, 10); // strtoul парсит строку в беззнаковое целое + int var_length_array[size]; // объявление динамического массива + printf("sizeof array = %zu\n", sizeof var_length_array); + + // Вывод программы (в зависимости от архитектуры) будет таким: + // > Enter the array size: 10 + // > sizeof array = 40 + + + // Строка – это просто массив символов, оканчивающийся нулевым (NUL (0x00)) байтом + // представляемым в строке специальным символом '\0'. + // Нам не нужно вставлять нулевой байт в строковой литерал, + // компилятор всё сделает за нас. + char a_string[20] = "This is a string"; + printf("%s\n", a_string); // %s обозначает вывод строки + + printf("%d\n", a_string[16]); // => 0 + // байт #17 тоже равен 0 (а также 18, 19, и 20) + + // Если между одинарными кавычками есть символ – это символьный литерал, + // но это тип int, а не char (по историческим причинам). + + int cha = 'a'; // хорошо + char chb = 'a'; // тоже хорошо (подразумевается преобразование int в char) + + /////////////////////////////////////// + // Операторы + /////////////////////////////////////// + + // Можно использовать множественное объявление + int i1 = 1, i2 = 2; + float f1 = 1.0, f2 = 2.0; + + // Арифметика обычная + i1 + i2; // => 3 + i2 - i1; // => 1 + i2 * i1; // => 2 + i1 / i2; // => 0 (0.5, но обрезается до 0) + + f1 / f2; // => 0.5, плюс-минус погрешность потому что, + // цифры с плавающей точкой вычисляются неточно! + + // Модуль + 11 % 3; // => 2 + + // Операции сравнения вам уже знакомы, но в Си нет булевого типа. + // Вместо него используется int. 0 это false, всё остальное это true. + // Операции сравнения всегда возвращают 1 или 0. + 3 == 2; // => 0 (false) + 3 != 2; // => 1 (true) + 3 > 2; // => 1 + 3 < 2; // => 0 + 2 <= 2; // => 1 + 2 >= 2; // => 1 + + // Си это не Питон – операции сравнения могут быть только парными. + int a = 1; + // ОШИБКА: + int between_0_and_2 = 0 < a < 2; + // Правильно: + int between_0_and_2 = 0 < a && a < 2; + + // Логика + !3; // => 0 (логическое НЕ) + !0; // => 1 + 1 && 1; // => 1 (логическое И) + 0 && 1; // => 0 + 0 || 1; // => 1 (лигическое ИЛИ) + 0 || 0; // => 0 + + // Битовые операторы + ~0x0F; // => 0xF0 (побитовое отрицание) + 0x0F & 0xF0; // => 0x00 (побитовое И) + 0x0F | 0xF0; // => 0xFF (побитовое ИЛИ) + 0x04 ^ 0x0F; // => 0x0B (исключающее ИЛИ (XOR)) + 0x01 << 1; // => 0x02 (побитовый сдвиг влево (на 1)) + 0x02 >> 1; // => 0x01 (побитовый сдвиг вправо (на 1)) + + // Будьте осторожны при сдвиге беззнакового int, эти операции не определены: + // - shifting into the sign bit of a signed integer (int a = 1 << 32) + // - сдвиг влево отрицательных чисел (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 + + /////////////////////////////////////// + // Структуры ветвления + /////////////////////////////////////// + + // Условный оператор + if (0) { + printf("I am never run\n"); + } else if (0) { + printf("I am also never run\n"); + } else { + printf("I print\n"); + } + + // Цикл с предусловием + int ii = 0; + while (ii < 10) { + printf("%d, ", ii++); // инкрементация происходит после того как + // знаечние ii передано ("postincrement") + } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + //Цикл с постусловием + int kk = 0; + do { + printf("%d, ", kk); + } while (++kk < 10); // инкрементация происходит перед тем как + // передаётся знаечние kk ("preincrement") + // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + // Цикл со счётчиком + int jj; + for (jj=0; jj < 10; jj++) { + printf("%d, ", jj); + } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + // Ветвление с множественным выбором + switch (some_integral_expression) { + case 0: // значения должны быть целыми константами (могут быть выражениями) + do_stuff(); + break; // если не написать break; то управление будет передено следующему блоку + case 1: + do_something_else(); + break; + default: + // если не было совпадения, то выполняется блок default: + fputs("ошибка!\n", stderr); + exit(-1); + break; + } + + + /////////////////////////////////////// + // Форматирование вывода + /////////////////////////////////////// + + // Каждое выражение в Си имеет тип, но вы можете привести один тип к другому + // если хотите (с некоторыми константами). + + int x_hex = 0x01; // Вы можете назначать переменные с помощью шеснадцатеричного кода + + // Приведение типов будет пытаться сохранять цифровые значения + printf("%d\n", x_hex); // => Prints 1 + printf("%d\n", (short) x_hex); // => Prints 1 + printf("%d\n", (char) x_hex); // => Prints 1 + + // Типы могут переполняться без предупреждения + printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long) + + // Для определения максимального значения типов `char`, `signed char` и `unisigned char`, + // соответственно используйте CHAR_MAX, SCHAR_MAX и UCHAR_MAX макросы из + + // Целые типы могут быть приведены к вещественным и наоборот + printf("%f\n", (float)100); // %f formats a float + printf("%lf\n", (double)100); // %lf formats a double + printf("%d\n", (char)100.0); + + /////////////////////////////////////// + // Указатели + /////////////////////////////////////// + + // A pointer is a variable declared to store a memory address. Its declaration will + // also tell you the type of data it points to. You can retrieve the memory address + // of your variables, then mess with them. + + + // Указатель – это переменная которая хранит адрес в памяти. При объявлении указателя указывается тип данных переменной на которую он будет ссылаться. Вы можете получить адрес любой переменной, а потом работать с ним. + + // Используйте & для получения адреса переменной + int x = 0; + printf("%p\n", (void *)&x); // => Напечатает адрес в памяти, где лежит переменная x + // (%p выводит указатель на void *) + + + // Для объявления указателя нужно поставить * перед именем. + int *px, not_a_pointer; // px это указатель на int + px = &x; // сохранит адрес x в px + printf("%p\n", (void *)px); // => Напечатает адрес в памяти, где лежит переменная px + printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); + // => Напечатает "8, 4" в 64 битной системе + + // Для того, чтобы получить знаечние по адресу, напечатайте * перед именем. + // Да, использование * при объявлении указателя и получении значения по адресу, + // немного запутано, но вы привыкнете. + printf("%d\n", *px); // => Напечаатет 0, значение перемененной x + + // Вы также можете изменять значение, на которое указывает указатель. + (*px)++; // Инкрементирует значение на которое указывает px на еденицу + printf("%d\n", *px); // => Напечатает 1 + printf("%d\n", x); // => Напечатает 1 + + // массивы хорошо использовать для болшого количества однотипных данных + int x_array[20]; + int xx; + for (xx = 0; xx < 20; xx++) { + x_array[xx] = 20 - xx; + } // Объявление x_array с значениями 20, 19, 18,... 2, 1 + + // Инициализация указателя на int с адресом массива. + int* x_ptr = x_array; + // x_ptr сейчас x_ptr указывает на первый элемент массива (со значением 20). + // Это рабоатет, потому что имя массива возвращает указатель на первый элемент. + // Например, когда массив передаётся в функцию или назначается указателю, он + // невявно преобразуется в указатель. + // Исключения: когда массив является аргументом для оператор '&': + int arr[10]; + int (*ptr_to_arr)[10] = &arr; // &arr не является 'int *'! + // он является "указатель на массив" (из десяти 'int'ов). + // или когда массив это строчный литерал или при объявлении массива символов: + char arr[] = "foobarbazquirk"; + // или когда массив является аргументом `sizeof` или `alignof` операторов: + int arr[10]; + int *ptr = arr; // то же самое что и int *ptr = &arr[0];" + printf("%zu %zu\n", sizeof arr, sizeof ptr); // напечатает "40, 4" или "40, 8" + + // Декрементация и инкрементация указателей зависит от их типа + // (это называется арифметика указателей) + printf("%d\n", *(x_ptr + 1)); // => Напечатает 19 + printf("%d\n", x_array[1]); // => Напечатает 19 + + // Вы также можете динамически выделять несколько боков памяти с помощью + // функции malloc из стандартной библиотеки, которая принимает один + // аргумент типа size_t – количество байт необходимых для выделения. + int *my_ptr = malloc(sizeof(*my_ptr) * 20); + for (xx = 0; xx < 20; xx++) { + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx + } // Выделяет память для 20, 19, 18, 17... 2, 1 (как int'ы) + + // Работа с памятью с помощью указателей может давать неожиданные и + // непредсказуемые результаты. + printf("%d\n", *(my_ptr + 21)); // => Напечатает кто-нибудь-знает-что? + // Скорей всего программа вылетит. + + // Когда вы закончили работать с памятью, которую ранее выделили, вам необходимо + // освободить её, иначе это может вызвать утечку памяти. + free(my_ptr); + + // Строки это массивы символов, но обычно они представляются как + // указатели на символ (как указатели на первый элемент массива). + // Хорошей практикой считается использование `const char *' при объявлении + // строчоного литерала. При таком подходе литерал не может быть изменён. + // (например "foo"[0] = 'a' вызовет ошибку!) + + const char *my_str = "This is my very own string literal"; + printf("%c\n", *my_str); // => 'T' + + // Это не работает, если строка является массивом + // (потенциально задаваемой с помощью строкового литерала) + // который находиться в перезаписываемой части памяти: + + char foo[] = "foo"; + foo[0] = 'a'; // это выполнится и строка теперь "aoo" + + void function_1() +} // конец функции main() + +/////////////////////////////////////// +// Функции +/////////////////////////////////////// + +// Синтаксис объявления функции: +// <возвращаемый тип> <имя функции>(аргументы) + +int add_two_ints(int x1, int x2) +{ + return x1 + x2; // Используйте return для возврата значения +} + +/* +Данные в функицию передаются "по значению", но никто не мешает +вам передавать в функцию указатели и менять данные по указателям. + +Например: инвертировать строку прямо в функции +*/ + +// void орзначает, что функция ничего не возвражщает +void str_reverse(char *str_in) +{ + char tmp; + int ii = 0; + size_t len = strlen(str_in); // `strlen()` является частью стандартной библиотеки + for (ii = 0; ii < len / 2; ii++) { + tmp = str_in[ii]; + str_in[ii] = str_in[len - ii - 1]; // ii-тый символ с конца + str_in[len - ii - 1] = tmp; + } +} + +char c[] = "This is a test."; +str_reverse(c); +printf("%s\n", c); // => Выведет ".tset a si sihT" + +/////////////////////////////////////// +// Типы и структуры определяемые пользователем +/////////////////////////////////////// + +// typedef исапользуется для задания стандартным типам своих названий +typedef int my_type; +my_type my_type_var = 0; + +// Структыры это просто коллекция данных, память выделяется последовательно, +// в том порядке в котором записаны данные. +struct rectangle { + int width; + int height; +}; + +// sizeof(struct rectangle) == sizeof(int) + sizeof(int) – не всегда верно +// из-за особенностей компиляции (проблема в отступах)[1]. + +void function_1() +{ + struct rectangle my_rec; + + // Доступ к структурам через точку + my_rec.width = 10; + my_rec.height = 20; + + // Вы можете объявить указатель на структуру + struct rectangle *my_rec_ptr = &my_rec; + + // Можно доступаться к структуре и через указатель + (*my_rec_ptr).width = 30; + + // ... или ещё лучше: успользуйте -> оператор для лучшей читабельночти + my_rec_ptr->height = 10; // то же что и "(*my_rec_ptr).height = 10;" +} + +// Вы можете применить typedef к структуре, для удобства +typedef struct rectangle rect; + +int area(rect r) +{ + return r.width * r.height; +} + +// Если вы имеете большую структуру, можно доступаться к ней "по указателю", +// чтобы избежать копирования всей структуры. +int area(const rect *r) +{ + return r->width * r->height; +} + +/////////////////////////////////////// +// Указатели на функции +/////////////////////////////////////// + +/* +At runtime, functions are located at known memory addresses. Function pointers are +much like any other pointer (they just store a memory address), but can be used +to invoke functions directly, and to pass handlers (or callback functions) around. +However, definition syntax may be initially confusing. + +Example: use str_reverse from a pointer +*/ + + +/* +Во время исполнения функции находятся по известным адресам в памяти. +Указатель на функцию может быть использован для непосредственного вызова функции. +Однако синтаксис может сбивать с толку. + +Пример: использование str_reverse по указателю +*/ +void str_reverse_through_pointer(char *str_in) { + // Определение функции через указатель. + void (*f)(char *); // Сигнатура должна полность совпадать с целевой функцией. + f = &str_reverse; // Присвоить фактический адрес (во время исполнения) + // "f = str_reverse;" тоже будет работать. + //Имя функции (как и массива) возвращает указатель на начало. + (*f)(str_in); // Просто вызываем функцию через указатель. + // "f(str_in);" или вот так +} +``` + +## На почитать + +Лучше всего найдите копию [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) +Это *книга* написанная создателями Си. Но будьте осторожны, она содержит которые больше не считаются хорошими. + +Другой хороший ресурс: [Learn C the hard way](http://c.learncodethehardway.org/book/). + +Если у вас появился вопрос, почитайте [compl.lang.c Frequently Asked Questions](http://c-faq.com). + +Очень важно использовать правильные отступы и ставить пробелы в нужных местах. +Читаемый код лучше чем красивый или быстрый код. +Чтобы научиться писать хороший код, почитайте [Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle). + +Также не забывайте, что [Google](http://google.com) и [Яндекс](http://yandex.ru) – ваши хорошие друзья. + +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member -- cgit v1.2.3 From b548dad5ee5d1c13f9cb61d6ce43a3141f7a8004 Mon Sep 17 00:00:00 2001 From: Andrew Popov Date: Sun, 17 Nov 2013 16:35:17 +0400 Subject: [c/ru] some fixes and improves --- ru-ru/c-ru.html.markdown | 87 ++++++++++++++++++++---------------------------- 1 file changed, 37 insertions(+), 50 deletions(-) diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index 80f79ffd..0b39586a 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -50,10 +50,10 @@ int main() { // int обычно имеет длину 4 байта int x_int = 0; - // shorts обычно имеет длину 2 байта + // short обычно имеет длину 2 байта short x_short = 0; - // chars гарантированно имеет длину 1 байта + // char гарантированно имеет длину 1 байта char x_char = 0; char y_char = 'y'; // Символьные литералы заключаются в кавычки '' @@ -82,7 +82,7 @@ int main() { int a = 1; // size_t это беззнаковый целый тип который использует как минимум 2 байта // для записи размера объекта - size_t size = sizeof(a++); // a++ считается во время компиляции + size_t size = sizeof(a++); // a++ не выполнится printf("sizeof(a++) = %zu, где a = %d\n", size, a); // выведет строку "sizeof(a++) = 4, где a = 1" (на 32-битной архитектуре) @@ -134,7 +134,7 @@ int main() { // Операторы /////////////////////////////////////// - // Можно использовать множественное объявление + // Можно использовать множественное объявление. int i1 = 1, i2 = 2; float f1 = 1.0, f2 = 2.0; @@ -184,10 +184,9 @@ int main() { 0x02 >> 1; // => 0x01 (побитовый сдвиг вправо (на 1)) // Будьте осторожны при сдвиге беззнакового int, эти операции не определены: - // - shifting into the sign bit of a signed integer (int a = 1 << 32) + // - сдвиг в знаковый бит у целого числа (int a = 1 << 32) // - сдвиг влево отрицательных чисел (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 + /////////////////////////////////////// // Структуры ветвления @@ -231,7 +230,7 @@ int main() { // Ветвление с множественным выбором switch (some_integral_expression) { - case 0: // значения должны быть целыми константами (могут быть выражениями) + case 0: // значения должны быть целыми константами (и могут быть выражениями) do_stuff(); break; // если не написать break; то управление будет передено следующему блоку case 1: @@ -249,23 +248,23 @@ int main() { // Форматирование вывода /////////////////////////////////////// - // Каждое выражение в Си имеет тип, но вы можете привести один тип к другому - // если хотите (с некоторыми константами). + // Каждое выражение в Си имеет тип, но вы можете привести один тип к другому, + // если хотите (с некоторыми искажениями). - int x_hex = 0x01; // Вы можете назначать переменные с помощью шеснадцатеричного кода + int x_hex = 0x01; // Вы можете назначать переменные с помощью шеснадцатеричного кода. - // Приведение типов будет пытаться сохранять цифровые значения + // Приведение типов будет пытаться сохранять цифровые значения. printf("%d\n", x_hex); // => Prints 1 printf("%d\n", (short) x_hex); // => Prints 1 printf("%d\n", (char) x_hex); // => Prints 1 - // Типы могут переполняться без предупреждения + // Типы могут переполняться без вызова предупреждения. printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long) // Для определения максимального значения типов `char`, `signed char` и `unisigned char`, // соответственно используйте CHAR_MAX, SCHAR_MAX и UCHAR_MAX макросы из - // Целые типы могут быть приведены к вещественным и наоборот + // Целые типы могут быть приведены к вещественным и наоборот. printf("%f\n", (float)100); // %f formats a float printf("%lf\n", (double)100); // %lf formats a double printf("%d\n", (char)100.0); @@ -274,14 +273,11 @@ int main() { // Указатели /////////////////////////////////////// - // A pointer is a variable declared to store a memory address. Its declaration will - // also tell you the type of data it points to. You can retrieve the memory address - // of your variables, then mess with them. - - - // Указатель – это переменная которая хранит адрес в памяти. При объявлении указателя указывается тип данных переменной на которую он будет ссылаться. Вы можете получить адрес любой переменной, а потом работать с ним. + // Указатель – это переменная которая хранит адрес в памяти. + // При объявлении указателя указывается тип данных переменной на которую он будет ссылаться. + // Вы можете получить адрес любой переменной, а потом работать с ним. - // Используйте & для получения адреса переменной + // Используйте & для получения адреса переменной. int x = 0; printf("%p\n", (void *)&x); // => Напечатает адрес в памяти, где лежит переменная x // (%p выводит указатель на void *) @@ -295,37 +291,37 @@ int main() { // => Напечатает "8, 4" в 64 битной системе // Для того, чтобы получить знаечние по адресу, напечатайте * перед именем. - // Да, использование * при объявлении указателя и получении значения по адресу, + // Да, использование * при объявлении указателя и получении значения по адресу // немного запутано, но вы привыкнете. printf("%d\n", *px); // => Напечаатет 0, значение перемененной x // Вы также можете изменять значение, на которое указывает указатель. - (*px)++; // Инкрементирует значение на которое указывает px на еденицу + (*px)++; // Инкрементирует значение на которое указывает px на единицу printf("%d\n", *px); // => Напечатает 1 printf("%d\n", x); // => Напечатает 1 - // массивы хорошо использовать для болшого количества однотипных данных + // Массивы удобно использовать для болшого количества однотипных данных. int x_array[20]; int xx; for (xx = 0; xx < 20; xx++) { x_array[xx] = 20 - xx; } // Объявление x_array с значениями 20, 19, 18,... 2, 1 - // Инициализация указателя на int с адресом массива. + // Объявление указателя на int с адресом массива. int* x_ptr = x_array; - // x_ptr сейчас x_ptr указывает на первый элемент массива (со значением 20). + // x_ptr сейчас указывает на первый элемент массива (со значением 20). // Это рабоатет, потому что имя массива возвращает указатель на первый элемент. // Например, когда массив передаётся в функцию или назначается указателю, он // невявно преобразуется в указатель. // Исключения: когда массив является аргументом для оператор '&': int arr[10]; int (*ptr_to_arr)[10] = &arr; // &arr не является 'int *'! - // он является "указатель на массив" (из десяти 'int'ов). - // или когда массив это строчный литерал или при объявлении массива символов: + // он является "указателем на массив" (из десяти 'int'ов). + // или когда массив это строчный литерал, используемый при объявлении массива символов: char arr[] = "foobarbazquirk"; // или когда массив является аргументом `sizeof` или `alignof` операторов: int arr[10]; - int *ptr = arr; // то же самое что и int *ptr = &arr[0];" + int *ptr = arr; // то же самое что и "int *ptr = &arr[0];" printf("%zu %zu\n", sizeof arr, sizeof ptr); // напечатает "40, 4" или "40, 8" // Декрементация и инкрементация указателей зависит от их типа @@ -333,7 +329,7 @@ int main() { printf("%d\n", *(x_ptr + 1)); // => Напечатает 19 printf("%d\n", x_array[1]); // => Напечатает 19 - // Вы также можете динамически выделять несколько боков памяти с помощью + // Вы также можете динамически выделять несколько блоков памяти с помощью // функции malloc из стандартной библиотеки, которая принимает один // аргумент типа size_t – количество байт необходимых для выделения. int *my_ptr = malloc(sizeof(*my_ptr) * 20); @@ -347,13 +343,13 @@ int main() { // Скорей всего программа вылетит. // Когда вы закончили работать с памятью, которую ранее выделили, вам необходимо - // освободить её, иначе это может вызвать утечку памяти. + // освободить её, иначе это может вызвать утечку памяти или ошибки. free(my_ptr); // Строки это массивы символов, но обычно они представляются как // указатели на символ (как указатели на первый элемент массива). // Хорошей практикой считается использование `const char *' при объявлении - // строчоного литерала. При таком подходе литерал не может быть изменён. + // строчного литерала. При таком подходе литерал не может быть изменён. // (например "foo"[0] = 'a' вызовет ошибку!) const char *my_str = "This is my very own string literal"; @@ -382,13 +378,13 @@ int add_two_ints(int x1, int x2) } /* -Данные в функицию передаются "по значению", но никто не мешает +Данные в функцию передаются "по значению", но никто не мешает вам передавать в функцию указатели и менять данные по указателям. Например: инвертировать строку прямо в функции */ -// void орзначает, что функция ничего не возвражщает +// void означает, что функция ничего не возвращает void str_reverse(char *str_in) { char tmp; @@ -409,11 +405,11 @@ printf("%s\n", c); // => Выведет ".tset a si sihT" // Типы и структуры определяемые пользователем /////////////////////////////////////// -// typedef исапользуется для задания стандартным типам своих названий +// typedef используется для задания стандартным типам своих названий typedef int my_type; my_type my_type_var = 0; -// Структыры это просто коллекция данных, память выделяется последовательно, +// Структуры это просто коллекция данных, память выделяется последовательно, // в том порядке в котором записаны данные. struct rectangle { int width; @@ -421,7 +417,7 @@ struct rectangle { }; // sizeof(struct rectangle) == sizeof(int) + sizeof(int) – не всегда верно -// из-за особенностей компиляции (проблема в отступах)[1]. +// из-за особенностей компиляции (необычное поведение при отступах)[1]. void function_1() { @@ -441,7 +437,7 @@ void function_1() my_rec_ptr->height = 10; // то же что и "(*my_rec_ptr).height = 10;" } -// Вы можете применить typedef к структуре, для удобства +// Вы можете применить typedef к структуре, для удобства. typedef struct rectangle rect; int area(rect r) @@ -460,16 +456,6 @@ int area(const rect *r) // Указатели на функции /////////////////////////////////////// -/* -At runtime, functions are located at known memory addresses. Function pointers are -much like any other pointer (they just store a memory address), but can be used -to invoke functions directly, and to pass handlers (or callback functions) around. -However, definition syntax may be initially confusing. - -Example: use str_reverse from a pointer -*/ - - /* Во время исполнения функции находятся по известным адресам в памяти. Указатель на функцию может быть использован для непосредственного вызова функции. @@ -477,6 +463,7 @@ Example: use str_reverse from a pointer Пример: использование str_reverse по указателю */ + void str_reverse_through_pointer(char *str_in) { // Определение функции через указатель. void (*f)(char *); // Сигнатура должна полность совпадать с целевой функцией. @@ -491,7 +478,7 @@ void str_reverse_through_pointer(char *str_in) { ## На почитать Лучше всего найдите копию [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) -Это *книга* написанная создателями Си. Но будьте осторожны, она содержит которые больше не считаются хорошими. +Это **книга** написанная создателями Си. Но будьте осторожны, она содержит идеи которые больше не считаются хорошими. Другой хороший ресурс: [Learn C the hard way](http://c.learncodethehardway.org/book/). @@ -503,4 +490,4 @@ void str_reverse_through_pointer(char *str_in) { Также не забывайте, что [Google](http://google.com) и [Яндекс](http://yandex.ru) – ваши хорошие друзья. -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file -- cgit v1.2.3 From 92faa7ce01ce727a2f7fc6d8bcf407e8547dfe1b Mon Sep 17 00:00:00 2001 From: Andrew Popov Date: Mon, 18 Nov 2013 05:08:17 +0400 Subject: [c/ru] some improves --- ru-ru/c-ru.html.markdown | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index 0b39586a..59d3c3b5 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -16,7 +16,7 @@ lang: ru-ru Держите это руководство в памяти и вы сможете использовать Си максимально эффективно. ```c -// Однострочный комментарий начинается с // - доступно только после С99. +// Однострочный комментарий начинается с // - доступен только после С99. /* Многострочный комментарий выглядит так. Работает начиная с С89. @@ -108,12 +108,10 @@ int main() { size_t size = strtoul(buf, NULL, 10); // strtoul парсит строку в беззнаковое целое int var_length_array[size]; // объявление динамического массива printf("sizeof array = %zu\n", sizeof var_length_array); - // Вывод программы (в зависимости от архитектуры) будет таким: // > Enter the array size: 10 // > sizeof array = 40 - // Строка – это просто массив символов, оканчивающийся нулевым (NUL (0x00)) байтом // представляемым в строке специальным символом '\0'. // Нам не нужно вставлять нулевой байт в строковой литерал, @@ -187,7 +185,6 @@ int main() { // - сдвиг в знаковый бит у целого числа (int a = 1 << 32) // - сдвиг влево отрицательных чисел (int a = -1 << 2) - /////////////////////////////////////// // Структуры ветвления /////////////////////////////////////// @@ -243,7 +240,6 @@ int main() { break; } - /////////////////////////////////////// // Форматирование вывода /////////////////////////////////////// @@ -282,7 +278,6 @@ int main() { printf("%p\n", (void *)&x); // => Напечатает адрес в памяти, где лежит переменная x // (%p выводит указатель на void *) - // Для объявления указателя нужно поставить * перед именем. int *px, not_a_pointer; // px это указатель на int px = &x; // сохранит адрес x в px @@ -372,8 +367,7 @@ int main() { // Синтаксис объявления функции: // <возвращаемый тип> <имя функции>(аргументы) -int add_two_ints(int x1, int x2) -{ +int add_two_ints(int x1, int x2) { return x1 + x2; // Используйте return для возврата значения } @@ -385,8 +379,7 @@ int add_two_ints(int x1, int x2) */ // void означает, что функция ничего не возвращает -void str_reverse(char *str_in) -{ +void str_reverse(char *str_in) { char tmp; int ii = 0; size_t len = strlen(str_in); // `strlen()` является частью стандартной библиотеки @@ -417,10 +410,9 @@ struct rectangle { }; // sizeof(struct rectangle) == sizeof(int) + sizeof(int) – не всегда верно -// из-за особенностей компиляции (необычное поведение при отступах)[1]. +// из-за особенностей компиляции ([необычное поведение при отступах][1]). -void function_1() -{ +void function_1() { struct rectangle my_rec; // Доступ к структурам через точку @@ -440,15 +432,13 @@ void function_1() // Вы можете применить typedef к структуре, для удобства. typedef struct rectangle rect; -int area(rect r) -{ +int area(rect r) { return r.width * r.height; } // Если вы имеете большую структуру, можно доступаться к ней "по указателю", // чтобы избежать копирования всей структуры. -int area(const rect *r) -{ +int area(const rect *r) { return r->width * r->height; } @@ -490,4 +480,4 @@ void str_reverse_through_pointer(char *str_in) { Также не забывайте, что [Google](http://google.com) и [Яндекс](http://yandex.ru) – ваши хорошие друзья. -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file +[1]: http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file -- cgit v1.2.3 From 14d637ddfe16d37de79b6723117f286ecc3d18b8 Mon Sep 17 00:00:00 2001 From: Andrew Popov Date: Mon, 18 Nov 2013 05:14:47 +0400 Subject: [c/ru] 413 line link fix --- ru-ru/c-ru.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index 59d3c3b5..6ef1dc2f 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -410,7 +410,7 @@ struct rectangle { }; // sizeof(struct rectangle) == sizeof(int) + sizeof(int) – не всегда верно -// из-за особенностей компиляции ([необычное поведение при отступах][1]). +// из-за особенностей компиляции (необычное поведение при отступах)[1]. void function_1() { struct rectangle my_rec; @@ -480,4 +480,4 @@ void str_reverse_through_pointer(char *str_in) { Также не забывайте, что [Google](http://google.com) и [Яндекс](http://yandex.ru) – ваши хорошие друзья. -[1]: http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file -- cgit v1.2.3 From ede6d0dd99898e7cd2085ddfd726d9abf78ddd69 Mon Sep 17 00:00:00 2001 From: mvalipour Date: Mon, 18 Nov 2013 22:39:13 +0000 Subject: update css article changed the format of the article to the one suggested in #405 --- css.html.markdown | 234 +++++++++++------------------------------------------- 1 file changed, 46 insertions(+), 188 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index e421e1b1..1999480f 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -15,10 +15,18 @@ different elements on an HTML page and assign different visual properties to the Like any other language, CSS has many versions. Here we focus on CSS2.0 which is not the most recent but the most widely supported and compatible version. -## Selectors +**NOTE:** Because the outcome of CSS is some visual effects, in order to +learn it, you need try all different things in a +CSS playground like [dabblet](http://dabblet.com/). +The main focus of this article is on the syntax and some general tips. + ```css -/* let's stick to the tradition and show how comments are made first! */ +/* comments appear inside slash-asterisk, just like this line! */ + +/* #################### + ## SELECTORS + ####################*/ /* Generally, the primary statement in CSS is very simple */ selector { property: value; /* more properties...*/ } @@ -103,195 +111,47 @@ based on it's page behaviour (rather than page structure) */ /* or an input element which is focused */ :focus {} -``` - -## Properties - -```css -/*## Units -can be like : - -- 50%: in percent -- 2em: two times the current font-size -- 20px: in pixels -- 20pt: in point -- 2cm: centimeter -- 20mm: millimeter -- 2in: inches - -*/ -/* ## Colors +/* #################### + ## PROPERTIES + ####################*/ -#F6E -- can be in short hex -#F262E2 -- or in long hex format -red or tomato -- can be a named color -rgb(255, 255, 255) -- in rgb -rgb(10%, 20%, 50%) -- in rgb percent - -*/ - -/* ## Font */ -selector { - font-style: italic; /* or normal */ - font-weight: bold; /* or normal, lighter or a number between 100 and 900*/ - font-size: 2em; /* see units */ - font-family: Verdana, Arial; /* if the first one is not supported the second one is taken.*/ -} - -/* you can set all in one declaration. */ -selector { font: bold italic 12px Consolas; } - -/*## Background */ selector { - background-color: red; /* see colors */ - background-image: url(/path/cat.jpg); - background-repeat: no-repaet; /* or repeat or repeat-x or repeat-y */ - background-attachment: scroll; /* or fixed */ - background-position: 10px 20px; /* or center, top, bottom, left, right */ -} - -/* again you can set all in one declaratio */ -selector { background: red url(image.jpg) no-repeat center top fixed; } - -/*## Box model - -All elements (other than inline elements like span) follow a box model -that consists of the following components. - - --------------- - margin - --------------- - border - --------------- - padding - --------------- -| margin | border | padding | [width/height] | padding | border | margin - --------------- - padding - --------------- - border - --------------- - margin - --------------- - -of these components all except margin add to the dimension of the element. - -e.g. padding-left: 10px; width: 100px; border-left: 2px; - => effective width of the element 112px (given all -right components are zero) - -*/ -selector { - width: 100px; - height: 100px; - - padding-top:10px; - padding-bottom:10px; - padding-left:10px; - padding-right:10px; - - margin-top:10px; - margin-bottom:10px; - margin-left:10px; - margin-right:10px; - border-top:10px solid red; - border-bottom:10px solid red; - border-left:10px solid red; - border-right:10px solid red; -} - -/* again you can use shorthands - -for padding, margin and border the order is: -[top] [right] [bottom] [left]*/ -selector { - padding: 10px 8px 6px 5px; - /* same for margin and border*/ -} - -/* a shorter one! -[top and bottom] [left and right] */ -selector { - padding: 6px 5px; - /* same for margin and border*/ -} - -/* and even shorter! -[all sides] */ -selector { - padding: 6px; - /* same for margin and border*/ -} - -/* border has three components that can be specified separately */ -selector { - border-left-style: solid; /* or dotted or dashed*/ - border-left-color: red; - border-left-width: 1px; -} - -/* this breakdown can also be done when the shorthand is used. */ -selector { - border-style: solid; - /* ... */ -} - -/*## Positioning - -elements are normally following the page flow based on where in the markup they are. - -some tags like `div` or `p` are full-width and the rest are inline by default. - -but all elements can have their layout changed*/ -selelctor { - display: inline; /* inline-block, block, table-cell, et.*/ -} - -/* elements can be absolutely positioned -- which means they won't follow -the page flow and will be independently positioned on the screen. */ -selector { position:absolute; left: 200px; top:10px; /* or right:10px; bottom:10px; */ } - -/* in this case the elements top left will be alighned with the page body. - -but if you want it to be relative to an earlier parent.*/ -parent-selector { position:relative; } - -/* if you want to have the same thing but moving with scroll: */ -selector { position:fixed; left: 200px; top:10px; /* or right:10px; bottom:10px; */ } - -/* when elements appear on the same absolute position. -the latest one in the markup appears on top. - -unless...*/ -selector { z-index: 2; /* or any number higher than others' */ } - -/* if you wish your element to follow the markup layout (not absolutely positioned) -but floated to a side in it's parent:*/ -selector { float: left; /* or right */ } - -/*## Lists - -you can also control how the lists appear on the screen:*/ - -selector { - list-style-type: circle; /* disc | square | decimal | etc... */ - list-style-position: inside; /* or outside */ - list-style-image: url(path/image.jpg); + /* Units */ + width: 50%; /* in percent */ + font-size: 2em; /* times current font-size */ + width: 200px; /* in pixels */ + font-size: 20pt; /* in points */ + width: 5cm; /* in centimeters */ + width: 50mm; /* in millimeters */ + width: 5in; /* in inches */ + + /* Colors */ + background-color: #F6E /* in short hex */ + background-color: #F262E2 /* in long hex format */ + background-color: tomato /* can be a named color */ + background-color: rgb(255, 255, 255) /* in rgb */ + background-color: rgb(10%, 20%, 50%) /* in rgb percent */ + background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb */ + + /* Images */ + background-image: url(/path-to-image/image.jpg); + + /* Fonts */ + font-family: Arial; + font-family: "Courier New"; /* if name has space it appears in double-quote */ + font-family: "Courier New", Trebuchet, Arial; /* if first one was not found + browser uses the second font, and so forth */ } -/*as always this can be shorthanded */ - -selector { list-tyle: disc inside url(...); } - - ``` ## Usage Save any CSS you want in a file with extension `.css`. -```markup +```xml @@ -332,25 +192,23 @@ p {} p { property: value !important; } ``` - -and the following markdown: -```markdown +and the following markup: +```xml

``` The precedence of style is as followed: -Note that the precedence is for each **property** in the style and -not for the entire block. +Remember, the precedence is for each **property**, not for the entire block. * `E` has the highest precedence because of the keyword `!important`. It is recommended to avoid this unless it is strictly necessary to use. -* `F` is the next because it is inline style. -* `A` is the next because is more "specific" that anything else. +* `F` is next, because it is inline style. +* `A` is next, because it is more "specific" than anything else. more specific = more specifiers. here 3 specifiers: 1 tagname `p` + class name `class1` + 1 attribute `attr='value'` -* `C` is the next. although it has the same specificness as `B` - but it appears after that. +* `C` is next. although it has the same specificness as `B` + but it appears last. * Then is `B` * and lastly is `D`. -- cgit v1.2.3 From fbb7ea38a1530d2e4cca6bce7f3db6b392e90ce1 Mon Sep 17 00:00:00 2001 From: mvalipour Date: Mon, 18 Nov 2013 22:58:27 +0000 Subject: Fix while loop iterator incorrect count The while loop is repeated 100 times not 99 times. 0~99 inclusive. --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 87c2f704..dad0c26b 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -233,7 +233,7 @@ on a new line! ""Wow!"", the masses cried"; int fooWhile = 0; while (fooWhile < 100) { - //Iterated 99 times, fooWhile 0->99 + //Iterated 100 times, fooWhile 0->99 fooWhile++; } -- cgit v1.2.3 From f5c9b8037788a6871e1193b48442f3a6d0e3f561 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Migda=C5=82?= Date: Tue, 19 Nov 2013 17:17:28 +0100 Subject: added an online intro into Python for scientists --- python.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/python.html.markdown b/python.html.markdown index 50c4e63f..22d236ac 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -484,6 +484,7 @@ dir(math) * [The Official Docs](http://docs.python.org/2.6/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) ### Dead Tree -- cgit v1.2.3 From 9a60d0a6e4fa2aba9d1a1cf2a834ae82b2a18aea Mon Sep 17 00:00:00 2001 From: Jake Romer Date: Wed, 20 Nov 2013 05:38:46 -0500 Subject: Corrects Array#[,] entry The #[i,l] method returns a subarray starting at index i and continuing for length l. [source](http://ruby-doc.org/core-1.9.3/Array.html#method-i-5B-5D) --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 8723e18f..bf4cb229 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -139,8 +139,8 @@ array.[] 12 #=> nil # From the end array[-1] #=> 5 -# With a start and end index -array[2, 4] #=> [3, 4, 5] +# With a start index and length +array[2, 3] #=> [3, 4, 5] # Or with a range array[1..3] #=> [2, 3, 4] -- cgit v1.2.3 From 85b5920550b870e2c2e3f12be27a731326da7b2a Mon Sep 17 00:00:00 2001 From: xuchunyang Date: Wed, 20 Nov 2013 23:42:29 +0800 Subject: [bash/zh-cn] chinese bash translation --- zh-cn/bash-cn.html.markdown | 148 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 zh-cn/bash-cn.html.markdown diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown new file mode 100644 index 00000000..beb20479 --- /dev/null +++ b/zh-cn/bash-cn.html.markdown @@ -0,0 +1,148 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] +translators: + - ["Chunyang Xu", "https://github.com/XuChunyang"] +filename: LearnBash-cn.sh +lang: zh-cn +--- + +Bash 是一个为GNU计划编写的Unix shell,是 Linux 和 Mac OS X 下的默认shell。 +以下绝大多数例子可以作为脚本的一部分也可直接在 shell 下执行。 + +[更多信息](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/sh +# 脚本的第一行叫 shebang,用来告知系统如何执行该脚本: +# 参见: http://en.wikipedia.org/wiki/Shebang_(Unix) +# 相信你已经明白了,注释以 # 开头,shebang 也是注释。 + +# 显示 “Hello world!” +echo Hello, world! + +# 每一句指令以换行或分号隔开: +echo 'This is the first line'; echo 'This is the second line' + +# 声明一个变量: +VARIABLE="Some string" + +# 下面是错误的做法: +VARIABLE = "Some string" +# Bash 会把 VARIABLE 当做一个指令,由于找不到该指令,因此这里会报错。 + + +# 使用变量: +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' +# 当你分配 (assign) 、导出 (export),或者以其他方式使用变量时,变量名前不加 $。 +# 如果要使用变量的值, 则要加 $。 +# 注意: ' (单引号) 不会展开变量(即会屏蔽掉变量)。 + + +# 在变量内部进行字符串代换 +echo ${VARIABLE/Some/A} +# 会把 VARIABLE 中首次出现的 "some" 替换成 “A”。 + +# 内置变量: +# 下面的内置变量很有用 +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..." + +# 获取输入: +echo "What's your name?" +read NAME # Note that we didn't need to declare new variable +echo Hello, $NAME! + +# 一般的 if 结构看起来像这样: +# 'man test' 查看更多的信息 +if [ $NAME -ne $USER ] +then + echo "Your name is you username" +else + echo "Your name isn't you username" +fi + +# 根据上一个指令执行结果决定是否执行下一个指令 +echo "Always executed" || echo "Only executed if first command fail" +echo "Always executed" && echo "Only executed if first command does NOT fail" + +# 表达式的格式如下: +echo $(( 10 + 5 )) + +# 与其他编程语言不同的是,bash 运行时依赖上下文。比如,使用 ls 时,列出当前目录。 +ls + +# 指令可以带有选项: +ls -l # Lists every file and directory on a separate line + +# 前一个指令的输出可以当作后一个指令的输入。grep 可以查找字符串。 +# 下面的指令可以,列出当前目录下所有的 txt 文件: +ls -l | grep "\.txt" + +# 重定向可以到输出,输入和错误输出。 +python2 hello.py < "input.in" +python2 hello.py > "output.out" +python2 hello.py 2> "error.err" +# > 会覆盖已存在的文件, >> 会以累加的方式输出文件中。 + +# 指令被 $( ) 嵌套在另一个指令内部: +# 以下的指令会打印当前目录下的目录和文件总数 +echo "There are $(ls | wc -l) items here." + +# Bash 的 case 语句与 Java 和 C++ 中的 switch 语句类似: +case "$VARIABLE" in + #List patterns for the conditions you want to meet + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# 循环遍历给定的参数序列: +# 变量$VARIABLE 的值会被打印 3 次。 +# 注意 ` ` 和 $( ) 等价。seq 返回长度为 3 的数组。 +for VARIABLE in `seq 3` +do + echo "$VARIABLE" +done + +# 你也可以使用函数 +# 定义函数: +function foo () +{ + echo "Arguments work just like script arguments: $@" + echo "And: $1 $2..." + echo "This is a function" + return 0 +} + +# 更简单的方法 +bar () +{ + echo "Another way to declare functions!" + return 0 +} + +# 调用函数 +foo "My name is" $NAME + +# 有很多有用的指令需要学习: +tail -n 10 file.txt +# 打印 file.txt 的最后 10 行 +head -n 10 file.txt +# 打印 file.txt 的前 10 行 +sort file.txt +# 将 file.txt 按行排序 +uniq -d file.txt +# 报告或忽略重复的行,用选项 -d 打印重复的行 +cut -d ',' -f 1 file.txt +# 仅打印字符 ',' 之前内容(以行为单位) +``` -- cgit v1.2.3 From 22da248750815552de41367700a99eac6342e23f Mon Sep 17 00:00:00 2001 From: xuchunyang Date: Thu, 21 Nov 2013 21:52:41 +0800 Subject: [bash/zh-cn] Better translation --- zh-cn/bash-cn.html.markdown | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index beb20479..e3eed3a6 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -11,8 +11,8 @@ filename: LearnBash-cn.sh lang: zh-cn --- -Bash 是一个为GNU计划编写的Unix shell,是 Linux 和 Mac OS X 下的默认shell。 -以下绝大多数例子可以作为脚本的一部分也可直接在 shell 下执行。 +Bash 是一个为 GNU 计划编写的 Unix shell,是 Linux 和 Mac OS X 下的默认 shell。 +以下大多数例子可以作为脚本的一部分运行也可直接在 shell 下交互执行。 [更多信息](http://www.gnu.org/software/bash/manual/bashref.html) @@ -20,7 +20,7 @@ Bash 是一个为GNU计划编写的Unix shell,是 Linux 和 Mac OS X 下的默 #!/bin/sh # 脚本的第一行叫 shebang,用来告知系统如何执行该脚本: # 参见: http://en.wikipedia.org/wiki/Shebang_(Unix) -# 相信你已经明白了,注释以 # 开头,shebang 也是注释。 +# 如你所见,注释以 # 开头,shebang 也是注释。 # 显示 “Hello world!” echo Hello, world! @@ -57,13 +57,13 @@ echo "Number of arguments: $#" echo "Scripts arguments: $@" echo "Scripts arguments separeted in different variables: $1 $2..." -# 获取输入: +# 读取输入: echo "What's your name?" -read NAME # Note that we didn't need to declare new variable +read NAME # 这里不需要声明新变量 echo Hello, $NAME! -# 一般的 if 结构看起来像这样: -# 'man test' 查看更多的信息 +# 通常的 if 结构看起来像这样: +# 'man test' 可查看更多的信息 if [ $NAME -ne $USER ] then echo "Your name is you username" @@ -82,10 +82,10 @@ echo $(( 10 + 5 )) ls # 指令可以带有选项: -ls -l # Lists every file and directory on a separate line +ls -l # 列出文件和目录的详细信息 -# 前一个指令的输出可以当作后一个指令的输入。grep 可以查找字符串。 -# 下面的指令可以,列出当前目录下所有的 txt 文件: +# 前一个指令的输出可以当作后一个指令的输入。grep 用来匹配字符串。 +# 用下面的指令列出当前目录下所有的 txt 文件: ls -l | grep "\.txt" # 重定向可以到输出,输入和错误输出。 @@ -94,13 +94,13 @@ python2 hello.py > "output.out" python2 hello.py 2> "error.err" # > 会覆盖已存在的文件, >> 会以累加的方式输出文件中。 -# 指令被 $( ) 嵌套在另一个指令内部: +# 一个指令可用 $( ) 嵌套在另一个指令内部: # 以下的指令会打印当前目录下的目录和文件总数 echo "There are $(ls | wc -l) items here." # Bash 的 case 语句与 Java 和 C++ 中的 switch 语句类似: case "$VARIABLE" in - #List patterns for the conditions you want to meet + # 列出需要匹配的字符串 0) echo "There is a zero.";; 1) echo "There is a one.";; *) echo "It is not null.";; @@ -144,5 +144,5 @@ sort file.txt uniq -d file.txt # 报告或忽略重复的行,用选项 -d 打印重复的行 cut -d ',' -f 1 file.txt -# 仅打印字符 ',' 之前内容(以行为单位) +# 打印每行中 ',' 之前内容 ``` -- cgit v1.2.3 From cc5799a17e6e9e6422d695150cd3cea94c57fb65 Mon Sep 17 00:00:00 2001 From: Andrew Popov Date: Fri, 22 Nov 2013 04:40:12 +0400 Subject: [objc/ru] translate objc man to ru --- ru-ru/objective-c-ru.html.markdown | 319 +++++++++++++++++++++++++++++++++++++ 1 file changed, 319 insertions(+) create mode 100644 ru-ru/objective-c-ru.html.markdown diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown new file mode 100644 index 00000000..83be5d7a --- /dev/null +++ b/ru-ru/objective-c-ru.html.markdown @@ -0,0 +1,319 @@ +language: Objective-C +filename: LearnObjectiveC.m +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] +translators: + - ["Evlogy Sutormin", "http://evlogii.com"] +lang: ru-ru +--- + +Objective-C — компилируемый объектно-ориентированный язык программирования, используемый корпорацией Apple, +построенный на основе языка Си и парадигм Smalltalk. +В частности, объектная модель построена в стиле Smalltalk — то есть объектам посылаются сообщения. + +```cpp + +// Однострочный комментарий + +/* +Многострочный +комментарий +*/ + +// Импорт файлов фреймворка Foundation с помощью #import +#import +#import "MyClass.h" + +// Точка входа в программу это функция main, +// которая возвращает целый тип integer +int main (int argc, const char * argv[]) +{ + // Создание autorelease pool для управления памятью + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + // Используйте NSLog для печати в консоль + NSLog(@"Hello World!"); // Напечатает строку "Hello World!" + + /////////////////////////////////////// + // Типы и переменные + /////////////////////////////////////// + + // Простое объявление + int myPrimitive1 = 1; + long myPrimitive2 = 234554664565; + + // Помещайте * в начало названия объекта для строго типизированного объявления + MyClass *myObject1 = nil; // Строгая типизация + id myObject2 = nil; // Слабая типизация + + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // напечатает "(null) and (null)" + // %@ – это объект + // 'description' это общий для всех объектов метод вывода данных + + // Строка + NSString *worldString = @"World"; + NSLog(@"Hello %@!", worldString); // напечатает "Hello World!" + + // Символьные литералы + NSNumber *theLetterZNumber = @'Z'; + char theLetterZ = [theLetterZNumber charValue]; + NSLog(@"%c", theLetterZ); + + // Целочисленный литералы + 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); + + // Вещественный литерал + NSNumber *piFloatNumber = @3.141592654F; + float piFloat = [piFloatNumber floatValue]; + NSLog(@"%f", piFloat); + + NSNumber *piDoubleNumber = @3.1415926535; + double piDouble = [piDoubleNumber doubleValue]; + NSLog(@"%f", piDouble); + + // BOOL (булевый) литерал + NSNumber *yesNumber = @YES; + NSNumber *noNumber = @NO; + + // Массив + NSArray *anArray = @[@1, @2, @3, @4]; + NSNumber *thirdNumber = anArray[2]; + NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" + + // Словарь + NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSObject *valueObject = aDictionary[@"A Key"]; + NSLog(@"Object = %@", valueObject); // Напечатает "Object = (null)" + + /////////////////////////////////////// + // Операторы + /////////////////////////////////////// + + // Операторы работают также как в Си. + // Например: + 2 + 5; // => 7 + 4.2f + 5.1f; // => 9.3f + 3 == 2; // => 0 (НЕТ) + 3 != 2; // => 1 (ДА) + 1 && 1; // => 1 (логическое И) + 0 || 1; // => 1 (логическое ИЛИ) + ~0x0F; // => 0xF0 (побитовое отрицание) + 0x0F & 0xF0; // => 0x00 (побитовое И) + 0x01 << 1; // => 0x02 (побитовый сдвиг влево (на 1)) + + /////////////////////////////////////// + // Структуры ветвления + /////////////////////////////////////// + + // Условный оператор + if (NO) + { + NSLog(@"I am never run"); + } else if (0) + { + NSLog(@"I am also never run"); + } else + { + NSLog(@"I print"); + } + + // Ветвление с множественным выбором + switch (2) + { + case 0: + { + NSLog(@"I am never run"); + } break; + case 1: + { + NSLog(@"I am also never run"); + } break; + default: + { + NSLog(@"I print"); + } break; + } + + // Цикл с предусловием + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++ инкрементирует ii после передачи значения + } // => напечатает "0," + // "1," + // "2," + // "3," + + // Цикл со счётчиком + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", jj); + } // => напечатает "0," + // "1," + // "2," + // "3," + + // // Цикл просмотра + NSArray *values = @[@0, @1, @2, @3]; + for (NSNumber *value in values) + { + NSLog(@"%@,", value); + } // => напечатает "0," + // "1," + // "2," + // "3," + + // Обработка исключений + @try + { + // Ваше исключение здесь + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"File Not Found on System" userInfo:nil]; + } @catch (NSException * e) + { + NSLog(@"Exception: %@", e); + } @finally + { + NSLog(@"Finally"); + } // => напечатает "Exception: File Not Found on System" + // "Finally" + + /////////////////////////////////////// + // Объекты + /////////////////////////////////////// + + // Создание объектов через выделение памяти и инициализацию. + // Объект не является полнофункциональным пока обе части не выполнятся. + MyClass *myObject = [[MyClass alloc] init]; + + // В Objective-C можель ООП базируется на передаче сообщений. + // В Objective-C Вы не просто вызваете метод; вы посылаете сообщение. + [myObject instanceMethodWithParameter:@"Steve Jobs"]; + + // Очищайте память, перед завершением работы программы. + [pool drain]; + + // Конец программы. + return 0; +} + +/////////////////////////////////////// +// Классы и функции +/////////////////////////////////////// + +// Объявляйте свой класс в файле МойКласс.h +// Синтаксис объявления: +// @interface ИмяКласса : ИмяКлассаРодителя <ИмплементируемыеПротоколы> +// { +// Объявление переменных; +// } +// -/+ (тип) Объявление метода(ов). +// @end + + +@interface MyClass : NSObject +{ + int count; + id data; + NSString *name; +} +// При объявлении свойств сразу генерируются геттер и сеттер +@property int count; +@property (copy) NSString *name; // Скопировать объект в ходе присвоения. +@property (readonly) id data; // Генерация только геттера + +// Методы ++/- (return type)methodSignature:(Parameter Type *)parameterName; + +// + для методов класса ++ (NSString *)classMethod; + +// - для метода объекта +- (NSString *)instanceMethodWithParameter:(NSString *)string; +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; + +@end + +// Имплементируйте методы в файле МойКласс.m: + +@implementation MyClass + +// Вызывается при высвобождении памяти под объектом +- (void)dealloc +{ +} + +// Конструкторы – это способ осздания объектов класса. +// Это обычный конструктор вызываемый при создании объекта клсааа. +- (id)init +{ + if ((self = [super init])) + { + self.count = 1; + } + return self; +} + ++ (NSString *)classMethod +{ + return [[self alloc] init]; +} + +- (NSString *)instanceMethodWithParameter:(NSString *)string +{ + return @"New string"; +} + +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number +{ + return @42; +} + +// Методы объявленные в МyProtocol (см. далее) +- (void)myProtocolMethod +{ + // имплементация +} + +@end + +/* + * Протокол объявляет методы которые должны быть имплементированы + * Протокол не является классом. Он просто определяет интерфейс, + * который должен быть имплементирован. + */ + +@protocol MyProtocol + - (void)myProtocolMethod; +@end + + +``` +## На почитать + +[Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) + +[Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) + +[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) + +[iOS разработчик: Обзор книг для новичка](http://habrahabr.ru/post/166213/) + +[Хочешь быть iOS разработчиком? Будь им!](http://www.pvsm.ru/ios/12662/print/) -- cgit v1.2.3 From 79eda34b3398f51f8c029ef2807845379583b009 Mon Sep 17 00:00:00 2001 From: Andrew Popov Date: Fri, 22 Nov 2013 04:40:34 +0400 Subject: [c/ru] some fixes --- ru-ru/c-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index 6ef1dc2f..874e0821 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -425,7 +425,7 @@ void function_1() { // Можно доступаться к структуре и через указатель (*my_rec_ptr).width = 30; - // ... или ещё лучше: успользуйте -> оператор для лучшей читабельночти + // ... или ещё лучше: используйте оператор -> для лучшей читабельночти my_rec_ptr->height = 10; // то же что и "(*my_rec_ptr).height = 10;" } -- cgit v1.2.3 From b2109ca54b5fb3bcedd521dada5d45273997345a Mon Sep 17 00:00:00 2001 From: Andrew Popov Date: Fri, 22 Nov 2013 04:47:43 +0400 Subject: [go/ru] delete name and category from header --- ru-ru/go-ru.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 8098f601..27b5d894 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -1,6 +1,4 @@ --- -name: Go -category: language language: Go filename: learngo-ru.go contributors: -- cgit v1.2.3 From aafbef6665728fba6965042919f72332f1dfefd2 Mon Sep 17 00:00:00 2001 From: Andrew Popov Date: Fri, 22 Nov 2013 18:17:39 +0400 Subject: some improves --- ru-ru/objective-c-ru.html.markdown | 3 --- 1 file changed, 3 deletions(-) diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown index 83be5d7a..af454074 100644 --- a/ru-ru/objective-c-ru.html.markdown +++ b/ru-ru/objective-c-ru.html.markdown @@ -13,7 +13,6 @@ Objective-C — компилируемый объектно-ориентиров В частности, объектная модель построена в стиле Smalltalk — то есть объектам посылаются сообщения. ```cpp - // Однострочный комментарий /* @@ -303,8 +302,6 @@ int main (int argc, const char * argv[]) @protocol MyProtocol - (void)myProtocolMethod; @end - - ``` ## На почитать -- cgit v1.2.3 From 19a37682e37e8223d92139127074f5637c4f311f Mon Sep 17 00:00:00 2001 From: Andrew Popov Date: Fri, 22 Nov 2013 18:20:35 +0400 Subject: fix top table --- ru-ru/objective-c-ru.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown index af454074..72e3b9e0 100644 --- a/ru-ru/objective-c-ru.html.markdown +++ b/ru-ru/objective-c-ru.html.markdown @@ -1,3 +1,4 @@ +--- language: Objective-C filename: LearnObjectiveC.m contributors: -- cgit v1.2.3 From 5be296e5b2b0f6ef9355b9d1cf9d0a7947a67094 Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Sat, 23 Nov 2013 17:01:14 -0200 Subject: Add translate until list comprehensions I'm translating haskell guide from Adit Bhargava (learnxinyminutes contribuitor) but adding a few more stuff about haskell --- pt-br/haskell-pt.html.markdown | 439 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 439 insertions(+) create mode 100644 pt-br/haskell-pt.html.markdown diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown new file mode 100644 index 00000000..ca0d847c --- /dev/null +++ b/pt-br/haskell-pt.html.markdown @@ -0,0 +1,439 @@ +--- +linguagem: haskell +tradutor/contribuidor: + - ["Lucas Tonussi", "http://www.inf.ufsc.br/~tonussi/"] +--- + +As linguagens funcionais são linguagens de programação com base em avaliação +de funções matemáticas (expressões), evitando-se o conceito de mudança de +estado com alteração de dados. Neste aspecto, este paradigma é oposto ao +paradigma imperativo que se baseia em alterações de estados. + +A programação funcional começou no cálculo lambda, que foi base teórica para +o desenvolvimento deste paradigma de programação. + + +```haskell +-- Para comentar a linha basta dois traços seguidos. + +{- Abre chaves traço e traço fecha chaves cria um campo + para comentário em múltiplas linhas. +-} + +---------------------------------------------------- +-- 1. Tipos Primitivos de Dados e Operadores +---------------------------------------------------- + +-- Numerais + +0 -- 3 +1 -- 1 +2 -- 2 ... + +-- Alguns Operadores Fundamentais + +7 + 7 -- 7 mais 7 +7 - 7 -- 7 menos 7 +7 * 7 -- 7 vezes 7 +7 / 7 -- 7 dividido por 7 + +-- Divisões não são inteiras, são fracionádas por padrão da linguagem +28736 / 82374 -- 0.3488479374559934 + + +-- Divisão inteira +82374 `div` 28736 -- 2 + +-- Divisão modular +82374 `mod` 28736 -- 24902 + +-- Booleanos como tipo primitivo de dado +True -- Verdadeiro +False -- Falso + +-- Operadores unitário +not True -- Nega uma verdade +not False -- Nega uma falácia + + +-- Operadores binários +7 == 7 -- 7 é igual a 7 ? +7 /= 7 -- 7 é diferente de 7 ? +7 < 7 -- 7 é menor que 7 ? +7 > 7 -- 7 é maior que 7 ? + + +{- Haskell é uma linguagem que tem uma sintáxe bastante familiar na + matemática, por exemplo em chamadas de funções você tem: + + NomeFunção ArgumentoA ArgumentoB ArgumentoC ... +-} + +-- Strings e Caractéres +"Texto entre abre áspas e fecha áspas define uma string" +'a' -- Caractere +'A' -- Caractere + +'Strings entre aspas simples sobe um erro' -- Erro léxico! + +-- Concatenação de Strings +"StringA" ++ "StringB" -- "StringAStringB" + +-- Você pode listar uma string pelos seus caractéres +"AbBbbcAbbcbBbcbcb" !! 0 -- 'A' +"AbBbbcAbbcbBbcbcb" !! 1 -- 'b' +"AbBbbcAbbcbBbcbcb" !! 2 -- 'B' + +---------------------------------------------------- +-- Listas e Túplas +---------------------------------------------------- + +-- A construção de uma lista precisa ser de elementos homogêneos +[1, 2, 3, 4, 5] -- Homogênea +[1, a, 2, b, 3] -- Heterogênea (Erro) + +-- Haskell permite que você crie sequências +[1..5] + +{- Haskell usa avaliação preguiçosa o que + Permite você ter listas "infinitas" +-} + +-- Uma lista "infinita" cuja razão é 1 +[1..] + +-- O 777º elemento de uma lista de razão 1 +[1..] !! 777 -- 778 + +-- União de listas [lista_0] ++ [lista_1] ++ [lista_i] +[1..5] ++ [6..10] ++ [1..4] -- [1,2,3,4,5,6,7,8,9,10,1,2,3,4] + +-- Adiciona um cabeçalho a sua lista e desloca a cauda +0:[1..10] -- [0, 1, 2, 3, 4, 5] +'a':['a'..'e'] -- "aabcde" + +-- Indexação em uma lista +[0..] !! 5 -- 5 + +-- Operadores de Listas usuais +head ['a'..'e'] -- Qual o cabeçalho da lista ? +tail ['a'..'e'] -- Qual a cauda da lista ? +init ['a'..'e'] -- Qual a lista menos o último elemento ? +last ['a'..'e'] -- Qual o último elemento ? + +-- list comprehensions +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- with a conditional +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Every element in a tuple can be a different type, but a tuple has a +-- fixed length. +-- A tuple: +("haskell", 1) + +-- accessing elements of a tuple +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Functions +---------------------------------------------------- +-- A simple function that takes two variables +add a b = a + b + +-- Note that if you are using ghci (the Haskell interpreter) +-- You'll need to use `let`, i.e. +-- let add a b = a + b + +-- Using the function +add 1 2 -- 3 + +-- You can also put the function name between the two arguments +-- with backticks: +1 `add` 2 -- 3 + +-- You can also define functions that have no letters! This lets +-- you define your own operators! Here's an operator that does +-- integer division +(//) a b = a `div` b +35 // 4 -- 8 + +-- Guards: an easy way to do branching in functions +fib x + | x < 2 = x + | otherwise = fib (x - 1) + fib (x - 2) + +-- Pattern matching is similar. Here we have given three different +-- definitions for fib. Haskell will automatically call the first +-- function that matches the pattern of the value. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Pattern matching on tuples: +foo (x, y) = (x + 1, y + 2) + +-- Pattern matching on lists. Here `x` is the first element +-- in the list, and `xs` is the rest of the list. We can write +-- our own map function: +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Anonymous functions are created with a backslash followed by +-- all the arguments. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- using fold (called `inject` in some languages) with an anonymous +-- function. foldl1 means fold left, and use the first value in the +-- list as the initial value for the accumulator. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. More functions +---------------------------------------------------- + +-- currying: if you don't pass in all the arguments to a function, +-- it gets "curried". That means it returns a function that takes the +-- rest of the arguments. + +add a b = a + b +foo = add 10 -- foo is now a function that takes a number and adds 10 to it +foo 5 -- 15 + +-- Another way to write the same thing +foo = (+10) +foo 5 -- 15 + +-- function composition +-- the (.) function chains functions together. +-- For example, here foo is a function that takes a value. It adds 10 to it, +-- multiplies the result of that by 5, and then returns the final value. +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +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 `.` and `$` to get rid of a lot +-- of parentheses: + +-- before +(even (fib 7)) -- true + +-- after +even . fib $ 7 -- true + +---------------------------------------------------- +-- 5. Type signatures +---------------------------------------------------- + +-- Haskell has a very strong type system, and everything has a type signature. + +-- Some basic types: +5 :: Integer +"hello" :: String +True :: Bool + +-- Functions have types too. +-- `not` takes a boolean and returns a boolean: +-- not :: Bool -> Bool + +-- Here's a function that takes two arguments: +-- add :: Integer -> Integer -> Integer + +-- When you define a value, it's good practice to write its type above it: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Control Flow and If Statements +---------------------------------------------------- + +-- if statements +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- if statements can be on multiple lines too, indentation is important +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- case statements: Here's how you could parse command line arguments +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- Haskell doesn't have loops because it uses recursion instead. +-- map applies a function over every element in an array + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- you can make a for function using map +for array func = map func array + +-- and then use it +for [0..5] $ \i -> show i + +-- we could've written that like this too: +for [0..5] show + +-- You can use foldl or foldr to reduce a list +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- This is the same as +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl is left-handed, foldr is right- +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- This is now the same as +(2 * 3 + (2 * 2 + (2 * 1 + 4))) + +---------------------------------------------------- +-- 7. Data Types +---------------------------------------------------- + +-- Here's how you make your own data type in Haskell + +data Color = Red | Blue | Green + +-- Now you can use it in a function: + + +say :: Color -> String +say Red = "You are Red!" +say Blue = "You are Blue!" +say Green = "You are Green!" + +-- Your data types can have parameters too: + +data Maybe a = Nothing | Just a + +-- These are all of type Maybe +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- While IO can't be explained fully without explaining monads, +-- it is not hard to explain enough to get going. + +-- When a Haskell program is executed, the function `main` is +-- called. It must return a value of type `IO ()`. For example: + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- putStrLn has type String -> IO () + +-- It is easiest to do IO if you can implement your program as +-- a function from String to String. The function +-- interact :: (String -> String) -> IO () +-- inputs some text, runs a function on it, and prints out the +-- output. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- You can think of a value of type `IO ()` as representing a +-- sequence of actions for the computer to do, much like a +-- computer program written in an imperative language. We can use +-- the `do` notation to chain actions together. For example: + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + 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 +-- one line of input. + +-- The code in `sayHello` will never be executed, however. The only +-- action that ever gets executed is the value of `main`. +-- To run `sayHello` comment out the above definition of `main` +-- and replace it with: +-- main = sayHello + +-- Let's understand better how the function `getLine` we just +-- used works. Its type is: +-- getLine :: IO String +-- You can think of a value of type `IO a` as representing a +-- computer program that will generate a value of type `a` +-- when executed (in addition to anything else it does). We can +-- store and reuse this value using `<-`. We can also +-- make our own action of type `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 + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- We can use this just like we used `getLine`: + +main'' = do + putStrLn "I will echo two lines!" + result <- action + putStrLn result + putStrLn "This was all, folks!" + +-- The type `IO` is an example of a "monad". The way Haskell uses a monad to +-- do IO allows it to be a purely functional language. Any function that +-- interacts with the outside world (i.e. does IO) gets marked as `IO` in its +-- type signature. This lets us reason about what functions are "pure" (don't +-- interact with the outside world or modify state) and what functions aren't. + +-- This is a powerful feature, because it's easy to run pure functions +-- concurrently; so, concurrency in Haskell is very easy. + + +---------------------------------------------------- +-- 9. The Haskell REPL +---------------------------------------------------- + +-- Start the repl by typing `ghci`. +-- Now you can type in Haskell code. Any new values +-- need to be created with `let`: + +let foo = 5 + +-- You can see the type of any value with `:t`: + +>:t foo +foo :: Integer + +-- You can also run any action of type `IO ()` + +> sayHello +What is your name? +Friend! +Hello, Friend! + +``` + +There's a lot more to Haskell, including typeclasses and monads. These are the big ideas that make Haskell such fun to code in. I'll leave you with one final Haskell example: an implementation of quicksort in Haskell: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell is easy to install. Get it [here](http://www.haskell.org/platform/). + +You can find a much gentler introduction from the excellent +[Learn you a Haskell](http://learnyouahaskell.com/) or +[Real World Haskell](http://book.realworldhaskell.org/). -- cgit v1.2.3 From 38de481179484d597d44fa934f87a5f21ebfaa6c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 23 Nov 2013 22:40:52 -0600 Subject: Add variety to function prototypes. --- c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index ee35cdd2..b4a874d3 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -38,8 +38,8 @@ enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; // Declare function signatures in advance in a .h file, or at the top of // your .c file. -void function_1(); -void function_2(); +void function_1(char s[]); +int function_2(void); // Must declare a 'function prototype' before main() when functions occur after // your main() function. -- cgit v1.2.3 From c8c937ef308e205b632bd709ce7fdb9761fc4b74 Mon Sep 17 00:00:00 2001 From: lyuehh Date: Sun, 24 Nov 2013 22:47:31 +0800 Subject: add Chinese translate of brainfuck --- zh-cn/brainfuck-cn.html.markdown | 70 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 zh-cn/brainfuck-cn.html.markdown diff --git a/zh-cn/brainfuck-cn.html.markdown b/zh-cn/brainfuck-cn.html.markdown new file mode 100644 index 00000000..a6f3fa09 --- /dev/null +++ b/zh-cn/brainfuck-cn.html.markdown @@ -0,0 +1,70 @@ +--- +language: brainfuck +lang: zh-cn +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["lyuehh", "https://github.com/lyuehh"] +--- + +Brainfuck 是一个极小的只有8个指令的图灵完全的编程语言。 + +``` +除"><+-.,[]"之外的的任何字符都会被忽略 (不包含双引号)。 + +Brainfuck 包含一个有30,000个单元为0的数组,和 +一个数据指针指向当前的单元。 + +8个指令如下: ++ : 指针指向的单元的值加1 +- : 指针指向的单元的值减1 +> : 将指针移动到下一个单元(右边的元素) +< : 将指针移动到上一个单元(左边的元素) +. : 打印当前单元的内容的ASCII值 (比如 65 = 'A'). +, : 读取一个字符到当前的单元 +[ : 如果当前单元的值是0,则向后调转到对应的]处 +] : 如果当前单元的值不是0,则向前跳转到对应的[处 + +[ 和 ] 组成了一个while循环。很明显,它们必须配对。 + +让我们看一些基本的brainfuck 程序。 + +++++++ [ > ++++++++++ < - ] > +++++ . + +这个程序打印字母'A'。首先,它把 #1 增加到6,使用它来作为循环条件, +然后,进入循环,将指针移动到 #2 ,将 #2 的值增加到10,然后 +移动回 #1,将单元 #1 的值减1,然后继续。循环共进行了6次。 + +这时,我们在 #1,它的值为0,#2 的值为60,我们移动到 +#2,将 #2 的内容加上5,然后将 #2 的内容打印出来,65在 +ASCII中表示'A', 所以'A'就会被打印出来。 + + +, [ > + < - ] > . + +这个程序从用户的输入中读取一个字符,然后把它复制到 #1。 +然后我们开始一个循环,移动到 #2,将 #2 的值加1,再移动回 #1,将 #1 +的值减1,直到 #1的值为0,这样 #2 里就保存了 #1 的旧值,循环结束时我们 +在 #1,这时我们移动到 #2,然后把字符以ASCII打印出来。 + +而且要记住的一点就是,空格在这里只是为了可读性,你可以将他们写成这样: + +,[>+<-]>. + +试着思考一下这段程序是干什么的: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +这段程序从输入接收2个参数,然后将他们相乘。 + +先读取2个输入,然后开始外层循环,以 #1 作为终止条件,然后将指针移动到 +#2,然后开始 #2 的内层循环,将 #3 加1。但是这里有一个小问题,在内层 +循环结束的时候,#2 的值是0了,那么下次执行外层循环的时候,就有问题了。 +为了解决这个问题,我们可以增加 #4 的值,然后把 #4 的值复制到 #2, +最后结果就保存在 #3 中了。 +``` +好了这就是brainfuck了。也没那么难,是吧?为了好玩,你可以写你自己的 +brainfuck程序,或者用其他语言写一个brainfuck的解释器,解释器非常容易 +实现,但是如果你是一个自虐狂的话,你可以尝试用brainfuck写一个brainfuk的 +解释器。 -- cgit v1.2.3 From e63232d2de1e2058dd381fe1094c7f775f2e3eb8 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 24 Nov 2013 14:17:32 -0600 Subject: Add static description to C. --- c.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index b4a874d3..7b95c969 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -469,6 +469,13 @@ void testFunc() { extern int i; //i here is now using external variable i } +//if external variable should only be visible to functions in the source file +// they are declared in, use static: +static int i = 0; //other source files using testFunc() cannot access variable i +void testFunc() { + extern int i; +} + /* char c[] = "This is a test."; str_reverse(c); -- cgit v1.2.3 From af9cc6e9b9748e43cb1c02013fe92465c3455503 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 24 Nov 2013 14:25:30 -0600 Subject: Edit static description wording. Add note about private functions. --- c.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 7b95c969..ab09a4a2 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -469,12 +469,12 @@ void testFunc() { extern int i; //i here is now using external variable i } -//if external variable should only be visible to functions in the source file -// they are declared in, use static: -static int i = 0; //other source files using testFunc() cannot access variable i +//make external variables private to source file with static: +static int i = 0; //other files using testFunc() cannot access variable i void testFunc() { extern int i; } +//**You may also declare functions as static to make them private** /* char c[] = "This is a test."; -- cgit v1.2.3 From bb4f644a19a086c3c6b32891a7240cc140b379f4 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 24 Nov 2013 15:01:24 -0600 Subject: Fix #define as it does not use = sign. --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index ab09a4a2..d8eccd78 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -21,7 +21,7 @@ Multi-line comments look like this. They work in C89 as well. */ // Constants: #define (no semicolon at end) -#define DAYS_IN_YEAR = 365 +#define DAYS_IN_YEAR 365 //enumeration constants are also ways to declare constants. enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; -- cgit v1.2.3 From 5c7f6d70b9477fcd4fe64460704d7dcf48799f98 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 24 Nov 2013 16:58:21 -0600 Subject: Remove bad description of function prototypes. --- c.html.markdown | 6 ------ 1 file changed, 6 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index d8eccd78..d029a00f 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -420,12 +420,6 @@ int add_two_ints(int x1, int x2) return x1 + x2; // Use return to return a value } -//if function takes no parameters, do: -int getInt(void); for function prototype -// and for the function declaration: -int getInt(void) {} -// (this is to keep compatibility with older versions of C). - /* Functions are call by value. So when a function is called, the arguments passed to the function are copies of original arguments (except arrays). Anything you -- cgit v1.2.3 From 3d29112cab44b33cacf8b231968744862554dbc5 Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Sun, 24 Nov 2013 21:45:30 -0200 Subject: Add traslate the topic more functions Extra-Add a topic about the refs and 'keep readings' --- pt-br/haskell-pt.html.markdown | 321 ++++++++++++++++++++++++++++------------- 1 file changed, 219 insertions(+), 102 deletions(-) diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index ca0d847c..3d80a44f 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -79,6 +79,10 @@ not False -- Nega uma falácia -- Concatenação de Strings "StringA" ++ "StringB" -- "StringAStringB" +-- Concatenação de Caracteres +"haskell" == ['h','a','s','k','e','l','l'] -- True +"haskell" == 'h':'a':'s':'k':'e':'l':'l':[] -- True + -- Você pode listar uma string pelos seus caractéres "AbBbbcAbbcbBbcbcb" !! 0 -- 'A' "AbBbbcAbbcbBbcbcb" !! 1 -- 'b' @@ -96,7 +100,7 @@ not False -- Nega uma falácia [1..5] {- Haskell usa avaliação preguiçosa o que - Permite você ter listas "infinitas" + permite você ter listas "infinitas". -} -- Uma lista "infinita" cuja razão é 1 @@ -121,81 +125,174 @@ tail ['a'..'e'] -- Qual a cauda da lista ? init ['a'..'e'] -- Qual a lista menos o último elemento ? last ['a'..'e'] -- Qual o último elemento ? --- list comprehensions -[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] +-- Compreensão de Lista (List Comprehension) + +{- Uma lista pode ser especificada + pela definição de eus elementos. + A compreensão de listas é feita + com um construtor de listas que + utiliza conceitos e notações + da teoria dos conjuntos. + + Exemplo: + + A = { x**2 | X pertence aos Naturais && x é par} +-} + +let par x = mod x 2 == 0 +let constroi_lista = [x * x | x <- [9 ..39], par x] +-- [100,144,196,256,324,400,484,576,676,784,900,1024,1156,1296,1444] --- with a conditional +par 4 -- True +par 3 -- False + + +-- Listas com regras +{- Para todo x se x é elemento da lista + faça 2 vezes x mas componha a lista + com apenas aqueles elementos cujo + 2*x é maior que 4 +-} [x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] --- Every element in a tuple can be a different type, but a tuple has a --- fixed length. --- A tuple: -("haskell", 1) +-- Tuplas +("Q", "Gamma", "b", "Sigma", "delta", "q0", "F") -- 7-Tuple Turing Machine + +-- Retirando da tupla + +{- Com as funções fst (primeiro) e snd (segundo) + você só pode enviar por parâmetro uma tupla + bi-dimensional ou seja, 2 dimensões == (x,y) +-} + +fst ((2,3), [2,3]) -- (2,3) +snd ((2,3), [4,3]) -- [4,3] --- accessing elements of a tuple -fst ("haskell", 1) -- "haskell" -snd ("haskell", 1) -- 1 ---------------------------------------------------- --- 3. Functions +-- 3. Funções em Haskell ---------------------------------------------------- --- A simple function that takes two variables -add a b = a + b --- Note that if you are using ghci (the Haskell interpreter) --- You'll need to use `let`, i.e. --- let add a b = a + b - --- Using the function -add 1 2 -- 3 - --- You can also put the function name between the two arguments --- with backticks: -1 `add` 2 -- 3 - --- You can also define functions that have no letters! This lets --- you define your own operators! Here's an operator that does --- integer division -(//) a b = a `div` b -35 // 4 -- 8 - --- Guards: an easy way to do branching in functions -fib x - | x < 2 = x - | otherwise = fib (x - 1) + fib (x - 2) - --- Pattern matching is similar. Here we have given three different --- definitions for fib. Haskell will automatically call the first --- function that matches the pattern of the value. -fib 1 = 1 -fib 2 = 2 -fib x = fib (x - 1) + fib (x - 2) - --- Pattern matching on tuples: -foo (x, y) = (x + 1, y + 2) - --- Pattern matching on lists. Here `x` is the first element --- in the list, and `xs` is the rest of the list. We can write --- our own map function: -myMap func [] = [] -myMap func (x:xs) = func x:(myMap func xs) - --- Anonymous functions are created with a backslash followed by --- all the arguments. -myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] - --- using fold (called `inject` in some languages) with an anonymous --- function. foldl1 means fold left, and use the first value in the --- list as the initial value for the accumulator. +-- Uma função simples que toma duas variáveis +{- Haskell trabalha em cima de recursão + Portanto certifique-se que você + Entende como recurssão funciona. +-} + +soma a b = a + b -- Função que vai em um programa.hs + +{- Dentro do GHCi (Interpretador Haskell) + Você terá que fazer da seguinte maneira-- Podemos criar nos + + Prelude> let soma a b = a + b + Prelude> soma 7 7 -- 14 +-} + +let constroi_lista = [x * x | x <- [9 ..39], par x] + +{- Você pode usar crases para chamar + Funcões de maneira diferente +-} + +7 `soma` 7 -- 14 + +{- Haskell permite que você crie os + seus próprios operadores baseados + nos já existendes +-} + +let (~/\) a b = a `mod` b +15^13 ~/\ 432 -- 759375 + +-- Casamento de Padrões em Tuplas +coordenadas (x, y) = (x + 13, y - 31) + +{- Haskell trabalha com casamento de padrões onde dada + um conjunto de funções definidas de diferentes maneiras + Haskell vai procurar por aquela que trabalha o seu tipo + de entrada. +-} + +-- Guardas "|" É um jeito simples de representar funções recursivas + +let fatorial n | n == 0 = 1 | otherwise = fatorial (n - 1) * n -- Teste: fatorial 5 + +-- Ainda podemos fazer: + +let fatorial 0 = 1 +let fatorial n = fatorial (n - 1) * n + +{- Podemos criar nossos próprios Mapeadores + Onde `primeiro` é o primeiro elemento de + uma lista é `resto` é o resto da lista. +-} + +mapa mapeador [] = [] +mapa mapeador (primeiro : resto) = mapeador primeiro : (mapa mapeador resto) + +{- Funções Anônimas são criadas com um `\` (barra invertida) + seguido por seus argumentos! +-} +mapa (\primeiro -> primeiro + 2) [1..5] -- [3, 4, 5, 6, 7] + +{- Usar "fold" (chamado `inject` em algumas outras línguagens) com + uma função anônima. + + significa E mapeia o primeiro valor + da lista para ser o acumulador. +-} foldl1 (\acc x -> acc + x) [1..5] -- 15 +foldl1 (\x y -> (x+y)/5) [7..55] -- 13.6875 + +---------------------------------------------------- +-- 4. Mais Funções +---------------------------------------------------- + +{- Currying: Se você não passar todos os argumentos + para uma função, ela irá ser "currificada". O que + significa que irá retornar a função que pega o resto + dos elementos. +-} + +soma a b = a + b +foo = soma 10 -- foo ganha a propriedade "currying" +foo 5 -- 15 + +-- Outra maneira +foo = (+10) +foo 5 -- 15 + +{- Composição de Funções + O (.) encadeia funções! Por exemplo, + aqui foo é uma função que recebe um valor. + Ela soma 10 a ela, multiplica o resultado por 5 + e então retorna o resultado final. +-} +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +{- Concertando precedência: + Haskell tem outra função chamada `$`. Isso altera a precedência + de computação. Ou seja Haskell computa o que está sendo sinalizado com $ + da esquerda para a direita . You can use `.` and `$` to get rid of a lot + of parentheses: +-} + +-- Antes +(even (fatorial 3)) -- true + +-- Depois +even . fatorial $ 3 -- true ---------------------------------------------------- -- 4. More functions ---------------------------------------------------- --- currying: if you don't pass in all the arguments to a function, --- it gets "curried". That means it returns a function that takes the --- rest of the arguments. +{- Mais Sobre Funções Currificadas: se você não passar + todos os argumentos para uma função. +-} add a b = a + b foo = add 10 -- foo is now a function that takes a number and adds 10 to it @@ -329,13 +426,13 @@ Nothing -- of type `Maybe a` for any `a` -- called. It must return a value of type `IO ()`. For example: main :: IO () -main = putStrLn $ "Hello, sky! " ++ (say Blue) +main = putStrLn $ "Hello, sky! " ++ (say Blue) -- putStrLn has type String -> IO () --- It is easiest to do IO if you can implement your program as --- a function from String to String. The function +-- It is easiest to do IO if you can implement your program as +-- a function from String to String. The function -- interact :: (String -> String) -> IO () --- inputs some text, runs a function on it, and prints out the +-- inputs some text, runs a function on it, and prints out the -- output. countLines :: String -> String @@ -349,43 +446,43 @@ main' = interact countLines -- the `do` notation to chain actions together. For example: sayHello :: IO () -sayHello = do +sayHello = do putStrLn "What is your name?" 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 -- one line of input. - + -- The code in `sayHello` will never be executed, however. The only --- action that ever gets executed is the value of `main`. --- To run `sayHello` comment out the above definition of `main` +-- action that ever gets executed is the value of `main`. +-- To run `sayHello` comment out the above definition of `main` -- and replace it with: -- main = sayHello --- Let's understand better how the function `getLine` we just +-- Let's understand better how the function `getLine` we just -- used works. Its type is: -- getLine :: IO String -- You can think of a value of type `IO a` as representing a --- computer program that will generate a value of type `a` +-- computer program that will generate a value of type `a` -- when executed (in addition to anything else it does). We can --- store and reuse this value using `<-`. We can also +-- store and reuse this value using `<-`. We can also -- make our own action of type `IO String`: action :: IO String action = do putStrLn "This is a line. Duh" - input1 <- getLine + 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 + -- `return` is not a keyword, but merely a function return (input1 ++ "\n" ++ input2) -- return :: String -> IO String -- We can use this just like we used `getLine`: main'' = do putStrLn "I will echo two lines!" - result <- action + result <- action putStrLn result putStrLn "This was all, folks!" @@ -400,40 +497,60 @@ main'' = do ---------------------------------------------------- --- 9. The Haskell REPL +-- 9. O Haskell REPL (Read Eval Print Loop) ---------------------------------------------------- --- Start the repl by typing `ghci`. --- Now you can type in Haskell code. Any new values --- need to be created with `let`: +{- Digite dhci no seu terminal + para começar o interpretador + lembre-se que para definir + funções e variáveis em haskell + pelo interpretador você precisar + iniciar com `let` +-} -let foo = 5 +Prelude> let foo = 1.4 --- You can see the type of any value with `:t`: +-- Você pode ver o tipo de algo usando `:t`: ->:t foo -foo :: Integer +Prelude> :t foo +foo :: Double +``` --- You can also run any action of type `IO ()` +---------------------------------------------------- +-- 9. Mônadas +---------------------------------------------------- -> sayHello -What is your name? -Friend! -Hello, Friend! -``` -There's a lot more to Haskell, including typeclasses and monads. These are the big ideas that make Haskell such fun to code in. I'll leave you with one final Haskell example: an implementation of quicksort in Haskell: -```haskell -qsort [] = [] -qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater - where lesser = filter (< p) xs - greater = filter (>= p) xs -``` +---------------------------------------------------- +-- 10. Extra +---------------------------------------------------- + +Compilador e Interpretador Haskell + +* [GHC](http://www.haskell.org/ghc/docs/latest/html/users_guide/index.html) +* [GHC/GHCi](http://www.haskell.org/haskellwiki/GHC) + +Instale Haskell [Aqui!](http://www.haskell.org/platform/). + +Aplicações Haskell Muito Interessantes: + +* [Música e Som](http://www.haskell.org/haskellwiki/Applications_and_libraries/Music_and_sound) +* [Haskell SuperCollider Servidor](https://github.com/kaoskorobase/hsc3-server) +* [Haskell SuperCollider Cliente](http://hackage.haskell.org/package/hsc3) +* [Física e Matemática](http://www.haskell.org/haskellwiki/Applications_and_libraries/Mathematics) +* [Jogos](http://www.haskell.org/haskellwiki/Applications_and_libraries/Games) +* [Bio Informática](http://www.haskell.org/haskellwiki/Applications_and_libraries/Bioinformatics) +* [Muitos Outras Aplicações](http://www.haskell.org/haskellwiki/Libraries_and_tools) + +Tutoriais: + +* [Mapeadores](http://www.haskell.org/ghc/docs/6.12.2/html/libraries/containers-0.3.0.0/Data-Map.html) +* [Aprenda Haskell!](http://haskell.tailorfontela.com.br/chapters) + +Obtenha Também Haskell Wiki Book [Aqui!](https://en.wikibooks.org/wiki/Haskell) -Haskell is easy to install. Get it [here](http://www.haskell.org/platform/). +Leia Sobre As Mônadas [Aqui!](http://www.haskell.org/haskellwiki/Monads) -You can find a much gentler introduction from the excellent -[Learn you a Haskell](http://learnyouahaskell.com/) or -[Real World Haskell](http://book.realworldhaskell.org/). +Livro: Haskell Uma Abordagem Prática - Claudio Cesar de Sá e Márcio Ferreira da Silva -- cgit v1.2.3 From 65b15b280b7c361af7c9baaabf5943a93a3a5931 Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Mon, 25 Nov 2013 01:54:35 -0200 Subject: Add translate until Haskell::IO Plus some extra references --- pt-br/haskell-pt.html.markdown | 221 ++++++++++++++++++++++------------------- 1 file changed, 119 insertions(+), 102 deletions(-) diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index 3d80a44f..f9f9f510 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -227,22 +227,38 @@ let fatorial n = fatorial (n - 1) * n uma lista é `resto` é o resto da lista. -} -mapa mapeador [] = [] +mapa mapeador _ [] = [] mapa mapeador (primeiro : resto) = mapeador primeiro : (mapa mapeador resto) -{- Funções Anônimas são criadas com um `\` (barra invertida) - seguido por seus argumentos! +{- Uma função anônima é uma função sem um nome. + É uma abstração do cálculo lambda: + + \x -> x + 1 + λ.x (x + 1) + + Em Haskell Barra Invertida é um jeito para + se escrever Lambda (λ). Uma ótima pedida + Para entender Haskell e outras linguagens como Lisp + É estudar Cálculo Lambda, é um entendimento matemático + mais apurado. E do ponto de vista computacional é + bastante interessante. Em EXTRAS você encontrará + Links para aprender Cálculo Lambda. -} -mapa (\primeiro -> primeiro + 2) [1..5] -- [3, 4, 5, 6, 7] -{- Usar "fold" (chamado `inject` em algumas outras línguagens) com - uma função anônima. +(\x -> x + 1) 4 -- 5 + - significa E mapeia o primeiro valor - da lista para ser o acumulador. +{- Algumas vezes é mais conveniente usar expressões lambda + do que definir um nome para uma função. Na matemática + Nomes são muito simbólicos. Isso acontece bastante + quando você estiver trabalhando `map` ou `foldl` / `foldr` -} -foldl1 (\acc x -> acc + x) [1..5] -- 15 -foldl1 (\x y -> (x+y)/5) [7..55] -- 13.6875 + +-- Sem usar expressões anônimas ! +listaSomaUm lst = map somaUm' lst where somaUm' x = x + 1 + +-- Usando expressões anônimas ! +listaSomaUm' lst = map (\x -> x + 1) lst ---------------------------------------------------- -- 4. Mais Funções @@ -276,144 +292,142 @@ foo 5 -- 75 {- Concertando precedência: Haskell tem outra função chamada `$`. Isso altera a precedência de computação. Ou seja Haskell computa o que está sendo sinalizado com $ - da esquerda para a direita . You can use `.` and `$` to get rid of a lot - of parentheses: + da esquerda para a direita . Você pode usar `.` e `$` para se livrar + de parentízação desnecessária. -} --- Antes (even (fatorial 3)) -- true --- Depois +-- Usando `.` e `$` even . fatorial $ 3 -- true ---------------------------------------------------- --- 4. More functions +-- 5. Tipos ---------------------------------------------------- -{- Mais Sobre Funções Currificadas: se você não passar - todos os argumentos para uma função. --} - -add a b = a + b -foo = add 10 -- foo is now a function that takes a number and adds 10 to it -foo 5 -- 15 - --- Another way to write the same thing -foo = (+10) -foo 5 -- 15 +-- Haskell é fortemente tipado e tudo tem uma assinatura típica. --- function composition --- the (.) function chains functions together. --- For example, here foo is a function that takes a value. It adds 10 to it, --- multiplies the result of that by 5, and then returns the final value. -foo = (*5) . (+10) +-- Tipos Básicos: +460 :: Integer +"music" :: String +True :: Bool --- (5 + 10) * 5 = 75 -foo 5 -- 75 +{- Funções também tem tipos. + `not` recebe um booleano e retorna um booleano: + not :: Bool -> Bool +-} --- 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 `.` and `$` to get rid of a lot --- of parentheses: +{- Aqui temos uma função que recebe dois argumentos + soma :: Integer -> Integer -> Integer +-} --- before -(even (fib 7)) -- true +{- Quando você define um valor em Haskell + uma boa prática de programação é escrever + o TIPO acima dessa mesma. Como segue: +-} --- after -even . fib $ 7 -- true +double :: Integer -> Integer +double x = x * 2 ---------------------------------------------------- --- 5. Type signatures +-- 6. Controle de Fluxo e IF-THEN-ELSE ---------------------------------------------------- --- Haskell has a very strong type system, and everything has a type signature. - --- Some basic types: -5 :: Integer -"hello" :: String -True :: Bool +-- Blocos IF-THEN-ELSE +let valor_alternado = if 144 `mod` 6 == 4 then "acertou" else "errou" -- errou --- Functions have types too. --- `not` takes a boolean and returns a boolean: --- not :: Bool -> Bool +-- É legal identar quando você tem múltiplos branchs para acontecer --- Here's a function that takes two arguments: --- add :: Integer -> Integer -> Integer +let valor_alternado = if 144 `mod` 6 == 4 + then "acertou" + else "errou" --- When you define a value, it's good practice to write its type above it: -double :: Integer -> Integer -double x = x * 2 +-- Blocos CASE ----------------------------------------------------- --- 6. Control Flow and If Statements ----------------------------------------------------- +{- caso seja : + -> mostra_ajuda + -> inicia_programa + <_> -> putStrLn "ExArgumentoInvalido" --- if statements -haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + Onde `_` Significa Qualquer Outra Coisa. +-} --- if statements can be on multiple lines too, indentation is important -haskell = if 1 == 1 - then "awesome" - else "awful" --- case statements: Here's how you could parse command line arguments case args of - "help" -> printHelp - "start" -> startProgram - _ -> putStrLn "bad args" + "ajuda" -> mostra_ajuda + "inicia" -> inicia_programa + _ -> putStrLn "ExArgumentoInvalido" --- Haskell doesn't have loops because it uses recursion instead. --- map applies a function over every element in an array +{- Haskell não funciona na base de loops pois ele é + fortemente baseado em funcões recursivas e cálculo lambda + Use `map` uma função build-in do interpretador + para, por exemplo, mapear uma lista: +-} map (*2) [1..5] -- [2, 4, 6, 8, 10] --- you can make a for function using map -for array func = map func array - --- and then use it +-- Você pode criar um FOR-LOOP usando map +let for array funcao = map funcao array for [0..5] $ \i -> show i --- we could've written that like this too: +-- Ou ainda (Pesquise sobre show em Haskell): for [0..5] show --- You can use foldl or foldr to reduce a list --- foldl + +{- foldl computação é feita esquerda para direita + foldr computação é feita direita para esquerda + + Você pode usar foldl or foldr a fim de reduzir uma lista + fold(l||r) +-} + +-- Fold Left foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 --- This is the same as -(2 * (2 * (2 * 4 + 1) + 2) + 3) +-- Pensando Recursivamente Esquerda-Direita +(2 * (2 * (2 * 4 + 1) + 2) + 3) -- 43 --- foldl is left-handed, foldr is right- +-- Fold Right foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 --- This is now the same as +-- Pensando Recursivamente Direita-Esquerda (2 * 3 + (2 * 2 + (2 * 1 + 4))) ---------------------------------------------------- --- 7. Data Types +-- 7. Declaração de Dados ---------------------------------------------------- --- Here's how you make your own data type in Haskell - -data Color = Red | Blue | Green +{- Vamos começar definindo um tipo de + dado que é uma cor rgb então ela + tem valores para vermelho azul e verde + ela é composta desses 3 comprimentos + Vamos usar `data` e `say` que são built-in: + + Haskell pede que você user letra + maiuscula para tipos (types) ou classes (Class) + + Por favor, visite: http://www.haskell.org/haskellwiki/Type + E de uma olhada na fórmula genérica de declaração de dados. +-} --- Now you can use it in a function: +data Cor = Vermelho | Azul | Verde +-- say :: Color -> String -say :: Color -> String -say Red = "You are Red!" -say Blue = "You are Blue!" -say Green = "You are Green!" +let say Vermelho = "Vermelho" +let say Azul = "Azul" +let say Verde = "Verde" --- Your data types can have parameters too: +{- O seu tipo de dados por receber parâmetros também + vamos com um exemplo usando `data` e a Classe `Maybe`. +-} data Maybe a = Nothing | Just a --- These are all of type Maybe -Just "hello" -- of type `Maybe String` -Just 1 -- of type `Maybe Int` -Nothing -- of type `Maybe a` for any `a` +-- Just e Nothing são todos derivadas de Maybe +Just "hello" -- tipo `Maybe String` +Just 1 -- tipo `Maybe Int` +Nothing -- tipo `Maybe a` para algum `a` ---------------------------------------------------- -- 8. Haskell IO @@ -514,18 +528,15 @@ Prelude> let foo = 1.4 Prelude> :t foo foo :: Double -``` ---------------------------------------------------- -- 9. Mônadas ---------------------------------------------------- +``` - ----------------------------------------------------- --- 10. Extra ----------------------------------------------------- +# Extra Compilador e Interpretador Haskell @@ -544,10 +555,16 @@ Aplicações Haskell Muito Interessantes: * [Bio Informática](http://www.haskell.org/haskellwiki/Applications_and_libraries/Bioinformatics) * [Muitos Outras Aplicações](http://www.haskell.org/haskellwiki/Libraries_and_tools) +Comunidade Haskell +* [Musica das Mônadas](http://www.haskell.org/haskellwiki/Music_of_monads) + Tutoriais: * [Mapeadores](http://www.haskell.org/ghc/docs/6.12.2/html/libraries/containers-0.3.0.0/Data-Map.html) * [Aprenda Haskell!](http://haskell.tailorfontela.com.br/chapters) +* [Fundação Teórica da Linguagem Haskell](http://www.haskell.org/haskellwiki/Lambda_calculus) +* [Classe Maybe](http://www.haskell.org/haskellwiki/Maybe) +* [Zvon Referência Haskell](http://www.zvon.org/other/haskell/) Obtenha Também Haskell Wiki Book [Aqui!](https://en.wikibooks.org/wiki/Haskell) -- cgit v1.2.3 From 83ffa7fa41c45ed62900811839700f2b1dbc860f Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Mon, 25 Nov 2013 01:57:49 -0200 Subject: Change header contribuitor id to english labels --- pt-br/haskell-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index f9f9f510..62cfd76c 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -1,6 +1,6 @@ --- -linguagem: haskell -tradutor/contribuidor: +language: haskell +translators/contributors: - ["Lucas Tonussi", "http://www.inf.ufsc.br/~tonussi/"] --- -- cgit v1.2.3 From 67a5236629b6c7748b609f23c0362925b5c4774d Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 24 Nov 2013 23:26:11 -0600 Subject: Add multi-dimensional array description. --- c.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index d029a00f..f4edfca5 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -148,6 +148,14 @@ int main() { int cha = 'a'; // fine char chb = 'a'; // fine too (implicit conversion from int to char) + //Multi-dimensional arrays: + int multi_array[2][5] = { + {1, 2, 3, 4, 5}, + {6, 7, 8, 9, 0} + } + //access elements: + int array_int = multi_array[0][2]; //=> 3 + /////////////////////////////////////// // Operators /////////////////////////////////////// -- cgit v1.2.3 From 3a5dd2320d6f9a669149203a3d4307c1cddfae6e Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Mon, 25 Nov 2013 09:24:50 -0200 Subject: Add a complete translation on haskell guide I have translated to brazilian portuguese your Haskell quick guide written by Adit Bhargava plus i have add some new ideas. --- pt-br/haskell-pt.html.markdown | 203 +++++++++++++++++++++++++---------------- 1 file changed, 123 insertions(+), 80 deletions(-) diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index 62cfd76c..6b175408 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -402,10 +402,10 @@ foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 tem valores para vermelho azul e verde ela é composta desses 3 comprimentos Vamos usar `data` e `say` que são built-in: - + Haskell pede que você user letra maiuscula para tipos (types) ou classes (Class) - + Por favor, visite: http://www.haskell.org/haskellwiki/Type E de uma olhada na fórmula genérica de declaração de dados. -} @@ -429,86 +429,132 @@ Just "hello" -- tipo `Maybe String` Just 1 -- tipo `Maybe Int` Nothing -- tipo `Maybe a` para algum `a` + ---------------------------------------------------- --- 8. Haskell IO +-- 8. Mônadas ---------------------------------------------------- --- While IO can't be explained fully without explaining monads, --- it is not hard to explain enough to get going. - --- When a Haskell program is executed, the function `main` is --- called. It must return a value of type `IO ()`. For example: - -main :: IO () -main = putStrLn $ "Hello, sky! " ++ (say Blue) --- putStrLn has type String -> IO () - --- It is easiest to do IO if you can implement your program as --- a function from String to String. The function --- interact :: (String -> String) -> IO () --- inputs some text, runs a function on it, and prints out the --- output. - -countLines :: String -> String -countLines = show . length . lines - -main' = interact countLines - --- You can think of a value of type `IO ()` as representing a --- sequence of actions for the computer to do, much like a --- computer program written in an imperative language. We can use --- the `do` notation to chain actions together. For example: - -sayHello :: IO () -sayHello = do - putStrLn "What is your name?" - 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 --- one line of input. - --- The code in `sayHello` will never be executed, however. The only --- action that ever gets executed is the value of `main`. --- To run `sayHello` comment out the above definition of `main` --- and replace it with: --- main = sayHello - --- Let's understand better how the function `getLine` we just --- used works. Its type is: --- getLine :: IO String --- You can think of a value of type `IO a` as representing a --- computer program that will generate a value of type `a` --- when executed (in addition to anything else it does). We can --- store and reuse this value using `<-`. We can also --- make our own action of type `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 - return (input1 ++ "\n" ++ input2) -- return :: String -> IO String - --- We can use this just like we used `getLine`: +{- As mônadas permitem que o programador construa computações + sando os blocos de comando sequenciais, os quais, por sua vez, + podem ter outras sequencias de computações. Para entender melhor + a classe Monads você precisa ler um pouco mais sobre Classes em + Haskell e o polímofirmo ad hoc do Haskell. -main'' = do - putStrLn "I will echo two lines!" - result <- action - putStrLn result - putStrLn "This was all, folks!" + A Classe Mônada padrão em Haskell é a seguinte: +-} + +class Monad m where + (>>=) :: m a -> (a -> m b) -> m b + (>>) :: m a -> m b -> m b + return :: m -> m a + fail :: String -> m a + + -- Definição completa mínima: + -- (>>=), return + + m >> k = m >>= \_ -> k + fail s = error s + +{- Como exemplo, a função le_imprime opera com a função ">=" da + classe mônada, a qual repassa o retorno obtido com a função + getLine para uma função lambda \e qualquer. + + GHC-BASICS + Cria um arquivo chamado le_imprime.hs + compile: ghc --make -c -O Programa_Haskell_Principal.hs + execute: ./Programa_Haskell_Principal +-} --- The type `IO` is an example of a "monad". The way Haskell uses a monad to --- do IO allows it to be a purely functional language. Any function that --- interacts with the outside world (i.e. does IO) gets marked as `IO` in its --- type signature. This lets us reason about what functions are "pure" (don't --- interact with the outside world or modify state) and what functions aren't. +le_imprime :: IO () +le_imprime = getLine >>= \e -> putStrLn e -- le_imprime = getLine >>= putStrLn --- This is a powerful feature, because it's easy to run pure functions --- concurrently; so, concurrency in Haskell is very easy. +{- Mônadas abrem a possibilidade de criar computações + no estilo imperativo dentro de um grande programa funcional + Leis das Mônadas: + + 1. return a >>= k = k a + 2. m >>= return = m + 3. m >>= (\x -> k x >>= h) = (m >>= k) >>= h +-} + +-- O operador >> é chamada então (p -> q, p então q) +let m >> n = m >>= \_ -> n + + +---------------------------------------------------- +-- 9. Haskell Entrada/Saída +---------------------------------------------------- + +{- Quando um programa Haskell é executado a função `main` é + chamada. E ela precisa retornar um valor do tipo IO(). +-} + +module Main where + main :: IO () + main = putStrLn $ "Oi Glasgow!" + +-- Ou simplesmente: + +main = putStrLn $ "Oi Glasgow!" + +{- putStrLn é do tipo String -> IO() + + É o jeito mais fácil de conseguir E/S se você implementar + o seu programa como uma função de String para String. + + A função: + interact :: (String -> String) -> IO () + Joga texto, roda a função nela mesma, e imprime a saída +-} + +module Main where + contadorLinhas = show . length . lines + main = interact contadorLinhas + +-- Use a notação `do` para encadear ações. Por exemplo: + +diga_oi :: IO () + +diga_oi = do + + putStrLn "Qual eh o seu nome?" + name <- getLine + putStrLn $ "Oi, " ++ name + +main = diga_oi + +{- Exercício! Escreva sua própria versão + onde irá ler apenas uma linhas de input. + + Vamos entender melhor como `getLine` funciona? + getLine :: IO String + Pense que o valor do tipo `IO a` representando um + programa de computador que irá gerar um valor do tipo `a` + quando for ele executado. + + Nós podemos guardar e reusar isso apenas apontando `<-`. + Nós podemos também cria nossas próprias ações do tipo `IO String` +-} + +nova_acao :: IO String + +nova_acao = do + putStrLn "Uma string curta o bastante." + entra1 <- getLine + entra2 <- getLine + -- return :: String -> IO String + return (entra1 ++ "\n" ++ entra2) + +{- Nós podemos usar da seguinte maneira + como acabamos de usar `getLine`, exemplo: +-} + +main'' = do + putStrLn "String A" + result <- action + putStrLn result + putStrLn "String B" ---------------------------------------------------- -- 9. O Haskell REPL (Read Eval Print Loop) @@ -528,11 +574,6 @@ Prelude> let foo = 1.4 Prelude> :t foo foo :: Double - ----------------------------------------------------- --- 9. Mônadas ----------------------------------------------------- - ``` @@ -542,6 +583,7 @@ Compilador e Interpretador Haskell * [GHC](http://www.haskell.org/ghc/docs/latest/html/users_guide/index.html) * [GHC/GHCi](http://www.haskell.org/haskellwiki/GHC) +* [Haskell em 5 Passos !!!](http://www.haskell.org/haskellwiki/Haskell_in_5_steps) Instale Haskell [Aqui!](http://www.haskell.org/platform/). @@ -557,6 +599,7 @@ Aplicações Haskell Muito Interessantes: Comunidade Haskell * [Musica das Mônadas](http://www.haskell.org/haskellwiki/Music_of_monads) +* [Entendendo Mônadas](https://en.wikibooks.org/wiki/Haskell/Understanding_monads) Tutoriais: -- cgit v1.2.3 From 67ec5027e56caebe2af2f9a6130c2e9d1803f203 Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Mon, 25 Nov 2013 09:31:18 -0200 Subject: Add the contribuior and translator id's header Just adding a better explained header --- pt-br/haskell-pt.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index 6b175408..55f90bd6 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -1,7 +1,11 @@ --- language: haskell -translators/contributors: +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: - ["Lucas Tonussi", "http://www.inf.ufsc.br/~tonussi/"] +lang: pt-br +filename: learnhaskell-pt.hs --- As linguagens funcionais são linguagens de programação com base em avaliação -- cgit v1.2.3 From df3cc00f5233dac96c0e063d87d3552f493e25f6 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 25 Nov 2013 09:21:40 -0600 Subject: Remove bad examples, reword places. --- c.html.markdown | 43 +++++++++++++++---------------------------- 1 file changed, 15 insertions(+), 28 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index f4edfca5..4187d757 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -20,7 +20,7 @@ memory management and C will take you as far as you need to go. Multi-line comments look like this. They work in C89 as well. */ -// Constants: #define (no semicolon at end) +// Constants: #define #define DAYS_IN_YEAR 365 //enumeration constants are also ways to declare constants. @@ -38,7 +38,7 @@ enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; // Declare function signatures in advance in a .h file, or at the top of // your .c file. -void function_1(char s[]); +void function_1(char c); int function_2(void); // Must declare a 'function prototype' before main() when functions occur after @@ -84,8 +84,8 @@ int main() { unsigned long long ux_long_long; // chars inside single quotes are integers in machine's character set. - '0' //==> 48 on the ASCII character set. - 'A' //==> 65 on the ASCII character set. + '0' // => 48 in the ASCII character set. + 'A' // => 65 in the ASCII character set. // sizeof(T) gives you the size of a variable with type T in bytes // sizeof(obj) yields the size of the expression (variable, literal, etc.). @@ -154,16 +154,16 @@ int main() { {6, 7, 8, 9, 0} } //access elements: - int array_int = multi_array[0][2]; //=> 3 + int array_int = multi_array[0][2]; // => 3 /////////////////////////////////////// // Operators /////////////////////////////////////// - int i1 = 1, i2 = 2; // Shorthand for multiple declaration + // Shorthands for multiple declarations: + int i1 = 1, i2 = 2; float f1 = 1.0, f2 = 2.0; - //more shorthands: int a, b, c; a = b = c = 0; @@ -215,9 +215,9 @@ int main() { //Increment and decrement operators: char *s = "iLoveC" int j = 0; - s[j++]; // => "i" Returns value of j to s THEN increments value of j. + s[j++]; // => "i". Returns the j-th item of s THEN increments value of j. j = 0; - s[++j]; // => "L" Increments value of j THEN returns value of j to s. + s[++j]; // => "L". Increments value of j THEN returns j-th value of s. // same with j-- and --j // Bitwise operators! @@ -271,7 +271,7 @@ int main() { printf("\n"); // *****NOTES*****: - // Loops MUST always have a body. If no body is needed, do: + // Loops and Functions MUST have a body. If no body is needed: int i; for (i = 0; i <= 5; i++) { ; // use semicolon to act as the body (null statement) @@ -429,12 +429,12 @@ int add_two_ints(int x1, int x2) } /* -Functions are call by value. So when a function is called, the arguments passed -to the function are copies of original arguments (except arrays). Anything you -do to your arguments do not change the value of the actual argument where the -function was called. +Functions are call by value. When a function is called, the arguments passed to +the function are copies of the original arguments (except arrays). Anything you +do to the arguments in the function do not change the value of the original +argument where the function was called. -You can use pointers if you need to edit the original argument values. +Use pointers if you need to edit the original argument values. Example: in-place string reversal */ @@ -452,19 +452,6 @@ void str_reverse(char *str_in) } } -///////////////////////////////////// -// Built in functions: -///////////////////////////////////// -// from: #include -// ** getchar() ** -// int c = getchar(); //reads character from input. -// If input = hi, 'h' is returned then next call, 'i' returned. -while ((c = getchar()) != EOF) { // EOF constant "end of file". - // Linux: CTRL+D, Windows: CTRL+X - // must have () around getchar() as != is run before =. - putchar(c); //prints character (without newline at end) -} - //if referring to external variables outside function, must use extern keyword. int i = 0; void testFunc() { -- cgit v1.2.3 From 9f1034674a4524946ae8b34cf26f4b9eb58e06e6 Mon Sep 17 00:00:00 2001 From: rscnt Date: Mon, 25 Nov 2013 10:56:11 -0600 Subject: git -es --- es-es/git-es.html.markdown | 411 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 411 insertions(+) create mode 100644 es-es/git-es.html.markdown diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown new file mode 100644 index 00000000..2c439fc2 --- /dev/null +++ b/es-es/git-es.html.markdown @@ -0,0 +1,411 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http:#github.com/JakeHP"] +translator: + - ["Raúl Ascencio", "http:#rscnt.github.io"] +filename: LearnGit.txt +language: es-es + +--- + +Git es un sistema de control de versiones distribuido diseñado para manejar +cualquier tipo de proyecto ya sea largos o pequeños, con velocidad y eficiencia. + +Git realiza esto haciendo "snapshots" del proyecto, con ello permite +versionar y administrar nuestro código fuente. + +## Versionamiento, conceptos. + +### Que es el control de versiones? +El control de versiones es un sistema que guarda todos los cambios realizados a +uno o varios archivos, a lo largo del tiempo. + +### Versionamiento centralizado vs Versionamiento Distribuido. + ++ El versionamiento centralizado se enfoca en sincronizar, rastrear, y respaldar + archivos. ++ El versionamiento distribuido se enfoca en compartir los cambios realizados. + Cada cambio tiene un único identificador. ++ El versionamiento distribuido no tiene una estructura definida, incluso se + puede mantener el estilo de los repositorios SVN con git. + +[Informacion adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones) + +### Por que usar Git? + +* Se puede trabajar sin conexion. +* Colaborar con otros es sencillo!. +* Derivar, Crear ramas del proyecto (aka: Branching) es facil!. +* Combinar (aka: Marging) +* Git es rapido. +* Git es flexible. + +## Arquitectura de Git. + +### Repositorio + +Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka: +comits), y encabezados (aka: headss). Imagina que un repositorio es una clase, +y que sus atributos otorgan acceso al historial del elemento, ademas de otras +cosas. + +Un repositorio esta compuesto por la carpeta .git y un "arbol de trabajo". + +### Directorio .git (componentes del repositorio) + +El directorio .git contiene todas las configuraciones, registros, branches, HEAD +y mas. + +[Lista detallada.](http://es.gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Directorio de trabajo (componentes del repositorio) + +Es basicamente los directorios y archivos dentro del repositorio. La mayorioa de +las veces se le llama "directorio de trabajo". + +### Inidice (componentes del directorio .git) + +El inidice es la area de inicio en git. Es basicamente la capa que separa el +directorio de trabajo, del repositorio en git. Esto otorga a los desarrolladores +mas poder sobre lo que envia y recibe en el repositorio. + +### Commit (aka: cambios) + +Un commit es una captura de un conjunto de cambios, o modificaciones hechas en +el directorio de trabajo. Por ejemplo, si se añaden 5 archivos, se remueven 2, +estos cambios se almacenaran en un commit (aka: captura). Este commit puede ser o +no ser enviado (aka: "pusheado") hacia un repositorio. + +### Branch (rama) + +Un "brach", es escencialmente un apuntador hacia el ultimo commit (cambio +registrado) que se ha realizado. A medida que se realizan mas commits, este +apuntador se actualizara automaticamente hacia el ultimo commit. + +### "HEAD" y "head" (component of .git dir) + +"HEAD" es un apuntador hacia la rama (branch) que se esta utilizando. Un +repositorio solo puede tener un HEAD activo. En cambio "head", es un apuntador a +cualquier commit realizado, un repositorio puede tener cualquier numero de +"heads". + +### conceptos - recursos. + +* [Git para informaticos](http://eagain.net/articles/git-for-computer-scientists/) +* [Git para diseñadores](http://hoth.entp.com/output/git_for_designers.html) + + +## Comandos. + + +### init + +Crear un repositorio de git vacio. Las configuraciones, informacion almacenada y +demas son almacenadas en el directorio ".git". + +```bash +$ git init +``` + +### config + +Se utiliza para configurar las opciones ya sea globalmente, o solamente en el +repositorio. + +```bash +# Imprime y guarda algunas variables de configuracion basicas. (Globalmente) +$ git config --global user.email +$ git config --global user.name + +$ git config --global user.email "corre@gmail.com" +$ git config --global user.name "nombre" +``` + +[Mas sobre git config.](http://git-scm.com/book/es/Personalizando-Git-Configuración-de-Git) + +### help + +Otorga un accceso rapido a una guia extremadamente detallada de cada comando en +git. O puede ser usada simplemente como un recordatorio de estos. + +```bash +# Una vista rapido de los comandos disponibles. +$ git help + +# Chequear todos los comandos disponibles +$ git help -a + +# Obtener ayuda especifica de un comando - manual de usuario +# git help +$ git help add +$ git help commit +$ git help init +``` + +### status + +Muestra las diferencias entre el archivo indice y el commit al cual apunta el +HEAD actualmente. + + +```bash +# Mostrara el "branch", archivos sin añadir a la repo, cambios y otras +# diferencias +$ git status + +# Devuelve ayuda sobre el comando status. +$ git help status +``` + +### add + +Para añadir archivos al arbol (directorio, repositorio) de trabajo. Si no se +utiliza `git add`, los nuevos archivos no se añadiran al arbol de trabajo, por +lo que no se incluiran en los commits (cambios). + +```bash +# Añade un archivo en el directorio de trabajo actual. +$ git add FooBar.java + +# Añade un archivo que se encuentra bajo un directorio. +$ git add /directorio/del/archivo/Foo.c + +# Soporte para expresiones regulares! +$ git add ./*.py +``` + +### branch + +Administra las ramas del repositorios ("branches"). Puedes ver, editar, crear y +borrar ramas ("branches"), usando este comando. + +```bash +# lista todas las ramas (remotas y locales) +$ git branch -a + +# Añada una nueva rama ("branch"). +$ git branch branchNueva + +# Eliminar una rama. +$ git branch -d branchFoo + +# Renombra una rama. +# git branch -m +$ git branch -m youngling padawan + +# Edita la descripcion de la rama. +$ git branch master --edit-description +``` + +### checkout + +Actualiza todos los archivos en el directorio de trabajo para que sean igual que +las versiones almacenadas en el indice, o en un arbol de trabajo especificado. + +```bash +# Despachar un repositorio. - Por defecto la master branch. (la rama principal llamada 'master') +$ git checkout +# Despacha una rama especifica. +$ git checkout padawan +# Crea una nueva rama y cambia hacia ella, es igual a utilizar: "git brach jedi; git checkout jedi" +$ git checkout -b jdei +``` + +### clone + +Clona, o copia, una repo existente en un nuevo directorio. Tambien añada el +seguimiento hacia las ramas existentes del repo que ha sido clonada, lo que +permite subir (push) los archivos hacia una rama remota. + +```bash +# Clonar la repo de jquery. +$ git clone https://github.com/jquery/jquery.git +``` + +### commit + +Almacena los cambios que almacenados en el indice en un nuevo "commit". Este +commit contiene los cambios hechos mas un resumen hecho por el desarrollador. + +```bash +# commit with a message +# realizar un commit y añadirle un mensaje. +$ git commit -m "jedi anakin wil be - jedis.list" +``` + +### diff + +Muestra las diferencias entre un archivo en el directorio de trabajo, el indice +y commits. + +```bash +# Muestra la diferencia entre un directorio de trabajo y el indice. +$ git diff + +# Muestra la diferencia entre el indice y los commits mas recientes. +$ git diff --cached + +# Muestra la diferencia entre el directorio de trabajo y el commit mas reciente. +$ git diff HEAD +``` + +### grep + +Permite realizar una busqueda rapida en un repositorio. + +Configuracion opcionales: + +```bash +# Gracias a Travis Jeffery por compartir lo siguiente. +# Permite mostrar numeros de lineas en la salida de grep. +$ git config --global grep.lineNumber true + +# Realiza una busqueda mas lejible, incluyendo agrupacion. +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Busca por "unaVariable" en todos los archivos ,java +$ git grep 'unaVariable' -- '*.java' + +# Busca por una linea que contenga "nombreArreglo" y , "agregar" o "remover" +$ git grep -e 'nombreArreglo' --and \( -e agregar -e remover \) +``` + +Mas ejemplos: +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Muestra los commits (cambios) registrados en el repositotrio. + +```bash +# Muestra todos los commits. +$ git log + +# Muestra un numero x de commits. +$ git log -n 10 + +# Muestra solo los commits que se han combinado en el hisotrial +$ git log --merges +``` + +### merge + +Combina los cambios de commits realizados externamente dentro de la rama en la +que se trabaja. + +```bash +# Combina la rama especificada en la rama actual. +$ git merge jediMaster + +# Siempre genere un solo merge commit cuando se utilizar merge. +$ git merge --no-ff jediMaster +``` + +### mv + +Renombra o mueve un archivo + +```bash +# Renombrando un archivo +$ git mv HolaMundo.c AdiosMundo.c + +# Moviendo un archivo. +$ git mv HolaOtraVezMundo.c ./nuevo/directorio/NuevoArchivo.c + +# Sustituye un archivo. +$ git mv -f archivoA archivoB +``` + +### pull + +Sube (Empuja) de un repositorio y lo combina en otro en una rama diferente. + +```bash +# Actualiza el repositorio local, combinando los nuevos cambios. +# de las ramas remotas "origin" y "master". +# from the remote "origin" and "master" branch. +# git pull +$ git pull origin master +``` + +### push + +Push and merge changes from a branch to a remote & branch. + +```bash +# Push and merge changes from a local repo to a +# Empuja y combina cambios de un repositorio local hacian un repositorio remoto +# llamados "origin" y "master", respectivamente. +# git push +# git push => por defecto es lo mismo que poner => git push origin master +$ git push origin master +``` + + +Toma todos los cambios que fueron registrados en una rama, y los repite dentro +de otra rama. +*No reescribe los commits que se han empujado antes a un repositorio publico* + +```bash +# Integrar ramaExperimento dentro de la rama "master" +# git rebase +$ git rebase master experimentBranch +``` + +[Informacion adicional.](http://git-scm.com/book/es/Ramificaciones-en-Git-Procedimientos-básicos-para-ramificar-y-fusionar) + +### reset (precaucion) + +Reinicia el cabezal actual hacia un estado especificado. Esto permite desacer +combinaciones (merges), pulls, commits, adds y mas. Es un comando util, pero +tambien peligrosa si no se sabe lo que se hace. + +```bash +# Reinica el area principal, con el ultimo cambio registrado. (deja los +# directorios sin cambios) +$ git reset + +# Reinica el area principal, con el ultimo cambio registrado, y reescribe el +# directorio de trabajo. +$ git reset --hard + +# Mueve la rama actual hacia el commit especificado (no realiza cambios a los +# directorios), todos los cambios aun existen el directorio. +$ git reset 31f2bb1 + +# Mueve la rama actual devuelta a un commit especificado asi como el +# directorios (borra todos los cambios que no fueron registros y todos los +# cambios realizados despues del commit especificado). +$ git reset --hard 31f2bb1 +``` + +### rm + +Lo contrario de git add, git rm remueve los archivos del directorio de trabajo +actual. + +```bash +# Remueve FooBar.c +$ git rm FooBar.c + +# Remueve un archivo de un directorio. +$ git rm /directorio/del/archivo/FooBar.c +``` + +## Informacion Adicional + +* [tryGit - Una forma entretenida y rapida de aprender Git.](http://try.github.io/levels/1/challenges/1) + +* [git-scm - Video-tutoriales](http://git-scm.com/videos) + +* [git-scm - Documentacion](http://git-scm.com/book/es) + +* [Atlassian Git - Tutoriales y Flujos de trabajo](https://www.atlassian.com/git/) + +* [SalesForce Chuleta](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) -- cgit v1.2.3 From 816bf94956f88b8bcaa56d800ca1f19bbc9b5bd0 Mon Sep 17 00:00:00 2001 From: rscnt Date: Mon, 25 Nov 2013 12:09:10 -0600 Subject: git es # -> // --- es-es/git-es.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 2c439fc2..54771bb6 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -2,9 +2,9 @@ category: tool tool: git contributors: - - ["Jake Prather", "http:#github.com/JakeHP"] + - ["Jake Prather", "http://github.com/JakeHP"] translator: - - ["Raúl Ascencio", "http:#rscnt.github.io"] + - ["Raúl Ascencio", "http://rscnt.github.io"] filename: LearnGit.txt language: es-es -- cgit v1.2.3 From 1b3053b3448cee90486204f4eeb9f28b5cb57eac Mon Sep 17 00:00:00 2001 From: rscnt Date: Mon, 25 Nov 2013 12:13:11 -0600 Subject: last check --- es-es/git-es.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 54771bb6..0623b29b 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -47,7 +47,7 @@ uno o varios archivos, a lo largo del tiempo. ### Repositorio Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka: -comits), y encabezados (aka: headss). Imagina que un repositorio es una clase, +comits), y encabezados (aka: heads). Imagina que un repositorio es una clase, y que sus atributos otorgan acceso al historial del elemento, ademas de otras cosas. @@ -80,7 +80,7 @@ no ser enviado (aka: "pusheado") hacia un repositorio. ### Branch (rama) -Un "brach", es escencialmente un apuntador hacia el ultimo commit (cambio +Un "branch", es escencialmente un apuntador hacia el ultimo commit (cambio registrado) que se ha realizado. A medida que se realizan mas commits, este apuntador se actualizara automaticamente hacia el ultimo commit. -- cgit v1.2.3 From 77facdeafe65b5e4c91e2e63c39e424da3c425b9 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 25 Nov 2013 14:55:07 -0800 Subject: Update css.html.markdown Fix rendering bug. --- css.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index 1999480f..b16b364d 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -71,7 +71,7 @@ div { } /* and more importantly you can combine these together -- there shouldn't be -any space between different parts because that makes it to have another +any spaaace between different parts because that makes it to have another meaning.*/ div.some-class[attr$='ue'] { } @@ -85,7 +85,7 @@ div.some-parent > .class-name {} and is child of a div with class name "some-parent" IN ANY DEPTH */ div.some-parent .class-name {} -/* warning: the same selector wihout space has another meaning. +/* warning: the same selector wihout spaaace has another meaning. can you say what? */ div.some-parent.class-name {} @@ -140,7 +140,7 @@ selector { /* Fonts */ font-family: Arial; - font-family: "Courier New"; /* if name has space it appears in double-quote */ + font-family: "Courier New"; /* if name has spaaace it appears in double-quote */ font-family: "Courier New", Trebuchet, Arial; /* if first one was not found browser uses the second font, and so forth */ } @@ -175,6 +175,7 @@ and may have a property set on it in more than one. In these cases, one of the rules takes precedence over others. Given the following CSS: + ```css /*A*/ p.class1[attr='value'] @@ -192,7 +193,9 @@ p {} p { property: value !important; } ``` + and the following markup: + ```xml

-- cgit v1.2.3 From 1e60055977dd82e6e69de43973e2481d93f78b64 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Tue, 26 Nov 2013 18:12:53 +1030 Subject: [python] == doesn't coerce types; use bool() to demonstrate truthiness instead. Closes #418. --- python.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 22d236ac..941ba9f4 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -105,8 +105,8 @@ None is None #=> True # None, 0, and empty strings/lists all evaluate to False. # All other values are True -0 == False #=> True -"" == False #=> True +bool(0) #=> False +bool("") #=> False #################################################### -- cgit v1.2.3 From ec3343839fb3b7bc548eb5cab8c716c97753c51b Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Tue, 26 Nov 2013 18:28:44 +1030 Subject: [javascript] Add notes about ASI. Closes #424. --- javascript.html.markdown | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index b6d4c8b7..348cbff5 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -31,8 +31,8 @@ doStuff(); // wherever there's a newline, except in certain cases. doStuff() -// So that we don't have to worry about those certain cases (for now), we'll -// leave them on. +// Because those cases can cause unexpected results, we'll keep on using +// semicolons in this guide. /////////////////////////////////// // 1. Numbers, Strings and Operators @@ -218,6 +218,18 @@ function myFunction(thing){ } myFunction("foo"); // = "FOO" +// Note that the value to be returned must start on the same line as the +// 'return' keyword, otherwise you'll always return 'undefined' due to +// automatic semicolon insertion. Watch out for this when using Allman style. +function myFunction() +{ + return // <- semicolon automatically inserted here + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + // JavaScript functions are first class objects, so they can be reassigned to // different variable names and passed to other functions as arguments - for // example, when supplying an event handler: -- cgit v1.2.3 From a36cee194b40dd59608d3e306e74e1b68ba9aa46 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Tue, 26 Nov 2013 09:32:11 +0100 Subject: fix #425 --- julia.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index c3d2195b..d05e165d 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -402,7 +402,7 @@ Set([1,2,3]...) #=> Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) x = (1,2,3) #=> (1,2,3) Set(x) #=> Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples -Set(x...) #=> Set{Int64}(2,3,1) +Set(x...) #=> Set{Int64}(1,2,3) # You can define functions with optional positional arguments -- cgit v1.2.3 From 02044c1eab7d7d8a670c1f63b004e91df83d22c4 Mon Sep 17 00:00:00 2001 From: David Underwood Date: Sun, 1 Dec 2013 21:42:51 -0500 Subject: Ruby: Adds attr_accessor, attr_reader, and attr_writer to class docs --- ruby.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index bf4cb229..a4c74a4f 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -323,6 +323,13 @@ class Human @name end + # The above functionality can be encapsulated using the attr_accessor method as follows + attr_accessor :name + + # Getter/setter methods can also be created individually like this + attr_reader :name + attr_writer :name + # A class method uses self to distinguish from instance methods. # It can only be called on the class, not an instance. def self.say(msg) -- cgit v1.2.3 From 6e6d88e25f66e7beccafa4a1c3cef739f1edac95 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Mon, 2 Dec 2013 13:08:28 +0100 Subject: [standard-ml/en-en] Created tutorial from scratch --- standard-ml.html.markdown | 334 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 334 insertions(+) create mode 100644 standard-ml.html.markdown diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown new file mode 100644 index 00000000..d1a8fc12 --- /dev/null +++ b/standard-ml.html.markdown @@ -0,0 +1,334 @@ +--- +language: Standard ML +contributors: + - ["Simon Shine", "http://shine.eu.org/"] +lang: en-en +--- + +Standard ML is a functional programming language with type inference and some +side-effects. Some of the hard parts of learning Standard ML are: Recursion, +pattern matching, type inference (guessing the right types but never allowing +implicit type conversion). If you have an imperative background, not being able +to update variables can feel severely inhibiting. + +``` +(* Comments in Standard ML begin with (* and end with *). Comments can be + nested which means that all (* tags must end with a *) tag. This comment + contains two nested comments. *) + +(* A Standard ML program consists of declarations, e.g. value declarations: *) +val rent = 1200 +val phone_no = 5551337 +val pi = 3.14159 +val negative_number = ~15 (* Yeah, unary minus is a so-called 'tilde' *) + +(* And just as importantly, functions: *) +fun is_large(x : int) = if x > 37 then true else false + +(* Floating-point numbers are called "reals". *) +val tau = 2.0 * pi (* You can multiply reals *) +val twice_rent = 2 * rent (* You can multiply ints *) +(* val meh = 1.25 * 10 *) (* But you can't multiply an int and a real *) + +(* +, - and * are overloaded so they work for both int and real. *) +(* The same cannot be said for division which has separate operators: *) +val real_division = 14.0 / 4.0 (* gives 3.5 *) +val int_division = 14 div 4 (* gives 3, rounding down *) +val int_remainder = 14 mod 4 (* gives 2, since 3*4 = 12 *) + +(* ~ is actually sometimes a function (e.g. when put in front of variables) *) +val negative_rent = ~(rent) (* Would also have worked if rent were a "real" *) + +(* There are also booleans and boolean operators *) +val got_milk = true +val got_bread = false +val has_breakfast = got_milk andalso got_bread (* Yes, it's called andalso *) +val has_something = got_milk orelse got_bread (* Yes, it's called orelse *) +val is_sad = not(has_something) (* not is a function *) + +(* Many values can be compared using equality operators: = and <> *) +val pays_same_rent = (rent = 1300) (* false *) +val is_wrong_phone_no = (phone_no <> 5551337) (* false *) + +(* The operator <> is what most other languages call != *) + + +(* Actually, most of the parentheses above are unnecessary. Here are some + different ways to say some of the things mentioned above: *) +fun is_large x = x > 37 (* The parens above were necessary because of ': int' *) +val is_sad = not has_something +val pays_same_rent = rent = 1300 (* Looks confusing, but works *) +val is_wrong_phone_no = phone_no <> 5551337 +val negative_rent = ~rent (* ~ rent (notice the space) would also work *) + +(* Parens are mostly necessary when grouping things: *) +val some_answer = is_large (5 + 5) (* Without parens, this would break! *) +(* val some_answer = is_large 5 + 5 *) (* Read as: (is_large 5) + 5. Bad! *) + + +(* Besides booleans, ints and reals, Standard ML also has chars and strings: *) +val foo = "Hello, World!\n" (* The \n is the escape sequence for linebreaks *) +val one_letter = #"a" (* That funky syntax is just one character, a *) + +val combined = "Hello " ^ "there, " ^ "fellow!\n" (* Concatenate strings *) + +val _ = print foo (* You can print things. We are not interested in the *) +val _ = print combined (* result of this computation, so we throw it away. *) +(* val _ = print one_letter *) (* Only strings can be printed this way *) + + +val bar = [ #"H", #"e", #"l", #"l", #"o" ] (* SML also has lists! *) +(* val _ = print bar *) (* Lists are unfortunately not the same as strings *) + +(* Fortunately they can be converted. String is a library and implode and size + are functions available in that library that take strings as argument. *) +val bob = String.implode bar (* gives "Hello" *) +val bob_char_count = String.size bob (* gives 5 *) +val _ = print (bob ^ "\n") (* For good measure, add a linebreak *) + +(* You can have lists of any kind *) +val numbers = [1, 3, 3, 7, 229, 230, 248] (* : int list *) +val names = [ "Fred", "Jane", "Alice" ] (* : string list *) +val groups = [ [ "Alice", "Bob" ], + [ "Huey", "Dewey", "Louie" ], + [ "Bonnie", "Clyde" ] ] (* : string list list *) + +val number_count = List.length numbers (* gives 7 *) + +(* You can put single values in front of lists of the same kind *) +val more_numbers = 13 :: numbers (* gives [13, 1, 3, 3, 7, ...] *) +val more_groups = ["Batman","Superman"] :: groups + +(* Lists of the same kind can be appended using the @ ("append") operator *) +val guest_list = [ "Mom", "Dad" ] @ [ "Aunt", "Uncle" ] + +(* This could have been done with the :: operator (pronounced "cons") *) +val guest_list = "Mom" :: "Dad" :: [ "Aunt", "Uncle" ] + +(* If you have many lists of the same kind, you can concatenate them all *) +val everyone = List.concat groups (* [ "Alice", "Bob", "Huey", ... ] *) + +(* A list can contain any (finite) amount of values *) +val lots = [ 5, 5, 5, 6, 4, 5, 6, 5, 4, 5, 7, 3 ] (* still just an int list *) + +(* Lists can only contain one kind of thing... *) +(* val bad_list = [ 1, "Hello", 3.14159 ] : ??? list *) + + +(* Tuples, on the other hand, can contain a fixed number of different things *) +val person1 = ("Simon", 28, 3.14159) (* : string * int * real *) + +(* You can even have tuples inside lists and lists inside tuples *) +val likes = [ ("Alice", "ice cream"), + ("Bob", "hot dogs"), + ("Bob", "Alice") ] (* : (string * string) list *) + +val mixup = [ ("Alice", 39), + ("Bob", 37), + ("Eve", 41) ] (* : (string * int) list *) + +val good_bad_stuff = + (["ice cream", "hot dogs", "chocolate"], + ["liver", "paying the rent" ]) (* string list * string list *) + + +(* Functions! *) +fun add_them (a, b) = a + b (* A simple function that adds two numbers *) +val test_it = add_them (3, 4) (* gives 7 *) + +(* Larger functions are usually broken into several lines for readability *) +fun thermometer temp = + if temp < 37 + then "Cold" + else if temp > 37 + then "Warm" + else "Normal" + +val test_thermo = thermometer 40 (* gives "Warm" *) + +(* if-sentences are actually expressions and not statements/declarations. + A function body can only contain one expression. There are some tricks + for making a function do more than just one thing, though. *) + +(* A function can call itself as part of its result (recursion!) *) +fun fibonacci n = + if n = 0 then 0 else (* Base case *) + if n = 1 then 1 else (* Base case *) + fibonacci (n - 1) + fibonacci (n - 2) (* Recursive case *) + +(* Sometimes recursion is best understood by evaluating a function by hand: + + fibonacci 4 + ~> fibonacci (4 - 1) + fibonacci (4 - 2) + ~> fibonacci 3 + fibonacci 2 + ~> (fibonacci (3 - 1) + fibonacci (3 - 2)) + fibonacci 2 + ~> (fibonacci 2 + fibonacci 1) + fibonacci 2 + ~> ((fibonacci (2 - 1) + fibonacci (2 - 2)) + fibonacci 1) + fibonacci 2 + ~> ((fibonacci 1 + fibonacci 0) + fibonacci 1) + fibonacci 2 + ~> ((1 + fibonacci 0) + fibonacci 1) + fibonacci 2 + ~> ((1 + 0) + fibonacci 1) + fibonacci 2 + ~> (1 + fibonacci 1) + fibonacci 2 + ~> (1 + 1) + fibonacci 2 + ~> 2 + fibonacci 2 + ~> 2 + (fibonacci (2 - 1) + fibonacci (2 - 2)) + ~> 2 + (fibonacci (2 - 1) + fibonacci (2 - 2)) + ~> 2 + (fibonacci 1 + fibonacci 0) + ~> 2 + (1 + fibonacci 0) + ~> 2 + (1 + 0) + ~> 2 + 1 + ~> 3 which is the 4th Fibonacci number, according to this definition + + *) + +(* A function cannot change the variables it can refer to. It can only + temporarily shadow them with new variables that have the same names. In this + sense, variables are really constants and only behave like variables when + dealing with recursion. For this reason, variables are also called value + bindings. An example of this: *) + +val x = 42 +fun answer(question) = + if question = "What is the meaning of life, the universe and everything?" + then x + else raise Fail "I'm an exception. Also, I don't know what the answer is." +val x = 43 +val hmm = answer "What is the meaning of life, the universe and everything?" +(* Now, hmm has the value 42. This is because the function answer refers to + the copy of x that was visible before its own function definition. *) + + +(* Functions can take several arguments by taking one tuples as argument: *) +fun solve2 (a : real, b : real, c : real) = + ( Math.sqrt (~b + Math.sqrt(b * b - 4.0*a*c) / (2.0 * a), + Math.sqrt (~b - Math.sqrt(b * b - 4.0*a*c) / (2.0 * a) ) + +(* Sometimes, the same computation is carried out several times. It makes sense + to save and re-use the result the first time. We can use "let-bindings": *) +fun solve2 (a : real, b : real, c : real) = + let val discr = b * b - 4.0*a*c + val sqr = Math.sqrt d + val denom = 2.0 * a + in (~b + sq / denom, + ~b - sq / denom) end + + +(* Pattern matching is a funky part of functional programming. It is an + alternative to if-sentences. The fibonacci function can be rewritten: *) +fun fibonacci 0 = 0 (* Base case *) + | fibonacci 1 = 1 (* Base case *) + | fibonacci n = fibonacci (n - 1) + fibonacci (n - 2) (* Recursive case *) + +(* Pattern matching is also possible on composite types like tuples and lists. + Writing "fun solve2 (a, b, c) = ..." is in fact a pattern match on the one + three-tuple solve2 takes as argument. Similarly, but less intuitively, you + can match on a list consisting of elements in it (from the beginning of the + list only). *) +fun first_elem (x::xs) = x +fun second_elem (x::y::xs) = y +fun evenly_positioned_elems (odd::even::xs) = even::evenly_positioned_elems xs + | evenly_positioned_elems [odd] = [] (* Base case: throw away *) + | evenly_positioned_elems [] = [] (* Base case *) + + +(* Higher order functions: Functions can take other functions as arguments. + Functions are just other kinds of values, and functions don't need names + to exist. Functions without names are called "anonymous functions" or + lambda expressions or closures (since they also have a lexical scope). *) +val is_large = (fn x => x > 37) +val add_them = fn (a,b) => a + b +val thermometer = + fn temp => if temp < 37 + then "Cold" + else if temp > 37 + then "Warm" + else "Normal" + +(* The following uses an anonymous function directly and gives "ColdWarm" *) +val some_result = (fn x => thermometer (x - 5) ^ thermometer (x + 5)) 37 + +(* Here is a higher-order function that works on lists (a list combinator) *) +val readings = [ 34, 39, 37, 38, 35, 36, 37, 37, 37 ] (* first an int list *) +val opinions = List.map thermometer readings (* gives [ "Cold", "Warm", ... ] *) + +(* And here is another one for filtering lists *) +val warm_readings = List.filter is_large readings (* gives [39, 38] *) + +(* You can create your own higher-order functions, too. Functions can also take + several arguments by "currying" them. Syntax-wise this means adding spaces + between function arguments instead of commas and surrounding parentheses. *) +fun map f [] = [] + | map f (x::xs) = f(x) :: map f xs + +(* map has type ('a -> 'b) -> 'a list -> 'b list and is called polymorphic. *) +(* 'a is called a type variable. *) + +(* Datatypes are useful for creating both simple and complex structures *) +datatype color = Red | Green | Blue + +(* Here is a function that takes one of these as argument *) +fun say(col) = + if col = Red then "You are red!" else + if col = Green then "You are green!" else + if col = Blue then "You are blue!" else + raise Fail "Unknown color" + +(* Datatypes are very often used in combination with pattern matching *) +fun say Red = "You are red!" + | say Green = "You are green!" + | say Blue = "You are blue!" + | _ = raise Fail "Unknown color" + + +(* Here is a binary tree datatype *) +datatype 'a btree = Leaf of 'a + | Node of 'a btree * 'a * 'a btree (* three-arg constructor *) + +(* Here is a binary tree *) +val myTree = Node (Leaf 9, 8, Node (Leaf 3, 5, Leaf 7)) + +(* Drawing it, it might look something like... + + 8 + / \ + leaf -> 9 5 + / \ + leaf -> 3 7 <- leaf + *) + +(* This function counts the sum of all the elements in a tree *) +fun count (Leaf n) = n + | count (Node (leftTree, n, rightTree)) = count leftTree + n + count rightTree + + +(* File I/O! *) +(* Write a nice poem to a file *) +fun writePoem(filename) = + let val file = TextIO.openOut(filename) + val _ = TextIO.output(file, "Roses are red,\nViolets are blue.\n") + val _ = TextIO.output(file, "I have a gun.\nGet in the van.\n") + in TextIO.closeOut(file) end + +(* Read a nice poem from a file into a list of strings *) +fun readPoem(filename) = + let val file = TextIO.openIn filename + val poem = TextIO.inputAll file + val _ = TextIO.closeIn file + in String.tokens (fn c => c = #"\n") poem + end + +val _ = writePoem "roses.txt" +val test_poem = readPoem "roses.txt" (* gives [ "Roses are red,", + "Violets are blue.", + "I have a gun.", + "Get in the van." ] *) +~~~~ + +## Further learning + +* Install an interactive compiler (REPL), for example + [http://www.polyml.org/](Poly/ML), + [http://mosml.org](Moscow ML) or + [http://smlnj.org/](SML/NJ). +* Follow the Coursera course [Programming Languages](https://www.coursera.org/course/proglang). +* Get the book *ML for the Working Programmer* by Larry C. Paulson. + -- cgit v1.2.3 From 29f06c2d2fd8e57a11816969da3d65f68b932a2d Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Mon, 2 Dec 2013 13:09:58 +0100 Subject: [haskell/en-en] Fixed 80-character margin --- haskell.html.markdown | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 267b40af..341c013e 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -4,9 +4,9 @@ contributors: - ["Adit Bhargava", "http://adit.io"] --- -Haskell was designed as a practical, purely functional programming language. It's famous for -its monads and its type system, but I keep coming back to it because of its elegance. Haskell -makes coding a real joy for me. +Haskell was designed as a practical, purely functional programming +language. It's famous for its monads and its type system, but I keep coming back +to it because of its elegance. Haskell makes coding a real joy for me. ```haskell -- Single line comments start with two dashes. @@ -401,7 +401,9 @@ Hello, Friend! ``` -There's a lot more to Haskell, including typeclasses and monads. These are the big ideas that make Haskell such fun to code in. I'll leave you with one final Haskell example: an implementation of quicksort in Haskell: +There's a lot more to Haskell, including typeclasses and monads. These are the +big ideas that make Haskell such fun to code in. I'll leave you with one final +Haskell example: an implementation of quicksort in Haskell: ```haskell qsort [] = [] -- cgit v1.2.3 From 9b43a17fb5cf88a31419d20fbb34f84749317b13 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Mon, 2 Dec 2013 13:12:39 +0100 Subject: [standard-ml/en-en] SML syntax highlighting on GitHub --- standard-ml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index d1a8fc12..98c2ea39 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -11,7 +11,7 @@ pattern matching, type inference (guessing the right types but never allowing implicit type conversion). If you have an imperative background, not being able to update variables can feel severely inhibiting. -``` +```sml (* Comments in Standard ML begin with (* and end with *). Comments can be nested which means that all (* tags must end with a *) tag. This comment contains two nested comments. *) -- cgit v1.2.3 From 02b8d51897502dab5253176162d996ca05ea9cdd Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Mon, 2 Dec 2013 13:21:00 +0100 Subject: [standard-ml/en-en] Silly reversal of Markdown URL tags --- standard-ml.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 98c2ea39..b586efa5 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -326,9 +326,9 @@ val test_poem = readPoem "roses.txt" (* gives [ "Roses are red,", ## Further learning * Install an interactive compiler (REPL), for example - [http://www.polyml.org/](Poly/ML), - [http://mosml.org](Moscow ML) or - [http://smlnj.org/](SML/NJ). + [Poly/ML](http://www.polyml.org/), + [Moscow ML](http://mosml.org) + [SML/NJ](http://smlnj.org/). * Follow the Coursera course [Programming Languages](https://www.coursera.org/course/proglang). * Get the book *ML for the Working Programmer* by Larry C. Paulson. -- cgit v1.2.3 From 699dc938e978f4b193c8d2967242386d1df61ac3 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Tue, 3 Dec 2013 07:27:29 +0100 Subject: [standard-ml/en-en] Removing syntax errors and fixing solve2 function --- standard-ml.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index b586efa5..ab5e4b84 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -199,17 +199,17 @@ val hmm = answer "What is the meaning of life, the universe and everything?" (* Functions can take several arguments by taking one tuples as argument: *) fun solve2 (a : real, b : real, c : real) = - ( Math.sqrt (~b + Math.sqrt(b * b - 4.0*a*c) / (2.0 * a), - Math.sqrt (~b - Math.sqrt(b * b - 4.0*a*c) / (2.0 * a) ) + ( (~b + Math.sqrt(b * b - 4.0*a*c)) / (2.0 * a), + (~b - Math.sqrt(b * b - 4.0*a*c)) / (2.0 * a) ) (* Sometimes, the same computation is carried out several times. It makes sense to save and re-use the result the first time. We can use "let-bindings": *) fun solve2 (a : real, b : real, c : real) = let val discr = b * b - 4.0*a*c - val sqr = Math.sqrt d + val sqr = Math.sqrt discr val denom = 2.0 * a - in (~b + sq / denom, - ~b - sq / denom) end + in ((~b + sqr) / denom, + (~b - sqr) / denom) end (* Pattern matching is a funky part of functional programming. It is an @@ -273,10 +273,10 @@ fun say(col) = raise Fail "Unknown color" (* Datatypes are very often used in combination with pattern matching *) -fun say Red = "You are red!" +fun say Red = "You are red!" | say Green = "You are green!" - | say Blue = "You are blue!" - | _ = raise Fail "Unknown color" + | say Blue = "You are blue!" + | say _ = raise Fail "Unknown color" (* Here is a binary tree datatype *) @@ -321,7 +321,7 @@ val test_poem = readPoem "roses.txt" (* gives [ "Roses are red,", "Violets are blue.", "I have a gun.", "Get in the van." ] *) -~~~~ +``` ## Further learning -- cgit v1.2.3 From 3bc960034c867fd4255db3f80ddbe6f85901647b Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Tue, 3 Dec 2013 14:40:05 +0100 Subject: typos --- julia.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index d05e165d..d1e17a26 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -357,7 +357,7 @@ end # 2 # 3 -# Handle exceptions with a try/except block +# Handle exceptions with a try/catch block try error("help") catch e @@ -402,7 +402,7 @@ Set([1,2,3]...) #=> Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) x = (1,2,3) #=> (1,2,3) Set(x) #=> Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples -Set(x...) #=> Set{Int64}(1,2,3) +Set(x...) #=> Set{Int64}(2,3,1) # You can define functions with optional positional arguments -- cgit v1.2.3 From f1a215521e9a570a7ce2e4c2ffcb70d14e2c5593 Mon Sep 17 00:00:00 2001 From: Nelson Rodrigues Date: Wed, 4 Dec 2013 11:34:42 +0000 Subject: Fixed typo --- pt-pt/brainfuck-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-pt/brainfuck-pt.html.markdown b/pt-pt/brainfuck-pt.html.markdown index 60750de8..da4c787f 100644 --- a/pt-pt/brainfuck-pt.html.markdown +++ b/pt-pt/brainfuck-pt.html.markdown @@ -37,7 +37,7 @@ Vejamos alguns programas básicos de 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. Incrementa-se o valor da célula #1 10 +o ponteiro de dados para a célula #2. Incrementa-se o valor da célula #2 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, -- cgit v1.2.3 From e76f7cd4525e135599719af7379b29ce625ccb6f Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Thu, 5 Dec 2013 11:45:43 +0100 Subject: [standard-ml/en-en] Update to list part --- standard-ml.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index ab5e4b84..f7526bb8 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -95,7 +95,8 @@ val groups = [ [ "Alice", "Bob" ], val number_count = List.length numbers (* gives 7 *) -(* You can put single values in front of lists of the same kind *) +(* You can put single values in front of lists of the same kind + using the :: ("cons") operator *) val more_numbers = 13 :: numbers (* gives [13, 1, 3, 3, 7, ...] *) val more_groups = ["Batman","Superman"] :: groups -- cgit v1.2.3 From ed82f1d8682ce6e5360177c216dc3c4eb7a148d0 Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Thu, 5 Dec 2013 11:47:48 +0100 Subject: [standard-ml/en-en] Add missing comma --- standard-ml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index f7526bb8..730ef445 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -328,7 +328,7 @@ val test_poem = readPoem "roses.txt" (* gives [ "Roses are red,", * Install an interactive compiler (REPL), for example [Poly/ML](http://www.polyml.org/), - [Moscow ML](http://mosml.org) + [Moscow ML](http://mosml.org), [SML/NJ](http://smlnj.org/). * Follow the Coursera course [Programming Languages](https://www.coursera.org/course/proglang). * Get the book *ML for the Working Programmer* by Larry C. Paulson. -- cgit v1.2.3 From b8857e92663aab608b0afe6e2e79949908ac205b Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Thu, 5 Dec 2013 11:48:02 +0100 Subject: [standard-ml/en-en] Add myself as a collaborator --- standard-ml.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 730ef445..b5fef910 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -2,6 +2,7 @@ language: Standard ML contributors: - ["Simon Shine", "http://shine.eu.org/"] + - ["David Pedersen", "http://lonelyproton.com/"] lang: en-en --- -- cgit v1.2.3 From 972a4bf80270a64466beb6fb882093cf7100dcc5 Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Thu, 5 Dec 2013 11:50:45 +0100 Subject: [standard-ml/en-en] Update list doc again --- standard-ml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index b5fef910..e17972a0 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -104,7 +104,7 @@ val more_groups = ["Batman","Superman"] :: groups (* Lists of the same kind can be appended using the @ ("append") operator *) val guest_list = [ "Mom", "Dad" ] @ [ "Aunt", "Uncle" ] -(* This could have been done with the :: operator (pronounced "cons") *) +(* This could have been done with the "cons" operator *) val guest_list = "Mom" :: "Dad" :: [ "Aunt", "Uncle" ] (* If you have many lists of the same kind, you can concatenate them all *) -- cgit v1.2.3 From f1c96d5db0dae92e13be96a03118da2565ab3327 Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Thu, 5 Dec 2013 11:51:56 +0100 Subject: [standard-ml/en-en] Small whitespace fix --- standard-ml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index e17972a0..56b6853c 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -186,7 +186,7 @@ fun fibonacci n = temporarily shadow them with new variables that have the same names. In this sense, variables are really constants and only behave like variables when dealing with recursion. For this reason, variables are also called value - bindings. An example of this: *) + bindings. An example of this: *) val x = 42 fun answer(question) = -- cgit v1.2.3 From a03869362b5706345ecbb3783bd7f6173d12b698 Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Thu, 5 Dec 2013 12:33:02 +0100 Subject: [standard-ml/en-en] Exceptions --- standard-ml.html.markdown | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 56b6853c..547ca39b 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -302,6 +302,28 @@ fun count (Leaf n) = n | count (Node (leftTree, n, rightTree)) = count leftTree + n + count rightTree +(* Exceptions! *) +(* Exceptions can be raised using "raise" *) +fun raiseException msg = raise Fail msg + +(* This raises exception `Fail "hello from exception"` *) +(* val _ = raiseException "hello from exception" *) + +(* Exceptions can be caught using "handle" *) +val x = raiseException "hello" handle Fail msg => msg +(* x now has the value "hello" *) + +(* We can pattern match in "handle" to make sure + a specfic exception was raised, or grab the message *) +val y = raiseException "..." handle Fail _ => "Fail was raised" + | Domain => "Domain was raised" +(* y now has the value "Fail was raised" *) + +(* We can define our own exceptions like this *) +exception MyException +exception MyExceptionWithMessage of string + + (* File I/O! *) (* Write a nice poem to a file *) fun writePoem(filename) = -- cgit v1.2.3 From acc2dda568ac3bad9173a1cf3f114905a102d893 Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Thu, 5 Dec 2013 12:34:04 +0100 Subject: [standard-ml/en-en] align things a little --- standard-ml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 547ca39b..9de31340 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -316,7 +316,7 @@ val x = raiseException "hello" handle Fail msg => msg (* We can pattern match in "handle" to make sure a specfic exception was raised, or grab the message *) val y = raiseException "..." handle Fail _ => "Fail was raised" - | Domain => "Domain was raised" + | Domain => "Domain was raised" (* y now has the value "Fail was raised" *) (* We can define our own exceptions like this *) -- cgit v1.2.3 From d71ac35d72529d3dee08d9591cd1c65cbdcccb6d Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Thu, 5 Dec 2013 12:43:13 +0100 Subject: [standard-ml/en-en] infix functions --- standard-ml.html.markdown | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 9de31340..849ba0f5 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -264,6 +264,24 @@ fun map f [] = [] (* map has type ('a -> 'b) -> 'a list -> 'b list and is called polymorphic. *) (* 'a is called a type variable. *) + +(* We can define functions as infix *) +fun plus (x, y) = x + y +infix plus +(* We can now call plus like "2 plus 5" *) + +(* Functions can also be made infix before they are defined *) +infix minus +fun x minus y = x - y + +(* An infix function/operator can be made prefix with "op" *) +val n = op + (5, 5) +(* n is now 10 *) + +(* op is useful when combined with high order functions *) +val listSum = foldl op + 0 [1,2,3,4,5] + + (* Datatypes are useful for creating both simple and complex structures *) datatype color = Red | Green | Blue -- cgit v1.2.3 From e4b82f94155af6c18236b0811be8defd214d68a8 Mon Sep 17 00:00:00 2001 From: lkdjiin Date: Sat, 7 Dec 2013 11:40:00 +0100 Subject: First draft for french translation of Racket --- fr-fr/racket-fr.html.markdown | 630 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 630 insertions(+) create mode 100644 fr-fr/racket-fr.html.markdown diff --git a/fr-fr/racket-fr.html.markdown b/fr-fr/racket-fr.html.markdown new file mode 100644 index 00000000..ab103647 --- /dev/null +++ b/fr-fr/racket-fr.html.markdown @@ -0,0 +1,630 @@ +--- +language: racket +filename: learnracket-fr.rkt +contributors: + - ["th3rac25", "https://github.com/voila"] + - ["Eli Barzilay", "https://github.com/elibarzilay"] + - ["Gustavo Schmidt", "https://github.com/gustavoschmidt"] +translators: + - ["Xavier Nayrac", "https://github.com/lkdjiin"] +lang: fr-fr +--- + +Racket est un langage de programmation généraliste, multi-paradigme, +descendant de Lisp/Scheme. + +Les retours et commentaires sont appréciés ! Vous pouvez joindre l'auteur +original ici : +[@th3rac25](http://twitter.com/th3rac25) ou là : th3rac25 [at] [google's email +service]. Vous pouvez joindre le traducteur de ce document ici : +[@lkdjiin](http://twitter.com/lkdjiin). + +```racket +#lang racket ; défini le dialecte à utiliser. + +;;; Commentaires + +;; Une ligne de commentaire commence par un point-virgule. + +#| Un bloc de commentaires + peut tenir sur plusieurs lignes… + #| + et on peut les imbriquer ! + |# +|# + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Types de données et opérateurs primitifs +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Nombres +9999999999999999999999 ; entier +#b111 ; binaire => 7 +#o111 ; octal => 73 +#x111 ; hexadécimal => 273 +3.14 ; réel +6.02e+23 +1/2 ; rationnel +1+2i ; complexe + +;; Une fonction s'écrit (f x y z ...) +;; où f est une fonction et x, y, z, ... sont des arguments. +;; Si vous voulez créer une liste de données litérales, utilisez ' pour +;; empécher l'évaluation de la liste. +'(+ 1 2) ; => (+ 1 2) +;; Et maintenant, un peu d'arithmétique +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(quotient 5 2) ; => 2 +(remainder 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(exact->inexact 1/3) ; => 0.3333333333333333 +(+ 1+2i 2-3i) ; => 3-1i + +;;; Booléens +#t ; for true +#f ; for false -- any value other than #f is true +(not #t) ; => #f +(and 0 #f (error "doesn't get here")) ; => #f +(or #f 0 (error "doesn't get here")) ; => 0 + +;;; Caractères +#\A ; => #\A +#\λ ; => #\λ +#\u03BB ; => #\λ + +;;; Une chaîne de caractères est un tableau de caractères de longueur +;;; fixe. +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; le backslash est le caractère d'échappement +"Foo\tbar\41\x21\u0021\a\r\n" ; sont inclus les échappements de type C + ; et unicode +"λx:(μα.α→α).xx" ; une chaîne peut inclure de l'unicode + +;; On peut ajouter une chaîne à une autre +(string-append "Hello " "world!") ; => "Hello world!" + +;; Une chaîne peut être traitée comme une liste de caractères +(string-ref "Apple" 0) ; => #\A + +;; format est utilisé pour formatter une chaîne +(format "~a can be ~a" "strings" "formatted") + +;; L'affichage est tout simple +(printf "I'm Racket. Nice to meet you!\n") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variables +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Vous pouvez créer une variable à l'aide de define +;; a variable name can use any character except: ()[]{}",'`;#|\ +;; Une variable peut contenir n'importe quel caractères, à l'exception +;; de : ()[]{}",'`;#|\ +(define some-var 5) +some-var ; => 5 + +;; Vous pouvez aussi utiliser des caractères unicode +(define ⊆ subset?) +(⊆ (set 3 2) (set 1 2 3)) ; => #t + +;; Accéder à une variable non-initialisée provoque une exception +; x ; => x: indéfini ... + +;; Attachement local : `me` est attaché à "Bob" seulement à l'intérieur +;; de (let ...) +(let ([me "Bob"]) + "Alice" + me) ; => "Bob" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Structures and Collections +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Structures +(struct dog (name breed age)) +(define my-pet + (dog "lassie" "collie" 5)) +my-pet ; => # +(dog? my-pet) ; => #t +(dog-name my-pet) ; => "lassie" + +;;; Paires (non-mutable) +;; `cons` construit une paire, `car` et `cdr` extraient respectivement les +;; premiers et seconds éléments. +(cons 1 2) ; => '(1 . 2) +(car (cons 1 2)) ; => 1 +(cdr (cons 1 2)) ; => 2 + +;;; Listes + +;; Les listes en Racket sont des structures de données de type *linked-list*, +;; produites avec des paires assemblées avec `cons` et terminée avec `null` +;; (ou '()). +(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) +;; `list` est un constructeur variadique plus commode à utiliser +(list 1 2 3) ; => '(1 2 3) +;; et un guillemet simple peut aussi être utilisé pour une liste litérale +'(1 2 3) ; => '(1 2 3) + +;; On peut toujours utiliser `cons` pour ajouter un élément au début +;; d'une liste +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; Utilisez `append` pour additionner des listes entre elles +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; Les listes sont un type très basique, il y a donc *beaucoup* de +;; fonctionnalités qui leur sont dédiées, quelques exemples : +(map add1 '(1 2 3)) ; => '(2 3 4) +(map + '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(filter even? '(1 2 3 4)) ; => '(2 4) +(count even? '(1 2 3 4)) ; => 2 +(take '(1 2 3 4) 2) ; => '(1 2) +(drop '(1 2 3 4) 2) ; => '(3 4) + +;;; Vecteurs + +;; Un vecteur est un tableau de taille fixe +#(1 2 3) ; => '#(1 2 3) + +;; Utilisez `vector-append` pour additionner des vecteurs entre eux +(vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; Sets + +;; Créew un set à partir d'une liste +(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) + +;; Ajoutez un membre avec `set-add` +;; (Fonctionnel: renvoit le set étendu, plutôt que de muter le set en entrée) +(set-add (set 1 2 3) 4) ; => (set 1 2 3 4) + +;; Retirer un membre avec `set-remove` +(set-remove (set 1 2 3) 1) ; => (set 2 3) + +;; Tester l'existence d'un membre avec `set-member?` +(set-member? (set 1 2 3) 1) ; => #t +(set-member? (set 1 2 3) 4) ; => #f + +;;; Tables de hashage + +;; Créer une table de hashage non-mutable (un exemple mutable plus loin) +(define m (hash 'a 1 'b 2 'c 3)) + +;; Retrouver une valeur +(hash-ref m 'a) ; => 1 + +;; Chercher une valeur inexistante provoque une exceptions +; (hash-ref m 'd) => no value found + +;; Vous pouvez fournir une valeur par défaut pour les clés manquantes +(hash-ref m 'd 0) ; => 0 + +;; Utilisez `hash-set` pour étendre une table de hashage non-mutable +;; (Renvoit la table étendu, plutôt que de la muter) +(define m2 (hash-set m 'd 4)) +m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) + +;; Rappelez-vous, ces tables de hashage sont non-mutables ! +m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' + +;; Utilisez `hash-remove` pour supprimer des clés (également fonctionnel) +(hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Fonctions +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Utilisez `lambda` pour créer des fonctions. +;; Une fonction renvoit toujours la valeur de sa dernière expression. +(lambda () "Hello World") ; => # +;; Can also use a unicode `λ' +;; On peut aussi utiliser le caractère unicode `λ' +(λ () "Hello World") ; => même fonction + +;; Utilisez des parenthèses pour appeler toutes les fonctions, ce qui +;; inclus aussi les expressions lambda +((lambda () "Hello World")) ; => "Hello World" +((λ () "Hello World")) ; => "Hello World" + +;; Assignez une fonction à une variable +(define hello-world (lambda () "Hello World")) +(hello-world) ; => "Hello World" + +;; Vous pouvez raccourcir ceci en utilisant le sucre syntaxique pour la +;; définition des fonctions : +(define (hello-world2) "Hello World") + +;; Entre les () après lambda, vous avez la liste des arguments de la fonction +(define hello + (lambda (name) + (string-append "Hello " name))) +(hello "Steve") ; => "Hello Steve" +;; … ou alors, en utilisant le sucre syntaxique, ce qui suit est équivalent +(define (hello2 name) + (string-append "Hello " name)) + +;; Vous pouvez obtenir des fonctions variadique en utilisant `case-lambda` +(define hello3 + (case-lambda + [() "Hello World"] + [(name) (string-append "Hello " name)])) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" +;; … ou spécifier des arguments optionnels avec une valeur par défaut +(define (hello4 [name "World"]) + (string-append "Hello " name)) + +;; Les fonctions peuvent rassembler des arguments supplémentaires dans une +;; liste +(define (count-args . args) + (format "You passed ~a args: ~a" (length args) args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" +;; … ou bien avec `lambda`, sans sucre syntaxique +(define count-args2 + (lambda args + (format "You passed ~a args: ~a" (length args) args))) + +;; Vous pouvez mixer arguments réguliers et supplémentaires +(define (hello-count name . args) + (format "Hello ~a, you passed ~a extra args" name (length args))) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" +;; … sans sucre syntaxique +(define hello-count2 + (lambda (name . args) + (format "Hello ~a, you passed ~a extra args" name (length args)))) + +;; Avec des mot-clés cette fois +(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) + (format "~a ~a, ~a extra args" g name (length args))) +(hello-k) ; => "Hello World, 0 extra args" +(hello-k 1 2 3) ; => "Hello World, 3 extra args" +(hello-k #:greeting "Hi") ; => "Hi World, 0 extra args" +(hello-k #:name "Finn" #:greeting "Hey") ; => "Hey Finn, 0 extra args" +(hello-k 1 2 3 #:greeting "Hi" #:name "Finn" 4 5 6) + ; => "Hi Finn, 6 extra args" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Égalité +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Pour les nombres, utilisez `=` +(= 3 3.0) ; => #t +(= 2 1) ; => #f + +;; Pour tester l'identité des objets, utilisez `eq?` +(eq? 3 3) ; => #t +(eq? 3 3.0) ; => #f +(eq? (list 3) (list 3)) ; => #f + +;; Pour les collections, utilisez `equal?` +(equal? (list 'a 'b) (list 'a 'b)) ; => #t +(equal? (list 'a 'b) (list 'b 'a)) ; => #f + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Contrôle du flot +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Conditions + +(if #t ; expression pour le test + "this is true" ; expression si vrai + "this is false") ; expression si faux +; => "this is true" + +;; Dans les condition, toutes les valeurs non-fausses sont traitées commentaires +;; étant vraies (c'est à dire toutes sauf #f) +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(Groucho Zeppo) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'yep + +;; `cond` permet d'enchaîner une série de tests afin d'obtenir un résultat +(cond [(> 2 2) (error "wrong!")] + [(< 2 2) (error "wrong again!")] + [else 'ok]) ; => 'ok + +;;; Filtrage par motif (*pattern matching*) + +(define (fizzbuzz? n) + (match (list (remainder n 3) (remainder n 5)) + [(list 0 0) 'fizzbuzz] + [(list 0 _) 'fizz] + [(list _ 0) 'buzz] + [_ #f])) + +(fizzbuzz? 15) ; => 'fizzbuzz +(fizzbuzz? 37) ; => #f + +;;; Les boucles + +;; On peut boucler en utilisant la récursion (terminale) +(define (loop i) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) +(loop 5) ; => i=5, i=6, ... + +;; D'une manière similaire, avec un `let` nommé +(let loop ((i 0)) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) ; => i=0, i=1, ... + +;; Voir plus loin pour l'ajout d'une nouvelle forme `loop`, mais Racket +;; possède déjà une forme `for` flexible et élaborée pour les itérations +(for ([i 10]) + (printf "i=~a\n" i)) ; => i=0, i=1, ... +(for ([i (in-range 5 10)]) + (printf "i=~a\n" i)) ; => i=5, i=6, ... + +;;; Itérer sur autre chose que des nombres +;; `for` permet d'itérer sur plein de type de séquences: +;; listes, vecteurs, chaînes de caractères, sets, tables de hashage, etc + +(for ([i (in-list '(l i s t))]) + (displayln i)) + +(for ([i (in-vector #(v e c t o r))]) + (displayln i)) + +(for ([i (in-string "string")]) + (displayln i)) + +(for ([i (in-set (set 'x 'y 'z))]) + (displayln i)) + +(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))]) + (printf "key:~a value:~a\n" k v)) + +;;; Itérations plus complexes + +;; Balayage parallèle de plusieurs séquences (on stoppe sur la plus petite) +(for ([i 10] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x 1:y 2:z + +;; Boucles imbriquées +(for* ([i 2] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x, 0:y, 0:z, 1:x, 1:y, 1:z + +;; Conditions dans les boucles +(for ([i 1000] + #:when (> i 5) + #:unless (odd? i) + #:break (> i 10)) + (printf "i=~a\n" i)) +; => i=6, i=8, i=10 + +;;; Compréhensions de liste +;; Très similaires aux boucles `for` -- renvoient en plus une collection + +(for/list ([i '(1 2 3)]) + (add1 i)) ; => '(2 3 4) + +(for/list ([i '(1 2 3)] #:when (even? i)) + i) ; => '(2) + +(for/list ([i 10] [j '(x y z)]) + (list i j)) ; => '((0 x) (1 y) (2 z)) + +(for/list ([i 1000] #:when (> i 5) #:unless (odd? i) #:break (> i 10)) + i) ; => '(6 8 10) + +(for/hash ([i '(1 2 3)]) + (values i (number->string i))) +; => '#hash((1 . "1") (2 . "2") (3 . "3")) + +;; Il y a plein d'autres fonctions natives pour collecter des données à +;; l'aide de boucles +(for/sum ([i 10]) (* i i)) ; => 285 +(for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000 +(for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t +(for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t +;; Et pour n'importe quell combinaison arbitraire, utilisez `for/fold` +(for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 +;; (Ceci peut souvent remplacer des boucles communes de style impératif) + +;;; Exceptions + +;; Pour capturer une exception, utilisez la forme `with-handlers` +(with-handlers ([exn:fail? (lambda (exn) 999)]) + (+ 1 "2")) ; => 999 +(with-handlers ([exn:break? (lambda (exn) "no time")]) + (sleep 3) + "phew") ; => "phew", but if you break it => "no time" + +;; Utilisez `raise` pour soulever une exception, ou encore n'importe quelle +;; autre valeur +(with-handlers ([number? ; capturer la valeur numérique soulevée + identity]) ; la renvoyer en tant que valeur simple + (+ 1 (raise 2))) ; => 2 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutabilité +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Util `set!` pour réassigner une valeur à une variable existante +(define n 5) +(set! n (add1 n)) +n ; => 6 + +;; Utilisez le mécanisme des boites (*box*) pour les valeurs explicitement +;; mutables (similaire aux pointeurs ou références dans d'autres langages) +(define n* (box 5)) +(set-box! n* (add1 (unbox n*))) +(unbox n*) ; => 6 + +;; Beaucoup de types de données en Racket sont non-mutables (paires, listes, +;; etc), certains ont à la fois une version mutable et une version +;; non-mutable (chaînes, vecteurs, tables de hashage, etc) + +;; Utilisez `vector` ou `make-vector` pour créer des vecteurs mutables +(define vec (vector 2 2 3 4)) +(define wall (make-vector 100 'bottle-of-beer)) +;; Utilisez `vector-set!` pour mettre à jour un emplacement +(vector-set! vec 0 1) +(vector-set! wall 99 'down) +vec ; => #(1 2 3 4) + +;; Créer une table de hashage mutable vide et la manipuler +(define m3 (make-hash)) +(hash-set! m3 'a 1) +(hash-set! m3 'b 2) +(hash-set! m3 'c 3) +(hash-ref m3 'a) ; => 1 +(hash-ref m3 'd 0) ; => 0 +(hash-remove! m3 'a) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Modules +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Les modules permettent d'organiser le code en plusieurs fichiers +;; et bibliothèques réutilisables. Ici, nous utiliserons des sous-modules, +;; imbriqués dans le grand module que forme ce texte (qui démarre à la +;; ligne `#lang`). + +(module cake racket/base ; défini un module `cake', basé sur racket/base + + (provide print-cake) ; fonction exportée par le module (publique) + + (define (print-cake n) + (show " ~a " n #\.) + (show " .-~a-. " n #\|) + (show " | ~a | " n #\space) + (show "---~a---" n #\-)) + + (define (show fmt n ch) ; fonction interne/privée + (printf fmt (make-string n ch)) + (newline))) + +;; Utilisez `require` pour importer les fonctions fournies par le +;; module (provide) +(require 'cake) ; le ' est pour un sous-module local +(print-cake 3) +; (show "~a" 1 #\A) ; => erreur, `show` n'est pas exportée + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. Classes et objets +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Créer une classe fish% (% est idiomatique pour les noms de classes) +(define fish% + (class object% + (init size) ; argument pour l'initialisation + (super-new) ; initialisation de la super-classe + ;; Les champs/membres/variables de classe + (define current-size size) + ;; Méthodes publiques + (define/public (get-size) + current-size) + (define/public (grow amt) + (set! current-size (+ amt current-size))) + (define/public (eat other-fish) + (grow (send other-fish get-size))))) + +;; Créer une instance de fish% +(define charlie + (new fish% [size 10])) + +;; Utilisez `send` pour appeler une méthode d'un objet +(send charlie get-size) ; => 10 +(send charlie grow 6) +(send charlie get-size) ; => 16 + +;; `fish%' is a plain "first class" value, which can get us mixins +;; `fish%` est une simple valeur de «première classe», ce qui va permettre +;; les mélanges (*mixins*) +(define (add-color c%) + (class c% + (init color) + (super-new) + (define my-color color) + (define/public (get-color) my-color))) +(define colored-fish% (add-color fish%)) +(define charlie2 (new colored-fish% [size 10] [color 'red])) +(send charlie2 get-color) +;; ou, sans les noms: +(send (new (add-color fish%) [size 10] [color 'red]) get-color) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 9. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Les macros permettent d'étendre la syntaxe du langage + +;; Ajoutons une boucle `loop` +(define-syntax-rule (while condition body ...) + (let loop () + (when condition + body ... + (loop)))) + +(let ([i 0]) + (while (< i 10) + (displayln i) + (set! i (add1 i)))) + +;; Les macros sont hygiéniques, vous ne pouvez pas *clasher* avec les +;; variables existantes ! +(define-syntax-rule (swap! x y) ; ! est idiomatique pour la mutation + (let ([tmp x]) + (set! x y) + (set! y tmp))) + +(define tmp 2) +(define other 3) +(swap! tmp other) +(printf "tmp = ~a; other = ~a\n" tmp other) +;; La variable `tmp` est renommée en `tmp_1` +;; dans le but d'éviter un conflit de nom +;; (let ([tmp_1 tmp]) +;; (set! tmp other) +;; (set! other tmp_1)) + +;; Mais il faut quand même faire bien attention avec les macros, par exemple: +(define-syntax-rule (bad-while condition body ...) + (when condition + body ... + (bad-while condition body ...))) +;; cette macro est cassée : ell génère un code infini, si vous l'essayez +;; le compilateur va entrer dans une boucle infinie. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 10. Contrats +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Les contrats imposent des contraintes aux valeurs exportées depuis +;; les modules + +(module bank-account racket + (provide (contract-out + [deposit (-> positive? any)] ; un dépot est toujours positif + [balance (-> positive?)])) + + (define amount 0) + (define (deposit a) (set! amount (+ amount a))) + (define (balance) amount) + ) + +(require 'bank-account) +(deposit 5) + +(balance) ; => 5 + +;; Les clients qui essaient de déposer un montant non-positif sont blamés +;; (deposit -5) ; => deposit: contract violation +;; expected: positive? +;; given: -5 +;; more details.... +``` + +## Pour aller plus loin + +Vous en voulez plus ? Essayez +[Getting Started with Racket](http://docs.racket-lang.org/getting-started/) -- cgit v1.2.3 From 9221714ccc15ec315d1df671ecd08697028ee358 Mon Sep 17 00:00:00 2001 From: lkdjiin Date: Sat, 7 Dec 2013 13:55:06 +0100 Subject: Second draft for french translation of Racket --- fr-fr/racket-fr.html.markdown | 52 +++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 27 deletions(-) diff --git a/fr-fr/racket-fr.html.markdown b/fr-fr/racket-fr.html.markdown index ab103647..8b2420f8 100644 --- a/fr-fr/racket-fr.html.markdown +++ b/fr-fr/racket-fr.html.markdown @@ -47,9 +47,9 @@ service]. Vous pouvez joindre le traducteur de ce document ici : 1/2 ; rationnel 1+2i ; complexe -;; Une fonction s'écrit (f x y z ...) +;; Un appel de fonction s'écrit (f x y z ...) ;; où f est une fonction et x, y, z, ... sont des arguments. -;; Si vous voulez créer une liste de données litérales, utilisez ' pour +;; Si vous voulez créer une liste littérales, utilisez ' pour ;; empécher l'évaluation de la liste. '(+ 1 2) ; => (+ 1 2) ;; Et maintenant, un peu d'arithmétique @@ -65,8 +65,8 @@ service]. Vous pouvez joindre le traducteur de ce document ici : (+ 1+2i 2-3i) ; => 3-1i ;;; Booléens -#t ; for true -#f ; for false -- any value other than #f is true +#t ; pour vrai +#f ; pour faux -- Toute autre valeur que #f est vraie (not #t) ; => #f (and 0 #f (error "doesn't get here")) ; => #f (or #f 0 (error "doesn't get here")) ; => 0 @@ -79,8 +79,8 @@ service]. Vous pouvez joindre le traducteur de ce document ici : ;;; Une chaîne de caractères est un tableau de caractères de longueur ;;; fixe. "Hello, world!" -"Benjamin \"Bugsy\" Siegel" ; le backslash est le caractère d'échappement -"Foo\tbar\41\x21\u0021\a\r\n" ; sont inclus les échappements de type C +"Benjamin \"Bugsy\" Siegel" ; Le backslash est le caractère d'échappement +"Foo\tbar\41\x21\u0021\a\r\n" ; Sont inclus les échappements de type C ; et unicode "λx:(μα.α→α).xx" ; une chaîne peut inclure de l'unicode @@ -100,7 +100,6 @@ service]. Vous pouvez joindre le traducteur de ce document ici : ;; 2. Variables ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Vous pouvez créer une variable à l'aide de define -;; a variable name can use any character except: ()[]{}",'`;#|\ ;; Une variable peut contenir n'importe quel caractères, à l'exception ;; de : ()[]{}",'`;#|\ (define some-var 5) @@ -113,7 +112,7 @@ some-var ; => 5 ;; Accéder à une variable non-initialisée provoque une exception ; x ; => x: indéfini ... -;; Attachement local : `me` est attaché à "Bob" seulement à l'intérieur +;; Déclaration locale : `me` est attaché à "Bob" seulement à l'intérieur ;; de (let ...) (let ([me "Bob"]) "Alice" @@ -131,9 +130,9 @@ my-pet ; => # (dog? my-pet) ; => #t (dog-name my-pet) ; => "lassie" -;;; Paires (non-mutable) -;; `cons` construit une paire, `car` et `cdr` extraient respectivement les -;; premiers et seconds éléments. +;;; Paires (non mutable) +;; `cons` construit une paire, `car` et `cdr` extraient respectivement le +;; premier et le second élément. (cons 1 2) ; => '(1 . 2) (car (cons 1 2)) ; => 1 (cdr (cons 1 2)) ; => 2 @@ -141,22 +140,22 @@ my-pet ; => # ;;; Listes ;; Les listes en Racket sont des structures de données de type *linked-list*, -;; produites avec des paires assemblées avec `cons` et terminée avec `null` +;; produites avec des paires assemblées avec `cons` et terminée par `null` ;; (ou '()). (cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) ;; `list` est un constructeur variadique plus commode à utiliser (list 1 2 3) ; => '(1 2 3) -;; et un guillemet simple peut aussi être utilisé pour une liste litérale +;; et un guillemet simple peut aussi être utilisé pour une liste littérale '(1 2 3) ; => '(1 2 3) ;; On peut toujours utiliser `cons` pour ajouter un élément au début ;; d'une liste (cons 4 '(1 2 3)) ; => '(4 1 2 3) -;; Utilisez `append` pour additionner des listes entre elles +;; Utilisez `append` pour ajouter une liste à une autre (append '(1 2) '(3 4)) ; => '(1 2 3 4) -;; Les listes sont un type très basique, il y a donc *beaucoup* de +;; Une liste est un type très basique, il y a donc *beaucoup* de ;; fonctionnalités qui leur sont dédiées, quelques exemples : (map add1 '(1 2 3)) ; => '(2 3 4) (map + '(1 2 3) '(10 20 30)) ; => '(11 22 33) @@ -175,17 +174,17 @@ my-pet ; => # ;;; Sets -;; Créew un set à partir d'une liste +;; Créez un set à partir d'une liste (list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) ;; Ajoutez un membre avec `set-add` ;; (Fonctionnel: renvoit le set étendu, plutôt que de muter le set en entrée) (set-add (set 1 2 3) 4) ; => (set 1 2 3 4) -;; Retirer un membre avec `set-remove` +;; Retirez un membre avec `set-remove` (set-remove (set 1 2 3) 1) ; => (set 2 3) -;; Tester l'existence d'un membre avec `set-member?` +;; Testez l'existence d'un membre avec `set-member?` (set-member? (set 1 2 3) 1) ; => #t (set-member? (set 1 2 3) 4) ; => #f @@ -219,9 +218,8 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Utilisez `lambda` pour créer des fonctions. -;; Une fonction renvoit toujours la valeur de sa dernière expression. +;; Une fonction renvoie toujours la valeur de sa dernière expression. (lambda () "Hello World") ; => # -;; Can also use a unicode `λ' ;; On peut aussi utiliser le caractère unicode `λ' (λ () "Hello World") ; => même fonction @@ -235,10 +233,11 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' (hello-world) ; => "Hello World" ;; Vous pouvez raccourcir ceci en utilisant le sucre syntaxique pour la -;; définition des fonctions : +;; définition de fonction : (define (hello-world2) "Hello World") -;; Entre les () après lambda, vous avez la liste des arguments de la fonction +;; Entre les () après lambda, vous déclarez la liste des arguments de la +;; fonction (define hello (lambda (name) (string-append "Hello " name))) @@ -306,7 +305,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' (equal? (list 'a 'b) (list 'b 'a)) ; => #f ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 5. Contrôle du flot +;; 5. Structures de contrôle ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Conditions @@ -448,7 +447,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' ;; 6. Mutabilité ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Util `set!` pour réassigner une valeur à une variable existante +;; Utilisez `set!` pour réassigner une valeur à une variable existante (define n 5) (set! n (add1 n)) n ; => 6 @@ -503,7 +502,7 @@ vec ; => #(1 2 3 4) (printf fmt (make-string n ch)) (newline))) -;; Utilisez `require` pour importer les fonctions fournies par le +;; Utilisez `require` pour importer les fonctions fournies par un ;; module (provide) (require 'cake) ; le ' est pour un sous-module local (print-cake 3) @@ -537,9 +536,8 @@ vec ; => #(1 2 3 4) (send charlie grow 6) (send charlie get-size) ; => 16 -;; `fish%' is a plain "first class" value, which can get us mixins ;; `fish%` est une simple valeur de «première classe», ce qui va permettre -;; les mélanges (*mixins*) +;; la composition (*mixins*) (define (add-color c%) (class c% (init color) -- cgit v1.2.3 From 5a5b0c32edbee01ccc5a1c71e2cdda2d55fb3c41 Mon Sep 17 00:00:00 2001 From: Mac David Date: Mon, 9 Dec 2013 23:50:19 +0800 Subject: The 1st Edition --- zh-cn/common-lisp.html.markdown | 611 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 611 insertions(+) create mode 100644 zh-cn/common-lisp.html.markdown diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown new file mode 100644 index 00000000..34739497 --- /dev/null +++ b/zh-cn/common-lisp.html.markdown @@ -0,0 +1,611 @@ +--- + +语言: "Common Lisp" +文件名: commonlisp.lisp +贡献者: + - ["Paul Nathan", "https://github.com/pnathan"] +译者: + - ["Mac David", "http://github.com/macdavid313"] +--- + +ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 +这门语言也经常被引用作“可编程的编程语言”(可以写代码的代码)。 + +经典的入门点为[已经完全免费提供的实用Common Lisp编程](http://www.gigamonkeys.com/book/) + +另外还有一本近期内比较热门的 +[Land of Lisp](http://landoflisp.com/). + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 0. 语法 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 一般形式 + +;; Lisp有两个基本的语法部件:原子,以及S-表达式。 +;; 一般的,一组S-表达式被称为“组合式”。 + +10 ; 一个原子; 它对自身进行求值 + +:THING ;同样是一个原子;它被求值为一个符号 :thing + +t ;还是一个原子,代表逻辑真值。 + +(+ 1 2 3 4) ; 一个S表达式。 + +'(4 :foo t) ;同样是一个S表达式。 + + +;;; 注释 + +;; 一个分号开头的注释表示仅用于此行(单行);两个分号开头的则表示一个所谓标准注释; +;; 三个分号开头的意味着段落注释,而四个分号开头的注释用于文件头注释(译者注:即对该文件的说明)。 + +#| 块注释 + 可以涵盖多行,而且... + #| + 他们可以被嵌套! + |# +|# + +;;; 运行环境 + +;; 有很多不同的Common Lisp的实现;并且大部分的实现是符合标准的。 +;; 对于入门学习来说,CLISP是个不错的选择。 + +;; 可以通过QuickLisp.org's Quicklisp系统可以管理你的库。 + +;; 通常,使用一个文本编辑器和一个同时在运行的“REPL”来开发Common Lisp; +;; (译者注:“REPL”指读取-求值-打印循环)。 +;; “REPL”允许对程序进行交互式的运行、调试,就好像在系统中这是一场“现场直播”。 + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 1. 基本数据类型以及运算符 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 符号 + +'foo ; => FOO 注意到这个符号被自动转换成大写了。 + +;; `intern`由一个给定的字符串而创建相应的符号 + +(intern "AAAA") ; => AAAA + +(intern "aaa") ; => |aaa| + +;;; 数字 +9999999999999999999999 ; 整型数 +#b111 ; 二进制 => 7 +#o111 ; 八进制 => 73 +#x111 ; 十六进制 => 273 +3.14159s0 ; 单精度 +3.14159d0 ; 双精度 +1/2 ; 分数 +#C(1 2) ; 复数 + + +;; 使用函数时,应当写成这样的形式:(f x y z ...); +;; 其中,f是一个函数(名),x, y, z为参数; +;; 如果你想创建一个“字面”意义上(即不求值)的列表, 只需使用单引号 ' , +;; 从而避免接下来的表达式被求值。即,只“引用”这个数据(而不求值)。 +'(+ 1 2) ; => (+ 1 2) +;; 你同样也可以手动地调用一个函数(译者注:即使用函数对象来调用函数): +(funcall #'+ 1 2 3) ; => 6 +;; 一些算术运算符 +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + + ;;; 布尔运算 +t ; 逻辑真(任何不是nil的值都被视为真值) +nil ; 逻辑假,或者空列表 +(not nil) ; => t +(and 0 t) ; => t +(or 0 nil) ; => 0 + + ;;; 字符 +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA(希腊字母Lambda的小写) +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA(Unicode形式的小写希腊字母Lambda) + +;;; 字符串被视为一个定长字符数组 +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ;反斜杠用作转义字符 + +;; 字符串可以被连接起来 +(concatenate 'string "Hello " "world!") ; => "Hello world!" + +;; 一个字符串也可被视作一个字符的序列 +(elt "Apple" 0) ; => #\A + +;; `format`被用于格式化字符串 +(format nil "~a can be ~a" "strings" "formatted") + +;; 利用`format`打印到屏幕上是非常简单的(译者注:注意到第二个参数是t,不同于刚刚的nil);~% 代表换行符 +(format t "Common Lisp is groovy. Dude.~%") + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. 变量 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 你可以通过`defparameter`创建一个全局(动态)变量 +;; 除了:()[]{}",'`;#|\ 这些字符,其他任何字符都可被用于变量名 + +;; 动态变量名应该由*号开头与结尾! + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;; 你也可以使用Unicode字符: +(defparameter *AΛB* nil) + + +;; 访问一个在之前从未未绑定的变量是一种不规范的行为(即使依然是可能发生的); +;; 不要尝试那样做。 + + +;; 局部绑定:'me'被绑定到"dance with you"上,当且仅当它在(let ...)内有效。 +;; `let`总是返回在其作用域内最后一个表达式的值 + +(let ((me "dance with you")) + me) +;; => "dance with you" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. 结构体和集合 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 结构体 +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) + +(dog-p *rover*) ; => t ;; ewww) +(dog-name *rover*) ; => "rover" + +;; Dog-p,make-dog,以及 dog-name都是由defstruct创建的! + +;;; 点对单元 +;; `cons`可用于生成一个点对单元, 利用`car`以及`cdr`将分别得到第一个和第二个元素 +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + +;;; 列表 + +;; 所有列表都是由点对单元构成、并以'nil'(或者'())结尾的一种被称为“链表”的数据结构 +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) +;; `list`是一个生成列表的便利途径 +(list 1 2 3) ; => '(1 2 3) +;; 并且,一个引用也可被用做字面意义上的列表值 +'(1 2 3) ; => '(1 2 3) + +;; 同样的,依然可以用`cons`来添加一项到列表的起始位置 +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; 而`append`也可用于连接两个列表 +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; 或者使用`concatenate` + +(concatenate 'list '(1 2) '(3 4)) + +;; 列表是一种非常核心的数据类型,所以有非常多的处理列表的函数 +;; 例如: +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => nil +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; 向量 + +;; 向量的字面意义是一个定长数组(译者注:此处所谓字面意义的,即为#(......)的形式,下文还会出现) +#(1 2 3) ; => #(1 2 3) + +;; 使用`concatenate`来将两个向量首尾连接在一起 +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; 数组 + +;; 向量和字符串只不过是数组的特例 + +;; 二维数组 + +(make-array (list 2 2)) + +;; (make-array '(2 2)) 也是可以的 + +; => #2A((0 0) (0 0)) + +(make-array (list 2 2 2)) + +; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;; 注意:数组的默认初始值是可以指定的 +;; 下面是如何指定的示例: + +(make-array '(2) :initial-element 'unset) + +; => #(UNSET UNSET) + +;; 若想获取数组[1][1][1]上的元素: +(aref (make-array (list 2 2 2)) 1 1 1) + +; => 0 + +;;; 变长向量 + +;; 若将变长向量打印出来,那么它的字面意义上的值和定长向量的是一样的 + +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) + +*adjvec* ; => #(1 2 3) + +;; 添加新的元素: +(vector-push-extend 4 *adjvec*) ; => 3 + +*adjvec* ; => #(1 2 3 4) + + + +;;; 不怎么严谨地说,集合也可被视为列表 + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;; 然而,你可能想使用一个更好的数据结构,而并非一个链表 + +;;; 在Common Lisp中,你也可以使用“字典”的概念——哈希表 + +;; 创建一个哈希表 +(defparameter *m* (make-hash-table)) + +;; 给定键,设置对应的值 +(setf (gethash 'a *m*) 1) + +;; (通过键)检索对应的值 +(gethash 'a *m*) ; => 1, t + +;; 注意此处有一细节:Common Lisp的`gethash`往往会返回两个值。 +;; (译者注:返回的第一个值表示给定的键所对应的值或者nil,第二个则表示在哈希表中是否存在这个给定的键) +;; 例如,如果可以找到给定的键所对应的值,则返回一个t,否则返回nil + +;; 由给定的键检索一个不存在的值,则返回nil(译者注:即第一个nil,第二个nil其实是指该键在哈希表中也不存在) + (gethash 'd *m*) ;=> nil, nil + +;; 给定一个键,你可以指定其对应的默认值: +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;; 在此,让我们看一看怎样处理`gethash`的多个返回值。 + +(multiple-value-bind + (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind + (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. 函数 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 使用`lambda`来创建一个匿名函数。 +;; 一个函数总是返回其最后一个表达式的值。 +;; 将一个函数对象打印出来后的形式是多种多样的... + +(lambda () "Hello World") ; => # + +;; 使用`funcall`来调用lambda函数 +(funcall (lambda () "Hello World")) ; => "Hello World" + +;; 或者使用`apply` +(apply (lambda () "Hello World") nil) ; => "Hello World" + +;; 显示地定义一个函数(译者注:即非匿名的) +(defun hello-world () + "Hello World") +(hello-world) ; => "Hello World" + +;; 刚刚上面函数名"hello-world"后的()其实是函数的参数列表 +(defun hello (name) + (format nil "Hello, ~a " name)) + +(hello "Steve") ; => "Hello, Steve" + +;; 函数可以有可选形参并且其默认值都为nil + +(defun hello (name &optional from) + (if from + (format t "Hello, ~a, from ~a" name from) + (format t "Hello, ~a" name))) + + (hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas + +;; 你也可以指定那些可选形参的默认值 +(defun hello (name &optional (from "The world")) + (format t "Hello, ~a, from ~a" name from)) + +(hello "Steve") +; => Hello, Steve, from The world + +(hello "Steve" "the alpacas") +; => Hello, Steve, from the alpacas + + +;; 当然,你也可以设置关键字形参; +;; 关键字形参往往比可选形参更具灵活性。 + +(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) + (format t "Hello, ~a ~a, from ~a" honorific name from)) + +(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world + +(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") +; => Hello, Mr Jim, from the alpacas you met last summer + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. 等价性的含义 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Common Lisp具有一个十分复杂的用于判断等价的系统,下面只是其中一部分的例子 + +;; 若要比较数值是否等价,使用`=` +(= 3 3.0) ; => t +(= 2 1) ; => nil + +;; 若要比较对象的类型,则使用`eql` +;;(译者注:抱歉,请忽略这句翻译;`eql`在二者`eq`等价,或者同为数字与字符下相同的类型,例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) +;; (想要弄清`eql`,其实有必要先了解`eq`) +;;(可以去CLHS上分别查看两者的文档,另外,《实用Common Lisp编程》里的4.8节也提到了两者的区别) +(eql 3 3) ; => t +(eql 3 3.0) ; => nil +(eql (list 3) (list 3)) ; => nil + +;; 对于列表、字符串、以及位向量,使用`equal` +(equal (list 'a 'b) (list 'a 'b)) ; => t +(equal (list 'a 'b) (list 'b 'a)) ; => nil + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. 控制流 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 条件判断语句 + +(if t ; “测试”,即判断语句 + "this is true" ; “下一步”,即判断条件为真时求值的表达式 + "this is false") ; “否则”,即判断条件为假时求值的表达式 +; => "this is true" + +;; 在“测试”(判断)语句中,所有非nil或者非()的值都被视为真值 +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;; `cond`将一系列测试语句串联起来,并对相应的表达式求值 +(cond ((> 2 2) (error "wrong!")) + ((< 2 2) (error "wrong again!")) + (t 'ok)) ; => 'OK + +;; 对于给定值的数据类型,`typecase`会做出相应地判断 +(typecase 1 + (string :string) + (integer :int)) + +; => :int + +;;; 迭代 + +;; 当然,递归是肯定被支持的: + +(defun walker (n) + (if (zerop n) + :walked + (walker (1- n)))) + +(walker) ; => :walked + +;; 而大部分场合下,我们使用`DOLIST`或者`LOOP`来进行迭代 + + +(dolist (i '(1 2 3 4)) + (format t "~a" i)) + +; => 1234 + +(loop for i from 0 below 10 + collect i) + +; => (0 1 2 3 4 5 6 7 8 9) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. 变异 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 使用`setf`可以对一个已经存在的变量进行赋值; +;; 事实上,刚刚在哈希表的例子中我们已经示范过了。 + +(let ((variable 10)) + (setf variable 2)) + ; => 2 + + +;; 所谓好的Lisp编码风格就是为了减少破坏性函数的使用,防止副作用的发生。 +;;(译者注:很惭愧,确实不明白原作者所说的"Mutation",即这里的“变异”到底指的是什么特性) +;;(毕竟他只给了一个例子,我猜测应该是和词法变量、闭包等特性有关,还望高人指点) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. 类与对象 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 我们就不写什么有关动物的类了,下面给出的是一个很“人文主义”的类 + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "A human powered conveyance")) + +;; `defclass`,后面接类名,以及超类列表 +;; 再接着是槽的列表(槽有点像Java里的字段),最后是一些可选的特性,例如文档说明“:documentation” + +;; 如果超类列表为空,则默认该类继承于“standard-object”类(standard-object又是T的子类); +;; 这种默认行为是可以改变的,但你最好有一定的基础并且知道自己到底在干什么; +;; 参阅《The Art of the Metaobject Protocol》来了解更多信息。 + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + + +;; 在REPL中对human-powered-conveyance类调用`DESCRIBE`如下: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;; 注意到这些有用的返回信息——Common Lisp一直是一个交互式的系统。 + +;; 若要定义一个方法; +;; 先让我们注意到我们计算自行车轮子周长时使用了这样一个公式:C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;; pi在Common Lisp中已经是一个内置的常量。 + +;; 假设我们已经知道效率值(“efficiency value”)和船桨数大概呈对数关系; +;; 那么效率值的定义应当在构造器/初始化过程中就被完成。 + +;; 下面是一个如何初始化实例的例子: +;; 构造它: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + +;; 接着初构造一个实例并检查平均效率... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. 宏 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 宏可以让你扩展语法 + +;; Common Lisp并没有自带WHILE循环——所以让我们自己来为他添加一个; +;; 如果按照“拼装者”的直觉来看,我们会这样写: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. + +`condition` is tested prior to each execution of `body`" + (let ((block-name (gensym))) + `(tagbody + (unless ,condition + (go ,block-name)) + (progn + ,@body) + ,block-name))) + +;; 让我们来看看它的高级版本: + + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. + +`condition` is tested prior to each execution of `body`" + `(loop while ,condition + do + (progn + ,@body))) + +;; 然而,在一个比较现代化的编译环境下,这样的WHILE是没有必要的; +;; LOOP形式的循环和这个WHILE同样的好,并且更易于阅读。 + +;; 注意到反引号'`',逗号','以及'@'符号,这三个符号; +;; 反引号'`'是一种所谓“quasiquote”的引用类型的运算符,有了它,之后的逗号“,”才有意义。 +;; 逗号“,”意味着解除引用(unquote,即开始求值);“@”符号则表示将当前的参数插入到当前整个列表中。 +;;(译者注:这三个符号只不过是语法糖罢了,而要想真正用好、用对,需要下一番功夫) +;;(甚至光看《实用 Common Lisp 编程》中关于宏的介绍都是不够的,建议再去读一读Paul Graham的两本著作《ANSI Common Lisp》和《On Lisp》) + +;; 函数`gensym`创建一个唯一的符号——这个符号确保不会出现在其他任何地方。 +;; 这样做是因为,宏是在编译期展开的,而在宏中声明的变量名极有可能和常规代码中使用的变量名发生冲突。 + +;; 可以去《实用 Common Lisp 编程》中阅读更多有关宏的内容。 +``` + + +## 拓展阅读 + +[继续阅读《实用 Common Lisp 编程》一书](http://www.gigamonkeys.com/book/) + + +## 致谢 + +非常感谢Scheme社区的人们,我基于他们的成果得以迅速的写出这篇有关Common Lisp的快速入门 +同时也感谢 +- [Paul Khuong](https://github.com/pkhuong) ,他提出了很多有用的点评。 -- cgit v1.2.3 From c09b59955c7408ae38f1b521db2c873afffb43e1 Mon Sep 17 00:00:00 2001 From: Mac David Date: Tue, 10 Dec 2013 00:01:35 +0800 Subject: Error --- zh-cn/common-lisp.html.markdown | 611 ---------------------------------------- 1 file changed, 611 deletions(-) delete mode 100644 zh-cn/common-lisp.html.markdown diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown deleted file mode 100644 index 34739497..00000000 --- a/zh-cn/common-lisp.html.markdown +++ /dev/null @@ -1,611 +0,0 @@ ---- - -语言: "Common Lisp" -文件名: commonlisp.lisp -贡献者: - - ["Paul Nathan", "https://github.com/pnathan"] -译者: - - ["Mac David", "http://github.com/macdavid313"] ---- - -ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 -这门语言也经常被引用作“可编程的编程语言”(可以写代码的代码)。 - -经典的入门点为[已经完全免费提供的实用Common Lisp编程](http://www.gigamonkeys.com/book/) - -另外还有一本近期内比较热门的 -[Land of Lisp](http://landoflisp.com/). - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; 0. 语法 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;;; 一般形式 - -;; Lisp有两个基本的语法部件:原子,以及S-表达式。 -;; 一般的,一组S-表达式被称为“组合式”。 - -10 ; 一个原子; 它对自身进行求值 - -:THING ;同样是一个原子;它被求值为一个符号 :thing - -t ;还是一个原子,代表逻辑真值。 - -(+ 1 2 3 4) ; 一个S表达式。 - -'(4 :foo t) ;同样是一个S表达式。 - - -;;; 注释 - -;; 一个分号开头的注释表示仅用于此行(单行);两个分号开头的则表示一个所谓标准注释; -;; 三个分号开头的意味着段落注释,而四个分号开头的注释用于文件头注释(译者注:即对该文件的说明)。 - -#| 块注释 - 可以涵盖多行,而且... - #| - 他们可以被嵌套! - |# -|# - -;;; 运行环境 - -;; 有很多不同的Common Lisp的实现;并且大部分的实现是符合标准的。 -;; 对于入门学习来说,CLISP是个不错的选择。 - -;; 可以通过QuickLisp.org's Quicklisp系统可以管理你的库。 - -;; 通常,使用一个文本编辑器和一个同时在运行的“REPL”来开发Common Lisp; -;; (译者注:“REPL”指读取-求值-打印循环)。 -;; “REPL”允许对程序进行交互式的运行、调试,就好像在系统中这是一场“现场直播”。 - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; 1. 基本数据类型以及运算符 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;;; 符号 - -'foo ; => FOO 注意到这个符号被自动转换成大写了。 - -;; `intern`由一个给定的字符串而创建相应的符号 - -(intern "AAAA") ; => AAAA - -(intern "aaa") ; => |aaa| - -;;; 数字 -9999999999999999999999 ; 整型数 -#b111 ; 二进制 => 7 -#o111 ; 八进制 => 73 -#x111 ; 十六进制 => 273 -3.14159s0 ; 单精度 -3.14159d0 ; 双精度 -1/2 ; 分数 -#C(1 2) ; 复数 - - -;; 使用函数时,应当写成这样的形式:(f x y z ...); -;; 其中,f是一个函数(名),x, y, z为参数; -;; 如果你想创建一个“字面”意义上(即不求值)的列表, 只需使用单引号 ' , -;; 从而避免接下来的表达式被求值。即,只“引用”这个数据(而不求值)。 -'(+ 1 2) ; => (+ 1 2) -;; 你同样也可以手动地调用一个函数(译者注:即使用函数对象来调用函数): -(funcall #'+ 1 2 3) ; => 6 -;; 一些算术运算符 -(+ 1 1) ; => 2 -(- 8 1) ; => 7 -(* 10 2) ; => 20 -(expt 2 3) ; => 8 -(mod 5 2) ; => 1 -(/ 35 5) ; => 7 -(/ 1 3) ; => 1/3 -(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) - - ;;; 布尔运算 -t ; 逻辑真(任何不是nil的值都被视为真值) -nil ; 逻辑假,或者空列表 -(not nil) ; => t -(and 0 t) ; => t -(or 0 nil) ; => 0 - - ;;; 字符 -#\A ; => #\A -#\λ ; => #\GREEK_SMALL_LETTER_LAMDA(希腊字母Lambda的小写) -#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA(Unicode形式的小写希腊字母Lambda) - -;;; 字符串被视为一个定长字符数组 -"Hello, world!" -"Benjamin \"Bugsy\" Siegel" ;反斜杠用作转义字符 - -;; 字符串可以被连接起来 -(concatenate 'string "Hello " "world!") ; => "Hello world!" - -;; 一个字符串也可被视作一个字符的序列 -(elt "Apple" 0) ; => #\A - -;; `format`被用于格式化字符串 -(format nil "~a can be ~a" "strings" "formatted") - -;; 利用`format`打印到屏幕上是非常简单的(译者注:注意到第二个参数是t,不同于刚刚的nil);~% 代表换行符 -(format t "Common Lisp is groovy. Dude.~%") - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 2. 变量 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 你可以通过`defparameter`创建一个全局(动态)变量 -;; 除了:()[]{}",'`;#|\ 这些字符,其他任何字符都可被用于变量名 - -;; 动态变量名应该由*号开头与结尾! - -(defparameter *some-var* 5) -*some-var* ; => 5 - -;; 你也可以使用Unicode字符: -(defparameter *AΛB* nil) - - -;; 访问一个在之前从未未绑定的变量是一种不规范的行为(即使依然是可能发生的); -;; 不要尝试那样做。 - - -;; 局部绑定:'me'被绑定到"dance with you"上,当且仅当它在(let ...)内有效。 -;; `let`总是返回在其作用域内最后一个表达式的值 - -(let ((me "dance with you")) - me) -;; => "dance with you" - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 3. 结构体和集合 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; 结构体 -(defstruct dog name breed age) -(defparameter *rover* - (make-dog :name "rover" - :breed "collie" - :age 5)) -*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) - -(dog-p *rover*) ; => t ;; ewww) -(dog-name *rover*) ; => "rover" - -;; Dog-p,make-dog,以及 dog-name都是由defstruct创建的! - -;;; 点对单元 -;; `cons`可用于生成一个点对单元, 利用`car`以及`cdr`将分别得到第一个和第二个元素 -(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) -(car (cons 'SUBJECT 'VERB)) ; => SUBJECT -(cdr (cons 'SUBJECT 'VERB)) ; => VERB - -;;; 列表 - -;; 所有列表都是由点对单元构成、并以'nil'(或者'())结尾的一种被称为“链表”的数据结构 -(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) -;; `list`是一个生成列表的便利途径 -(list 1 2 3) ; => '(1 2 3) -;; 并且,一个引用也可被用做字面意义上的列表值 -'(1 2 3) ; => '(1 2 3) - -;; 同样的,依然可以用`cons`来添加一项到列表的起始位置 -(cons 4 '(1 2 3)) ; => '(4 1 2 3) - -;; 而`append`也可用于连接两个列表 -(append '(1 2) '(3 4)) ; => '(1 2 3 4) - -;; 或者使用`concatenate` - -(concatenate 'list '(1 2) '(3 4)) - -;; 列表是一种非常核心的数据类型,所以有非常多的处理列表的函数 -;; 例如: -(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) -(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) -(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) -(every #'evenp '(1 2 3 4)) ; => nil -(some #'oddp '(1 2 3 4)) ; => T -(butlast '(subject verb object)) ; => (SUBJECT VERB) - - -;;; 向量 - -;; 向量的字面意义是一个定长数组(译者注:此处所谓字面意义的,即为#(......)的形式,下文还会出现) -#(1 2 3) ; => #(1 2 3) - -;; 使用`concatenate`来将两个向量首尾连接在一起 -(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) - -;;; 数组 - -;; 向量和字符串只不过是数组的特例 - -;; 二维数组 - -(make-array (list 2 2)) - -;; (make-array '(2 2)) 也是可以的 - -; => #2A((0 0) (0 0)) - -(make-array (list 2 2 2)) - -; => #3A(((0 0) (0 0)) ((0 0) (0 0))) - -;; 注意:数组的默认初始值是可以指定的 -;; 下面是如何指定的示例: - -(make-array '(2) :initial-element 'unset) - -; => #(UNSET UNSET) - -;; 若想获取数组[1][1][1]上的元素: -(aref (make-array (list 2 2 2)) 1 1 1) - -; => 0 - -;;; 变长向量 - -;; 若将变长向量打印出来,那么它的字面意义上的值和定长向量的是一样的 - -(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) - :adjustable t :fill-pointer t)) - -*adjvec* ; => #(1 2 3) - -;; 添加新的元素: -(vector-push-extend 4 *adjvec*) ; => 3 - -*adjvec* ; => #(1 2 3 4) - - - -;;; 不怎么严谨地说,集合也可被视为列表 - -(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) -(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 -(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) -(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) - -;; 然而,你可能想使用一个更好的数据结构,而并非一个链表 - -;;; 在Common Lisp中,你也可以使用“字典”的概念——哈希表 - -;; 创建一个哈希表 -(defparameter *m* (make-hash-table)) - -;; 给定键,设置对应的值 -(setf (gethash 'a *m*) 1) - -;; (通过键)检索对应的值 -(gethash 'a *m*) ; => 1, t - -;; 注意此处有一细节:Common Lisp的`gethash`往往会返回两个值。 -;; (译者注:返回的第一个值表示给定的键所对应的值或者nil,第二个则表示在哈希表中是否存在这个给定的键) -;; 例如,如果可以找到给定的键所对应的值,则返回一个t,否则返回nil - -;; 由给定的键检索一个不存在的值,则返回nil(译者注:即第一个nil,第二个nil其实是指该键在哈希表中也不存在) - (gethash 'd *m*) ;=> nil, nil - -;; 给定一个键,你可以指定其对应的默认值: -(gethash 'd *m* :not-found) ; => :NOT-FOUND - -;; 在此,让我们看一看怎样处理`gethash`的多个返回值。 - -(multiple-value-bind - (a b) - (gethash 'd *m*) - (list a b)) -; => (NIL NIL) - -(multiple-value-bind - (a b) - (gethash 'a *m*) - (list a b)) -; => (1 T) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 3. 函数 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; 使用`lambda`来创建一个匿名函数。 -;; 一个函数总是返回其最后一个表达式的值。 -;; 将一个函数对象打印出来后的形式是多种多样的... - -(lambda () "Hello World") ; => # - -;; 使用`funcall`来调用lambda函数 -(funcall (lambda () "Hello World")) ; => "Hello World" - -;; 或者使用`apply` -(apply (lambda () "Hello World") nil) ; => "Hello World" - -;; 显示地定义一个函数(译者注:即非匿名的) -(defun hello-world () - "Hello World") -(hello-world) ; => "Hello World" - -;; 刚刚上面函数名"hello-world"后的()其实是函数的参数列表 -(defun hello (name) - (format nil "Hello, ~a " name)) - -(hello "Steve") ; => "Hello, Steve" - -;; 函数可以有可选形参并且其默认值都为nil - -(defun hello (name &optional from) - (if from - (format t "Hello, ~a, from ~a" name from) - (format t "Hello, ~a" name))) - - (hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas - -;; 你也可以指定那些可选形参的默认值 -(defun hello (name &optional (from "The world")) - (format t "Hello, ~a, from ~a" name from)) - -(hello "Steve") -; => Hello, Steve, from The world - -(hello "Steve" "the alpacas") -; => Hello, Steve, from the alpacas - - -;; 当然,你也可以设置关键字形参; -;; 关键字形参往往比可选形参更具灵活性。 - -(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) - (format t "Hello, ~a ~a, from ~a" honorific name from)) - -(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world - -(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") -; => Hello, Mr Jim, from the alpacas you met last summer - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 4. 等价性的含义 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; Common Lisp具有一个十分复杂的用于判断等价的系统,下面只是其中一部分的例子 - -;; 若要比较数值是否等价,使用`=` -(= 3 3.0) ; => t -(= 2 1) ; => nil - -;; 若要比较对象的类型,则使用`eql` -;;(译者注:抱歉,请忽略这句翻译;`eql`在二者`eq`等价,或者同为数字与字符下相同的类型,例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) -;; (想要弄清`eql`,其实有必要先了解`eq`) -;;(可以去CLHS上分别查看两者的文档,另外,《实用Common Lisp编程》里的4.8节也提到了两者的区别) -(eql 3 3) ; => t -(eql 3 3.0) ; => nil -(eql (list 3) (list 3)) ; => nil - -;; 对于列表、字符串、以及位向量,使用`equal` -(equal (list 'a 'b) (list 'a 'b)) ; => t -(equal (list 'a 'b) (list 'b 'a)) ; => nil - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 5. 控制流 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;;; 条件判断语句 - -(if t ; “测试”,即判断语句 - "this is true" ; “下一步”,即判断条件为真时求值的表达式 - "this is false") ; “否则”,即判断条件为假时求值的表达式 -; => "this is true" - -;; 在“测试”(判断)语句中,所有非nil或者非()的值都被视为真值 -(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) -(if (member 'Groucho '(Harpo Groucho Zeppo)) - 'yep - 'nope) -; => 'YEP - -;; `cond`将一系列测试语句串联起来,并对相应的表达式求值 -(cond ((> 2 2) (error "wrong!")) - ((< 2 2) (error "wrong again!")) - (t 'ok)) ; => 'OK - -;; 对于给定值的数据类型,`typecase`会做出相应地判断 -(typecase 1 - (string :string) - (integer :int)) - -; => :int - -;;; 迭代 - -;; 当然,递归是肯定被支持的: - -(defun walker (n) - (if (zerop n) - :walked - (walker (1- n)))) - -(walker) ; => :walked - -;; 而大部分场合下,我们使用`DOLIST`或者`LOOP`来进行迭代 - - -(dolist (i '(1 2 3 4)) - (format t "~a" i)) - -; => 1234 - -(loop for i from 0 below 10 - collect i) - -; => (0 1 2 3 4 5 6 7 8 9) - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 6. 变异 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; 使用`setf`可以对一个已经存在的变量进行赋值; -;; 事实上,刚刚在哈希表的例子中我们已经示范过了。 - -(let ((variable 10)) - (setf variable 2)) - ; => 2 - - -;; 所谓好的Lisp编码风格就是为了减少破坏性函数的使用,防止副作用的发生。 -;;(译者注:很惭愧,确实不明白原作者所说的"Mutation",即这里的“变异”到底指的是什么特性) -;;(毕竟他只给了一个例子,我猜测应该是和词法变量、闭包等特性有关,还望高人指点) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 7. 类与对象 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; 我们就不写什么有关动物的类了,下面给出的是一个很“人文主义”的类 - -(defclass human-powered-conveyance () - ((velocity - :accessor velocity - :initarg :velocity) - (average-efficiency - :accessor average-efficiency - :initarg :average-efficiency)) - (:documentation "A human powered conveyance")) - -;; `defclass`,后面接类名,以及超类列表 -;; 再接着是槽的列表(槽有点像Java里的字段),最后是一些可选的特性,例如文档说明“:documentation” - -;; 如果超类列表为空,则默认该类继承于“standard-object”类(standard-object又是T的子类); -;; 这种默认行为是可以改变的,但你最好有一定的基础并且知道自己到底在干什么; -;; 参阅《The Art of the Metaobject Protocol》来了解更多信息。 - -(defclass bicycle (human-powered-conveyance) - ((wheel-size - :accessor wheel-size - :initarg :wheel-size - :documentation "Diameter of the wheel.") - (height - :accessor height - :initarg :height))) - -(defclass recumbent (bicycle) - ((chain-type - :accessor chain-type - :initarg :chain-type))) - -(defclass unicycle (human-powered-conveyance) nil) - -(defclass canoe (human-powered-conveyance) - ((number-of-rowers - :accessor number-of-rowers - :initarg :number-of-rowers))) - - -;; 在REPL中对human-powered-conveyance类调用`DESCRIBE`如下: - -(describe 'human-powered-conveyance) - -; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE -; [symbol] -; -; HUMAN-POWERED-CONVEYANCE names the standard-class #: -; Documentation: -; A human powered conveyance -; Direct superclasses: STANDARD-OBJECT -; Direct subclasses: UNICYCLE, BICYCLE, CANOE -; Not yet finalized. -; Direct slots: -; VELOCITY -; Readers: VELOCITY -; Writers: (SETF VELOCITY) -; AVERAGE-EFFICIENCY -; Readers: AVERAGE-EFFICIENCY -; Writers: (SETF AVERAGE-EFFICIENCY) - -;; 注意到这些有用的返回信息——Common Lisp一直是一个交互式的系统。 - -;; 若要定义一个方法; -;; 先让我们注意到我们计算自行车轮子周长时使用了这样一个公式:C = d * pi - -(defmethod circumference ((object bicycle)) - (* pi (wheel-size object))) - -;; pi在Common Lisp中已经是一个内置的常量。 - -;; 假设我们已经知道效率值(“efficiency value”)和船桨数大概呈对数关系; -;; 那么效率值的定义应当在构造器/初始化过程中就被完成。 - -;; 下面是一个如何初始化实例的例子: -;; 构造它: - -(defmethod initialize-instance :after ((object canoe) &rest args) - (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) - -;; 接着初构造一个实例并检查平均效率... - -(average-efficiency (make-instance 'canoe :number-of-rowers 15)) -; => 2.7725887 - - - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 8. 宏 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; 宏可以让你扩展语法 - -;; Common Lisp并没有自带WHILE循环——所以让我们自己来为他添加一个; -;; 如果按照“拼装者”的直觉来看,我们会这样写: - -(defmacro while (condition &body body) - "While `condition` is true, `body` is executed. - -`condition` is tested prior to each execution of `body`" - (let ((block-name (gensym))) - `(tagbody - (unless ,condition - (go ,block-name)) - (progn - ,@body) - ,block-name))) - -;; 让我们来看看它的高级版本: - - -(defmacro while (condition &body body) - "While `condition` is true, `body` is executed. - -`condition` is tested prior to each execution of `body`" - `(loop while ,condition - do - (progn - ,@body))) - -;; 然而,在一个比较现代化的编译环境下,这样的WHILE是没有必要的; -;; LOOP形式的循环和这个WHILE同样的好,并且更易于阅读。 - -;; 注意到反引号'`',逗号','以及'@'符号,这三个符号; -;; 反引号'`'是一种所谓“quasiquote”的引用类型的运算符,有了它,之后的逗号“,”才有意义。 -;; 逗号“,”意味着解除引用(unquote,即开始求值);“@”符号则表示将当前的参数插入到当前整个列表中。 -;;(译者注:这三个符号只不过是语法糖罢了,而要想真正用好、用对,需要下一番功夫) -;;(甚至光看《实用 Common Lisp 编程》中关于宏的介绍都是不够的,建议再去读一读Paul Graham的两本著作《ANSI Common Lisp》和《On Lisp》) - -;; 函数`gensym`创建一个唯一的符号——这个符号确保不会出现在其他任何地方。 -;; 这样做是因为,宏是在编译期展开的,而在宏中声明的变量名极有可能和常规代码中使用的变量名发生冲突。 - -;; 可以去《实用 Common Lisp 编程》中阅读更多有关宏的内容。 -``` - - -## 拓展阅读 - -[继续阅读《实用 Common Lisp 编程》一书](http://www.gigamonkeys.com/book/) - - -## 致谢 - -非常感谢Scheme社区的人们,我基于他们的成果得以迅速的写出这篇有关Common Lisp的快速入门 -同时也感谢 -- [Paul Khuong](https://github.com/pkhuong) ,他提出了很多有用的点评。 -- cgit v1.2.3 From 2ba6501acc207925a283cae1fe7d20a613fba03a Mon Sep 17 00:00:00 2001 From: Mac David Date: Tue, 10 Dec 2013 00:02:27 +0800 Subject: 1st edition --- zh-cn/common-lisp.html.markdown | 610 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 610 insertions(+) create mode 100644 zh-cn/common-lisp.html.markdown diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown new file mode 100644 index 00000000..48530fbd --- /dev/null +++ b/zh-cn/common-lisp.html.markdown @@ -0,0 +1,610 @@ +--- +Language: "Common Lisp" +Filename: commonlisp.lisp +Contributors: + - ["Paul Nathan", "https://github.com/pnathan"] +Translator: + - ["Mac David", "http://github.com/macdavid313"] +--- + +ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 +这门语言也经常被引用作“可编程的编程语言”(可以写代码的代码)。 + +经典的入门点为[已经完全免费提供的实用Common Lisp编程](http://www.gigamonkeys.com/book/) + +另外还有一本近期内比较热门的 +[Land of Lisp](http://landoflisp.com/). + +```scheme +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 0. 语法 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 一般形式 + +;; Lisp有两个基本的语法部件:原子,以及S-表达式。 +;; 一般的,一组S-表达式被称为“组合式”。 + +10 ; 一个原子; 它对自身进行求值 + +:THING ;同样是一个原子;它被求值为一个符号 :thing + +t ;还是一个原子,代表逻辑真值。 + +(+ 1 2 3 4) ; 一个S表达式。 + +'(4 :foo t) ;同样是一个S表达式。 + + +;;; 注释 + +;; 一个分号开头的注释表示仅用于此行(单行);两个分号开头的则表示一个所谓标准注释; +;; 三个分号开头的意味着段落注释,而四个分号开头的注释用于文件头注释(译者注:即对该文件的说明)。 + +#| 块注释 + 可以涵盖多行,而且... + #| + 他们可以被嵌套! + |# +|# + +;;; 运行环境 + +;; 有很多不同的Common Lisp的实现;并且大部分的实现是符合标准的。 +;; 对于入门学习来说,CLISP是个不错的选择。 + +;; 可以通过QuickLisp.org's Quicklisp系统可以管理你的库。 + +;; 通常,使用一个文本编辑器和一个同时在运行的“REPL”来开发Common Lisp; +;; (译者注:“REPL”指读取-求值-打印循环)。 +;; “REPL”允许对程序进行交互式的运行、调试,就好像在系统中这是一场“现场直播”。 + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 1. 基本数据类型以及运算符 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 符号 + +'foo ; => FOO 注意到这个符号被自动转换成大写了。 + +;; `intern`由一个给定的字符串而创建相应的符号 + +(intern "AAAA") ; => AAAA + +(intern "aaa") ; => |aaa| + +;;; 数字 +9999999999999999999999 ; 整型数 +#b111 ; 二进制 => 7 +#o111 ; 八进制 => 73 +#x111 ; 十六进制 => 273 +3.14159s0 ; 单精度 +3.14159d0 ; 双精度 +1/2 ; 分数 +#C(1 2) ; 复数 + + +;; 使用函数时,应当写成这样的形式:(f x y z ...); +;; 其中,f是一个函数(名),x, y, z为参数; +;; 如果你想创建一个“字面”意义上(即不求值)的列表, 只需使用单引号 ' , +;; 从而避免接下来的表达式被求值。即,只“引用”这个数据(而不求值)。 +'(+ 1 2) ; => (+ 1 2) +;; 你同样也可以手动地调用一个函数(译者注:即使用函数对象来调用函数): +(funcall #'+ 1 2 3) ; => 6 +;; 一些算术运算符 +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + + ;;; 布尔运算 +t ; 逻辑真(任何不是nil的值都被视为真值) +nil ; 逻辑假,或者空列表 +(not nil) ; => t +(and 0 t) ; => t +(or 0 nil) ; => 0 + + ;;; 字符 +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA(希腊字母Lambda的小写) +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA(Unicode形式的小写希腊字母Lambda) + +;;; 字符串被视为一个定长字符数组 +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ;反斜杠用作转义字符 + +;; 字符串可以被连接起来 +(concatenate 'string "Hello " "world!") ; => "Hello world!" + +;; 一个字符串也可被视作一个字符的序列 +(elt "Apple" 0) ; => #\A + +;; `format`被用于格式化字符串 +(format nil "~a can be ~a" "strings" "formatted") + +;; 利用`format`打印到屏幕上是非常简单的(译者注:注意到第二个参数是t,不同于刚刚的nil);~% 代表换行符 +(format t "Common Lisp is groovy. Dude.~%") + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. 变量 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 你可以通过`defparameter`创建一个全局(动态)变量 +;; 除了:()[]{}",'`;#|\ 这些字符,其他任何字符都可被用于变量名 + +;; 动态变量名应该由*号开头与结尾! + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;; 你也可以使用Unicode字符: +(defparameter *AΛB* nil) + + +;; 访问一个在之前从未未绑定的变量是一种不规范的行为(即使依然是可能发生的); +;; 不要尝试那样做。 + + +;; 局部绑定:'me'被绑定到"dance with you"上,当且仅当它在(let ...)内有效。 +;; `let`总是返回在其作用域内最后一个表达式的值 + +(let ((me "dance with you")) + me) +;; => "dance with you" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. 结构体和集合 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 结构体 +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) + +(dog-p *rover*) ; => t ;; ewww) +(dog-name *rover*) ; => "rover" + +;; Dog-p,make-dog,以及 dog-name都是由defstruct创建的! + +;;; 点对单元 +;; `cons`可用于生成一个点对单元, 利用`car`以及`cdr`将分别得到第一个和第二个元素 +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + +;;; 列表 + +;; 所有列表都是由点对单元构成、并以'nil'(或者'())结尾的一种被称为“链表”的数据结构 +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) +;; `list`是一个生成列表的便利途径 +(list 1 2 3) ; => '(1 2 3) +;; 并且,一个引用也可被用做字面意义上的列表值 +'(1 2 3) ; => '(1 2 3) + +;; 同样的,依然可以用`cons`来添加一项到列表的起始位置 +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; 而`append`也可用于连接两个列表 +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; 或者使用`concatenate` + +(concatenate 'list '(1 2) '(3 4)) + +;; 列表是一种非常核心的数据类型,所以有非常多的处理列表的函数 +;; 例如: +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => nil +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; 向量 + +;; 向量的字面意义是一个定长数组(译者注:此处所谓字面意义的,即为#(......)的形式,下文还会出现) +#(1 2 3) ; => #(1 2 3) + +;; 使用`concatenate`来将两个向量首尾连接在一起 +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; 数组 + +;; 向量和字符串只不过是数组的特例 + +;; 二维数组 + +(make-array (list 2 2)) + +;; (make-array '(2 2)) 也是可以的 + +; => #2A((0 0) (0 0)) + +(make-array (list 2 2 2)) + +; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;; 注意:数组的默认初始值是可以指定的 +;; 下面是如何指定的示例: + +(make-array '(2) :initial-element 'unset) + +; => #(UNSET UNSET) + +;; 若想获取数组[1][1][1]上的元素: +(aref (make-array (list 2 2 2)) 1 1 1) + +; => 0 + +;;; 变长向量 + +;; 若将变长向量打印出来,那么它的字面意义上的值和定长向量的是一样的 + +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) + +*adjvec* ; => #(1 2 3) + +;; 添加新的元素: +(vector-push-extend 4 *adjvec*) ; => 3 + +*adjvec* ; => #(1 2 3 4) + + + +;;; 不怎么严谨地说,集合也可被视为列表 + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;; 然而,你可能想使用一个更好的数据结构,而并非一个链表 + +;;; 在Common Lisp中,你也可以使用“字典”的概念——哈希表 + +;; 创建一个哈希表 +(defparameter *m* (make-hash-table)) + +;; 给定键,设置对应的值 +(setf (gethash 'a *m*) 1) + +;; (通过键)检索对应的值 +(gethash 'a *m*) ; => 1, t + +;; 注意此处有一细节:Common Lisp的`gethash`往往会返回两个值。 +;; (译者注:返回的第一个值表示给定的键所对应的值或者nil,第二个则表示在哈希表中是否存在这个给定的键) +;; 例如,如果可以找到给定的键所对应的值,则返回一个t,否则返回nil + +;; 由给定的键检索一个不存在的值,则返回nil(译者注:即第一个nil,第二个nil其实是指该键在哈希表中也不存在) + (gethash 'd *m*) ;=> nil, nil + +;; 给定一个键,你可以指定其对应的默认值: +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;; 在此,让我们看一看怎样处理`gethash`的多个返回值。 + +(multiple-value-bind + (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind + (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. 函数 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 使用`lambda`来创建一个匿名函数。 +;; 一个函数总是返回其最后一个表达式的值。 +;; 将一个函数对象打印出来后的形式是多种多样的... + +(lambda () "Hello World") ; => # + +;; 使用`funcall`来调用lambda函数 +(funcall (lambda () "Hello World")) ; => "Hello World" + +;; 或者使用`apply` +(apply (lambda () "Hello World") nil) ; => "Hello World" + +;; 显示地定义一个函数(译者注:即非匿名的) +(defun hello-world () + "Hello World") +(hello-world) ; => "Hello World" + +;; 刚刚上面函数名"hello-world"后的()其实是函数的参数列表 +(defun hello (name) + (format nil "Hello, ~a " name)) + +(hello "Steve") ; => "Hello, Steve" + +;; 函数可以有可选形参并且其默认值都为nil + +(defun hello (name &optional from) + (if from + (format t "Hello, ~a, from ~a" name from) + (format t "Hello, ~a" name))) + + (hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas + +;; 你也可以指定那些可选形参的默认值 +(defun hello (name &optional (from "The world")) + (format t "Hello, ~a, from ~a" name from)) + +(hello "Steve") +; => Hello, Steve, from The world + +(hello "Steve" "the alpacas") +; => Hello, Steve, from the alpacas + + +;; 当然,你也可以设置关键字形参; +;; 关键字形参往往比可选形参更具灵活性。 + +(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) + (format t "Hello, ~a ~a, from ~a" honorific name from)) + +(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world + +(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") +; => Hello, Mr Jim, from the alpacas you met last summer + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. 等价性的含义 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Common Lisp具有一个十分复杂的用于判断等价的系统,下面只是其中一部分的例子 + +;; 若要比较数值是否等价,使用`=` +(= 3 3.0) ; => t +(= 2 1) ; => nil + +;; 若要比较对象的类型,则使用`eql` +;;(译者注:抱歉,请忽略这句翻译;`eql`在二者`eq`等价,或者同为数字与字符下相同的类型,例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) +;; (想要弄清`eql`,其实有必要先了解`eq`) +;;(可以去CLHS上分别查看两者的文档,另外,《实用Common Lisp编程》里的4.8节也提到了两者的区别) +(eql 3 3) ; => t +(eql 3 3.0) ; => nil +(eql (list 3) (list 3)) ; => nil + +;; 对于列表、字符串、以及位向量,使用`equal` +(equal (list 'a 'b) (list 'a 'b)) ; => t +(equal (list 'a 'b) (list 'b 'a)) ; => nil + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. 控制流 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 条件判断语句 + +(if t ; “测试”,即判断语句 + "this is true" ; “下一步”,即判断条件为真时求值的表达式 + "this is false") ; “否则”,即判断条件为假时求值的表达式 +; => "this is true" + +;; 在“测试”(判断)语句中,所有非nil或者非()的值都被视为真值 +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;; `cond`将一系列测试语句串联起来,并对相应的表达式求值 +(cond ((> 2 2) (error "wrong!")) + ((< 2 2) (error "wrong again!")) + (t 'ok)) ; => 'OK + +;; 对于给定值的数据类型,`typecase`会做出相应地判断 +(typecase 1 + (string :string) + (integer :int)) + +; => :int + +;;; 迭代 + +;; 当然,递归是肯定被支持的: + +(defun walker (n) + (if (zerop n) + :walked + (walker (1- n)))) + +(walker) ; => :walked + +;; 而大部分场合下,我们使用`DOLIST`或者`LOOP`来进行迭代 + + +(dolist (i '(1 2 3 4)) + (format t "~a" i)) + +; => 1234 + +(loop for i from 0 below 10 + collect i) + +; => (0 1 2 3 4 5 6 7 8 9) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. 变异 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 使用`setf`可以对一个已经存在的变量进行赋值; +;; 事实上,刚刚在哈希表的例子中我们已经示范过了。 + +(let ((variable 10)) + (setf variable 2)) + ; => 2 + + +;; 所谓好的Lisp编码风格就是为了减少破坏性函数的使用,防止副作用的发生。 +;;(译者注:很惭愧,确实不明白原作者所说的"Mutation",即这里的“变异”到底指的是什么特性) +;;(毕竟他只给了一个例子,我猜测应该是和词法变量、闭包等特性有关,还望高人指点) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. 类与对象 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 我们就不写什么有关动物的类了,下面给出的是一个很“人文主义”的类 + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "A human powered conveyance")) + +;; `defclass`,后面接类名,以及超类列表 +;; 再接着是槽的列表(槽有点像Java里的字段),最后是一些可选的特性,例如文档说明“:documentation” + +;; 如果超类列表为空,则默认该类继承于“standard-object”类(standard-object又是T的子类); +;; 这种默认行为是可以改变的,但你最好有一定的基础并且知道自己到底在干什么; +;; 参阅《The Art of the Metaobject Protocol》来了解更多信息。 + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + + +;; 在REPL中对human-powered-conveyance类调用`DESCRIBE`如下: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;; 注意到这些有用的返回信息——Common Lisp一直是一个交互式的系统。 + +;; 若要定义一个方法; +;; 先让我们注意到我们计算自行车轮子周长时使用了这样一个公式:C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;; pi在Common Lisp中已经是一个内置的常量。 + +;; 假设我们已经知道效率值(“efficiency value”)和船桨数大概呈对数关系; +;; 那么效率值的定义应当在构造器/初始化过程中就被完成。 + +;; 下面是一个如何初始化实例的例子: +;; 构造它: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + +;; 接着初构造一个实例并检查平均效率... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. 宏 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 宏可以让你扩展语法 + +;; Common Lisp并没有自带WHILE循环——所以让我们自己来为他添加一个; +;; 如果按照“拼装者”的直觉来看,我们会这样写: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. + +`condition` is tested prior to each execution of `body`" + (let ((block-name (gensym))) + `(tagbody + (unless ,condition + (go ,block-name)) + (progn + ,@body) + ,block-name))) + +;; 让我们来看看它的高级版本: + + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. + +`condition` is tested prior to each execution of `body`" + `(loop while ,condition + do + (progn + ,@body))) + +;; 然而,在一个比较现代化的编译环境下,这样的WHILE是没有必要的; +;; LOOP形式的循环和这个WHILE同样的好,并且更易于阅读。 + +;; 注意到反引号'`',逗号','以及'@'符号,这三个符号; +;; 反引号'`'是一种所谓“quasiquote”的引用类型的运算符,有了它,之后的逗号“,”才有意义。 +;; 逗号“,”意味着解除引用(unquote,即开始求值);“@”符号则表示将当前的参数插入到当前整个列表中。 +;;(译者注:这三个符号只不过是语法糖罢了,而要想真正用好、用对,需要下一番功夫) +;;(甚至光看《实用 Common Lisp 编程》中关于宏的介绍都是不够的,建议再去读一读Paul Graham的两本著作《ANSI Common Lisp》和《On Lisp》) + +;; 函数`gensym`创建一个唯一的符号——这个符号确保不会出现在其他任何地方。 +;; 这样做是因为,宏是在编译期展开的,而在宏中声明的变量名极有可能和常规代码中使用的变量名发生冲突。 + +;; 可以去《实用 Common Lisp 编程》中阅读更多有关宏的内容。 +``` + + +## 拓展阅读 + +[继续阅读《实用 Common Lisp 编程》一书](http://www.gigamonkeys.com/book/) + + +## 致谢 + +非常感谢Scheme社区的人们,我基于他们的成果得以迅速的写出这篇有关Common Lisp的快速入门 +同时也感谢 +- [Paul Khuong](https://github.com/pkhuong) ,他提出了很多有用的点评。 -- cgit v1.2.3 From 1bb3cea0c2a528c501dd8c2cf597336eb7b07d40 Mon Sep 17 00:00:00 2001 From: Mac David Date: Tue, 10 Dec 2013 00:08:11 +0800 Subject: 1st Edition --- zh-cn/common-lisp.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown index 48530fbd..d7534109 100644 --- a/zh-cn/common-lisp.html.markdown +++ b/zh-cn/common-lisp.html.markdown @@ -374,7 +374,8 @@ nil ; 逻辑假,或者空列表 (= 2 1) ; => nil ;; 若要比较对象的类型,则使用`eql` -;;(译者注:抱歉,请忽略这句翻译;`eql`在二者`eq`等价,或者同为数字与字符下相同的类型,例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) +;;(译者注:抱歉,翻译水平实在有限,下面是我个人的补充说明) +;;(`eql`在二者`eq`等价,或者同为数字与字符下相同的类型,例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) ;; (想要弄清`eql`,其实有必要先了解`eq`) ;;(可以去CLHS上分别查看两者的文档,另外,《实用Common Lisp编程》里的4.8节也提到了两者的区别) (eql 3 3) ; => t @@ -589,7 +590,8 @@ nil ; 逻辑假,或者空列表 ;; 反引号'`'是一种所谓“quasiquote”的引用类型的运算符,有了它,之后的逗号“,”才有意义。 ;; 逗号“,”意味着解除引用(unquote,即开始求值);“@”符号则表示将当前的参数插入到当前整个列表中。 ;;(译者注:这三个符号只不过是语法糖罢了,而要想真正用好、用对,需要下一番功夫) -;;(甚至光看《实用 Common Lisp 编程》中关于宏的介绍都是不够的,建议再去读一读Paul Graham的两本著作《ANSI Common Lisp》和《On Lisp》) +;;(甚至光看《实用 Common Lisp 编程》中关于宏的介绍都是不够的) +;;(建议再去读一读Paul Graham的两本著作《ANSI Common Lisp》和《On Lisp》) ;; 函数`gensym`创建一个唯一的符号——这个符号确保不会出现在其他任何地方。 ;; 这样做是因为,宏是在编译期展开的,而在宏中声明的变量名极有可能和常规代码中使用的变量名发生冲突。 -- cgit v1.2.3 From 86751331c66c4031b76eb6919f3c7b1c3d3c2c8a Mon Sep 17 00:00:00 2001 From: Mac David Date: Tue, 10 Dec 2013 00:10:58 +0800 Subject: temp --- zh-cn/common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown index d7534109..fe5f81ec 100644 --- a/zh-cn/common-lisp.html.markdown +++ b/zh-cn/common-lisp.html.markdown @@ -10,7 +10,7 @@ Translator: ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 这门语言也经常被引用作“可编程的编程语言”(可以写代码的代码)。 -经典的入门点为[已经完全免费提供的实用Common Lisp编程](http://www.gigamonkeys.com/book/) +经典的入门点为[已经完全免费提供的《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) 另外还有一本近期内比较热门的 [Land of Lisp](http://landoflisp.com/). -- cgit v1.2.3 From 139a9af08c1095bd655a3fc324da093969f78be2 Mon Sep 17 00:00:00 2001 From: Mac David Date: Tue, 10 Dec 2013 00:14:39 +0800 Subject: add Chinese translate of Common Lisp --- zh-cn/common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown index fe5f81ec..aaa33c83 100644 --- a/zh-cn/common-lisp.html.markdown +++ b/zh-cn/common-lisp.html.markdown @@ -10,7 +10,7 @@ Translator: ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 这门语言也经常被引用作“可编程的编程语言”(可以写代码的代码)。 -经典的入门点为[已经完全免费提供的《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) +经典的入门点为[已完全免费提供的《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) 另外还有一本近期内比较热门的 [Land of Lisp](http://landoflisp.com/). -- cgit v1.2.3 From 248284c91b641f2bd635dfe5a640f1fd3b8cd6a3 Mon Sep 17 00:00:00 2001 From: jakub-g Date: Mon, 9 Dec 2013 13:17:20 +0100 Subject: [bash] Replace `seq` with `{1..3}`, explain backticks `seq` is not standard, it's not available in MINGW and others. Using backticks is not the recommended way - e.g. they can't be nested. --- bash.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index afc46eb0..1f1c32c0 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -99,6 +99,10 @@ python2 hello.py 2> "error.err" # current directory. echo "There are $(ls | wc -l) items here." +# The same can be done using backticks `` but they can't be nested - the preferred way +# is to use $( ). +echo "There are `ls | wc -l` items here." + # Bash uses a case statement that works similarly to switch in Java and C++: case "$VARIABLE" in #List patterns for the conditions you want to meet @@ -109,8 +113,7 @@ esac # 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` +for VARIABLE in {1..3} do echo "$VARIABLE" done -- cgit v1.2.3 From 48ba096ac73a07aa56799e569ba9a56264319731 Mon Sep 17 00:00:00 2001 From: Ryan Date: Tue, 10 Dec 2013 18:57:05 +0800 Subject: =?UTF-8?q?assign=20=E5=BA=94=E8=AF=A5=E7=BF=BB=E8=AF=91=E6=88=90?= =?UTF-8?q?=20=E8=B5=8B=E5=80=BC=20=EF=BC=8C=E8=80=8C=E9=9D=9E=20=E5=88=86?= =?UTF-8?q?=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zh-cn/bash-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index e3eed3a6..fb55947d 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -40,7 +40,7 @@ VARIABLE = "Some string" echo $VARIABLE echo "$VARIABLE" echo '$VARIABLE' -# 当你分配 (assign) 、导出 (export),或者以其他方式使用变量时,变量名前不加 $。 +# 当你赋值 (assign) 、导出 (export),或者以其他方式使用变量时,变量名前不加 $。 # 如果要使用变量的值, 则要加 $。 # 注意: ' (单引号) 不会展开变量(即会屏蔽掉变量)。 -- cgit v1.2.3 From 27ae8bc889a09595898ffa7de5bb3dd6aba50ff6 Mon Sep 17 00:00:00 2001 From: Ryan Date: Tue, 10 Dec 2013 19:01:01 +0800 Subject: =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=A0=87=E7=82=B9=E7=AC=A6=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zh-cn/bash-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index e3eed3a6..e9cc7a9c 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -12,7 +12,7 @@ lang: zh-cn --- Bash 是一个为 GNU 计划编写的 Unix shell,是 Linux 和 Mac OS X 下的默认 shell。 -以下大多数例子可以作为脚本的一部分运行也可直接在 shell 下交互执行。 +以下大多数例子可以作为脚本的一部分运行,也可直接在 shell 下交互执行。 [更多信息](http://www.gnu.org/software/bash/manual/bashref.html) -- cgit v1.2.3 From ba78de82349549f521c899dd45493e0d9b20659c Mon Sep 17 00:00:00 2001 From: Mac David Date: Tue, 10 Dec 2013 19:04:35 +0800 Subject: Just update and correct some contents --- zh-cn/common-lisp.html.markdown | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown index aaa33c83..acecf60c 100644 --- a/zh-cn/common-lisp.html.markdown +++ b/zh-cn/common-lisp.html.markdown @@ -1,10 +1,10 @@ --- Language: "Common Lisp" Filename: commonlisp.lisp -Contributors: +Contributor: - ["Paul Nathan", "https://github.com/pnathan"] Translator: - - ["Mac David", "http://github.com/macdavid313"] + - ["Mac David", "http://macdavid313.com"] --- ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 @@ -31,9 +31,9 @@ ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范 t ;还是一个原子,代表逻辑真值。 -(+ 1 2 3 4) ; 一个S表达式。 +(+ 1 2 3 4) ; 一个S-表达式。 -'(4 :foo t) ;同样是一个S表达式。 +'(4 :foo t) ;同样是一个S-表达式。 ;;; 注释 @@ -146,7 +146,7 @@ nil ; 逻辑假,或者空列表 (defparameter *AΛB* nil) -;; 访问一个在之前从未未绑定的变量是一种不规范的行为(即使依然是可能发生的); +;; 访问一个在之前从未被绑定的变量是一种不规范的行为(即使依然是可能发生的); ;; 不要尝试那样做。 @@ -211,7 +211,7 @@ nil ; 逻辑假,或者空列表 ;;; 向量 -;; 向量的字面意义是一个定长数组(译者注:此处所谓字面意义的,即为#(......)的形式,下文还会出现) +;; 向量的字面意义是一个定长数组(译者注:此处所谓“字面意义”,即指#(......)的形式,下文还会出现) #(1 2 3) ; => #(1 2 3) ;; 使用`concatenate`来将两个向量首尾连接在一起 @@ -282,10 +282,12 @@ nil ; 逻辑假,或者空列表 (gethash 'a *m*) ; => 1, t ;; 注意此处有一细节:Common Lisp的`gethash`往往会返回两个值。 -;; (译者注:返回的第一个值表示给定的键所对应的值或者nil,第二个则表示在哈希表中是否存在这个给定的键) +;;(译者注:返回的第一个值表示给定的键所对应的值或者nil;) +;;(第二个是一个布尔值,表示在哈希表中是否存在这个给定的键) ;; 例如,如果可以找到给定的键所对应的值,则返回一个t,否则返回nil -;; 由给定的键检索一个不存在的值,则返回nil(译者注:即第一个nil,第二个nil其实是指该键在哈希表中也不存在) +;; 由给定的键检索一个不存在的值,则返回nil +;;(译者注:这个nil是第一个nil,第二个nil其实是指该键在哈希表中也不存在) (gethash 'd *m*) ;=> nil, nil ;; 给定一个键,你可以指定其对应的默认值: @@ -310,7 +312,7 @@ nil ; 逻辑假,或者空列表 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 使用`lambda`来创建一个匿名函数。 -;; 一个函数总是返回其最后一个表达式的值。 +;; 一个函数总是返回其形式体内最后一个表达式的值。 ;; 将一个函数对象打印出来后的形式是多种多样的... (lambda () "Hello World") ; => # @@ -352,7 +354,7 @@ nil ; 逻辑假,或者空列表 ; => Hello, Steve, from the alpacas -;; 当然,你也可以设置关键字形参; +;; 当然,你也可以设置所谓关键字形参; ;; 关键字形参往往比可选形参更具灵活性。 (defun generalized-greeter (name &key (from "the world") (honorific "Mx")) @@ -377,7 +379,7 @@ nil ; 逻辑假,或者空列表 ;;(译者注:抱歉,翻译水平实在有限,下面是我个人的补充说明) ;;(`eql`在二者`eq`等价,或者同为数字与字符下相同的类型,例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) ;; (想要弄清`eql`,其实有必要先了解`eq`) -;;(可以去CLHS上分别查看两者的文档,另外,《实用Common Lisp编程》里的4.8节也提到了两者的区别) +;;(可以去CLHS上分别查看两者的文档,另外,《实用Common Lisp编程》的4.8节也提到了两者的区别) (eql 3 3) ; => t (eql 3 3.0) ; => nil (eql (list 3) (list 3)) ; => nil @@ -455,7 +457,7 @@ nil ; 逻辑假,或者空列表 ;; 所谓好的Lisp编码风格就是为了减少破坏性函数的使用,防止副作用的发生。 ;;(译者注:很惭愧,确实不明白原作者所说的"Mutation",即这里的“变异”到底指的是什么特性) -;;(毕竟他只给了一个例子,我猜测应该是和词法变量、闭包等特性有关,还望高人指点) +;;(我猜测应该是和词法变量、闭包等特性有关,还望高人指点、修正与完善) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 7. 类与对象 @@ -501,7 +503,7 @@ nil ; 逻辑假,或者空列表 :initarg :number-of-rowers))) -;; 在REPL中对human-powered-conveyance类调用`DESCRIBE`如下: +;; 在REPL中对human-powered-conveyance类调用`DESCRIBE`后结果如下: (describe 'human-powered-conveyance) @@ -533,7 +535,7 @@ nil ; 逻辑假,或者空列表 ;; pi在Common Lisp中已经是一个内置的常量。 -;; 假设我们已经知道效率值(“efficiency value”)和船桨数大概呈对数关系; +;; 假设我们已经知道了效率值(“efficiency value”)和船桨数大概呈对数关系; ;; 那么效率值的定义应当在构造器/初始化过程中就被完成。 ;; 下面是一个如何初始化实例的例子: @@ -548,15 +550,13 @@ nil ; 逻辑假,或者空列表 ; => 2.7725887 - - ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 8. 宏 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 宏可以让你扩展语法 -;; Common Lisp并没有自带WHILE循环——所以让我们自己来为他添加一个; +;; 例如,Common Lisp并没有自带WHILE循环——所以让我们自己来为他添加一个; ;; 如果按照“拼装者”的直觉来看,我们会这样写: (defmacro while (condition &body body) @@ -573,7 +573,6 @@ nil ; 逻辑假,或者空列表 ;; 让我们来看看它的高级版本: - (defmacro while (condition &body body) "While `condition` is true, `body` is executed. @@ -589,7 +588,7 @@ nil ; 逻辑假,或者空列表 ;; 注意到反引号'`',逗号','以及'@'符号,这三个符号; ;; 反引号'`'是一种所谓“quasiquote”的引用类型的运算符,有了它,之后的逗号“,”才有意义。 ;; 逗号“,”意味着解除引用(unquote,即开始求值);“@”符号则表示将当前的参数插入到当前整个列表中。 -;;(译者注:这三个符号只不过是语法糖罢了,而要想真正用好、用对,需要下一番功夫) +;;(译者注:要想真正用好、用对这三个符号,需要下一番功夫) ;;(甚至光看《实用 Common Lisp 编程》中关于宏的介绍都是不够的) ;;(建议再去读一读Paul Graham的两本著作《ANSI Common Lisp》和《On Lisp》) @@ -610,3 +609,6 @@ nil ; 逻辑假,或者空列表 非常感谢Scheme社区的人们,我基于他们的成果得以迅速的写出这篇有关Common Lisp的快速入门 同时也感谢 - [Paul Khuong](https://github.com/pkhuong) ,他提出了很多有用的点评。 + +##译者寄语 +“祝福那些将思想镶嵌在重重括号之内的人们。” \ No newline at end of file -- cgit v1.2.3 From 19e7828719934bbd760f87d6e52d9cf08eb65056 Mon Sep 17 00:00:00 2001 From: Ryan Date: Tue, 10 Dec 2013 19:19:10 +0800 Subject: it should be `some_set` --- zh-cn/python-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown index 51efaac3..deb94cdc 100755 --- a/zh-cn/python-cn.html.markdown +++ b/zh-cn/python-cn.html.markdown @@ -232,7 +232,7 @@ filled_dict.setdefault("five", 6) # filled_dict["five"] 的值仍然是 5 # 集合储存无顺序的元素 empty_set = set() # 初始化一个集合 -some_set = set([1, 2, 2, 3, 4]) # filled_set 现在是 set([1, 2, 3, 4]) +some_set = set([1, 2, 2, 3, 4]) # some_set 现在是 set([1, 2, 3, 4]) # Python 2.7 之后,大括号可以用来表示集合 filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} -- cgit v1.2.3 From 55e01bd88c3dd44430fe9b11e584b97a5a1011cf Mon Sep 17 00:00:00 2001 From: Ryan Date: Tue, 10 Dec 2013 22:06:44 +0800 Subject: correct typo --- zh-cn/java-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index 9422ac2f..f7d319e6 100755 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -322,7 +322,7 @@ class Bicycle { // 方法声明的语法: // <作用域> <返回值类型> <方法名>(<参数列表>) public int getCadence() { - retur450635425n cadence; + return cadence; } // void返450635425回值函数没有返回值 -- cgit v1.2.3 From 9573bcce9fa5f4ed931442930199b8bdca6064bb Mon Sep 17 00:00:00 2001 From: Ryan Date: Tue, 10 Dec 2013 22:11:42 +0800 Subject: typo --- zh-cn/git-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown index 86952eba..1b93d162 100755 --- a/zh-cn/git-cn.html.markdown +++ b/zh-cn/git-cn.html.markdown @@ -219,7 +219,7 @@ $ git diff # 显示索引和最近一次提交的不同 $ git diff --cached -# 显示宫缩目录和最近一次提交的不同 +# 显示工作目录和最近一次提交的不同 $ git diff HEAD ``` -- cgit v1.2.3 From 4e12a861065592acae6b028a399372a13e5dfb21 Mon Sep 17 00:00:00 2001 From: Ryan Date: Tue, 10 Dec 2013 22:17:51 +0800 Subject: fix typo or that is not a typo? I'm not sure, so I request a pull, you make the choice. --- zh-cn/git-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown index 86952eba..6a45bd9e 100755 --- a/zh-cn/git-cn.html.markdown +++ b/zh-cn/git-cn.html.markdown @@ -349,7 +349,7 @@ $ git reset --hard 31f2bb1 ### rm -和add相反,从工作空间中去掉某个文件爱你 +和add相反,从工作空间中去掉某个文件 ```bash # 移除 HelloWorld.c -- cgit v1.2.3 From f9cff00e891225be0a3effc51b3261d5a10f60fb Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 11 Dec 2013 08:31:45 -0800 Subject: Fix problems with zh-cn common lisp --- zh-cn/common-lisp.html.markdown | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown index acecf60c..a1b76da5 100644 --- a/zh-cn/common-lisp.html.markdown +++ b/zh-cn/common-lisp.html.markdown @@ -1,10 +1,11 @@ --- -Language: "Common Lisp" -Filename: commonlisp.lisp -Contributor: +language: "Common Lisp" +filename: commonlisp-cn.lisp +contributors: - ["Paul Nathan", "https://github.com/pnathan"] -Translator: +translators: - ["Mac David", "http://macdavid313.com"] +lang: zh-cn --- ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 @@ -611,4 +612,4 @@ nil ; 逻辑假,或者空列表 - [Paul Khuong](https://github.com/pkhuong) ,他提出了很多有用的点评。 ##译者寄语 -“祝福那些将思想镶嵌在重重括号之内的人们。” \ No newline at end of file +“祝福那些将思想镶嵌在重重括号之内的人们。” -- cgit v1.2.3 From e26c663f75d45cf8495494a51e95c8abebda3167 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 11 Dec 2013 08:40:07 -0800 Subject: Fix standard ml --- standard-ml.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 849ba0f5..bd26709c 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -1,9 +1,8 @@ --- -language: Standard ML +language: "Standard ML" contributors: - ["Simon Shine", "http://shine.eu.org/"] - ["David Pedersen", "http://lonelyproton.com/"] -lang: en-en --- Standard ML is a functional programming language with type inference and some @@ -12,7 +11,7 @@ pattern matching, type inference (guessing the right types but never allowing implicit type conversion). If you have an imperative background, not being able to update variables can feel severely inhibiting. -```sml +```ocaml (* Comments in Standard ML begin with (* and end with *). Comments can be nested which means that all (* tags must end with a *) tag. This comment contains two nested comments. *) -- cgit v1.2.3 From 264241659deb4510ee4323684f0c7bd7889d2865 Mon Sep 17 00:00:00 2001 From: Mac David Date: Thu, 12 Dec 2013 01:00:18 +0800 Subject: Just a update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some lines’ words are just too much and I correct that. --- zh-cn/common-lisp.html.markdown | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown index acecf60c..72fd4787 100644 --- a/zh-cn/common-lisp.html.markdown +++ b/zh-cn/common-lisp.html.markdown @@ -10,7 +10,11 @@ Translator: ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 这门语言也经常被引用作“可编程的编程语言”(可以写代码的代码)。 +<<<<<<< HEAD 经典的入门点为[已完全免费提供的《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) +======= +经典的入门点为[已经完全免费提供的实用Common Lisp编程](http://www.gigamonkeys.com/book/) +>>>>>>> parent of 8675133... temp 另外还有一本近期内比较热门的 [Land of Lisp](http://landoflisp.com/). @@ -39,7 +43,8 @@ t ;还是一个原子,代表逻辑真值。 ;;; 注释 ;; 一个分号开头的注释表示仅用于此行(单行);两个分号开头的则表示一个所谓标准注释; -;; 三个分号开头的意味着段落注释,而四个分号开头的注释用于文件头注释(译者注:即对该文件的说明)。 +;; 三个分号开头的意味着段落注释; +;; 而四个分号开头的注释用于文件头注释(译者注:即对该文件的说明)。 #| 块注释 可以涵盖多行,而且... @@ -127,7 +132,8 @@ nil ; 逻辑假,或者空列表 ;; `format`被用于格式化字符串 (format nil "~a can be ~a" "strings" "formatted") -;; 利用`format`打印到屏幕上是非常简单的(译者注:注意到第二个参数是t,不同于刚刚的nil);~% 代表换行符 +;; 利用`format`打印到屏幕上是非常简单的 +;;(译者注:注意到第二个参数是t,不同于刚刚的nil);~% 代表换行符 (format t "Common Lisp is groovy. Dude.~%") @@ -211,7 +217,8 @@ nil ; 逻辑假,或者空列表 ;;; 向量 -;; 向量的字面意义是一个定长数组(译者注:此处所谓“字面意义”,即指#(......)的形式,下文还会出现) +;; 向量的字面意义是一个定长数组 +;;(译者注:此处所谓“字面意义”,即指#(......)的形式,下文还会出现) #(1 2 3) ; => #(1 2 3) ;; 使用`concatenate`来将两个向量首尾连接在一起 @@ -366,7 +373,7 @@ nil ; 逻辑假,或者空列表 ; => Hello, Mr Jim, from the alpacas you met last summer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 4. 等价性的含义 +;; 4. 等价性 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common Lisp具有一个十分复杂的用于判断等价的系统,下面只是其中一部分的例子 @@ -377,9 +384,11 @@ nil ; 逻辑假,或者空列表 ;; 若要比较对象的类型,则使用`eql` ;;(译者注:抱歉,翻译水平实在有限,下面是我个人的补充说明) -;;(`eql`在二者`eq`等价,或者同为数字与字符下相同的类型,例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) +;;(`eql`在二者`eq`等价,或者同为数字与字符下相同的类型) +;;(例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) ;; (想要弄清`eql`,其实有必要先了解`eq`) -;;(可以去CLHS上分别查看两者的文档,另外,《实用Common Lisp编程》的4.8节也提到了两者的区别) +;;(可以去CLHS上分别查看两者的文档) +;;(另外,《实用Common Lisp编程》的4.8节也提到了两者的区别) (eql 3 3) ; => t (eql 3 3.0) ; => nil (eql (list 3) (list 3)) ; => nil @@ -456,7 +465,7 @@ nil ; 逻辑假,或者空列表 ;; 所谓好的Lisp编码风格就是为了减少破坏性函数的使用,防止副作用的发生。 -;;(译者注:很惭愧,确实不明白原作者所说的"Mutation",即这里的“变异”到底指的是什么特性) +;;(译者注:很惭愧,确实不明白原作者的“变异”到底指的是什么特性) ;;(我猜测应该是和词法变量、闭包等特性有关,还望高人指点、修正与完善) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -475,9 +484,10 @@ nil ; 逻辑假,或者空列表 (:documentation "A human powered conveyance")) ;; `defclass`,后面接类名,以及超类列表 -;; 再接着是槽的列表(槽有点像Java里的字段),最后是一些可选的特性,例如文档说明“:documentation” +;; 再接着是槽的列表(槽有点像Java里的字段),最后是一些可选的特性 +;; 例如文档说明“:documentation” -;; 如果超类列表为空,则默认该类继承于“standard-object”类(standard-object又是T的子类); +;; 如果超类列表为空,则默认该类继承于“standard-object”类(standard-object又是T的子类) ;; 这种默认行为是可以改变的,但你最好有一定的基础并且知道自己到底在干什么; ;; 参阅《The Art of the Metaobject Protocol》来了解更多信息。 @@ -587,13 +597,15 @@ nil ; 逻辑假,或者空列表 ;; 注意到反引号'`',逗号','以及'@'符号,这三个符号; ;; 反引号'`'是一种所谓“quasiquote”的引用类型的运算符,有了它,之后的逗号“,”才有意义。 -;; 逗号“,”意味着解除引用(unquote,即开始求值);“@”符号则表示将当前的参数插入到当前整个列表中。 +;; 逗号“,”意味着解除引用(unquote,即开始求值); +;; “@”符号则表示将当前的参数插入到当前整个列表中。 ;;(译者注:要想真正用好、用对这三个符号,需要下一番功夫) ;;(甚至光看《实用 Common Lisp 编程》中关于宏的介绍都是不够的) ;;(建议再去读一读Paul Graham的两本著作《ANSI Common Lisp》和《On Lisp》) ;; 函数`gensym`创建一个唯一的符号——这个符号确保不会出现在其他任何地方。 -;; 这样做是因为,宏是在编译期展开的,而在宏中声明的变量名极有可能和常规代码中使用的变量名发生冲突。 +;; 这样做是因为,宏是在编译期展开的 +;; 而在宏中声明的变量名极有可能和常规代码中使用的变量名发生冲突。 ;; 可以去《实用 Common Lisp 编程》中阅读更多有关宏的内容。 ``` @@ -611,4 +623,4 @@ nil ; 逻辑假,或者空列表 - [Paul Khuong](https://github.com/pkhuong) ,他提出了很多有用的点评。 ##译者寄语 -“祝福那些将思想镶嵌在重重括号之内的人们。” \ No newline at end of file +“祝福那些将思想镶嵌在重重括号之内的人们。” -- cgit v1.2.3 From 48d9eecbfd6b53895c719c4903850cc8a561014c Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 11 Dec 2013 21:27:04 -0800 Subject: Fixed merge conflict --- zh-cn/common-lisp.html.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown index 9cc24198..e623ad1a 100644 --- a/zh-cn/common-lisp.html.markdown +++ b/zh-cn/common-lisp.html.markdown @@ -11,11 +11,7 @@ lang: zh-cn ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 这门语言也经常被引用作“可编程的编程语言”(可以写代码的代码)。 -<<<<<<< HEAD 经典的入门点为[已完全免费提供的《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) -======= -经典的入门点为[已经完全免费提供的实用Common Lisp编程](http://www.gigamonkeys.com/book/) ->>>>>>> parent of 8675133... temp 另外还有一本近期内比较热门的 [Land of Lisp](http://landoflisp.com/). -- cgit v1.2.3 From 432eb6f53df3a78dd5d3f564a1bbaa551a970732 Mon Sep 17 00:00:00 2001 From: cubuspl42 Date: Sat, 14 Dec 2013 14:41:07 +0100 Subject: Note about how declaring functions affects scope. --- javascript.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index 348cbff5..5f0b7951 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -271,6 +271,8 @@ permanent; // = 10 // outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!"; + // Inner functions are put in the local scope local by default, as if they + // were declared with 'var'. function inner(){ alert(prompt); } -- cgit v1.2.3 From eafeb3b4611d705f0c83bd652089bab364a8b2db Mon Sep 17 00:00:00 2001 From: cubuspl42 Date: Sat, 14 Dec 2013 14:44:06 +0100 Subject: typo --- javascript.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 5f0b7951..4584a28c 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -271,8 +271,8 @@ permanent; // = 10 // outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!"; - // Inner functions are put in the local scope local by default, as if they - // were declared with 'var'. + // Inner functions are put in the local scope by default, as if they were + // declared with 'var'. function inner(){ alert(prompt); } -- cgit v1.2.3 From b32d26240c5c4c51c7df6b219c656fd11a862410 Mon Sep 17 00:00:00 2001 From: Adrian Lopez Date: Mon, 16 Dec 2013 18:41:44 +0100 Subject: Trying to set a value in index 0. Is confusing --- julia.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index d1e17a26..4869e207 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -210,7 +210,7 @@ length(a) #=> 8 tup = (1, 2, 3) #=> (1,2,3) # an (Int64,Int64,Int64) tuple. tup[1] #=> 1 try: - tup[0] = 3 #=> ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) + tup[1] = 3 #=> ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) catch e println(e) end -- cgit v1.2.3 From bf659f14cf55e815cae22230c100e31a96b7d1c4 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Mon, 16 Dec 2013 21:42:15 +0100 Subject: [standard-ml/en-en] Some format fixing, variable renaming, some more about exceptions --- standard-ml.html.markdown | 99 ++++++++++++++++++++++++++++------------------- 1 file changed, 60 insertions(+), 39 deletions(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index bd26709c..b545f3e1 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -13,21 +13,21 @@ to update variables can feel severely inhibiting. ```ocaml (* Comments in Standard ML begin with (* and end with *). Comments can be - nested which means that all (* tags must end with a *) tag. This comment - contains two nested comments. *) + nested which means that all (* tags must end with a *) tag. This comment, + for example, contains two nested comments. *) (* A Standard ML program consists of declarations, e.g. value declarations: *) val rent = 1200 val phone_no = 5551337 val pi = 3.14159 -val negative_number = ~15 (* Yeah, unary minus is a so-called 'tilde' *) +val negative_number = ~15 (* Yeah, unary minus uses the 'tilde' symbol *) (* And just as importantly, functions: *) fun is_large(x : int) = if x > 37 then true else false (* Floating-point numbers are called "reals". *) -val tau = 2.0 * pi (* You can multiply reals *) -val twice_rent = 2 * rent (* You can multiply ints *) +val tau = 2.0 * pi (* You can multiply two reals *) +val twice_rent = 2 * rent (* You can multiply two ints *) (* val meh = 1.25 * 10 *) (* But you can't multiply an int and a real *) (* +, - and * are overloaded so they work for both int and real. *) @@ -42,16 +42,16 @@ val negative_rent = ~(rent) (* Would also have worked if rent were a "real" *) (* There are also booleans and boolean operators *) val got_milk = true val got_bread = false -val has_breakfast = got_milk andalso got_bread (* Yes, it's called andalso *) -val has_something = got_milk orelse got_bread (* Yes, it's called orelse *) +val has_breakfast = got_milk andalso got_bread (* 'andalso' is the operator *) +val has_something = got_milk orelse got_bread (* 'orelse' is the operator *) val is_sad = not(has_something) (* not is a function *) (* Many values can be compared using equality operators: = and <> *) val pays_same_rent = (rent = 1300) (* false *) val is_wrong_phone_no = (phone_no <> 5551337) (* false *) -(* The operator <> is what most other languages call != *) - +(* The operator <> is what most other languages call !=. *) +(* 'andalso' and 'orelse' are called && and || in many other languages. *) (* Actually, most of the parentheses above are unnecessary. Here are some different ways to say some of the things mentioned above: *) @@ -61,7 +61,7 @@ val pays_same_rent = rent = 1300 (* Looks confusing, but works *) val is_wrong_phone_no = phone_no <> 5551337 val negative_rent = ~rent (* ~ rent (notice the space) would also work *) -(* Parens are mostly necessary when grouping things: *) +(* Parentheses are mostly necessary when grouping things: *) val some_answer = is_large (5 + 5) (* Without parens, this would break! *) (* val some_answer = is_large 5 + 5 *) (* Read as: (is_large 5) + 5. Bad! *) @@ -84,32 +84,37 @@ val bar = [ #"H", #"e", #"l", #"l", #"o" ] (* SML also has lists! *) are functions available in that library that take strings as argument. *) val bob = String.implode bar (* gives "Hello" *) val bob_char_count = String.size bob (* gives 5 *) -val _ = print (bob ^ "\n") (* For good measure, add a linebreak *) +val _ = print (bob ^ "\n") (* For good measure, add a linebreak *) (* You can have lists of any kind *) val numbers = [1, 3, 3, 7, 229, 230, 248] (* : int list *) val names = [ "Fred", "Jane", "Alice" ] (* : string list *) + +(* Even lists of lists of things *) val groups = [ [ "Alice", "Bob" ], [ "Huey", "Dewey", "Louie" ], [ "Bonnie", "Clyde" ] ] (* : string list list *) val number_count = List.length numbers (* gives 7 *) -(* You can put single values in front of lists of the same kind - using the :: ("cons") operator *) +(* You can put single values in front of lists of the same kind using + the :: operator, called "the cons operator" (known from Lisp). *) val more_numbers = 13 :: numbers (* gives [13, 1, 3, 3, 7, ...] *) val more_groups = ["Batman","Superman"] :: groups (* Lists of the same kind can be appended using the @ ("append") operator *) val guest_list = [ "Mom", "Dad" ] @ [ "Aunt", "Uncle" ] -(* This could have been done with the "cons" operator *) +(* This could have been done with the "cons" operator. It is tricky because the + left-hand-side must be an element whereas the right-hand-side must be a list + of those elements. *) val guest_list = "Mom" :: "Dad" :: [ "Aunt", "Uncle" ] +val guest_list = "Mom" :: ("Dad" :: ("Aunt" :: ("Uncle" :: []))) (* If you have many lists of the same kind, you can concatenate them all *) val everyone = List.concat groups (* [ "Alice", "Bob", "Huey", ... ] *) -(* A list can contain any (finite) amount of values *) +(* A list can contain any (finite) number of values *) val lots = [ 5, 5, 5, 6, 4, 5, 6, 5, 4, 5, 7, 3 ] (* still just an int list *) (* Lists can only contain one kind of thing... *) @@ -264,21 +269,23 @@ fun map f [] = [] (* 'a is called a type variable. *) -(* We can define functions as infix *) -fun plus (x, y) = x + y -infix plus -(* We can now call plus like "2 plus 5" *) +(* We can declare functions as infix *) +val plus = add_them (* plus is now equal to the same function as add_them *) +infix plus (* plus is now an infix operator *) +val seven = 2 plus 5 (* seven is now bound to 7 *) -(* Functions can also be made infix before they are defined *) +(* Functions can also be made infix before they are declared *) infix minus -fun x minus y = x - y +fun x minus y = x - y (* It becomes a little hard to see what's the argument *) +val four = 8 minus 4 (* four is now bound to 4 *) -(* An infix function/operator can be made prefix with "op" *) -val n = op + (5, 5) -(* n is now 10 *) +(* An infix function/operator can be made prefix with 'op' *) +val n = op + (5, 5) (* n is now 10 *) -(* op is useful when combined with high order functions *) -val listSum = foldl op + 0 [1,2,3,4,5] +(* 'op' is useful when combined with high order functions because they expect + functions and not operators as arguments. Most operators are really just + infix functions. *) +val sum_of_numbers = foldl op+ 0 [1,2,3,4,5] (* Datatypes are useful for creating both simple and complex structures *) @@ -291,6 +298,8 @@ fun say(col) = if col = Blue then "You are blue!" else raise Fail "Unknown color" +val _ = print (say(Red) ^ "\n") + (* Datatypes are very often used in combination with pattern matching *) fun say Red = "You are red!" | say Green = "You are green!" @@ -318,28 +327,40 @@ val myTree = Node (Leaf 9, 8, Node (Leaf 3, 5, Leaf 7)) fun count (Leaf n) = n | count (Node (leftTree, n, rightTree)) = count leftTree + n + count rightTree +val myTreeCount = count myTree (* myTreeCount is now bound to 32 *) -(* Exceptions! *) -(* Exceptions can be raised using "raise" *) -fun raiseException msg = raise Fail msg -(* This raises exception `Fail "hello from exception"` *) -(* val _ = raiseException "hello from exception" *) +(* Exceptions! *) +(* Exceptions can be raised/thrown using the reserved word 'raise' *) +fun calculate_interest(n) = if n < 0.0 + then raise Domain + else n * 1.04 (* Exceptions can be caught using "handle" *) -val x = raiseException "hello" handle Fail msg => msg -(* x now has the value "hello" *) +val balance = calculate_interest ~180.0 + handle Domain => ~180.0 (* x now has the value ~180.0 *) -(* We can pattern match in "handle" to make sure +(* Some exceptions carry extra information with them *) +(* Here are some examples of built-in exceptions *) +fun failing_function [] = raise Empty (* used for empty lists *) + | failing_function [x] = raise Fail "This list is too short!" + | failing_function [x,y] = raise Overflow (* used for arithmetic *) + | failing_function xs = raise Fail "This list is too long!" + +(* We can pattern match in 'handle' to make sure a specfic exception was raised, or grab the message *) -val y = raiseException "..." handle Fail _ => "Fail was raised" - | Domain => "Domain was raised" -(* y now has the value "Fail was raised" *) +val err_msg = failing_function [1,2] handle Fail _ => "Fail was raised" + | Domain => "Domain was raised" + | Empty => "Empty was raised" + | _ => "Unknown exception" + +(* err_msg now has the value "Unknown exception" because Overflow isn't + listed as one of the patterns -- thus, the catch-all pattern _ is used. *) (* We can define our own exceptions like this *) exception MyException exception MyExceptionWithMessage of string - +exception SyntaxError of string * (int * int) (* File I/O! *) (* Write a nice poem to a file *) @@ -372,4 +393,4 @@ val test_poem = readPoem "roses.txt" (* gives [ "Roses are red,", [SML/NJ](http://smlnj.org/). * Follow the Coursera course [Programming Languages](https://www.coursera.org/course/proglang). * Get the book *ML for the Working Programmer* by Larry C. Paulson. - +* Use [StackOverflow's sml tag](http://stackoverflow.com/questions/tagged/sml). -- cgit v1.2.3 From d297853c06f4651da4c83f536d601140ae4d571d Mon Sep 17 00:00:00 2001 From: Adrian Lopez Date: Mon, 16 Dec 2013 23:33:41 +0100 Subject: Is a little confusing naming the variable as the abstract. At first I was thinking that cat::Lion means that you are waiting for a Lion type of super type Cat --- julia.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index d1e17a26..4e89bea5 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -575,15 +575,15 @@ end # For a non-constructor example, let's make a function meow: # Definitions for Lion, Panther, Tiger -function meow(cat::Lion) - cat.roar # access type properties using dot notation +function meow(animal::Lion) + animal.roar # access type properties using dot notation end -function meow(cat::Panther) +function meow(animal::Panther) "grrr" end -function meow(cat::Tiger) +function meow(animal::Tiger) "rawwwr" end -- cgit v1.2.3 From a670e63723953e71c32d79023ea05bf1d16915fd Mon Sep 17 00:00:00 2001 From: savior Date: Tue, 17 Dec 2013 21:37:30 +0800 Subject: fix common lisp --- zh-cn/common-lisp.html.markdown | 59 +++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 29 deletions(-) diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown index e623ad1a..f005dd58 100644 --- a/zh-cn/common-lisp.html.markdown +++ b/zh-cn/common-lisp.html.markdown @@ -5,15 +5,16 @@ contributors: - ["Paul Nathan", "https://github.com/pnathan"] translators: - ["Mac David", "http://macdavid313.com"] + - ["mut0u", "http://github.com/mut0u"] lang: zh-cn --- ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 这门语言也经常被引用作“可编程的编程语言”(可以写代码的代码)。 -经典的入门点为[已完全免费提供的《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) +免费的经典的入门书籍[《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) -另外还有一本近期内比较热门的 +另外还有一本热门的近期出版的 [Land of Lisp](http://landoflisp.com/). ```scheme @@ -23,7 +24,7 @@ ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范 ;;; 一般形式 -;; Lisp有两个基本的语法部件:原子,以及S-表达式。 +;; Lisp有两个基本的语法单元:原子(atom),以及S-表达式。 ;; 一般的,一组S-表达式被称为“组合式”。 10 ; 一个原子; 它对自身进行求值 @@ -52,12 +53,12 @@ t ;还是一个原子,代表逻辑真值。 ;;; 运行环境 -;; 有很多不同的Common Lisp的实现;并且大部分的实现是符合标准的。 +;; 有很多不同的Common Lisp的实现;并且大部分的实现是一致(可移植)的。 ;; 对于入门学习来说,CLISP是个不错的选择。 ;; 可以通过QuickLisp.org's Quicklisp系统可以管理你的库。 -;; 通常,使用一个文本编辑器和一个同时在运行的“REPL”来开发Common Lisp; +;; 通常,使用一个文本编辑器和一个的“REPL”来开发Common Lisp; ;; (译者注:“REPL”指读取-求值-打印循环)。 ;; “REPL”允许对程序进行交互式的运行、调试,就好像在系统中这是一场“现场直播”。 @@ -120,10 +121,10 @@ nil ; 逻辑假,或者空列表 "Hello, world!" "Benjamin \"Bugsy\" Siegel" ;反斜杠用作转义字符 -;; 字符串可以被连接起来 +;; 可以拼接字符串 (concatenate 'string "Hello " "world!") ; => "Hello world!" -;; 一个字符串也可被视作一个字符的序列 +;; 一个字符串也可被视作一个字符序列 (elt "Apple" 0) ; => #\A ;; `format`被用于格式化字符串 @@ -138,9 +139,10 @@ nil ; 逻辑假,或者空列表 ;; 2. 变量 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 你可以通过`defparameter`创建一个全局(动态)变量 -;; 除了:()[]{}",'`;#|\ 这些字符,其他任何字符都可被用于变量名 +;; 变量名可以是除了:()[]{}",'`;#|\ 这些字符之外的其他任何字符 ;; 动态变量名应该由*号开头与结尾! +;; (译者注:这个只是一个习惯) (defparameter *some-var* 5) *some-var* ; => 5 @@ -153,7 +155,7 @@ nil ; 逻辑假,或者空列表 ;; 不要尝试那样做。 -;; 局部绑定:'me'被绑定到"dance with you"上,当且仅当它在(let ...)内有效。 +;; 局部绑定:在(let ...)语句内,'me'被绑定到"dance with you"上。 ;; `let`总是返回在其作用域内最后一个表达式的值 (let ((me "dance with you")) @@ -177,7 +179,7 @@ nil ; 逻辑假,或者空列表 ;; Dog-p,make-dog,以及 dog-name都是由defstruct创建的! -;;; 点对单元 +;;; 点对单元(Pairs) ;; `cons`可用于生成一个点对单元, 利用`car`以及`cdr`将分别得到第一个和第二个元素 (cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) (car (cons 'SUBJECT 'VERB)) ; => SUBJECT @@ -185,7 +187,7 @@ nil ; 逻辑假,或者空列表 ;;; 列表 -;; 所有列表都是由点对单元构成、并以'nil'(或者'())结尾的一种被称为“链表”的数据结构 +;; 所有列表都是由点对单元构成的“链表”。它以'nil'(或者'())作为列表的最后一个元素。 (cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) ;; `list`是一个生成列表的便利途径 (list 1 2 3) ; => '(1 2 3) @@ -274,7 +276,7 @@ nil ; 逻辑假,或者空列表 ;; 然而,你可能想使用一个更好的数据结构,而并非一个链表 -;;; 在Common Lisp中,你也可以使用“字典”的概念——哈希表 +;;; 在Common Lisp中,“字典”和哈希表的实现是一样的。 ;; 创建一个哈希表 (defparameter *m* (make-hash-table)) @@ -285,7 +287,7 @@ nil ; 逻辑假,或者空列表 ;; (通过键)检索对应的值 (gethash 'a *m*) ; => 1, t -;; 注意此处有一细节:Common Lisp的`gethash`往往会返回两个值。 +;; 注意此处有一细节:Common Lisp往往返回多个值。`gethash`返回的两个值是t,代表找到了这个元素;返回nil表示没有找到这个元素。 ;;(译者注:返回的第一个值表示给定的键所对应的值或者nil;) ;;(第二个是一个布尔值,表示在哈希表中是否存在这个给定的键) ;; 例如,如果可以找到给定的键所对应的值,则返回一个t,否则返回nil @@ -370,7 +372,7 @@ nil ; 逻辑假,或者空列表 ; => Hello, Mr Jim, from the alpacas you met last summer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 4. 等价性 +;; 4. 等式 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common Lisp具有一个十分复杂的用于判断等价的系统,下面只是其中一部分的例子 @@ -381,9 +383,11 @@ nil ; 逻辑假,或者空列表 ;; 若要比较对象的类型,则使用`eql` ;;(译者注:抱歉,翻译水平实在有限,下面是我个人的补充说明) -;;(`eql`在二者`eq`等价,或者同为数字与字符下相同的类型) +;;(`eq` 返回真,如果对象的内存地址相等) +;;(`eql` 返回真,如果两个对象内存地址相等,或者对象的类型相同,并且值相等) ;;(例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) -;; (想要弄清`eql`,其实有必要先了解`eq`) +;;(想要弄清`eql`,其实有必要先了解`eq`) +;;([可以参考](http://stackoverflow.com/questions/547436/whats-the-difference-between-eq-eql-equal-and-equalp-in-common-lisp)) ;;(可以去CLHS上分别查看两者的文档) ;;(另外,《实用Common Lisp编程》的4.8节也提到了两者的区别) (eql 3 3) ; => t @@ -400,12 +404,12 @@ nil ; 逻辑假,或者空列表 ;;; 条件判断语句 -(if t ; “测试”,即判断语句 - "this is true" ; “下一步”,即判断条件为真时求值的表达式 - "this is false") ; “否则”,即判断条件为假时求值的表达式 +(if t ; “test”,即判断语句 + "this is true" ; “then”,即判断条件为真时求值的表达式 + "this is false") ; “else”,即判断条件为假时求值的表达式 ; => "this is true" -;; 在“测试”(判断)语句中,所有非nil或者非()的值都被视为真值 +;; 在“test”(判断)语句中,所有非nil或者非()的值都被视为真值 (member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) (if (member 'Groucho '(Harpo Groucho Zeppo)) 'yep @@ -450,7 +454,7 @@ nil ; 逻辑假,或者空列表 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 6. 变异 +;; 6. 可变性 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 使用`setf`可以对一个已经存在的变量进行赋值; @@ -461,15 +465,13 @@ nil ; 逻辑假,或者空列表 ; => 2 -;; 所谓好的Lisp编码风格就是为了减少破坏性函数的使用,防止副作用的发生。 -;;(译者注:很惭愧,确实不明白原作者的“变异”到底指的是什么特性) -;;(我猜测应该是和词法变量、闭包等特性有关,还望高人指点、修正与完善) +;; 所谓好的Lisp编码风格就是为了减少使用破坏性函数,防止发生副作用。 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 7. 类与对象 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 我们就不写什么有关动物的类了,下面给出的是一个很“人文主义”的类 +;; 我们就不写什么有关动物的类了,下面给出的人力车的类 (defclass human-powered-conveyance () ((velocity @@ -481,7 +483,7 @@ nil ; 逻辑假,或者空列表 (:documentation "A human powered conveyance")) ;; `defclass`,后面接类名,以及超类列表 -;; 再接着是槽的列表(槽有点像Java里的字段),最后是一些可选的特性 +;; 再接着是槽的列表(槽有点像Java里的成员变量),最后是一些可选的特性 ;; 例如文档说明“:documentation” ;; 如果超类列表为空,则默认该类继承于“standard-object”类(standard-object又是T的子类) @@ -545,8 +547,7 @@ nil ; 逻辑假,或者空列表 ;; 假设我们已经知道了效率值(“efficiency value”)和船桨数大概呈对数关系; ;; 那么效率值的定义应当在构造器/初始化过程中就被完成。 -;; 下面是一个如何初始化实例的例子: -;; 构造它: +;; 下面是一个Common Lisp构造实例时初始化实例的例子: (defmethod initialize-instance :after ((object canoe) &rest args) (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) @@ -564,7 +565,7 @@ nil ; 逻辑假,或者空列表 ;; 宏可以让你扩展语法 ;; 例如,Common Lisp并没有自带WHILE循环——所以让我们自己来为他添加一个; -;; 如果按照“拼装者”的直觉来看,我们会这样写: +;; 如果按照汇编程序的直觉来看,我们会这样写: (defmacro while (condition &body body) "While `condition` is true, `body` is executed. -- cgit v1.2.3 From 91d1227001ef24276de66cc0f46572b202c00f4b Mon Sep 17 00:00:00 2001 From: cattail Date: Tue, 17 Dec 2013 17:32:35 +0800 Subject: [all/zh-cn] fix incorrect language-specific suffix Also change useless executable file mode. --- zh-cn/c-cn.html.markdown | 0 zh-cn/common-lisp-cn.html.markdown | 624 +++++++++++++++++++++++++++++++++++++ zh-cn/common-lisp.html.markdown | 624 ------------------------------------- zh-cn/elisp-cn.html.markdown | 0 zh-cn/git-cn.html.markdown | 0 zh-cn/go-cn.html.markdown | 284 +++++++++++++++++ zh-cn/go-zh.html.markdown | 284 ----------------- zh-cn/haskell-cn.html.markdown | 0 zh-cn/java-cn.html.markdown | 0 zh-cn/javascript-cn.html.markdown | 0 zh-cn/php-cn.html.markdown | 0 zh-cn/python-cn.html.markdown | 0 12 files changed, 908 insertions(+), 908 deletions(-) mode change 100755 => 100644 zh-cn/c-cn.html.markdown create mode 100644 zh-cn/common-lisp-cn.html.markdown delete mode 100644 zh-cn/common-lisp.html.markdown mode change 100755 => 100644 zh-cn/elisp-cn.html.markdown mode change 100755 => 100644 zh-cn/git-cn.html.markdown create mode 100644 zh-cn/go-cn.html.markdown delete mode 100644 zh-cn/go-zh.html.markdown mode change 100755 => 100644 zh-cn/haskell-cn.html.markdown mode change 100755 => 100644 zh-cn/java-cn.html.markdown mode change 100755 => 100644 zh-cn/javascript-cn.html.markdown mode change 100755 => 100644 zh-cn/php-cn.html.markdown mode change 100755 => 100644 zh-cn/python-cn.html.markdown diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown old mode 100755 new mode 100644 diff --git a/zh-cn/common-lisp-cn.html.markdown b/zh-cn/common-lisp-cn.html.markdown new file mode 100644 index 00000000..f005dd58 --- /dev/null +++ b/zh-cn/common-lisp-cn.html.markdown @@ -0,0 +1,624 @@ +--- +language: "Common Lisp" +filename: commonlisp-cn.lisp +contributors: + - ["Paul Nathan", "https://github.com/pnathan"] +translators: + - ["Mac David", "http://macdavid313.com"] + - ["mut0u", "http://github.com/mut0u"] +lang: zh-cn +--- + +ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 +这门语言也经常被引用作“可编程的编程语言”(可以写代码的代码)。 + +免费的经典的入门书籍[《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) + +另外还有一本热门的近期出版的 +[Land of Lisp](http://landoflisp.com/). + +```scheme +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 0. 语法 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 一般形式 + +;; Lisp有两个基本的语法单元:原子(atom),以及S-表达式。 +;; 一般的,一组S-表达式被称为“组合式”。 + +10 ; 一个原子; 它对自身进行求值 + +:THING ;同样是一个原子;它被求值为一个符号 :thing + +t ;还是一个原子,代表逻辑真值。 + +(+ 1 2 3 4) ; 一个S-表达式。 + +'(4 :foo t) ;同样是一个S-表达式。 + + +;;; 注释 + +;; 一个分号开头的注释表示仅用于此行(单行);两个分号开头的则表示一个所谓标准注释; +;; 三个分号开头的意味着段落注释; +;; 而四个分号开头的注释用于文件头注释(译者注:即对该文件的说明)。 + +#| 块注释 + 可以涵盖多行,而且... + #| + 他们可以被嵌套! + |# +|# + +;;; 运行环境 + +;; 有很多不同的Common Lisp的实现;并且大部分的实现是一致(可移植)的。 +;; 对于入门学习来说,CLISP是个不错的选择。 + +;; 可以通过QuickLisp.org's Quicklisp系统可以管理你的库。 + +;; 通常,使用一个文本编辑器和一个的“REPL”来开发Common Lisp; +;; (译者注:“REPL”指读取-求值-打印循环)。 +;; “REPL”允许对程序进行交互式的运行、调试,就好像在系统中这是一场“现场直播”。 + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 1. 基本数据类型以及运算符 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 符号 + +'foo ; => FOO 注意到这个符号被自动转换成大写了。 + +;; `intern`由一个给定的字符串而创建相应的符号 + +(intern "AAAA") ; => AAAA + +(intern "aaa") ; => |aaa| + +;;; 数字 +9999999999999999999999 ; 整型数 +#b111 ; 二进制 => 7 +#o111 ; 八进制 => 73 +#x111 ; 十六进制 => 273 +3.14159s0 ; 单精度 +3.14159d0 ; 双精度 +1/2 ; 分数 +#C(1 2) ; 复数 + + +;; 使用函数时,应当写成这样的形式:(f x y z ...); +;; 其中,f是一个函数(名),x, y, z为参数; +;; 如果你想创建一个“字面”意义上(即不求值)的列表, 只需使用单引号 ' , +;; 从而避免接下来的表达式被求值。即,只“引用”这个数据(而不求值)。 +'(+ 1 2) ; => (+ 1 2) +;; 你同样也可以手动地调用一个函数(译者注:即使用函数对象来调用函数): +(funcall #'+ 1 2 3) ; => 6 +;; 一些算术运算符 +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + + ;;; 布尔运算 +t ; 逻辑真(任何不是nil的值都被视为真值) +nil ; 逻辑假,或者空列表 +(not nil) ; => t +(and 0 t) ; => t +(or 0 nil) ; => 0 + + ;;; 字符 +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA(希腊字母Lambda的小写) +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA(Unicode形式的小写希腊字母Lambda) + +;;; 字符串被视为一个定长字符数组 +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ;反斜杠用作转义字符 + +;; 可以拼接字符串 +(concatenate 'string "Hello " "world!") ; => "Hello world!" + +;; 一个字符串也可被视作一个字符序列 +(elt "Apple" 0) ; => #\A + +;; `format`被用于格式化字符串 +(format nil "~a can be ~a" "strings" "formatted") + +;; 利用`format`打印到屏幕上是非常简单的 +;;(译者注:注意到第二个参数是t,不同于刚刚的nil);~% 代表换行符 +(format t "Common Lisp is groovy. Dude.~%") + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. 变量 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 你可以通过`defparameter`创建一个全局(动态)变量 +;; 变量名可以是除了:()[]{}",'`;#|\ 这些字符之外的其他任何字符 + +;; 动态变量名应该由*号开头与结尾! +;; (译者注:这个只是一个习惯) + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;; 你也可以使用Unicode字符: +(defparameter *AΛB* nil) + + +;; 访问一个在之前从未被绑定的变量是一种不规范的行为(即使依然是可能发生的); +;; 不要尝试那样做。 + + +;; 局部绑定:在(let ...)语句内,'me'被绑定到"dance with you"上。 +;; `let`总是返回在其作用域内最后一个表达式的值 + +(let ((me "dance with you")) + me) +;; => "dance with you" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. 结构体和集合 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 结构体 +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) + +(dog-p *rover*) ; => t ;; ewww) +(dog-name *rover*) ; => "rover" + +;; Dog-p,make-dog,以及 dog-name都是由defstruct创建的! + +;;; 点对单元(Pairs) +;; `cons`可用于生成一个点对单元, 利用`car`以及`cdr`将分别得到第一个和第二个元素 +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + +;;; 列表 + +;; 所有列表都是由点对单元构成的“链表”。它以'nil'(或者'())作为列表的最后一个元素。 +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) +;; `list`是一个生成列表的便利途径 +(list 1 2 3) ; => '(1 2 3) +;; 并且,一个引用也可被用做字面意义上的列表值 +'(1 2 3) ; => '(1 2 3) + +;; 同样的,依然可以用`cons`来添加一项到列表的起始位置 +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; 而`append`也可用于连接两个列表 +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; 或者使用`concatenate` + +(concatenate 'list '(1 2) '(3 4)) + +;; 列表是一种非常核心的数据类型,所以有非常多的处理列表的函数 +;; 例如: +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => nil +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; 向量 + +;; 向量的字面意义是一个定长数组 +;;(译者注:此处所谓“字面意义”,即指#(......)的形式,下文还会出现) +#(1 2 3) ; => #(1 2 3) + +;; 使用`concatenate`来将两个向量首尾连接在一起 +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; 数组 + +;; 向量和字符串只不过是数组的特例 + +;; 二维数组 + +(make-array (list 2 2)) + +;; (make-array '(2 2)) 也是可以的 + +; => #2A((0 0) (0 0)) + +(make-array (list 2 2 2)) + +; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;; 注意:数组的默认初始值是可以指定的 +;; 下面是如何指定的示例: + +(make-array '(2) :initial-element 'unset) + +; => #(UNSET UNSET) + +;; 若想获取数组[1][1][1]上的元素: +(aref (make-array (list 2 2 2)) 1 1 1) + +; => 0 + +;;; 变长向量 + +;; 若将变长向量打印出来,那么它的字面意义上的值和定长向量的是一样的 + +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) + +*adjvec* ; => #(1 2 3) + +;; 添加新的元素: +(vector-push-extend 4 *adjvec*) ; => 3 + +*adjvec* ; => #(1 2 3 4) + + + +;;; 不怎么严谨地说,集合也可被视为列表 + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;; 然而,你可能想使用一个更好的数据结构,而并非一个链表 + +;;; 在Common Lisp中,“字典”和哈希表的实现是一样的。 + +;; 创建一个哈希表 +(defparameter *m* (make-hash-table)) + +;; 给定键,设置对应的值 +(setf (gethash 'a *m*) 1) + +;; (通过键)检索对应的值 +(gethash 'a *m*) ; => 1, t + +;; 注意此处有一细节:Common Lisp往往返回多个值。`gethash`返回的两个值是t,代表找到了这个元素;返回nil表示没有找到这个元素。 +;;(译者注:返回的第一个值表示给定的键所对应的值或者nil;) +;;(第二个是一个布尔值,表示在哈希表中是否存在这个给定的键) +;; 例如,如果可以找到给定的键所对应的值,则返回一个t,否则返回nil + +;; 由给定的键检索一个不存在的值,则返回nil +;;(译者注:这个nil是第一个nil,第二个nil其实是指该键在哈希表中也不存在) + (gethash 'd *m*) ;=> nil, nil + +;; 给定一个键,你可以指定其对应的默认值: +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;; 在此,让我们看一看怎样处理`gethash`的多个返回值。 + +(multiple-value-bind + (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind + (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. 函数 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 使用`lambda`来创建一个匿名函数。 +;; 一个函数总是返回其形式体内最后一个表达式的值。 +;; 将一个函数对象打印出来后的形式是多种多样的... + +(lambda () "Hello World") ; => # + +;; 使用`funcall`来调用lambda函数 +(funcall (lambda () "Hello World")) ; => "Hello World" + +;; 或者使用`apply` +(apply (lambda () "Hello World") nil) ; => "Hello World" + +;; 显示地定义一个函数(译者注:即非匿名的) +(defun hello-world () + "Hello World") +(hello-world) ; => "Hello World" + +;; 刚刚上面函数名"hello-world"后的()其实是函数的参数列表 +(defun hello (name) + (format nil "Hello, ~a " name)) + +(hello "Steve") ; => "Hello, Steve" + +;; 函数可以有可选形参并且其默认值都为nil + +(defun hello (name &optional from) + (if from + (format t "Hello, ~a, from ~a" name from) + (format t "Hello, ~a" name))) + + (hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas + +;; 你也可以指定那些可选形参的默认值 +(defun hello (name &optional (from "The world")) + (format t "Hello, ~a, from ~a" name from)) + +(hello "Steve") +; => Hello, Steve, from The world + +(hello "Steve" "the alpacas") +; => Hello, Steve, from the alpacas + + +;; 当然,你也可以设置所谓关键字形参; +;; 关键字形参往往比可选形参更具灵活性。 + +(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) + (format t "Hello, ~a ~a, from ~a" honorific name from)) + +(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world + +(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") +; => Hello, Mr Jim, from the alpacas you met last summer + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. 等式 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Common Lisp具有一个十分复杂的用于判断等价的系统,下面只是其中一部分的例子 + +;; 若要比较数值是否等价,使用`=` +(= 3 3.0) ; => t +(= 2 1) ; => nil + +;; 若要比较对象的类型,则使用`eql` +;;(译者注:抱歉,翻译水平实在有限,下面是我个人的补充说明) +;;(`eq` 返回真,如果对象的内存地址相等) +;;(`eql` 返回真,如果两个对象内存地址相等,或者对象的类型相同,并且值相等) +;;(例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) +;;(想要弄清`eql`,其实有必要先了解`eq`) +;;([可以参考](http://stackoverflow.com/questions/547436/whats-the-difference-between-eq-eql-equal-and-equalp-in-common-lisp)) +;;(可以去CLHS上分别查看两者的文档) +;;(另外,《实用Common Lisp编程》的4.8节也提到了两者的区别) +(eql 3 3) ; => t +(eql 3 3.0) ; => nil +(eql (list 3) (list 3)) ; => nil + +;; 对于列表、字符串、以及位向量,使用`equal` +(equal (list 'a 'b) (list 'a 'b)) ; => t +(equal (list 'a 'b) (list 'b 'a)) ; => nil + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. 控制流 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 条件判断语句 + +(if t ; “test”,即判断语句 + "this is true" ; “then”,即判断条件为真时求值的表达式 + "this is false") ; “else”,即判断条件为假时求值的表达式 +; => "this is true" + +;; 在“test”(判断)语句中,所有非nil或者非()的值都被视为真值 +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;; `cond`将一系列测试语句串联起来,并对相应的表达式求值 +(cond ((> 2 2) (error "wrong!")) + ((< 2 2) (error "wrong again!")) + (t 'ok)) ; => 'OK + +;; 对于给定值的数据类型,`typecase`会做出相应地判断 +(typecase 1 + (string :string) + (integer :int)) + +; => :int + +;;; 迭代 + +;; 当然,递归是肯定被支持的: + +(defun walker (n) + (if (zerop n) + :walked + (walker (1- n)))) + +(walker) ; => :walked + +;; 而大部分场合下,我们使用`DOLIST`或者`LOOP`来进行迭代 + + +(dolist (i '(1 2 3 4)) + (format t "~a" i)) + +; => 1234 + +(loop for i from 0 below 10 + collect i) + +; => (0 1 2 3 4 5 6 7 8 9) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. 可变性 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 使用`setf`可以对一个已经存在的变量进行赋值; +;; 事实上,刚刚在哈希表的例子中我们已经示范过了。 + +(let ((variable 10)) + (setf variable 2)) + ; => 2 + + +;; 所谓好的Lisp编码风格就是为了减少使用破坏性函数,防止发生副作用。 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. 类与对象 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 我们就不写什么有关动物的类了,下面给出的人力车的类 + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "A human powered conveyance")) + +;; `defclass`,后面接类名,以及超类列表 +;; 再接着是槽的列表(槽有点像Java里的成员变量),最后是一些可选的特性 +;; 例如文档说明“:documentation” + +;; 如果超类列表为空,则默认该类继承于“standard-object”类(standard-object又是T的子类) +;; 这种默认行为是可以改变的,但你最好有一定的基础并且知道自己到底在干什么; +;; 参阅《The Art of the Metaobject Protocol》来了解更多信息。 + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + + +;; 在REPL中对human-powered-conveyance类调用`DESCRIBE`后结果如下: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;; 注意到这些有用的返回信息——Common Lisp一直是一个交互式的系统。 + +;; 若要定义一个方法; +;; 先让我们注意到我们计算自行车轮子周长时使用了这样一个公式:C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;; pi在Common Lisp中已经是一个内置的常量。 + +;; 假设我们已经知道了效率值(“efficiency value”)和船桨数大概呈对数关系; +;; 那么效率值的定义应当在构造器/初始化过程中就被完成。 + +;; 下面是一个Common Lisp构造实例时初始化实例的例子: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + +;; 接着初构造一个实例并检查平均效率... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. 宏 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 宏可以让你扩展语法 + +;; 例如,Common Lisp并没有自带WHILE循环——所以让我们自己来为他添加一个; +;; 如果按照汇编程序的直觉来看,我们会这样写: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. + +`condition` is tested prior to each execution of `body`" + (let ((block-name (gensym))) + `(tagbody + (unless ,condition + (go ,block-name)) + (progn + ,@body) + ,block-name))) + +;; 让我们来看看它的高级版本: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. + +`condition` is tested prior to each execution of `body`" + `(loop while ,condition + do + (progn + ,@body))) + +;; 然而,在一个比较现代化的编译环境下,这样的WHILE是没有必要的; +;; LOOP形式的循环和这个WHILE同样的好,并且更易于阅读。 + +;; 注意到反引号'`',逗号','以及'@'符号,这三个符号; +;; 反引号'`'是一种所谓“quasiquote”的引用类型的运算符,有了它,之后的逗号“,”才有意义。 +;; 逗号“,”意味着解除引用(unquote,即开始求值); +;; “@”符号则表示将当前的参数插入到当前整个列表中。 +;;(译者注:要想真正用好、用对这三个符号,需要下一番功夫) +;;(甚至光看《实用 Common Lisp 编程》中关于宏的介绍都是不够的) +;;(建议再去读一读Paul Graham的两本著作《ANSI Common Lisp》和《On Lisp》) + +;; 函数`gensym`创建一个唯一的符号——这个符号确保不会出现在其他任何地方。 +;; 这样做是因为,宏是在编译期展开的 +;; 而在宏中声明的变量名极有可能和常规代码中使用的变量名发生冲突。 + +;; 可以去《实用 Common Lisp 编程》中阅读更多有关宏的内容。 +``` + + +## 拓展阅读 + +[继续阅读《实用 Common Lisp 编程》一书](http://www.gigamonkeys.com/book/) + + +## 致谢 + +非常感谢Scheme社区的人们,我基于他们的成果得以迅速的写出这篇有关Common Lisp的快速入门 +同时也感谢 +- [Paul Khuong](https://github.com/pkhuong) ,他提出了很多有用的点评。 + +##译者寄语 +“祝福那些将思想镶嵌在重重括号之内的人们。” diff --git a/zh-cn/common-lisp.html.markdown b/zh-cn/common-lisp.html.markdown deleted file mode 100644 index f005dd58..00000000 --- a/zh-cn/common-lisp.html.markdown +++ /dev/null @@ -1,624 +0,0 @@ ---- -language: "Common Lisp" -filename: commonlisp-cn.lisp -contributors: - - ["Paul Nathan", "https://github.com/pnathan"] -translators: - - ["Mac David", "http://macdavid313.com"] - - ["mut0u", "http://github.com/mut0u"] -lang: zh-cn ---- - -ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范式的编程语言。 -这门语言也经常被引用作“可编程的编程语言”(可以写代码的代码)。 - -免费的经典的入门书籍[《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) - -另外还有一本热门的近期出版的 -[Land of Lisp](http://landoflisp.com/). - -```scheme -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; 0. 语法 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;;; 一般形式 - -;; Lisp有两个基本的语法单元:原子(atom),以及S-表达式。 -;; 一般的,一组S-表达式被称为“组合式”。 - -10 ; 一个原子; 它对自身进行求值 - -:THING ;同样是一个原子;它被求值为一个符号 :thing - -t ;还是一个原子,代表逻辑真值。 - -(+ 1 2 3 4) ; 一个S-表达式。 - -'(4 :foo t) ;同样是一个S-表达式。 - - -;;; 注释 - -;; 一个分号开头的注释表示仅用于此行(单行);两个分号开头的则表示一个所谓标准注释; -;; 三个分号开头的意味着段落注释; -;; 而四个分号开头的注释用于文件头注释(译者注:即对该文件的说明)。 - -#| 块注释 - 可以涵盖多行,而且... - #| - 他们可以被嵌套! - |# -|# - -;;; 运行环境 - -;; 有很多不同的Common Lisp的实现;并且大部分的实现是一致(可移植)的。 -;; 对于入门学习来说,CLISP是个不错的选择。 - -;; 可以通过QuickLisp.org's Quicklisp系统可以管理你的库。 - -;; 通常,使用一个文本编辑器和一个的“REPL”来开发Common Lisp; -;; (译者注:“REPL”指读取-求值-打印循环)。 -;; “REPL”允许对程序进行交互式的运行、调试,就好像在系统中这是一场“现场直播”。 - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; 1. 基本数据类型以及运算符 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;;; 符号 - -'foo ; => FOO 注意到这个符号被自动转换成大写了。 - -;; `intern`由一个给定的字符串而创建相应的符号 - -(intern "AAAA") ; => AAAA - -(intern "aaa") ; => |aaa| - -;;; 数字 -9999999999999999999999 ; 整型数 -#b111 ; 二进制 => 7 -#o111 ; 八进制 => 73 -#x111 ; 十六进制 => 273 -3.14159s0 ; 单精度 -3.14159d0 ; 双精度 -1/2 ; 分数 -#C(1 2) ; 复数 - - -;; 使用函数时,应当写成这样的形式:(f x y z ...); -;; 其中,f是一个函数(名),x, y, z为参数; -;; 如果你想创建一个“字面”意义上(即不求值)的列表, 只需使用单引号 ' , -;; 从而避免接下来的表达式被求值。即,只“引用”这个数据(而不求值)。 -'(+ 1 2) ; => (+ 1 2) -;; 你同样也可以手动地调用一个函数(译者注:即使用函数对象来调用函数): -(funcall #'+ 1 2 3) ; => 6 -;; 一些算术运算符 -(+ 1 1) ; => 2 -(- 8 1) ; => 7 -(* 10 2) ; => 20 -(expt 2 3) ; => 8 -(mod 5 2) ; => 1 -(/ 35 5) ; => 7 -(/ 1 3) ; => 1/3 -(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) - - ;;; 布尔运算 -t ; 逻辑真(任何不是nil的值都被视为真值) -nil ; 逻辑假,或者空列表 -(not nil) ; => t -(and 0 t) ; => t -(or 0 nil) ; => 0 - - ;;; 字符 -#\A ; => #\A -#\λ ; => #\GREEK_SMALL_LETTER_LAMDA(希腊字母Lambda的小写) -#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA(Unicode形式的小写希腊字母Lambda) - -;;; 字符串被视为一个定长字符数组 -"Hello, world!" -"Benjamin \"Bugsy\" Siegel" ;反斜杠用作转义字符 - -;; 可以拼接字符串 -(concatenate 'string "Hello " "world!") ; => "Hello world!" - -;; 一个字符串也可被视作一个字符序列 -(elt "Apple" 0) ; => #\A - -;; `format`被用于格式化字符串 -(format nil "~a can be ~a" "strings" "formatted") - -;; 利用`format`打印到屏幕上是非常简单的 -;;(译者注:注意到第二个参数是t,不同于刚刚的nil);~% 代表换行符 -(format t "Common Lisp is groovy. Dude.~%") - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 2. 变量 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 你可以通过`defparameter`创建一个全局(动态)变量 -;; 变量名可以是除了:()[]{}",'`;#|\ 这些字符之外的其他任何字符 - -;; 动态变量名应该由*号开头与结尾! -;; (译者注:这个只是一个习惯) - -(defparameter *some-var* 5) -*some-var* ; => 5 - -;; 你也可以使用Unicode字符: -(defparameter *AΛB* nil) - - -;; 访问一个在之前从未被绑定的变量是一种不规范的行为(即使依然是可能发生的); -;; 不要尝试那样做。 - - -;; 局部绑定:在(let ...)语句内,'me'被绑定到"dance with you"上。 -;; `let`总是返回在其作用域内最后一个表达式的值 - -(let ((me "dance with you")) - me) -;; => "dance with you" - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 3. 结构体和集合 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; 结构体 -(defstruct dog name breed age) -(defparameter *rover* - (make-dog :name "rover" - :breed "collie" - :age 5)) -*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) - -(dog-p *rover*) ; => t ;; ewww) -(dog-name *rover*) ; => "rover" - -;; Dog-p,make-dog,以及 dog-name都是由defstruct创建的! - -;;; 点对单元(Pairs) -;; `cons`可用于生成一个点对单元, 利用`car`以及`cdr`将分别得到第一个和第二个元素 -(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) -(car (cons 'SUBJECT 'VERB)) ; => SUBJECT -(cdr (cons 'SUBJECT 'VERB)) ; => VERB - -;;; 列表 - -;; 所有列表都是由点对单元构成的“链表”。它以'nil'(或者'())作为列表的最后一个元素。 -(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) -;; `list`是一个生成列表的便利途径 -(list 1 2 3) ; => '(1 2 3) -;; 并且,一个引用也可被用做字面意义上的列表值 -'(1 2 3) ; => '(1 2 3) - -;; 同样的,依然可以用`cons`来添加一项到列表的起始位置 -(cons 4 '(1 2 3)) ; => '(4 1 2 3) - -;; 而`append`也可用于连接两个列表 -(append '(1 2) '(3 4)) ; => '(1 2 3 4) - -;; 或者使用`concatenate` - -(concatenate 'list '(1 2) '(3 4)) - -;; 列表是一种非常核心的数据类型,所以有非常多的处理列表的函数 -;; 例如: -(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) -(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) -(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) -(every #'evenp '(1 2 3 4)) ; => nil -(some #'oddp '(1 2 3 4)) ; => T -(butlast '(subject verb object)) ; => (SUBJECT VERB) - - -;;; 向量 - -;; 向量的字面意义是一个定长数组 -;;(译者注:此处所谓“字面意义”,即指#(......)的形式,下文还会出现) -#(1 2 3) ; => #(1 2 3) - -;; 使用`concatenate`来将两个向量首尾连接在一起 -(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) - -;;; 数组 - -;; 向量和字符串只不过是数组的特例 - -;; 二维数组 - -(make-array (list 2 2)) - -;; (make-array '(2 2)) 也是可以的 - -; => #2A((0 0) (0 0)) - -(make-array (list 2 2 2)) - -; => #3A(((0 0) (0 0)) ((0 0) (0 0))) - -;; 注意:数组的默认初始值是可以指定的 -;; 下面是如何指定的示例: - -(make-array '(2) :initial-element 'unset) - -; => #(UNSET UNSET) - -;; 若想获取数组[1][1][1]上的元素: -(aref (make-array (list 2 2 2)) 1 1 1) - -; => 0 - -;;; 变长向量 - -;; 若将变长向量打印出来,那么它的字面意义上的值和定长向量的是一样的 - -(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) - :adjustable t :fill-pointer t)) - -*adjvec* ; => #(1 2 3) - -;; 添加新的元素: -(vector-push-extend 4 *adjvec*) ; => 3 - -*adjvec* ; => #(1 2 3 4) - - - -;;; 不怎么严谨地说,集合也可被视为列表 - -(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) -(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 -(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) -(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) - -;; 然而,你可能想使用一个更好的数据结构,而并非一个链表 - -;;; 在Common Lisp中,“字典”和哈希表的实现是一样的。 - -;; 创建一个哈希表 -(defparameter *m* (make-hash-table)) - -;; 给定键,设置对应的值 -(setf (gethash 'a *m*) 1) - -;; (通过键)检索对应的值 -(gethash 'a *m*) ; => 1, t - -;; 注意此处有一细节:Common Lisp往往返回多个值。`gethash`返回的两个值是t,代表找到了这个元素;返回nil表示没有找到这个元素。 -;;(译者注:返回的第一个值表示给定的键所对应的值或者nil;) -;;(第二个是一个布尔值,表示在哈希表中是否存在这个给定的键) -;; 例如,如果可以找到给定的键所对应的值,则返回一个t,否则返回nil - -;; 由给定的键检索一个不存在的值,则返回nil -;;(译者注:这个nil是第一个nil,第二个nil其实是指该键在哈希表中也不存在) - (gethash 'd *m*) ;=> nil, nil - -;; 给定一个键,你可以指定其对应的默认值: -(gethash 'd *m* :not-found) ; => :NOT-FOUND - -;; 在此,让我们看一看怎样处理`gethash`的多个返回值。 - -(multiple-value-bind - (a b) - (gethash 'd *m*) - (list a b)) -; => (NIL NIL) - -(multiple-value-bind - (a b) - (gethash 'a *m*) - (list a b)) -; => (1 T) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 3. 函数 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; 使用`lambda`来创建一个匿名函数。 -;; 一个函数总是返回其形式体内最后一个表达式的值。 -;; 将一个函数对象打印出来后的形式是多种多样的... - -(lambda () "Hello World") ; => # - -;; 使用`funcall`来调用lambda函数 -(funcall (lambda () "Hello World")) ; => "Hello World" - -;; 或者使用`apply` -(apply (lambda () "Hello World") nil) ; => "Hello World" - -;; 显示地定义一个函数(译者注:即非匿名的) -(defun hello-world () - "Hello World") -(hello-world) ; => "Hello World" - -;; 刚刚上面函数名"hello-world"后的()其实是函数的参数列表 -(defun hello (name) - (format nil "Hello, ~a " name)) - -(hello "Steve") ; => "Hello, Steve" - -;; 函数可以有可选形参并且其默认值都为nil - -(defun hello (name &optional from) - (if from - (format t "Hello, ~a, from ~a" name from) - (format t "Hello, ~a" name))) - - (hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas - -;; 你也可以指定那些可选形参的默认值 -(defun hello (name &optional (from "The world")) - (format t "Hello, ~a, from ~a" name from)) - -(hello "Steve") -; => Hello, Steve, from The world - -(hello "Steve" "the alpacas") -; => Hello, Steve, from the alpacas - - -;; 当然,你也可以设置所谓关键字形参; -;; 关键字形参往往比可选形参更具灵活性。 - -(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) - (format t "Hello, ~a ~a, from ~a" honorific name from)) - -(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world - -(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") -; => Hello, Mr Jim, from the alpacas you met last summer - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 4. 等式 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; Common Lisp具有一个十分复杂的用于判断等价的系统,下面只是其中一部分的例子 - -;; 若要比较数值是否等价,使用`=` -(= 3 3.0) ; => t -(= 2 1) ; => nil - -;; 若要比较对象的类型,则使用`eql` -;;(译者注:抱歉,翻译水平实在有限,下面是我个人的补充说明) -;;(`eq` 返回真,如果对象的内存地址相等) -;;(`eql` 返回真,如果两个对象内存地址相等,或者对象的类型相同,并且值相等) -;;(例如同为整形数或浮点数,并且他们的值相等时,二者`eql`等价) -;;(想要弄清`eql`,其实有必要先了解`eq`) -;;([可以参考](http://stackoverflow.com/questions/547436/whats-the-difference-between-eq-eql-equal-and-equalp-in-common-lisp)) -;;(可以去CLHS上分别查看两者的文档) -;;(另外,《实用Common Lisp编程》的4.8节也提到了两者的区别) -(eql 3 3) ; => t -(eql 3 3.0) ; => nil -(eql (list 3) (list 3)) ; => nil - -;; 对于列表、字符串、以及位向量,使用`equal` -(equal (list 'a 'b) (list 'a 'b)) ; => t -(equal (list 'a 'b) (list 'b 'a)) ; => nil - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 5. 控制流 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;;; 条件判断语句 - -(if t ; “test”,即判断语句 - "this is true" ; “then”,即判断条件为真时求值的表达式 - "this is false") ; “else”,即判断条件为假时求值的表达式 -; => "this is true" - -;; 在“test”(判断)语句中,所有非nil或者非()的值都被视为真值 -(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) -(if (member 'Groucho '(Harpo Groucho Zeppo)) - 'yep - 'nope) -; => 'YEP - -;; `cond`将一系列测试语句串联起来,并对相应的表达式求值 -(cond ((> 2 2) (error "wrong!")) - ((< 2 2) (error "wrong again!")) - (t 'ok)) ; => 'OK - -;; 对于给定值的数据类型,`typecase`会做出相应地判断 -(typecase 1 - (string :string) - (integer :int)) - -; => :int - -;;; 迭代 - -;; 当然,递归是肯定被支持的: - -(defun walker (n) - (if (zerop n) - :walked - (walker (1- n)))) - -(walker) ; => :walked - -;; 而大部分场合下,我们使用`DOLIST`或者`LOOP`来进行迭代 - - -(dolist (i '(1 2 3 4)) - (format t "~a" i)) - -; => 1234 - -(loop for i from 0 below 10 - collect i) - -; => (0 1 2 3 4 5 6 7 8 9) - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 6. 可变性 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; 使用`setf`可以对一个已经存在的变量进行赋值; -;; 事实上,刚刚在哈希表的例子中我们已经示范过了。 - -(let ((variable 10)) - (setf variable 2)) - ; => 2 - - -;; 所谓好的Lisp编码风格就是为了减少使用破坏性函数,防止发生副作用。 - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 7. 类与对象 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; 我们就不写什么有关动物的类了,下面给出的人力车的类 - -(defclass human-powered-conveyance () - ((velocity - :accessor velocity - :initarg :velocity) - (average-efficiency - :accessor average-efficiency - :initarg :average-efficiency)) - (:documentation "A human powered conveyance")) - -;; `defclass`,后面接类名,以及超类列表 -;; 再接着是槽的列表(槽有点像Java里的成员变量),最后是一些可选的特性 -;; 例如文档说明“:documentation” - -;; 如果超类列表为空,则默认该类继承于“standard-object”类(standard-object又是T的子类) -;; 这种默认行为是可以改变的,但你最好有一定的基础并且知道自己到底在干什么; -;; 参阅《The Art of the Metaobject Protocol》来了解更多信息。 - -(defclass bicycle (human-powered-conveyance) - ((wheel-size - :accessor wheel-size - :initarg :wheel-size - :documentation "Diameter of the wheel.") - (height - :accessor height - :initarg :height))) - -(defclass recumbent (bicycle) - ((chain-type - :accessor chain-type - :initarg :chain-type))) - -(defclass unicycle (human-powered-conveyance) nil) - -(defclass canoe (human-powered-conveyance) - ((number-of-rowers - :accessor number-of-rowers - :initarg :number-of-rowers))) - - -;; 在REPL中对human-powered-conveyance类调用`DESCRIBE`后结果如下: - -(describe 'human-powered-conveyance) - -; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE -; [symbol] -; -; HUMAN-POWERED-CONVEYANCE names the standard-class #: -; Documentation: -; A human powered conveyance -; Direct superclasses: STANDARD-OBJECT -; Direct subclasses: UNICYCLE, BICYCLE, CANOE -; Not yet finalized. -; Direct slots: -; VELOCITY -; Readers: VELOCITY -; Writers: (SETF VELOCITY) -; AVERAGE-EFFICIENCY -; Readers: AVERAGE-EFFICIENCY -; Writers: (SETF AVERAGE-EFFICIENCY) - -;; 注意到这些有用的返回信息——Common Lisp一直是一个交互式的系统。 - -;; 若要定义一个方法; -;; 先让我们注意到我们计算自行车轮子周长时使用了这样一个公式:C = d * pi - -(defmethod circumference ((object bicycle)) - (* pi (wheel-size object))) - -;; pi在Common Lisp中已经是一个内置的常量。 - -;; 假设我们已经知道了效率值(“efficiency value”)和船桨数大概呈对数关系; -;; 那么效率值的定义应当在构造器/初始化过程中就被完成。 - -;; 下面是一个Common Lisp构造实例时初始化实例的例子: - -(defmethod initialize-instance :after ((object canoe) &rest args) - (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) - -;; 接着初构造一个实例并检查平均效率... - -(average-efficiency (make-instance 'canoe :number-of-rowers 15)) -; => 2.7725887 - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 8. 宏 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; 宏可以让你扩展语法 - -;; 例如,Common Lisp并没有自带WHILE循环——所以让我们自己来为他添加一个; -;; 如果按照汇编程序的直觉来看,我们会这样写: - -(defmacro while (condition &body body) - "While `condition` is true, `body` is executed. - -`condition` is tested prior to each execution of `body`" - (let ((block-name (gensym))) - `(tagbody - (unless ,condition - (go ,block-name)) - (progn - ,@body) - ,block-name))) - -;; 让我们来看看它的高级版本: - -(defmacro while (condition &body body) - "While `condition` is true, `body` is executed. - -`condition` is tested prior to each execution of `body`" - `(loop while ,condition - do - (progn - ,@body))) - -;; 然而,在一个比较现代化的编译环境下,这样的WHILE是没有必要的; -;; LOOP形式的循环和这个WHILE同样的好,并且更易于阅读。 - -;; 注意到反引号'`',逗号','以及'@'符号,这三个符号; -;; 反引号'`'是一种所谓“quasiquote”的引用类型的运算符,有了它,之后的逗号“,”才有意义。 -;; 逗号“,”意味着解除引用(unquote,即开始求值); -;; “@”符号则表示将当前的参数插入到当前整个列表中。 -;;(译者注:要想真正用好、用对这三个符号,需要下一番功夫) -;;(甚至光看《实用 Common Lisp 编程》中关于宏的介绍都是不够的) -;;(建议再去读一读Paul Graham的两本著作《ANSI Common Lisp》和《On Lisp》) - -;; 函数`gensym`创建一个唯一的符号——这个符号确保不会出现在其他任何地方。 -;; 这样做是因为,宏是在编译期展开的 -;; 而在宏中声明的变量名极有可能和常规代码中使用的变量名发生冲突。 - -;; 可以去《实用 Common Lisp 编程》中阅读更多有关宏的内容。 -``` - - -## 拓展阅读 - -[继续阅读《实用 Common Lisp 编程》一书](http://www.gigamonkeys.com/book/) - - -## 致谢 - -非常感谢Scheme社区的人们,我基于他们的成果得以迅速的写出这篇有关Common Lisp的快速入门 -同时也感谢 -- [Paul Khuong](https://github.com/pkhuong) ,他提出了很多有用的点评。 - -##译者寄语 -“祝福那些将思想镶嵌在重重括号之内的人们。” diff --git a/zh-cn/elisp-cn.html.markdown b/zh-cn/elisp-cn.html.markdown old mode 100755 new mode 100644 diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown old mode 100755 new mode 100644 diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown new file mode 100644 index 00000000..7cc9c171 --- /dev/null +++ b/zh-cn/go-cn.html.markdown @@ -0,0 +1,284 @@ +--- +language: Go +lang: zh-cn +filename: learngo-cn.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["pantaovay", "https://github.com/pantaovay"] +--- + +发明Go语言是出于更好地完成工作的需要。Go不是计算机科学的最新发展潮流,但它却提供了解决现实问题的最新最快的方法。 + +Go拥有命令式语言的静态类型,编译很快,执行也很快,同时加入了对于目前多核CPU的并发计算支持,也有相应的特性来实现大规模编程。 + +Go语言有非常棒的标准库,还有一个充满热情的社区。 + +```go +// 单行注释 +/* 多行 + 注释 */ + +// 导入包的子句在每个源文件的开头。 +// Main比较特殊,它用来声明可执行文件,而不是一个库。 +package main + +// Import语句声明了当前文件引用的包。 +import ( + "fmt" // Go语言标准库中的包 + "net/http" // 一个web服务器包 + "strconv" // 字符串转换 +) + +// 函数声明:Main是程序执行的入口。 +// 不管你喜欢还是不喜欢,反正G就用了花括号来包住函数体。 +func main() { + // 往标准输出打印一行。 + // 用包名fmt限制打印函数。 + fmt.Println("Hello world!") + + // 调用当前包的另一个函数。 + beyondHello() +} + +// 函数可以在括号里加参数。 +// 如果没有参数的话,也需要一个空括号。 +func beyondHello() { + var x int // 变量声明,变量必须在使用之前声明。 + x = 3 // 变量赋值。 + // 可以用:=来偷懒,它自动把变量类型、声明和赋值都搞定了。 + y := 4 + sum, prod := learnMultiple(x, y) // 多个返回变量的函数 + fmt.Println("sum:", sum, "prod:", prod) // 简单输出 + learnTypes() // 少于y分钟,学的更多! +} + +// 多变量和多返回值的函数 +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // 返回两个值 +} + +// 内置变量类型和关键词 +func learnTypes() { + // 短声明给你所想。 + s := "Learn Go!" // String类型 + + s2 := `A "raw" string literal +can include line breaks.` // 同样是String类型 + + // 非ascii字符。Go使用UTF-8编码。 + g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码 + + f := 3.14195 // float64类型,IEEE-754 64位浮点数 + c := 3 + 4i // complex128类型,内部使用两个float64表示 + + // Var变量可以直接初始化。 + var u uint = 7 // unsigned 无符号变量,但是实现依赖int型变量的长度 + var pi float32 = 22. / 7 + + // 字符转换 + n := byte('\n') // byte是uint8的别名 + + // 数组类型编译的时候大小固定。 + var a4 [4] int // 有4个int变量的数组,初始为0 + a3 := [...]int{3, 1, 5} // 有3个int变量的数组,同时进行了初始化 + + // Slice 有动态大小。Array和Slice各有千秋,但是使用slice的地方更多些。 + s3 := []int{4, 5, 9} // 和a3相比,这里没有省略号 + s4 := make([]int, 4) // 分配一个有4个int型变量的slice,全部被初始化为0 + + var d2 [][]float64 // 声明而已,什么都没有分配 + bs := []byte("a slice") // 类型转换的语法 + + p, q := learnMemory() // 声明p,q为int型变量的指针 + fmt.Println(*p, *q) // * 取值 + + // Map是动态可增长关联数组,和其他语言中的hash或者字典相似。 + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // 在Go语言中未使用的变量在编译的时候会报错,而不是warning。 + // 下划线 _ 可以使你“使用”一个变量,但是丢弃它的值。 + _,_,_,_,_,_,_,_,_ = s2, g, f, u, pi, n, a3, s4, bs + // 输出变量 + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // 回到流程控制 +} + +// Go全面支持垃圾回收。Go有指针,但是不支持指针运算。 +// 你会因为空指针而犯错,但是不会因为增加指针而犯错。 +func learnMemory() (p, q *int) { + // 返回int型变量指针p和q + p = new(int) // 内置函数new分配内存 + // 自动将分配的int赋值0,p不再是空的了。 + s := make([]int, 20) // 给20个int变量分配一块内存 + s[3] = 7 // 赋值 + r := -2 // 声明另一个局部变量 + return &s[3], &r // & 取址 +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // If需要花括号,括号就免了 + if true { + fmt.Println("told ya") + } + // 用go fmt 命令可以帮你格式化代码,所以不用怕被人吐槽代码风格了, + // 也不用容忍被人的代码风格。 + if false { + // pout + } else { + // gloat + } + // 如果太多嵌套的if语句,推荐使用switch + x := 1 + switch x { + case 0: + case 1: + // 隐式调用break语句,匹配上一个即停止 + case 2: + // 不会运行 + } + // 和if一样,for也不用括号 + for x := 0; x < 3; x++ { // ++ 自增 + fmt.Println("iteration", x) + } + // x在这里还是1。为什么? + + // for 是go里唯一的循环关键字,不过它有很多变种 + for { // 无限循环 + break // 骗你的 + continue // 不会运行的 + } + // 和for一样,if中的:=先给y赋值,然后再和x作比较。 + if y := expensiveComputation(); y > x { + x = y + } + // 闭包函数 + xBig := func() bool { + return x > 100 // x是上面声明的变量引用 + } + fmt.Println("xBig:", xBig()) // true (上面把y赋给x了) + x /= 1e5 // x变成10 + fmt.Println("xBig:", xBig()) // 现在是false + + // 当你需要goto的时候,你会爱死它的! + goto love +love: + + learnInterfaces() // 好东西来了! +} + +// 定义Stringer为一个接口类型,有一个方法String +type Stringer interface { + String() string +} + +// 定义pair为一个结构体,有x和y两个int型变量。 +type pair struct { + x, y int +} + +// 定义pair类型的方法,实现Stringer接口。 +func (p pair) String() string { // p被叫做“接收器” + // Sprintf是fmt包中的另一个公有函数。 + // 用 . 调用p中的元素。 + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // 花括号用来定义结构体变量,:=在这里将一个结构体变量赋值给p。 + p := pair{3, 4} + fmt.Println(p.String()) // 调用pair类型p的String方法 + var i Stringer // 声明i为Stringer接口类型 + i = p // 有效!因为p实现了Stringer接口(类似java中的塑型) + // 调用i的String方法,输出和上面一样 + fmt.Println(i.String()) + + // fmt包中的Println函数向对象要它们的string输出,实现了String方法就可以这样使用了。 + // (类似java中的序列化) + fmt.Println(p) // 输出和上面一样,自动调用String函数。 + fmt.Println(i) // 输出和上面一样。 + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok"用来判断有没有正常工作 + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok 为false,因为m中没有1 + fmt.Println("no one there") + } else { + fmt.Print(x) // 如果x在map中的话,x就是那个值喽。 + } + // 错误可不只是ok,它还可以给出关于问题的更多细节。 + if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value + // 输出"strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // 待会再说接口吧。同时, + learnConcurrency() +} + +// c是channel类型,一个并发安全的通信对象。 +func inc(i int, c chan int) { + c <- i + 1 // <-把右边的发送到左边的channel。 +} + +// 我们将用inc函数来并发地增加一些数字。 +func learnConcurrency() { + // 用make来声明一个slice,make会分配和初始化slice,map和channel。 + c := make(chan int) + // 用go关键字开始三个并发的goroutine,如果机器支持的话,还可能是并行执行。 + // 三个都被发送到同一个channel。 + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) + // 从channel中独处结果并打印。 + // 打印出什么东西是不可预知的。 + fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是接收操作。 + + cs := make(chan string) // 操作string的channel + cc := make(chan chan string) // 操作channel的channel + go func() { c <- 84 }() // 开始一个goroutine来发送一个新的数字 + go func() { cs <- "wordy" }() // 发送给cs + // Select类似于switch,但是每个case包括一个channel操作。 + // 它随机选择一个准备好通讯的case。 + select { + case i := <-c: // 从channel接收的值可以赋给其他变量 + fmt.Println("it's a", i) + case <-cs: // 或者直接丢弃 + fmt.Println("it's a string") + case <-cc: // 空的,还没作好通讯的准备 + fmt.Println("didn't happen.") + } + // 上面c或者cs的值被取到,其中一个goroutine结束,另外一个保持阻塞。 + + learnWebProgramming() // Go很适合web编程,我知道你也想学! +} + +// http包中的一个简单的函数就可以开启web服务器。 +func learnWebProgramming() { + // ListenAndServe第一个参数指定了监听端口,第二个参数是一个接口,特定是http.Handler。 + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // 不要无视错误。 +} + +// 使pair实现http.Handler接口的ServeHTTP方法。 +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // 使用http.ResponseWriter返回数据 + w.Write([]byte("You learned Go in Y minutes!")) +} +``` + +## 更进一步 + +Go的根源在[Go官方网站](http://golang.org/)。 +在那里你可以学习入门教程,通过浏览器交互式地学习,而且可以读到很多东西。 + +强烈推荐阅读语言定义部分,很简单而且很简洁!(as language definitions go these days.) + +学习Go还要阅读Go标准库的源代码,全部文档化了,可读性非常好,可以学到go,go style和go idioms。在文档中点击函数名,源代码就出来了! diff --git a/zh-cn/go-zh.html.markdown b/zh-cn/go-zh.html.markdown deleted file mode 100644 index 7cc9c171..00000000 --- a/zh-cn/go-zh.html.markdown +++ /dev/null @@ -1,284 +0,0 @@ ---- -language: Go -lang: zh-cn -filename: learngo-cn.go -contributors: - - ["Sonia Keys", "https://github.com/soniakeys"] - - ["pantaovay", "https://github.com/pantaovay"] ---- - -发明Go语言是出于更好地完成工作的需要。Go不是计算机科学的最新发展潮流,但它却提供了解决现实问题的最新最快的方法。 - -Go拥有命令式语言的静态类型,编译很快,执行也很快,同时加入了对于目前多核CPU的并发计算支持,也有相应的特性来实现大规模编程。 - -Go语言有非常棒的标准库,还有一个充满热情的社区。 - -```go -// 单行注释 -/* 多行 - 注释 */ - -// 导入包的子句在每个源文件的开头。 -// Main比较特殊,它用来声明可执行文件,而不是一个库。 -package main - -// Import语句声明了当前文件引用的包。 -import ( - "fmt" // Go语言标准库中的包 - "net/http" // 一个web服务器包 - "strconv" // 字符串转换 -) - -// 函数声明:Main是程序执行的入口。 -// 不管你喜欢还是不喜欢,反正G就用了花括号来包住函数体。 -func main() { - // 往标准输出打印一行。 - // 用包名fmt限制打印函数。 - fmt.Println("Hello world!") - - // 调用当前包的另一个函数。 - beyondHello() -} - -// 函数可以在括号里加参数。 -// 如果没有参数的话,也需要一个空括号。 -func beyondHello() { - var x int // 变量声明,变量必须在使用之前声明。 - x = 3 // 变量赋值。 - // 可以用:=来偷懒,它自动把变量类型、声明和赋值都搞定了。 - y := 4 - sum, prod := learnMultiple(x, y) // 多个返回变量的函数 - fmt.Println("sum:", sum, "prod:", prod) // 简单输出 - learnTypes() // 少于y分钟,学的更多! -} - -// 多变量和多返回值的函数 -func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // 返回两个值 -} - -// 内置变量类型和关键词 -func learnTypes() { - // 短声明给你所想。 - s := "Learn Go!" // String类型 - - s2 := `A "raw" string literal -can include line breaks.` // 同样是String类型 - - // 非ascii字符。Go使用UTF-8编码。 - g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码 - - f := 3.14195 // float64类型,IEEE-754 64位浮点数 - c := 3 + 4i // complex128类型,内部使用两个float64表示 - - // Var变量可以直接初始化。 - var u uint = 7 // unsigned 无符号变量,但是实现依赖int型变量的长度 - var pi float32 = 22. / 7 - - // 字符转换 - n := byte('\n') // byte是uint8的别名 - - // 数组类型编译的时候大小固定。 - var a4 [4] int // 有4个int变量的数组,初始为0 - a3 := [...]int{3, 1, 5} // 有3个int变量的数组,同时进行了初始化 - - // Slice 有动态大小。Array和Slice各有千秋,但是使用slice的地方更多些。 - s3 := []int{4, 5, 9} // 和a3相比,这里没有省略号 - s4 := make([]int, 4) // 分配一个有4个int型变量的slice,全部被初始化为0 - - var d2 [][]float64 // 声明而已,什么都没有分配 - bs := []byte("a slice") // 类型转换的语法 - - p, q := learnMemory() // 声明p,q为int型变量的指针 - fmt.Println(*p, *q) // * 取值 - - // Map是动态可增长关联数组,和其他语言中的hash或者字典相似。 - m := map[string]int{"three": 3, "four": 4} - m["one"] = 1 - - // 在Go语言中未使用的变量在编译的时候会报错,而不是warning。 - // 下划线 _ 可以使你“使用”一个变量,但是丢弃它的值。 - _,_,_,_,_,_,_,_,_ = s2, g, f, u, pi, n, a3, s4, bs - // 输出变量 - fmt.Println(s, c, a4, s3, d2, m) - - learnFlowControl() // 回到流程控制 -} - -// Go全面支持垃圾回收。Go有指针,但是不支持指针运算。 -// 你会因为空指针而犯错,但是不会因为增加指针而犯错。 -func learnMemory() (p, q *int) { - // 返回int型变量指针p和q - p = new(int) // 内置函数new分配内存 - // 自动将分配的int赋值0,p不再是空的了。 - s := make([]int, 20) // 给20个int变量分配一块内存 - s[3] = 7 // 赋值 - r := -2 // 声明另一个局部变量 - return &s[3], &r // & 取址 -} - -func expensiveComputation() int { - return 1e6 -} - -func learnFlowControl() { - // If需要花括号,括号就免了 - if true { - fmt.Println("told ya") - } - // 用go fmt 命令可以帮你格式化代码,所以不用怕被人吐槽代码风格了, - // 也不用容忍被人的代码风格。 - if false { - // pout - } else { - // gloat - } - // 如果太多嵌套的if语句,推荐使用switch - x := 1 - switch x { - case 0: - case 1: - // 隐式调用break语句,匹配上一个即停止 - case 2: - // 不会运行 - } - // 和if一样,for也不用括号 - for x := 0; x < 3; x++ { // ++ 自增 - fmt.Println("iteration", x) - } - // x在这里还是1。为什么? - - // for 是go里唯一的循环关键字,不过它有很多变种 - for { // 无限循环 - break // 骗你的 - continue // 不会运行的 - } - // 和for一样,if中的:=先给y赋值,然后再和x作比较。 - if y := expensiveComputation(); y > x { - x = y - } - // 闭包函数 - xBig := func() bool { - return x > 100 // x是上面声明的变量引用 - } - fmt.Println("xBig:", xBig()) // true (上面把y赋给x了) - x /= 1e5 // x变成10 - fmt.Println("xBig:", xBig()) // 现在是false - - // 当你需要goto的时候,你会爱死它的! - goto love -love: - - learnInterfaces() // 好东西来了! -} - -// 定义Stringer为一个接口类型,有一个方法String -type Stringer interface { - String() string -} - -// 定义pair为一个结构体,有x和y两个int型变量。 -type pair struct { - x, y int -} - -// 定义pair类型的方法,实现Stringer接口。 -func (p pair) String() string { // p被叫做“接收器” - // Sprintf是fmt包中的另一个公有函数。 - // 用 . 调用p中的元素。 - return fmt.Sprintf("(%d, %d)", p.x, p.y) -} - -func learnInterfaces() { - // 花括号用来定义结构体变量,:=在这里将一个结构体变量赋值给p。 - p := pair{3, 4} - fmt.Println(p.String()) // 调用pair类型p的String方法 - var i Stringer // 声明i为Stringer接口类型 - i = p // 有效!因为p实现了Stringer接口(类似java中的塑型) - // 调用i的String方法,输出和上面一样 - fmt.Println(i.String()) - - // fmt包中的Println函数向对象要它们的string输出,实现了String方法就可以这样使用了。 - // (类似java中的序列化) - fmt.Println(p) // 输出和上面一样,自动调用String函数。 - fmt.Println(i) // 输出和上面一样。 - - learnErrorHandling() -} - -func learnErrorHandling() { - // ", ok"用来判断有没有正常工作 - m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok 为false,因为m中没有1 - fmt.Println("no one there") - } else { - fmt.Print(x) // 如果x在map中的话,x就是那个值喽。 - } - // 错误可不只是ok,它还可以给出关于问题的更多细节。 - if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value - // 输出"strconv.ParseInt: parsing "non-int": invalid syntax" - fmt.Println(err) - } - // 待会再说接口吧。同时, - learnConcurrency() -} - -// c是channel类型,一个并发安全的通信对象。 -func inc(i int, c chan int) { - c <- i + 1 // <-把右边的发送到左边的channel。 -} - -// 我们将用inc函数来并发地增加一些数字。 -func learnConcurrency() { - // 用make来声明一个slice,make会分配和初始化slice,map和channel。 - c := make(chan int) - // 用go关键字开始三个并发的goroutine,如果机器支持的话,还可能是并行执行。 - // 三个都被发送到同一个channel。 - go inc(0, c) // go is a statement that starts a new goroutine. - go inc(10, c) - go inc(-805, c) - // 从channel中独处结果并打印。 - // 打印出什么东西是不可预知的。 - fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是接收操作。 - - cs := make(chan string) // 操作string的channel - cc := make(chan chan string) // 操作channel的channel - go func() { c <- 84 }() // 开始一个goroutine来发送一个新的数字 - go func() { cs <- "wordy" }() // 发送给cs - // Select类似于switch,但是每个case包括一个channel操作。 - // 它随机选择一个准备好通讯的case。 - select { - case i := <-c: // 从channel接收的值可以赋给其他变量 - fmt.Println("it's a", i) - case <-cs: // 或者直接丢弃 - fmt.Println("it's a string") - case <-cc: // 空的,还没作好通讯的准备 - fmt.Println("didn't happen.") - } - // 上面c或者cs的值被取到,其中一个goroutine结束,另外一个保持阻塞。 - - learnWebProgramming() // Go很适合web编程,我知道你也想学! -} - -// http包中的一个简单的函数就可以开启web服务器。 -func learnWebProgramming() { - // ListenAndServe第一个参数指定了监听端口,第二个参数是一个接口,特定是http.Handler。 - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // 不要无视错误。 -} - -// 使pair实现http.Handler接口的ServeHTTP方法。 -func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // 使用http.ResponseWriter返回数据 - w.Write([]byte("You learned Go in Y minutes!")) -} -``` - -## 更进一步 - -Go的根源在[Go官方网站](http://golang.org/)。 -在那里你可以学习入门教程,通过浏览器交互式地学习,而且可以读到很多东西。 - -强烈推荐阅读语言定义部分,很简单而且很简洁!(as language definitions go these days.) - -学习Go还要阅读Go标准库的源代码,全部文档化了,可读性非常好,可以学到go,go style和go idioms。在文档中点击函数名,源代码就出来了! diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown old mode 100755 new mode 100644 diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown old mode 100755 new mode 100644 diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown old mode 100755 new mode 100644 diff --git a/zh-cn/php-cn.html.markdown b/zh-cn/php-cn.html.markdown old mode 100755 new mode 100644 diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown old mode 100755 new mode 100644 -- cgit v1.2.3 From c9a282d08fb1f8670fa328e0e7cdb8801382b88a Mon Sep 17 00:00:00 2001 From: Denis Arh Date: Wed, 18 Dec 2013 09:37:27 +0100 Subject: Add example for default value --- bash.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 1f1c32c0..815290dd 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Darren Lin", "https://github.com/CogBear"] - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] filename: LearnBash.sh --- @@ -45,6 +46,10 @@ echo '$VARIABLE' echo ${VARIABLE/Some/A} # This will substitute the first occurance of "Some" with "A" +# Default value for variable +echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} +# This works for null (FOO=), empty string (FOO=""), zero (FOO=0) returns 0 + # Bultin variables: # There are some useful builtin variables, like echo "Last program return value: $?" -- cgit v1.2.3 From e7b43c1ba3239d7e13fb5fa40a7dd44fba6a48de Mon Sep 17 00:00:00 2001 From: chappers Date: Thu, 19 Dec 2013 16:23:25 +1100 Subject: [julia/en] Fixed Spelling Mistake --- julia.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 4869e207..f1e1a4a2 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -83,7 +83,7 @@ false # A string can be indexed like an array of characters "This is a string"[1] #=> 'T' # Julia indexes from 1 # However, this is will not work well for UTF8 strings, -# so iterating over strings is reccommended (map, for loops, etc). +# so iterating over strings is recommended (map, for loops, etc). # $ can be used for string interpolation: "2 + 2 = $(2 + 2)" #=> "2 + 2 = 4" -- cgit v1.2.3 From d854062e8b77d94a7232d49dbcbab6324b9bda11 Mon Sep 17 00:00:00 2001 From: Rogaboru Kujimoshi Date: Thu, 19 Dec 2013 19:11:58 +0300 Subject: Update python-ru.html.markdown Fixed comment on line 39 --- ru-ru/python-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index df4a38a8..204eb357 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -36,7 +36,7 @@ filename: learnpython-ru.py 35 / 5 #=> 7 # А вот деление немного сложнее. В этом случае происходит деление -№ целых чисел и результат автоматически округляется в меньшую сторону. +# целых чисел и результат автоматически округляется в меньшую сторону. 5 / 2 #=> 2 # Чтобы научиться делить, сначала нужно немного узнать о дробных числах. -- cgit v1.2.3 From 7927c1bf3a57538d39bfa3c5c5385b2cd8d84a91 Mon Sep 17 00:00:00 2001 From: Joel Birchler Date: Thu, 26 Dec 2013 22:50:17 -0800 Subject: Added call, apply, bind JavaScript examples --- javascript.html.markdown | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index 4584a28c..7fb7ba55 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -319,6 +319,37 @@ var myOtherFunc = function(){ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" +// We can also specify a context for a function to execute in when we invoke it +// using 'call' or 'apply'. + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// The 'apply' function is nearly identical, but takes an array for an argument list. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// This is useful when working with a function that accepts a sequence of arguments +// and you want to pass an array. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// But, 'call' and 'apply' are only temporary. When we want it to stick, we can use +// bind. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// Bind can also be used to partially apply (curry) a function. + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + // When you call a function with the new keyword, a new object is created, and // made available to the function via the this keyword. Functions designed to be // called like that are called constructors. -- cgit v1.2.3 From 5bd86ec047ba12decea1105d47b0496ab7e435cb Mon Sep 17 00:00:00 2001 From: kyr Date: Fri, 27 Dec 2013 16:21:24 +0100 Subject: spelling fixes in bash (en) --- bash.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 815290dd..a6bd2b7c 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -21,7 +21,7 @@ Nearly all examples below can be a part of a shell script or executed directly i # As you already figured, comments start with #. Shebang is also a comment. # Simple hello world example: -echo Hello, world! +echo Hello world! # Each command starts on a new line, or after semicolon: echo 'This is the first line'; echo 'This is the second line' @@ -56,24 +56,24 @@ 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..." +echo "Scripts arguments seperated in different variables: $1 $2..." # Reading a value from input: echo "What's your name?" -read NAME # Note that we didn't need to declare new variable +read NAME # Note that we didn't need to declare a new variable echo Hello, $NAME! # We have the usual if structure: # use 'man test' for more info about conditionals if [ $NAME -ne $USER ] then - echo "Your name is you username" + echo "Your name is your username" else - echo "Your name isn't you username" + echo "Your name isn't your 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 fails" echo "Always executed" && echo "Only executed if first command does NOT fail" # Expressions are denoted with the following format: @@ -81,7 +81,7 @@ echo $(( 10 + 5 )) # Unlike other programming languages, bash is a shell — so it works in a context # of current directory. You can list files and directories in the current -# directories with ls command: +# directory with the ls command: ls # These commands have options that control their execution: @@ -89,10 +89,10 @@ ls -l # Lists every file and directory on a separate line # Results of the previous command can be passed to the next command as input. # grep command filters the input with provided patterns. That's how we can list -# txt files in the current directory: +# .txt files in the current directory: ls -l | grep "\.txt" -# You can also redirect a command output, input and error output. +# You can also redirect a command, input and error output. python2 hello.py < "input.in" python2 hello.py > "output.out" python2 hello.py 2> "error.err" @@ -116,7 +116,7 @@ case "$VARIABLE" in *) echo "It is not null.";; esac -# For loops iterate for as many arguments given: +# for loops iterate for as many arguments given: # The contents of var $VARIABLE is printed three times. for VARIABLE in {1..3} do -- cgit v1.2.3 From 837eb79185828dbe1be55b667b90c22eeb8b27e9 Mon Sep 17 00:00:00 2001 From: kyr Date: Sat, 28 Dec 2013 02:15:25 +0100 Subject: added one half of the translated stuff --- de-de/css-de.html.markdown | 226 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 de-de/css-de.html.markdown diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown new file mode 100644 index 00000000..0f186748 --- /dev/null +++ b/de-de/css-de.html.markdown @@ -0,0 +1,226 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] +translators: + - ["Kyr", "http://github.com/kyrami"] +lang: de-de +--- + +In den frühen Tagen des Internets gab es keine visuellen Elemente, alles war nur reiner Text. Aber mit der Weiterentwickliung von Browsern wurden auch vollständig visuelle Webseiten zu einem Standard. +CSS ist die allgemeine Sprache, die dazu da ist, damit man den HTML-Code und die Designelemente von Webseiten (strikt) unterscheiden kann. + +Kurzgefasst, CSS ermöglicht es, verschiedene HTML-Elemente anzuvisieren und ihnen stilistische Eigenschaften zu geben. + +CSS hat wie jede andere Sprache viele Versionen. Hier fokussieren wir uns auf CSS2.0, welche nicht die neueste, aber die am weitesten verbreitete und unterstützte Version ist. + +**NOTE:** Weil die Ausgabe von CSS visuelle Eigenschaften sind, wirst du wahrscheinlich einen CSS-Playground wie [dabblet](http://dabblet.com/) benutzen müssen, um die Sprache richtig zu lernen. +In diesem Artikel wird am meisten auf generelle Hinweise und die Syntax geachtet. + + +```css +/* kommentare werden in sternchen-schrägstrichkombinationen gepackt (genauso wie hier!) */ + +/* #################### + ## SELEKTOREN + ####################*/ + +/* Eigentlich ist die häufigste Anwendungsweise von CSS sehr simpel */ +selektor { eigenschaft: wert; /* mehr eigenschaften...*/ } + +/* der selektor wird dazu benutzt, ein element auf der seite anzuvisieren + +Aber man kann auch alle Elemente auf einer Seite anvisieren! */ +* { color:red; } /* farbe:rot */ + +/* +Wenn wir so ein Element auf einer Seite haben: + +
+*/ + +/* kann man es so bei seiner klasse anvisieren */ +.eine-klasse { } + +/*oder bei beiden klassen! */ +.eine-klasse.klasse2 { } + +/* oder beim namen des tags */ +div { } + +/* oder bei seiner id */ +#eineId { } + +/* oder daran, dass es ein Attribut hat! */ +[attr] { font-size:smaller; } + +/* oder daran, dass das attribut einen bestimmten wert hat*/ +[attr='wert'] { font-size:smaller; } + +/* beginnt mit einem wert*/ +[attr^='wert'] { font-size:smaller; } + +/* oder endet mit */ +[attr$='rt'] { font-size:smaller; } + +/* oder sogar nur beinhaltet */ +[attr~='er'] { font-size:smaller; } + + +/* was aber nich wichtiger ist, ist dass man alle diese kombinieren kann - man sollte nur mit der leerzeichensetzung vorsichtig sein, da es mit einem leerzeichen zwei verschiedene selektoren wären*/ +div.eine-klasse[attr$='rt'] { } /* so ist es richtig */ + +/* man kann auch ein element daran festmachen, wie sich die übergeordneten elemente verhalten!*/ + +/*es muss allerdings ein direktes kind sein */ +div.some-parent > .class-name {} + +/* or any of it's parents in the tree */ +/* the following basically means any element that has class "class-name" +and is child of a div with class name "some-parent" IN ANY DEPTH */ +div.some-parent .class-name {} + +/* warning: the same selector wihout spaaace has another meaning. +can you say what? */ +div.some-parent.class-name {} + +/* you also might choose to select an element based on it's direct +previous sibling */ +.i-am-before + .this-element { } + +/*or any sibling before this */ +.i-am-any-before ~ .this-element {} + +/* There are some pseudo classes that allows you to select an element +based on it's page behaviour (rather than page structure) */ + +/* for example for when an element is hovered */ +:hover {} + +/* or a visited link*/ +:visited {} + +/* or not visited link*/ +:link {} + +/* or an input element which is focused */ +:focus {} + + +/* #################### + ## PROPERTIES + ####################*/ + +selector { + + /* Units */ + width: 50%; /* in percent */ + font-size: 2em; /* times current font-size */ + width: 200px; /* in pixels */ + font-size: 20pt; /* in points */ + width: 5cm; /* in centimeters */ + width: 50mm; /* in millimeters */ + width: 5in; /* in inches */ + + /* Colors */ + background-color: #F6E /* in short hex */ + background-color: #F262E2 /* in long hex format */ + background-color: tomato /* can be a named color */ + background-color: rgb(255, 255, 255) /* in rgb */ + background-color: rgb(10%, 20%, 50%) /* in rgb percent */ + background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb */ + + /* Images */ + background-image: url(/path-to-image/image.jpg); + + /* Fonts */ + font-family: Arial; + font-family: "Courier New"; /* if name has spaaace it appears in double-quote */ + font-family: "Courier New", Trebuchet, Arial; /* if first one was not found + browser uses the second font, and so forth */ +} + +``` + +## Usage + +Save any CSS you want in a file with extension `.css`. + +```xml + + + + + + + +
+
+ +``` + +## Precedence + +As you noticed an element may be targetted by more than one selector. +and may have a property set on it in more than one. +In these cases, one of the rules takes precedence over others. + +Given the following CSS: + +```css +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +and the following markup: + +```xml +

+

+``` + +The precedence of style is as followed: +Remember, the precedence is for each **property**, not for the entire block. + +* `E` has the highest precedence because of the keyword `!important`. + It is recommended to avoid this unless it is strictly necessary to use. +* `F` is next, because it is inline style. +* `A` is next, because it is more "specific" than anything else. + more specific = more specifiers. here 3 specifiers: 1 tagname `p` + + class name `class1` + 1 attribute `attr='value'` +* `C` is next. although it has the same specificness as `B` + but it appears last. +* Then is `B` +* and lastly is `D`. + +## Compatibility + +Most of the features in CSS2 (and gradually in CSS3) are compatible across +all browsers and devices. But it's always vital to have in mind the compatiblity +of what you use in CSS with your target browsers. + +[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. + +## Further Reading + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) + -- cgit v1.2.3 From 4fe001ec8a179bc3ade8eb529a1df1fb20baf740 Mon Sep 17 00:00:00 2001 From: kyr Date: Sat, 28 Dec 2013 02:17:04 +0100 Subject: spelling fixes --- de-de/css-de.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown index 0f186748..e212e555 100644 --- a/de-de/css-de.html.markdown +++ b/de-de/css-de.html.markdown @@ -67,7 +67,9 @@ div { } [attr~='er'] { font-size:smaller; } -/* was aber nich wichtiger ist, ist dass man alle diese kombinieren kann - man sollte nur mit der leerzeichensetzung vorsichtig sein, da es mit einem leerzeichen zwei verschiedene selektoren wären*/ +/* was aber noch wichtiger ist, ist dass man alle diese kombinieren +kann - man sollte nur mit der leerzeichensetzung vorsichtig sein, +da es mit einem leerzeichen zwei verschiedene selektoren wären*/ div.eine-klasse[attr$='rt'] { } /* so ist es richtig */ /* man kann auch ein element daran festmachen, wie sich die übergeordneten elemente verhalten!*/ -- cgit v1.2.3 From e7dcbed40ddbbcad60dd43edd6fd372141a75077 Mon Sep 17 00:00:00 2001 From: Alex Altair Date: Sat, 28 Dec 2013 02:22:25 -0800 Subject: Fix typos and indentation --- julia.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index ce55f956..4b946d46 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -105,7 +105,7 @@ some_var #=> 5 # Accessing a previously unassigned variable is an error try - some_other_var #=> ERROR: some_other_var not defined + some_other_var #=> ERROR: some_other_var not defined catch e println(e) end @@ -417,7 +417,7 @@ try defaults('h') #=> ERROR: no method defaults(Char,) defaults() #=> ERROR: no methods defaults() catch e -println(e) + println(e) end # You can define functions that take keyword arguments @@ -509,7 +509,7 @@ type Tiger end # The default constructor's arguments are the properties -# of the tyep, in order the order they are listed in the definition +# of the type, in the order they are listed in the definition tigger = Tiger(3.5,"orange") #=> Tiger(3.5,"orange") # The type doubles as the constructor function for values of that type -- cgit v1.2.3 From c0a9eabb6c6780c6ab1a9501a6aa2bc49b2dd54c Mon Sep 17 00:00:00 2001 From: Cengiz Can Date: Mon, 30 Dec 2013 09:45:15 +0200 Subject: Source.fromPath no longer exists (https://github.com/scala/scala/blob/master/src/library/scala/io/Source.scala) Changed example to use Source.fromFile --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 03c1ea76..5dfaefe0 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -396,7 +396,7 @@ object Application { // To read a file line by line import scala.io.Source -for(line <- Source.fromPath("myfile.txt").getLines()) +for(line <- Source.fromFile("myfile.txt").getLines()) println(line) // To write a file use Java's PrintWriter -- cgit v1.2.3 From 071de314fd97959f6defb6fffd077cc185c9400e Mon Sep 17 00:00:00 2001 From: Yonaba Date: Mon, 30 Dec 2013 14:49:43 +0000 Subject: Added french translation for Lua --- fr-fr/lua-fr.html.markdown | 450 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 450 insertions(+) create mode 100644 fr-fr/lua-fr.html.markdown diff --git a/fr-fr/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown new file mode 100644 index 00000000..e3979f08 --- /dev/null +++ b/fr-fr/lua-fr.html.markdown @@ -0,0 +1,450 @@ +--- +language: lua +filename: learnlua-fr.lua +contributors: + - ["Tyler Neylon", "http://tylerneylon.com/"] +translators: + - ["Roland Yonaba", "http://github.com/Yonaba"] +lang: fr-fr +--- + +```lua +-- Les commentaires unilignes commencent par un double-tiret. + +--[[ + Les doubles crochets ouverts ([[) et fermés (]]) à la suite + du double-tiret permettent d'avoir des commentaires + multilignes. +--]] + +---------------------------------------------------- +-- 1. Variables et contrôle d'exécution. +---------------------------------------------------- + +num = 42 -- Tous les nombres sont de type double. +-- Rassurez vous cependant, les doubles stockés sur 64-bits +-- en réservent 52 pour la valeur exacte des entiers. La +-- précision n'est donc pas un problème pour tout entier qui +-- peut être codé sur moins de 52 bits. + +s = 'walternate' -- Chaines de caractères immuables comme en Python. +t = "une chaine avec des guillemets doubles" +u = [[les double crochets permettent + d'avoir une chaine de caractères + sur plusieurs lignes.]] +t = nil -- Affecte la valeur nulle à t; Lua possède un ramasse-miettes + +-- Le do/end définit un bloc de code +while num < 50 do + num = num + 1 -- Pas d'opérateurs de type ++ ou +=. +end + +-- Les structures en if: +if num > 40 then + print('supérieur à 40') +elseif s ~= 'walternate' then -- ~= : est différent de. + -- Le test d'égalité se fait avec == comme en Python. + io.write('inférieur à 40\n') -- Ecrit par defaut sur la sortie stdout. +else + -- Les variables sont globales par défaut. + thisIsGlobal = 5 -- le style camelCase est courant. + + -- Une variable locale est déclarée avec le mot-clé local: + local line = io.read() -- Permet de lire la ligne suivante dans stdin. + + -- .. est l'opérateur de concaténation: + print("L'hiver approche, " .. line) +end + +-- Les variables non définies reçoivent par défaut la valeur nil. +foo = anUnknownVariable -- Maintenant, foo = nil. + +aBoolValue = false + +-- Seuls nil et false sont des valeurs fausses. +-- Mais 0 et '' sont des valeurs vraies! +if not aBoolValue then print('etait faux') end + +-- L'évaluation du 'or' et du 'and' est court-circuitée. +-- Comme avec les ternaires du C et de JS: a?b:c +ans = aBoolValue and 'oui' or 'non' --> 'non' + +karlSum = 0 +for i = 1, 100 do -- Les bornes sont incluses dans l'intervalle. + karlSum = karlSum + i +end + +-- Utilisez "100, 1, -1" pour la décrémentation: +fredSum = 0 +for j = 100, 1, -1 do fredSum = fredSum + j end + +-- En général, l'intervalle est début, fin[, pas]. + +-- Un autre type de boucle: +repeat + print('the way of the future') + num = num - 1 +until num == 0 + + +---------------------------------------------------- +-- 2. Fonctions. +---------------------------------------------------- + +function fib(n) + if n < 2 then return n end + return fib(n - 2) + fib(n - 1) +end + +-- Lua implémente les fermetures et les fonctions anonymes: +function adder(x) + -- La fonction retournée est créée lorsque adder est appelé + -- et elle se rappelle de la valeur de x. + return function (y) return x + y end +end +a1 = adder(9) +a2 = adder(36) +print(a1(16)) --> 25 +print(a2(64)) --> 100 + +-- Les valeurs de retour, les appels de fonction, les assignations +-- supportent tous les listes qui peuvent ne pas correspondre en longueur. +-- Dans ce cas, les variables à assigner en supplément recoivent nil +-- tandis que les valeurs à attribuer en supplément sont ignorées + +x, y = 1, 2 -- x = 1 et y = 2 +x, y, z = 1, 2 -- x = 1, y = 2 et z = nil +x, y, z = 1, 2, 3, 4 -- x = 1, y = 2, z = 3, et 4 est ignoré. + +function bar(a, b, c) + print(a, b, c) + return 4, 8, 15, 16, 23, 42 +end + +x, y = bar('zaphod') --> affiche "zaphod nil nil" +-- x = 4, y = 8, les valeurs 15 à 42 sont ignorées. + +-- Les fonctions sont des valeurs de première classe +-- et peuvent être locales/globales. +-- Les déclarations suivantes sont identiques: +function f(x) return x * x end +f = function (x) return x * x end + +-- Il en va de même pour les déclarations suivantes: +local function g(x) return math.sin(x) end +local g = function(x) return math.sin(x) end +-- Sauf que pour le dernier cas, même si local g = function(x) +-- est équivalent à local function g(x), il n'est pas possible +-- de faire appel à g à l'intérieur du corps de la fonction (récursion) + +-- A moins de déclarer la fonction auparavant: +local g; g = function (x) return math.sin(x) end + +-- A propos, les fonctions trigonométriques interprètent +-- leurs arguments en radians. +print(math.cos(math.pi)) -- affiche "-1" +print(math.sin(math.pi)) -- affiche "0" + +-- Lorsqu'une fonction est appellée avec un seul argument qui est une chaine, +-- les parenthèses peuvent être omises: +print 'hello' -- équivalent à print('hello'). + +-- Lorsqu'une fonction est appellée avec un seul argument qui est une table, +-- les parenthèses peuvent aussi être omises. +print {} -- équivalent à print({}). + + +---------------------------------------------------- +-- 3. Tables. +---------------------------------------------------- + +-- Tables = Seule structure de données en Lua; +-- Ce sont des listes assotiatives. +-- Elles sont similaires aux tables PHP ou aux objets JS : +-- des tables-dictionnaires que l'on peut utiliser en tant que listes. + +-- Tables en tant que dictionnaires: + +-- Les clés sont des chaines de caractères par défaut: +t = {key1 = 'valeur1', key2 = false} + +-- Elles peuvent être indexées avec la notation en point, comme en JS: +print(t.key1) -- Affiche "valeur1". +t.newKey = {} -- Ajoute une nouvelle paire clé/valeur. +t.key2 = nil -- Supprime la clé "key2" de la table. + +-- Notation littérale pour toute valeur non nulle en tant que clé: +u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} +print(u[6.28]) -- affiche "tau" + +-- La correspondance des clés se fait par valeur pour +-- les nombres et les chaines, mais par référence pour les tables. +a = u['@!#'] -- a = 'qbert'. +b = u[{}] -- On pourrait s'attendre à 1729, mais l'on obtient nil: +-- b = nil car la clé utilisée n'est pas le même objet que celui +-- utilisé pour stocker la valeur originale 1729. + +-- Si une fonction prend en argument une seule table, l'on peut +-- omettre les parenthèses: +function h(x) print(x.key1) end +h{key1 = 'Sonmi~451'} -- Affiche 'Sonmi~451'. + +for key, val in pairs(u) do -- Parcours d'une table. + print(key, val) +end + +-- _G est une table spéciale contenant toutes les variables globales, +-- et donc elle même. +print(_G['_G'] == _G) -- Affiche 'true'. + +-- Tables en tant que listes: + +-- De manière implicite, les clés sont des nombres entiers: +v = {'value1', 'value2', 1.21, 'gigawatts'} +for i = 1, #v do -- #v retourne la taille d'une table si elle est une liste. + print(v[i]) -- Attention, en Lua, les index commencent à 1! +end +-- Il n'existe pas vraiment de type 'liste' en Lua, v est juste +-- une table avec des clés qui sont des nombres entiers consécutifs +-- commençant à 1. Lua le traite comme étant une liste. + +---------------------------------------------------- +-- 3.1 Métatables and métaméthodes. +---------------------------------------------------- + +-- Une table peut avoir une métatable qui confère à la table +-- un patron/prototype de conception (surcharge d'opération). Nous verrons +-- dans la suite comment les métatables imitent le prototypage de JS. + +f1 = {a = 1, b = 2} -- Représente la fraction a/b. +f2 = {a = 2, b = 3} + +-- Ceci créée une erreur: +-- s = f1 + f2 + +metafraction = {} +function metafraction.__add(f1, f2) + local sum = {} + sum.b = f1.b * f2.b + sum.a = f1.a * f2.b + f2.a * f1.b + return sum +end + +setmetatable(f1, metafraction) +setmetatable(f2, metafraction) + +s = f1 + f2 -- appèle __add(f1, f2) de la métatable de f1 + +-- f1, f2 ne possède pas de clé qui pointent vers leur métatable, comme +-- avec les prototypes en JS. Mais l'on peut utiliser getmetatable(f1). +-- La métatable est une table normale avec des clés prédéfinie, comme __add. + +-- Mais la ligne suivante génère une erreur puisque s n'a pas de métatable: +-- t = s + s +-- En implémentant de l'orienté-objet, comme nous le verrons dans la suite, +-- le problème est résolu. + +-- Une clé __index dans une métatable mt surcharge l'indexation dans sa table t +-- si la clé est absente de cette table t: +defaultFavs = {animal = 'gru', food = 'donuts'} +myFavs = {food = 'pizza'} +setmetatable(myFavs, {__index = defaultFavs}) +eatenBy = myFavs.animal -- Affiche "gru"! merci à la métatable! + +-- Ainsi donc, un accès direct à une valeur dans une table via une clé +-- inexistante (ce qui normalement retourne "nil") conduira à exploiter +-- le champ __index de la métatable. Cela peut être récursif. + +-- Le champ __index peut aussi être une fonction (tbl, clé) +-- ce qui permet une gestion plus souple des indexations. + +-- Les clés __index, __add,... sont appelées métaméthodes. +-- En voici la liste complète: + +-- __add(a, b) pour a + b +-- __sub(a, b) pour a - b +-- __mul(a, b) pour a * b +-- __div(a, b) pour a / b +-- __mod(a, b) pour a % b +-- __pow(a, b) pour a ^ b +-- __unm(a) pour -a +-- __concat(a, b) pour a .. b +-- __len(a) pour #a +-- __eq(a, b) pour a == b +-- __lt(a, b) pour a < b +-- __le(a, b) pour a <= b +-- __index(a, b) pour a.b +-- __newindex(a, b, c) pour a.b = c +-- __call(a, ...) pour a(...) + +---------------------------------------------------- +-- 3.2 Pseudo-orienté objet et héritage. +---------------------------------------------------- + +-- Lua n'implémente pas d'orienté objet par défaut. +-- Mais il reste possible d'imiter de plusieurs manières +-- le concept de "classe" grâce aux tables et aux métatables. + +-- L'explication pour l'exemple qui suit vient juste après. + +Dog = {} -- 1. + +function Dog:new() -- 2. + local newObj = {sound = 'woof'} -- 3. + self.__index = self -- 4. + return setmetatable(newObj, self) -- 5. +end + +function Dog:makeSound() -- 6. + print('Je dis: ' .. self.sound..'!') +end + +mrDog = Dog:new() -- 7. +mrDog:makeSound() -- 'Je dis: woof! -- 8. + +-- 1. Dog agit comme une classe; c'est une simple table. +-- 2. L'expression tbl:fn(...) est identique à +-- tbl.fn(self, ...) +-- La notation : permet de passer par défaut un premier +-- argument appellé "self" à la fonction tbl.fn +-- Voir 7 & 8 ci-après pour comprendre comment self prend +-- sa valeur. +-- 3. newObj sera une instance de la classe Dog. +-- 4. self = la classe instanciée. Souvent, self = Dog, mais +-- cela peut changer du fait de l'héritage. +-- newObj reçoit les fonctions de self si l'__index des +-- métatables de newObj et de self pointent vers self. +-- 5. Rappel: setmetatable retourne son premier argument. +-- 6. La notation : fonctionne comme au 2, mais cette fois, self +-- est une instance au lieu d'être une classe. +-- 7. Similaire à Dog.new(Dog), donc self = Dog dans new(). +-- 8. Similaire à mrDog.makeSound(mrDog); self = mrDog. + +---------------------------------------------------- + +-- Exemple d'héritage: + +LoudDog = Dog:new() -- 1. + +function LoudDog:makeSound() + local s = self.sound .. ' ' -- 2. + print(s .. s .. s..'!') +end + +seymour = LoudDog:new() -- 3. +seymour:makeSound() -- 'woof woof woof!' -- 4. + +-- 1. LoudDog reçoit les méthodes et les variables de Dog. +-- 2. self possède une clé 'sound', reçue de new(), voir 3. +-- 3. Similaire à LoudDog.new(LoudDog) et traduit en Dog.new(LoudDog), +-- puisque LoudDog ne possède pas de clé 'new', mais a une métatable +-- qui a la clé __index = Dog. +-- Résulat: la métatable de seymour est LoudDog, et +-- LoudDog.__index = LoudDog. Donc seymour.key deviendra soit égal à +-- seymour.key, LoudDog.key, Dog.key, selon le fait qu'il s'agira +-- de la première table ayant la clé 'key' en question, en remontant +-- dans la hiérarchie. +-- 4. La clé 'makeSound' est trouvée dans LoudDog; cela est similaire +-- à LoudDog.makeSound(seymour). + +-- Si besoin est, la méthode new() de la sous-classe est +-- identique à la méthode new() de sa classe mère: +function LoudDog:new() + local newObj = {} + -- Prépare self à être la superclasse de newObj: + self.__index = self + return setmetatable(newObj, self) +end + +---------------------------------------------------- +-- 4. Modules. +---------------------------------------------------- + + +--[[ Cette section est mise en commentaire afin que le reste du +-- ce script reste exécutable. +``` + +```lua +-- Supposons que le fichier mod.lua contienne ceci: +local M = {} + +local function sayMyName() + print('Hrunkner') +end + +function M.sayHello() + print('hello') + sayMyName() +end + +return M + +-- Un autre fichier peut exploiter le contenu défini dans mod.lua's: +local mod = require('mod') -- Exécute le fichier mod.lua. + +-- require est le moyen par défaut d'inclure des modules. +-- require agit comme: (si non trouvé en cache; voir ci-après) +local mod = (function () + +end)() +-- Comme si le contenu de mod.lua est enveloppé dans le corps d'une fonction, +-- si bien que les variables locales contenues dans mod.lua deviennent +-- inaccessibles en dehors de ce module. + +-- Le code suivant fonctionne car mod = M (dans mod.lua): +mod.sayHello() -- Dis bonjour à Hrunkner. + +-- Le code suivant génère une erreur car sayMyName est local à mod.lua: +mod.sayMyName() -- erreur! + +-- Les valeurs retournées par require sont mises en cache, ce qui fait +-- qu'un module est toujours chargé une seule fois, même s'il est inclus +-- avec require à plusieurs reprises. + +-- Supposons que mod2.lua contienne le code "print('Hi!')". +local a = require('mod2') -- Affiche "Hi!" +local b = require('mod2') -- N'affiche rien; et a = b. + +-- dofile est identique à require, sauf qu'il ne fait pas de mise en cache: +dofile('mod2') --> Hi! +dofile('mod2') --> Hi! (le code de mod2.lua est encore exécuté) + +-- loadfile charge le contenu d'un fichier, sans l'exécuter. +f = loadfile('mod2') -- L'appel f() exécute le contenu de mod2.lua. + +-- loadstring est similaire à loadfile, mais pour les chaines de caractères. +g = loadstring('print(343)') -- Retourne une fonction. +g() -- Affiche 343; Rien n'est affiché avant cet appel. + +--]] + +``` +## Références + +*Les références qui suivent sont en Anglais.* + +Les sujets non abordés dans ce tutoriel sont couverts en intégralité par +les librairies standard: + +* la librairie string +* la librairie table +* la librairie math +* la librairie io +* la librairie os + +Autres références complémentaires: + +* Lua for programmers +* Courte de référence de Lua +* Programming In Lua +* Les manuels de référence Lua + +A propos, ce fichier est exécutable. Sauvegardez-le sous le nom learn.lua et +exécutez-le avec la commande "lua learn.lua" ! + +Ce tutoriel a été originalement écrit pour tylerneylon.com et est aussi +disponible en tant que gist. +Il a été traduit en français par Roland Yonaba (voir son github). + +Amusez-vous bien avec Lua! \ No newline at end of file -- cgit v1.2.3 From bb673a40a9779a8abe9e3a430160f58670e01a5b Mon Sep 17 00:00:00 2001 From: Yonaba Date: Mon, 30 Dec 2013 14:54:30 +0000 Subject: Bit of prettification --- fr-fr/lua-fr.html.markdown | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/fr-fr/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown index e3979f08..63b65c38 100644 --- a/fr-fr/lua-fr.html.markdown +++ b/fr-fr/lua-fr.html.markdown @@ -12,9 +12,8 @@ lang: fr-fr -- Les commentaires unilignes commencent par un double-tiret. --[[ - Les doubles crochets ouverts ([[) et fermés (]]) à la suite - du double-tiret permettent d'avoir des commentaires - multilignes. + Les doubles crochets à la suite du double-tiret + permettent d'insérer des commentaires multilignes. --]] ---------------------------------------------------- @@ -427,11 +426,11 @@ g() -- Affiche 343; Rien n'est affiché avant cet appel. Les sujets non abordés dans ce tutoriel sont couverts en intégralité par les librairies standard: -* la librairie string -* la librairie table -* la librairie math -* la librairie io -* la librairie os +* La librairie string +* La librairie table +* La librairie math +* La librairie io +* La librairie os Autres références complémentaires: @@ -440,8 +439,8 @@ Autres références complémentaires: * Programming In Lua * Les manuels de référence Lua -A propos, ce fichier est exécutable. Sauvegardez-le sous le nom learn.lua et -exécutez-le avec la commande "lua learn.lua" ! +A propos, ce fichier est exécutable. Sauvegardez-le sous le nom *learn.lua* et +exécutez-le avec la commande `lua learn.lua` ! Ce tutoriel a été originalement écrit pour tylerneylon.com et est aussi disponible en tant que gist. -- cgit v1.2.3 From a0ee6f45a973092ef58b08759c0300a2ce772e00 Mon Sep 17 00:00:00 2001 From: Yonaba Date: Mon, 30 Dec 2013 15:35:44 +0000 Subject: Fixed a lot of typos (thanks @Nami-Doc for the proofreading) --- fr-fr/lua-fr.html.markdown | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/fr-fr/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown index 63b65c38..8535848a 100644 --- a/fr-fr/lua-fr.html.markdown +++ b/fr-fr/lua-fr.html.markdown @@ -9,10 +9,10 @@ lang: fr-fr --- ```lua --- Les commentaires unilignes commencent par un double-tiret. +-- Les commentaires unilignes commencent par un double tiret. --[[ - Les doubles crochets à la suite du double-tiret + Les doubles crochets à la suite du double tiret permettent d'insérer des commentaires multilignes. --]] @@ -43,7 +43,7 @@ if num > 40 then print('supérieur à 40') elseif s ~= 'walternate' then -- ~= : est différent de. -- Le test d'égalité se fait avec == comme en Python. - io.write('inférieur à 40\n') -- Ecrit par defaut sur la sortie stdout. + io.write('inférieur à 40\n') -- Écrit par defaut sur la sortie stdout. else -- Les variables sont globales par défaut. thisIsGlobal = 5 -- le style camelCase est courant. @@ -64,8 +64,8 @@ aBoolValue = false -- Mais 0 et '' sont des valeurs vraies! if not aBoolValue then print('etait faux') end --- L'évaluation du 'or' et du 'and' est court-circuitée. --- Comme avec les ternaires du C et de JS: a?b:c +-- L'évaluation du 'or' et du 'and' est court-circuité. +-- Comme avec les ternaires du C et du JS: a?b:c ans = aBoolValue and 'oui' or 'non' --> 'non' karlSum = 0 @@ -108,7 +108,7 @@ print(a2(64)) --> 100 -- Les valeurs de retour, les appels de fonction, les assignations -- supportent tous les listes qui peuvent ne pas correspondre en longueur. --- Dans ce cas, les variables à assigner en supplément recoivent nil +-- Dans ce cas, les variables à assigner en supplément reçoivent nil -- tandis que les valeurs à attribuer en supplément sont ignorées x, y = 1, 2 -- x = 1 et y = 2 @@ -120,7 +120,7 @@ function bar(a, b, c) return 4, 8, 15, 16, 23, 42 end -x, y = bar('zaphod') --> affiche "zaphod nil nil" +x, y = bar('zaphod') --> affiche "zaphod nil nil" -- x = 4, y = 8, les valeurs 15 à 42 sont ignorées. -- Les fonctions sont des valeurs de première classe @@ -136,19 +136,19 @@ local g = function(x) return math.sin(x) end -- est équivalent à local function g(x), il n'est pas possible -- de faire appel à g à l'intérieur du corps de la fonction (récursion) --- A moins de déclarer la fonction auparavant: +-- À moins de déclarer la fonction auparavant: local g; g = function (x) return math.sin(x) end --- A propos, les fonctions trigonométriques interprètent +-- À propos, les fonctions trigonométriques interprètent -- leurs arguments en radians. print(math.cos(math.pi)) -- affiche "-1" print(math.sin(math.pi)) -- affiche "0" --- Lorsqu'une fonction est appellée avec un seul argument qui est une chaine, +-- Lorsqu'une fonction est appelée avec un seul argument qui est une chaine, -- les parenthèses peuvent être omises: print 'hello' -- équivalent à print('hello'). --- Lorsqu'une fonction est appellée avec un seul argument qui est une table, +-- Lorsqu'une fonction est appelée avec un seul argument qui est une table, -- les parenthèses peuvent aussi être omises. print {} -- équivalent à print({}). @@ -200,8 +200,8 @@ print(_G['_G'] == _G) -- Affiche 'true'. -- De manière implicite, les clés sont des nombres entiers: v = {'value1', 'value2', 1.21, 'gigawatts'} -for i = 1, #v do -- #v retourne la taille d'une table si elle est une liste. - print(v[i]) -- Attention, en Lua, les index commencent à 1! +for i = 1, #v do -- #v retourne la taille de la table v si elle est une liste. + print(v[i]) -- Attention, en Lua, les indices commencent à 1! end -- Il n'existe pas vraiment de type 'liste' en Lua, v est juste -- une table avec des clés qui sont des nombres entiers consécutifs @@ -213,7 +213,7 @@ end -- Une table peut avoir une métatable qui confère à la table -- un patron/prototype de conception (surcharge d'opération). Nous verrons --- dans la suite comment les métatables imitent le prototypage de JS. +-- dans la suite comment les métatables imitent le prototypage du JS. f1 = {a = 1, b = 2} -- Représente la fraction a/b. f2 = {a = 2, b = 3} @@ -236,11 +236,11 @@ s = f1 + f2 -- appèle __add(f1, f2) de la métatable de f1 -- f1, f2 ne possède pas de clé qui pointent vers leur métatable, comme -- avec les prototypes en JS. Mais l'on peut utiliser getmetatable(f1). --- La métatable est une table normale avec des clés prédéfinie, comme __add. +-- La métatable est une table normale avec des clés prédéfinies, comme __add. -- Mais la ligne suivante génère une erreur puisque s n'a pas de métatable: -- t = s + s --- En implémentant de l'orienté-objet, comme nous le verrons dans la suite, +-- En implémentant de l'orienté objet, comme nous le verrons par la suite, -- le problème est résolu. -- Une clé __index dans une métatable mt surcharge l'indexation dans sa table t @@ -305,7 +305,7 @@ mrDog:makeSound() -- 'Je dis: woof! -- 8. -- 2. L'expression tbl:fn(...) est identique à -- tbl.fn(self, ...) -- La notation : permet de passer par défaut un premier --- argument appellé "self" à la fonction tbl.fn +-- argument appelé "self" à la fonction tbl.fn -- Voir 7 & 8 ci-après pour comprendre comment self prend -- sa valeur. -- 3. newObj sera une instance de la classe Dog. @@ -383,12 +383,12 @@ return M local mod = require('mod') -- Exécute le fichier mod.lua. -- require est le moyen par défaut d'inclure des modules. --- require agit comme: (si non trouvé en cache; voir ci-après) +-- require agit comme: (si non trouvé en cache; voir ci-après) local mod = (function () end)() --- Comme si le contenu de mod.lua est enveloppé dans le corps d'une fonction, --- si bien que les variables locales contenues dans mod.lua deviennent +-- Comme si le contenu de mod.lua était enveloppé dans le corps d'une fonction, +-- si bien que les variables locales contenues dans mod.lua sont -- inaccessibles en dehors de ce module. -- Le code suivant fonctionne car mod = M (dans mod.lua): -- cgit v1.2.3 From f3d043f7b8d8e318557eabd0a9cdac05bc39779d Mon Sep 17 00:00:00 2001 From: Yonaba Date: Mon, 30 Dec 2013 15:50:33 +0000 Subject: Typo fix, again --- fr-fr/lua-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown index 8535848a..922d6ebc 100644 --- a/fr-fr/lua-fr.html.markdown +++ b/fr-fr/lua-fr.html.markdown @@ -234,7 +234,7 @@ setmetatable(f2, metafraction) s = f1 + f2 -- appèle __add(f1, f2) de la métatable de f1 --- f1, f2 ne possède pas de clé qui pointent vers leur métatable, comme +-- f1, f2 ne possèdent pas de clé qui pointent vers leur métatable, comme -- avec les prototypes en JS. Mais l'on peut utiliser getmetatable(f1). -- La métatable est une table normale avec des clés prédéfinies, comme __add. -- cgit v1.2.3 From 5d5f3309faf8c6cf0bb5242ea7220e4ae772d6a3 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 21 Dec 2013 17:37:19 -0600 Subject: Add more description to @property getters and setters. --- objective-c.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 1ed0ed58..0a197e03 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -233,6 +233,9 @@ int main (int argc, const char * argv[]) @property int count; @property (copy) NSString *name; // Copy the object during assignment. @property (readonly) id data; // Declare only a getter method. +// To access variable in implementation file, use '_' followed by variable name: +_count = 5; +NSLog("%@", _count); // => prints 5 to console // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; -- cgit v1.2.3 From 643a3ec67bb5d7b453b4a4d59bbb8b254eccb0db Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 21 Dec 2013 17:37:19 -0600 Subject: Add getters and setters examples. --- objective-c.html.markdown | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 0a197e03..1cfe8ed6 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -233,9 +233,13 @@ int main (int argc, const char * argv[]) @property int count; @property (copy) NSString *name; // Copy the object during assignment. @property (readonly) id data; // Declare only a getter method. -// To access variable in implementation file, use '_' followed by variable name: +// To access public variable in implementation file, use '_' followed by variable name: _count = 5; -NSLog("%@", _count); // => prints 5 to console +NSLog(@"%d", _count); // prints => 5 +// To access public variable outside implementation file, @property generates setter method +// automatically. Method name is 'set' followed by @property variable name: +[objInitVar setCount:10]; // objInitVar = variable of object instance @property resides in. +NSLog(@"%@", [objInitVar count]); // prints => 10 // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; -- cgit v1.2.3 From 0b73244aa3c53d51a7031a04a6cb7f85895af101 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 22 Dec 2013 10:37:02 -0600 Subject: Add data types with examples. --- objective-c.html.markdown | 58 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 9 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 1cfe8ed6..0131a34c 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -50,53 +50,93 @@ int main (int argc, const char * argv[]) // String NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // Print "Hello World!" + NSLog(@"Hello %@!", worldString); // prints => "Hello World!" + // The mutable version of NSString is NSMutableString that allows to edit + // individual characters or append strings together. + NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; + [mutableString appendString:@" World!"]; + NSLog(@"%@", mutableString); // prints => "Hello World!" // Character literals NSNumber *theLetterZNumber = @'Z'; - char theLetterZ = [theLetterZNumber charValue]; + char theLetterZ = [theLetterZNumber charValue]; // or 'Z' NSLog(@"%c", theLetterZ); // Integral literals NSNumber *fortyTwoNumber = @42; - int fortyTwo = [fortyTwoNumber intValue]; + int fortyTwo = [fortyTwoNumber intValue]; // or 42 NSLog(@"%i", fortyTwo); NSNumber *fortyTwoUnsignedNumber = @42U; - unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42 NSLog(@"%u", fortyTwoUnsigned); NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; - short fortyTwoShort = [fortyTwoShortNumber shortValue]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 NSLog(@"%hi", fortyTwoShort); + + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:41]; + unsigned short fortyTwoUnsigned = [fortyTwoShortNumber unsignedShortValue]; // or 41 + NSLog(@"%hu", fortyTwoUnsigned); NSNumber *fortyTwoLongNumber = @42L; - long fortyTwoLong = [fortyTwoLongNumber longValue]; + long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 NSLog(@"%li", fortyTwoLong); + NSNumber *fortyTwoLongNumber = @53L; + unsigned long fiftyThreeUnsigned = [fortyTwoLongNumber unsignedLongValue]; // or 53 + NSLog(@"%lu", fiftyThreeUnsigned); + // Floating point literals NSNumber *piFloatNumber = @3.141592654F; - float piFloat = [piFloatNumber floatValue]; - NSLog(@"%f", piFloat); + float piFloat = [piFloatNumber floatValue]; // or 3.141592654f + NSLog(@"%f", piFloat); // prints => 3.141592654 + NSLog(@"%5.2f", piFloat); // prints => " 3.14" NSNumber *piDoubleNumber = @3.1415926535; - double piDouble = [piDoubleNumber doubleValue]; + double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 NSLog(@"%f", piDouble); + NSLog(@"%4.2f", piDouble); // prints => "3.14" + + // NSDecimalNumber is Objective-C's fixed-point class more precise then float or double + NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; + NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; + // NSDecimal isn't able to use standard +, -, *, / operators. NSDecimalNumber has its own: + [oneDecNum decimalNumberByAdding:twoDecNum]; // add + [oneDecNum decimalNumberBySubtracting:twoDecNum]; + [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; + [oneDecNum decimalNumberByDividingBy:twoDecNum]; + NSLog(@"%@", oneDecNum); // prints => 10.99 as NSDecimalNumber is immutable. // BOOL literals NSNumber *yesNumber = @YES; NSNumber *noNumber = @NO; + // or + BOOL yesBool = YES; + BOOL noBool = NO; + NSLog(@"%i", yesBool); // prints => 1 // Array object NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" + // NSMutableArray is mutable version of NSArray allowing to change items in array + // and extend or shrink array object. Convenient, but not as efficient as NSArray. + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; + [mutableArray addObject:@"Hello"]; + [mutableArray addObject:@"World"]; + [mutableArray removeObjectAtIndex:0]; + NSLog(@"%@", [mutableArray objectAtIndex:0]); // prints => "World" // Dictionary object NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // Print "Object = (null)" + // Set object + NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; + NSLog(@"%@", set); // prints => {(Hello, World)} + /////////////////////////////////////// // Operators /////////////////////////////////////// -- cgit v1.2.3 From 18f669089e0f5a65adfdfeddaa571a801dd4b865 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 23 Dec 2013 02:26:11 -0600 Subject: Add examples of methods to work with NSSets. Add note of NSSets being unordered. Remove for loop to iterate on NSSet. Moved for loop to loop section. --- objective-c.html.markdown | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 0131a34c..95012152 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -50,9 +50,8 @@ int main (int argc, const char * argv[]) // String NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // prints => "Hello World!" - // The mutable version of NSString is NSMutableString that allows to edit - // individual characters or append strings together. + NSLog(@"Hello %@!", worldString); // prints => "Hello World!" + // NSMutableString is a mutable version of the NSString object. NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; [mutableString appendString:@" World!"]; NSLog(@"%@", mutableString); // prints => "Hello World!" @@ -98,11 +97,11 @@ int main (int argc, const char * argv[]) NSLog(@"%f", piDouble); NSLog(@"%4.2f", piDouble); // prints => "3.14" - // NSDecimalNumber is Objective-C's fixed-point class more precise then float or double + // NSDecimalNumber is a fixed-point class that's more precise then float or double NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; - // NSDecimal isn't able to use standard +, -, *, / operators. NSDecimalNumber has its own: - [oneDecNum decimalNumberByAdding:twoDecNum]; // add + // NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own: + [oneDecNum decimalNumberByAdding:twoDecNum]; [oneDecNum decimalNumberBySubtracting:twoDecNum]; [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; [oneDecNum decimalNumberByDividingBy:twoDecNum]; @@ -132,10 +131,12 @@ int main (int argc, const char * argv[]) NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // Print "Object = (null)" + // NSMutableDictionary also available as mutable dictionary object. // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; - NSLog(@"%@", set); // prints => {(Hello, World)} + NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) + // NSMutableSet also available as mutable set object. /////////////////////////////////////// // Operators @@ -216,6 +217,14 @@ int main (int argc, const char * argv[]) // "2," // "3," + // Object for loop statement. Can be used with any Objective-C object type. + for (id item in values) { + NSLog(@"%@,", item); + } // => prints "0," + // "1," + // "2," + // "3," + // Try-Catch-Finally statements @try { @@ -278,7 +287,7 @@ _count = 5; NSLog(@"%d", _count); // prints => 5 // To access public variable outside implementation file, @property generates setter method // automatically. Method name is 'set' followed by @property variable name: -[objInitVar setCount:10]; // objInitVar = variable of object instance @property resides in. +[objInitVar setCount:10]; // objInitVar = random object instance @property resides in. NSLog(@"%@", [objInitVar count]); // prints => 10 // Methods -- cgit v1.2.3 From f15a2b5f782b0f5fb2de6359353f948218860484 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 26 Dec 2013 12:20:16 -0600 Subject: Add more data type examples. Add NSMutableSet examples. --- objective-c.html.markdown | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 95012152..bbdbac4c 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -131,12 +131,19 @@ int main (int argc, const char * argv[]) NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // Print "Object = (null)" - // NSMutableDictionary also available as mutable dictionary object. + // NSMutableDictionary also available as a mutable dictionary object. + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; + [mutableDictionary setObject:@"value1" forKey:@"key1"]; + [mutableDictionary setObject:@"value2" forKey:@"key2"]; + [mutableDictionary removeObjectForKey:@"key1"]; // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) - // NSMutableSet also available as mutable set object. + // NSMutableSet also available as a mutable set object. + NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; + [mutableSet addObject:@"Hello"]; + [mutableSet addObject:@"Hello"]; /////////////////////////////////////// // Operators -- cgit v1.2.3 From 03ada8d9751993ad1b36d3d5848678b31ac9021c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 26 Dec 2013 22:26:34 -0600 Subject: Add instance variable definition examples. --- objective-c.html.markdown | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index bbdbac4c..419c0475 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -74,7 +74,7 @@ int main (int argc, const char * argv[]) short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 NSLog(@"%hi", fortyTwoShort); - NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:41]; + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:41]; unsigned short fortyTwoUnsigned = [fortyTwoShortNumber unsignedShortValue]; // or 41 NSLog(@"%hu", fortyTwoUnsigned); @@ -82,7 +82,7 @@ int main (int argc, const char * argv[]) long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 NSLog(@"%li", fortyTwoLong); - NSNumber *fortyTwoLongNumber = @53L; + NSNumber *fortyTwoLongNumber = @53L; unsigned long fiftyThreeUnsigned = [fortyTwoLongNumber unsignedLongValue]; // or 53 NSLog(@"%lu", fiftyThreeUnsigned); @@ -93,7 +93,7 @@ int main (int argc, const char * argv[]) NSLog(@"%5.2f", piFloat); // prints => " 3.14" NSNumber *piDoubleNumber = @3.1415926535; - double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 + double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 NSLog(@"%f", piDouble); NSLog(@"%4.2f", piDouble); // prints => "3.14" @@ -112,7 +112,7 @@ int main (int argc, const char * argv[]) NSNumber *noNumber = @NO; // or BOOL yesBool = YES; - BOOL noBool = NO; + BOOL noBool = NO; NSLog(@"%i", yesBool); // prints => 1 // Array object @@ -144,6 +144,7 @@ int main (int argc, const char * argv[]) NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; [mutableSet addObject:@"Hello"]; [mutableSet addObject:@"Hello"]; + NSLog(@"%@", mutableSet); // prints => {(Hello)} /////////////////////////////////////// // Operators @@ -281,11 +282,12 @@ int main (int argc, const char * argv[]) // @end @interface MyClass : NSObject { - int count; - id data; - NSString *name; + // Instance variable declarations (can exist in either interface or implementation file) + int count; // Protected access by default. + @private id data; // Private access. (More convenient to declare in implementation file) + NSString *name; } -// Convenience notation to auto generate public getter and setter +// Convenient notation to auto generate public access getter and setter @property int count; @property (copy) NSString *name; // Copy the object during assignment. @property (readonly) id data; // Declare only a getter method. @@ -294,8 +296,16 @@ _count = 5; NSLog(@"%d", _count); // prints => 5 // To access public variable outside implementation file, @property generates setter method // automatically. Method name is 'set' followed by @property variable name: -[objInitVar setCount:10]; // objInitVar = random object instance @property resides in. -NSLog(@"%@", [objInitVar count]); // prints => 10 +MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. +[myClass setCount:10]; +NSLog(@"%@", [myClass count]); // prints => 10 +// You can customize the getter and setter names instead of using default 'set' name: +@property (getter=countGet, setter=countSet:) int count; +[myClass countSet:32]; +NSLog(@"%i", [myClass countGet]); // prints => 32 +// For convenience, you may use dot notation to set object instance variables: +myClass.count = 45; +NSLog(@"%i", myClass.count); // prints => 45 // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; @@ -310,8 +320,9 @@ NSLog(@"%@", [objInitVar count]); // prints => 10 @end // Implement the methods in an implementation (MyClass.m) file: - -@implementation MyClass +@implementation MyClass { + long count; // Private access instance variable. +} // Call when the object is releasing - (void)dealloc -- cgit v1.2.3 From ce770c61df6670f3ac20241dae6314dea5a9c846 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 23 Dec 2013 02:19:18 -0600 Subject: Add simple NSSet example. --- objective-c.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 419c0475..98019404 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -146,6 +146,10 @@ int main (int argc, const char * argv[]) [mutableSet addObject:@"Hello"]; NSLog(@"%@", mutableSet); // prints => {(Hello)} + // Set object + NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; + NSLog(@"%@", set); // prints => {(Hello, World)} + /////////////////////////////////////// // Operators /////////////////////////////////////// -- cgit v1.2.3 From dff26a28afbdc138cd21154e733839f52afaaab9 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 31 Dec 2013 13:50:37 -0600 Subject: Add memory management examples. --- objective-c.html.markdown | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 98019404..9a11ebc8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -377,6 +377,34 @@ NSLog(@"%i", myClass.count); // prints => 45 @end +/////////////////////////////////////// +// Memory Management +/////////////////////////////////////// +/* +For each object used in an application, memory must be allocated for that object. When the application +is done using that object, memory must be deallocated to ensure application efficiency. +Objective-C does not use garbage collection and instead uses reference counting. As long as +there is at least one reference to an object (also called "owning" an object), then the object +will be available to use (known as "ownership"). + +When an instance owns an object, its reference counter is increments by one. When the +object is released, the reference counter decrements by one. When reference count is zero, +the object is removed from memory. + +With all object interactions, follow the pattern of: +(1) create the object, (2) use the object, (3) then free the object from memory. +*/ + +MyClass *classVar = [MyClass alloc]; // alloc sets classVar's reference count to one. Returns pointer to object. +[classVar release]; // Decrements classVar's reference count. +// retain claims ownership of existing object instance and increments reference count. Returns pointer to object. +MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner. +[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object. + +// @property can use retain or assign as well for small convenient definitions. +@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). +@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). + ``` ## Further Reading -- cgit v1.2.3 From 8e04611520cc385ccfd96ca1e8cfd8e30fc2ce40 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 31 Dec 2013 14:04:07 -0600 Subject: Add automatic reference counting examples. --- objective-c.html.markdown | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 9a11ebc8..406b2e92 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -405,6 +405,21 @@ MyClass *newVar = [classVar retain]; // If classVar is released, object is still @property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). @property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). +// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). +// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, +// you must not use retain, relase, or autorelease. +MyClass *arcMyClass = [[MyClass alloc] init]; // Without ARC, you will need to call: [arcMyClass release] after +// you're done using arcMyClass. But with ARC, there is no need. It will insert this release statement for you. + +// As for the "assign" and "retain" @property attributes, with ARC you use "weak" and "strong". +@property (weak) MyClass *weakVar; // weak does not take ownership of object. If original instance's reference count +// is set to zero, weakVar will automatically receive value of nil to avoid application crashing. +@property (strong) MyClass *strongVar; // strong takes ownership of object. Ensures object will stay in memory to use. + +// For regular variables (not @property declared variables), use the following: +__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope. +__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil. +__unsafe_unretained NSArray *unsafeArray; // Like __weak but unsafeArray not set to nil when existing object is released. ``` ## Further Reading -- cgit v1.2.3 From fff847f09e67144a67ec6e0db2198273ef8d91ad Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 1 Jan 2014 19:01:50 -0600 Subject: Add @autoreleasepool as alternative to NSAutoreleasePool object. --- objective-c.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 406b2e92..b9460127 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -28,7 +28,9 @@ int main (int argc, const char * argv[]) { // Create an autorelease pool to manage the memory into the program NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - + // If using automatic reference counting (ARC), use @autoreleasepool instead: + @autoreleasepool { + // Use NSLog to print lines to the console NSLog(@"Hello World!"); // Print the string "Hello World!" @@ -267,6 +269,9 @@ int main (int argc, const char * argv[]) // Clean up the memory you used into your program [pool drain]; + + // End of @autoreleasepool. + } // End the program return 0; -- cgit v1.2.3 From fb72fe9256a604a0e5dac164709b5ac24595e40d Mon Sep 17 00:00:00 2001 From: kyr Date: Thu, 2 Jan 2014 17:30:48 +0100 Subject: translated css to german --- de-de/css-de.html.markdown | 152 +++++++++++++++++++++++---------------------- 1 file changed, 77 insertions(+), 75 deletions(-) diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown index e212e555..da6489ee 100644 --- a/de-de/css-de.html.markdown +++ b/de-de/css-de.html.markdown @@ -72,155 +72,157 @@ kann - man sollte nur mit der leerzeichensetzung vorsichtig sein, da es mit einem leerzeichen zwei verschiedene selektoren wären*/ div.eine-klasse[attr$='rt'] { } /* so ist es richtig */ -/* man kann auch ein element daran festmachen, wie sich die übergeordneten elemente verhalten!*/ +/* man kann auch ein element daran festmachen, wie sich die übergeordneten +elemente verhalten!*/ /*es muss allerdings ein direktes kind sein */ -div.some-parent > .class-name {} +div.ein-elternteil > .klassen-name {} -/* or any of it's parents in the tree */ -/* the following basically means any element that has class "class-name" -and is child of a div with class name "some-parent" IN ANY DEPTH */ -div.some-parent .class-name {} +/* oder jeder seiner eltern in der struktur */ +/* das folgende heißt also dass jedes element mit der klasse 'klassen-name' und dem +elternteil IN JEDER TIEFE ausgewählt wird */ +div.ein-elternteil .klassen-name {} -/* warning: the same selector wihout spaaace has another meaning. -can you say what? */ -div.some-parent.class-name {} +/* achtung: dasselbe ohne das leerzeichen hat eine andere bedeutung +kannst du mir sagen, was? */ +div.ein-elternteil.klassen-name {} -/* you also might choose to select an element based on it's direct -previous sibling */ -.i-am-before + .this-element { } +/* man kann auch ein element nach seinem direkten vorherigen zwilling +auswählen */ +.ich-bin-vorher + .dieses-element { } -/*or any sibling before this */ -.i-am-any-before ~ .this-element {} +/*oder jeden zwilling davor */ +.ich-kann-jeder-davor-sein ~ .dieses-element {} -/* There are some pseudo classes that allows you to select an element -based on it's page behaviour (rather than page structure) */ +/* es gibt ein paar pseudoklassen, die sich basierend auf dem +seitenverhalten, nämlich nicht auf der seitenstruktur auswählen +lassen können */ -/* for example for when an element is hovered */ +/* zum beispiel, wenn über ein element mit dem mauszeiger gefahren wird */ :hover {} -/* or a visited link*/ +/* oder eine bereits besuchten link*/ :visited {} -/* or not visited link*/ +/* oder einen noch nicht besuchten link*/ :link {} -/* or an input element which is focused */ +/* oder ein eingabeelement, das zurzeit im fokus steht */ :focus {} /* #################### - ## PROPERTIES + ## EIGENSCHAFTEN ####################*/ selector { - /* Units */ - width: 50%; /* in percent */ - font-size: 2em; /* times current font-size */ - width: 200px; /* in pixels */ - font-size: 20pt; /* in points */ - width: 5cm; /* in centimeters */ - width: 50mm; /* in millimeters */ - width: 5in; /* in inches */ + /* einheiten */ + width: 50%; /* in prozent */ + font-size: 2em; /* mal der derzeitigen schriftgröße */ + width: 200px; /* in pixeln */ + font-size: 20pt; /* in punkten */ + width: 5cm; /* in zentimetern */ + width: 50mm; /* in millimetern */ + width: 5in; /* in zoll */ - /* Colors */ - background-color: #F6E /* in short hex */ - background-color: #F262E2 /* in long hex format */ - background-color: tomato /* can be a named color */ + /* farben */ + background-color: #F6E /* in kurzem hex */ + background-color: #F262E2 /* in langem hex */ + background-color: tomato /* kann auch eine genannte farbe sein */ background-color: rgb(255, 255, 255) /* in rgb */ - background-color: rgb(10%, 20%, 50%) /* in rgb percent */ - background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb */ + background-color: rgb(10%, 20%, 50%) /* in rgb prozent */ + background-color: rgba(255, 0, 0, 0.3); /* in semi-transparentem rgb */ - /* Images */ + /* bilder */ background-image: url(/path-to-image/image.jpg); - /* Fonts */ + /* schriften */ font-family: Arial; - font-family: "Courier New"; /* if name has spaaace it appears in double-quote */ - font-family: "Courier New", Trebuchet, Arial; /* if first one was not found - browser uses the second font, and so forth */ + font-family: "Courier New"; /* wenn der name ein leerzeichen beinhält, kommt er in + gänsefüßchen */ + font-family: "Courier New", Trebuchet, Arial; /* wenn der erste nicht gefunden wird, wird + der zweite benutzt und so weiter */ } ``` -## Usage +## Benutzung -Save any CSS you want in a file with extension `.css`. +speichere das css, das du benutzen willst mit der endung '.css'. ```xml - + - + - +
``` -## Precedence +## Wichtigkeit -As you noticed an element may be targetted by more than one selector. -and may have a property set on it in more than one. -In these cases, one of the rules takes precedence over others. +ein element kann von mehr als einem selektoren angezielt werden. +und kann auch eine eigenschaft mehr als einmal zugewiesen bekommen. +in diesen fällen gibt es regeln, die wichtigkeit von selektoren einführen. -Given the following CSS: +wie haben dieses CSS: ```css /*A*/ -p.class1[attr='value'] +p.klasse1[attr='wert'] /*B*/ -p.class1 {} +p.klasse1 {} /*C*/ -p.class2 {} +p.klasse2 {} /*D*/ p {} /*E*/ -p { property: value !important; } +p { property: wert !important; } ``` -and the following markup: +und das folgende markup: ```xml

``` -The precedence of style is as followed: -Remember, the precedence is for each **property**, not for the entire block. +die wichtigkeit der stile ist wie folgt: +(die wichtigkeit gilt nur für **eigenschaften**, nicht für ganze blöcke) -* `E` has the highest precedence because of the keyword `!important`. - It is recommended to avoid this unless it is strictly necessary to use. -* `F` is next, because it is inline style. -* `A` is next, because it is more "specific" than anything else. - more specific = more specifiers. here 3 specifiers: 1 tagname `p` + - class name `class1` + 1 attribute `attr='value'` -* `C` is next. although it has the same specificness as `B` - but it appears last. -* Then is `B` -* and lastly is `D`. +* `E` hat die größte wichtigkeit wegen dem schlüsselwort `!important`. + man sollte diese form aber vermeiden. +* `F` ist als nächstes, da es direkt an dem element definiert ist. +* `A` ist als nächstes, da es "spezifischer" als alle anderen ist. + spezifischer = mehr zuweisungen: 1 tagname `p` + + klassenname `klasse1` + 1 attribut `attr='value'` +* `C` ist als nächstes obwohl es genau so ist wie `B` + aber es erscheint als letztes. +* dann ist `B` +* und als letztes `D`. -## Compatibility +## Kompabilität -Most of the features in CSS2 (and gradually in CSS3) are compatible across -all browsers and devices. But it's always vital to have in mind the compatiblity -of what you use in CSS with your target browsers. +die meisten features von CSS sind in allen browsern verfügbar. +man sollte jedoch immer darauf achten, wenn man etwas mit CSS +programmiert. -[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. +[QuirksMode CSS](http://www.quirksmode.org/css/) ist eine der besten quellen dafür. -## Further Reading +## Weiterlesen * [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) * [QuirksMode CSS](http://www.quirksmode.org/css/) -- cgit v1.2.3 From f13427127597c966417a8e5e00f4c0f2788f4486 Mon Sep 17 00:00:00 2001 From: kyr Date: Thu, 2 Jan 2014 17:38:25 +0100 Subject: spelling, punctuation and more translation --- de-de/css-de.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown index da6489ee..e03b3174 100644 --- a/de-de/css-de.html.markdown +++ b/de-de/css-de.html.markdown @@ -14,7 +14,7 @@ Kurzgefasst, CSS ermöglicht es, verschiedene HTML-Elemente anzuvisieren und ihn CSS hat wie jede andere Sprache viele Versionen. Hier fokussieren wir uns auf CSS2.0, welche nicht die neueste, aber die am weitesten verbreitete und unterstützte Version ist. -**NOTE:** Weil die Ausgabe von CSS visuelle Eigenschaften sind, wirst du wahrscheinlich einen CSS-Playground wie [dabblet](http://dabblet.com/) benutzen müssen, um die Sprache richtig zu lernen. +**NOTE:** Weil die Ausgabe von CSS visuelle Eigenschaften sind, wirst du wahrscheinlich eine CSS-Sandbox wie [dabblet](http://dabblet.com/) benutzen müssen, um die Sprache richtig zu lernen. In diesem Artikel wird am meisten auf generelle Hinweise und die Syntax geachtet. @@ -79,11 +79,11 @@ elemente verhalten!*/ div.ein-elternteil > .klassen-name {} /* oder jeder seiner eltern in der struktur */ -/* das folgende heißt also dass jedes element mit der klasse 'klassen-name' und dem -elternteil IN JEDER TIEFE ausgewählt wird */ +/* das folgende heißt also, dass jedes element mit der klasse 'klassen-name' +und dem elternteil IN JEDER TIEFE ausgewählt wird */ div.ein-elternteil .klassen-name {} -/* achtung: dasselbe ohne das leerzeichen hat eine andere bedeutung +/* achtung: dasselbe ohne das leerzeichen hat eine andere bedeutung, kannst du mir sagen, was? */ div.ein-elternteil.klassen-name {} @@ -91,7 +91,7 @@ div.ein-elternteil.klassen-name {} auswählen */ .ich-bin-vorher + .dieses-element { } -/*oder jeden zwilling davor */ +/* oder jeden zwilling davor */ .ich-kann-jeder-davor-sein ~ .dieses-element {} /* es gibt ein paar pseudoklassen, die sich basierend auf dem @@ -101,7 +101,7 @@ lassen können */ /* zum beispiel, wenn über ein element mit dem mauszeiger gefahren wird */ :hover {} -/* oder eine bereits besuchten link*/ +/* oder einen bereits besuchten link*/ :visited {} /* oder einen noch nicht besuchten link*/ @@ -135,14 +135,14 @@ selector { background-color: rgba(255, 0, 0, 0.3); /* in semi-transparentem rgb */ /* bilder */ - background-image: url(/path-to-image/image.jpg); + background-image: url(/pfad-zum-bild/image.jpg); /* schriften */ font-family: Arial; font-family: "Courier New"; /* wenn der name ein leerzeichen beinhält, kommt er in - gänsefüßchen */ + apostrophe */ font-family: "Courier New", Trebuchet, Arial; /* wenn der erste nicht gefunden wird, wird - der zweite benutzt und so weiter */ + der zweite benutzt, und so weiter */ } ``` @@ -171,7 +171,7 @@ empfohlen ist --> ein element kann von mehr als einem selektoren angezielt werden. und kann auch eine eigenschaft mehr als einmal zugewiesen bekommen. -in diesen fällen gibt es regeln, die wichtigkeit von selektoren einführen. +in diesen fällen gibt es regeln, die die wichtigkeit von selektoren einführen. wie haben dieses CSS: -- cgit v1.2.3 From db691596bb0a549a01c22e097d0c8d2d84beed5f Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 3 Jan 2014 12:50:35 -0600 Subject: Move statements out of @interface that did not allow file to compile. Fix various typos/confusing wording. --- objective-c.html.markdown | 68 +++++++++++++++++++++++++++-------------------- 1 file changed, 39 insertions(+), 29 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index b9460127..4ba1e5d5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -281,41 +281,30 @@ int main (int argc, const char * argv[]) // Classes And Functions /////////////////////////////////////// -// Declare your class in a header(MyClass.h) file: -// Class Declaration Syntax: +// Declare your class in a header file (MyClass.h): +// Class declaration syntax: // @interface ClassName : ParentClassName // { -// Member variable declarations; +// type name; <= variable declarations; // } -// -/+ (type) Method declarations; +// @property type name; <= property declarations. +// -/+ (type) Method declarations; <= Method declarations. // @end -@interface MyClass : NSObject +@interface MyClass : NSObject // NSObject is Objective-C base object class. { - // Instance variable declarations (can exist in either interface or implementation file) + // Instance variable declarations (can exist in either interface or implementation file). int count; // Protected access by default. - @private id data; // Private access. (More convenient to declare in implementation file) + @private id data; // Private access. (More convenient to declare in implementation file). NSString *name; } -// Convenient notation to auto generate public access getter and setter -@property int count; -@property (copy) NSString *name; // Copy the object during assignment. -@property (readonly) id data; // Declare only a getter method. -// To access public variable in implementation file, use '_' followed by variable name: -_count = 5; -NSLog(@"%d", _count); // prints => 5 -// To access public variable outside implementation file, @property generates setter method -// automatically. Method name is 'set' followed by @property variable name: -MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. -[myClass setCount:10]; -NSLog(@"%@", [myClass count]); // prints => 10 +// Convenient notation for public access variables to auto generate a setter method. +// By default, setter method name is 'set' followed by @property variable name. +@property int count; // Setter name = 'setCount' +@property (copy) NSString *name; // (copy) => Copy the object during assignment. +@property (readonly) id data; // (readonly) => Declare only a getter method. // You can customize the getter and setter names instead of using default 'set' name: -@property (getter=countGet, setter=countSet:) int count; -[myClass countSet:32]; -NSLog(@"%i", [myClass countGet]); // prints => 32 -// For convenience, you may use dot notation to set object instance variables: -myClass.count = 45; -NSLog(@"%i", myClass.count); // prints => 45 - +@property (getter=lengthGet, setter=lengthSet:) int length; + // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; @@ -326,13 +315,34 @@ NSLog(@"%i", myClass.count); // prints => 45 - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; -@end +@end // States the end of the interface. + + +// To access public variables from the implementation file, @property generates a setter method +// automatically. Method name is 'set' followed by @property variable name: +MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. +[myClass setCount:10]; +NSLog(@"%@", [myClass count]); // prints => 10 +// Or using the custom getter and setter method defined in @interface: +[myClass lengthSet:32]; +NSLog(@"%i", [myClass lengthGet]); // prints => 32 +// For convenience, you may use dot notation to set and access object instance variables: +myClass.count = 45; +NSLog(@"%i", myClass.count); // prints => 45 + // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { - long count; // Private access instance variable. + long distance; // Private access instance variable. } +// To access public variable from the interface file, use '_' followed by variable name: +_count = 5; // References "int count" from MyClass interface. +NSLog(@"%d", _count); // prints => 5 +// Access variables defined in implementation file: +distance = 18; // References "long distance" from MyClass implementation. +NSLog(@"%li", distance); // prints => 18 + // Call when the object is releasing - (void)dealloc { @@ -370,7 +380,7 @@ NSLog(@"%i", myClass.count); // prints => 45 // statements } -@end +@end // States the end of the implementation. /* * A protocol declares methods that can be implemented by any class. -- cgit v1.2.3 From 527fc37efa9cdd9881a2afa3b5e217b91a12db9e Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 3 Jan 2014 12:52:23 -0600 Subject: Remove broken Apple website link to Learning Objective-C and replaced with Programming with Objective-C Apple book link. --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 4ba1e5d5..248e132e 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -441,6 +441,6 @@ __unsafe_unretained NSArray *unsafeArray; // Like __weak but unsafeArray not set [Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) -[Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) +[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From b93df3fee7df0452e144e7900c4076d16df622d8 Mon Sep 17 00:00:00 2001 From: jingege Date: Sat, 4 Jan 2014 16:26:11 +0800 Subject: [clojure/cn]Commit the clojure-cn doc. --- zh-cn/clojure-cn.html.markdown | 362 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 362 insertions(+) create mode 100644 zh-cn/clojure-cn.html.markdown diff --git a/zh-cn/clojure-cn.html.markdown b/zh-cn/clojure-cn.html.markdown new file mode 100644 index 00000000..f65dda9d --- /dev/null +++ b/zh-cn/clojure-cn.html.markdown @@ -0,0 +1,362 @@ +--- +language: clojure +filename: learnclojure-cn.clj +contributors: + - ["Bill Zhang", "http://jingege.github.io/"] +lang: zh-cn +--- + +Clojure是运行在JVM上的Lisp家族中的一员。她比Common Lisp更强调纯[函数式编程](https://en.wikipedia.org/wiki/Functional_programming),且自发布时便包含了一组工具来处理状态。 + +这种组合让她能十分简单且自动地处理并发问题。 + +(你需要使用Clojure 1.2或更新的发行版) + +```clojure +; 注释以分号开始。 + +; Clojure代码由一个个form组成, 即写在小括号里的由空格分开的一组语句。 +; Clojure解释器会把第一个元素当做一个函数或者宏来调用,其余的被认为是参数。 + +; Clojure代码的第一条语句一般是用ns来指定当前的命名空间。 +(ns learnclojure) + +; 更基本的例子: + +; str会使用所有参数来创建一个字符串 +(str "Hello" " " "World") ; => "Hello World" + +; 数学计算比较直观 +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 + +; 等号是 = +(= 1 1) ; => true +(= 2 1) ; => false + +; 逻辑非 +(not true) ; => false + +; 嵌套的form工作起来应该和你预想的一样 +(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 + +; 类型 +;;;;;;;;;;;;; + +; Clojure使用Java的Object来描述布尔值、字符串和数字 +; 用函数 `class` 来查看具体的类型 +(class 1) ; 整形默认是java.lang.Long类型 +(class 1.); 浮点默认是java.lang.Double类型的 +(class ""); String是java.lang.String类型的,要用双引号引起来 +(class false) ; 布尔值是java.lang.Boolean类型的 +(class nil); "null"被称作nil + +; 如果你想创建一组数据字面量,用单引号(')来阻止form被解析和求值 +'(+ 1 2) ; => (+ 1 2) +; (单引号是quote的简写形式,故上式等价于(quote (+ 1 2))) + +; 可以对一个引用列表求值 +(eval '(+ 1 2)) ; => 3 + +; 集合(Collection)和序列 +;;;;;;;;;;;;;;;;;;; + +; List的底层实现是链表,Vector的底层实现是数组 +; 二者也都是java类 +(class [1 2 3]); => clojure.lang.PersistentVector +(class '(1 2 3)); => clojure.lang.PersistentList + +; list本可以写成(1 2 3), 但必须用引用来避免被解释器当做函数来求值。 +; (list 1 2 3)等价于'(1 2 3) + +; 集合其实就是一组数据 +; List和Vector都是集合: +(coll? '(1 2 3)) ; => true +(coll? [1 2 3]) ; => true + +; 序列 (seqs) 是数据列表的抽象描述 +; 只有列表才可称作序列。 +(seq? '(1 2 3)) ; => true +(seq? [1 2 3]) ; => false + +; 序列被访问时只需要提供一个值,所以序列可以被懒加载 —— 也就意味着可以定义一个无限序列: +(range 4) ; => (0 1 2 3) +(range) ; => (0 1 2 3 4 ...) (无限序列) +(take 4 (range)) ; (0 1 2 3) + +; cons用以向列表或向量的起始位置添加元素 +(cons 4 [1 2 3]) ; => (4 1 2 3) +(cons 4 '(1 2 3)) ; => (4 1 2 3) + +; conj将以最高效的方式向集合中添加元素。 +; 对于列表,数据会在起始位置插入,而对于向量,则在末尾位置插入。 +(conj [1 2 3] 4) ; => [1 2 3 4] +(conj '(1 2 3) 4) ; => (4 1 2 3) + +; 用concat来合并列表或向量 +(concat [1 2] '(3 4)) ; => (1 2 3 4) + +; 用filter来过滤集合中的元素,用map来根据指定的函数来映射得到一个新的集合 +(map inc [1 2 3]) ; => (2 3 4) +(filter even? [1 2 3]) ; => (2) + +; recuce使用函数来规约集合 +(reduce + [1 2 3 4]) +; = (+ (+ (+ 1 2) 3) 4) +; => 10 + +; reduce还能指定一个初始参数 +(reduce conj [] '(3 2 1)) +; = (conj (conj (conj [] 3) 2) 1) +; => [3 2 1] + +; 函数 +;;;;;;;;;;;;;;;;;;;;; + +; 用fn来创建函数。函数的返回值是最后一个表达式的值 +(fn [] "Hello World") ; => fn + +; (你需要再嵌套一组小括号来调用它) +((fn [] "Hello World")) ; => "Hello World" + +; 你可以用def来创建一个变量(var) +(def x 1) +x ; => 1 + +; 将函数定义为一个变量(var) +(def hello-world (fn [] "Hello World")) +(hello-world) ; => "Hello World" + +; 你可用defn来简化函数的定义 +(defn hello-world [] "Hello World") + +; 中括号内的内容是函数的参数。 +(defn hello [name] + (str "Hello " name)) +(hello "Steve") ; => "Hello Steve" + +; 你还可以用这种简写的方式来创建函数: +(def hello2 #(str "Hello " %1)) +(hello2 "Fanny") ; => "Hello Fanny" + +; 函数也可以有多个参数列表。 +(defn hello3 + ([] "Hello World") + ([name] (str "Hello " name))) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" + +; 可以定义变参函数,即把&后面的参数全部放入一个序列 +(defn count-args [& args] + (str "You passed " (count args) " args: " args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" + +; 可以混用定参和变参(用&来界定) +(defn hello-count [name & args] + (str "Hello " name ", you passed " (count args) " extra args")) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" + + +; 哈希表 +;;;;;;;;;; + +; 基于hash的map和基于数组的map(即arraymap)实现了相同的接口,hashmap查询起来比较快,但不保证元素的顺序。 +(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap +(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap + +; arraymap在足够大的时候,大多数操作会将其自动转换成hashmap,所以不用担心(对大的arraymap的查询性能)。 + +; map支持很多类型的key,但推荐使用keyword类型 +; keyword类型和字符串类似,但做了一些优化。 +(class :a) ; => clojure.lang.Keyword + +(def stringmap {"a" 1, "b" 2, "c" 3}) +stringmap ; => {"a" 1, "b" 2, "c" 3} + +(def keymap {:a 1, :b 2, :c 3}) +keymap ; => {:a 1, :c 3, :b 2} + +; 顺便说一下,map里的逗号是可有可无的,作用只是提高map的可读性。 + +; 从map中查找元素就像把map名作为函数调用一样。 +(stringmap "a") ; => 1 +(keymap :a) ; => 1 + +; 可以把keyword写在前面来从map中查找元素。 +(:b keymap) ; => 2 + +; 但不要试图用字符串类型的key来这么做。 +;("a" stringmap) +; => Exception: java.lang.String cannot be cast to clojure.lang.IFn + +; 查找不存在的key会返回nil。 +(stringmap "d") ; => nil + +; 用assoc函数来向hashmap里添加元素 +(def newkeymap (assoc keymap :d 4)) +newkeymap ; => {:a 1, :b 2, :c 3, :d 4} + +; 但是要记住的是clojure的数据类型是不可变的! +keymap ; => {:a 1, :b 2, :c 3} + +; 用dissoc来移除元素 +(dissoc keymap :a :b) ; => {:c 3} + +; 集合(Set) +;;;;;; + +(class #{1 2 3}) ; => clojure.lang.PersistentHashSet +(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} + +; 用conj新增元素 +(conj #{1 2 3} 4) ; => #{1 2 3 4} + +; 用disj移除元素 +(disj #{1 2 3} 1) ; => #{2 3} + +; 把集合当做函数调用来检查元素是否存在: +(#{1 2 3} 1) ; => 1 +(#{1 2 3} 4) ; => nil + +; 在clojure.sets模块下有很多相关函数。 + +; 常用的form +;;;;;;;;;;;;;;;;; + +; clojure里的逻辑控制结构都是用宏(macro)实现的,这在语法上看起来没什么不同。 +(if false "a" "b") ; => "b" +(if false "a") ; => nil + +; 用let来创建临时的绑定变量。 +(let [a 1 b 2] + (> a b)) ; => false + +; 用do将多个语句组合在一起依次执行 +(do + (print "Hello") + "World") ; => "World" (prints "Hello") + +; 函数定义里有一个隐式的do +(defn print-and-say-hello [name] + (print "Saying hello to " name) + (str "Hello " name)) +(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") + +; let也是如此 +(let [name "Urkel"] + (print "Saying hello to " name) + (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; 模块 +;;;;;;;;;;;;;;; + +; 用use来导入模块里的所有函数 +(use 'clojure.set) + +; 然后就可以使用set相关的函数了 +(intersection #{1 2 3} #{2 3 4}) ; => #{2 3} +(difference #{1 2 3} #{2 3 4}) ; => #{1} + +; 你也可以从一个模块里导入一部分函数。 +(use '[clojure.set :only [intersection]]) + +; 用require来导入一个模块 +(require 'clojure.string) + +; 用/来调用模块里的函数 +; 下面是从模块`clojure.string`里调用`blank?`函数。 +(clojure.string/blank? "") ; => true + +; 在`import`里你可以给模块名指定一个较短的别名。 +(require '[clojure.string :as str]) +(str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." +; (#""用来表示一个正则表达式) + +; 你可以在一个namespace定义里用`:require`的方式来require(或者use,但最好不要用)模块。 +; 这样的话你无需引用模块列表。 +(ns test + (:require + [clojure.string :as str] + [clojure.set :as set])) + +; Java +;;;;;;;;;;;;;;;;; + +; Java有大量的优秀的库,你肯定想学会如何用clojure来使用这些Java库。 + +; 用import来导入java类 +(import java.util.Date) + +; 也可以在ns定义里导入 +(ns test + (:import java.util.Date + java.util.Calendar)) + +; 用类名末尾加`.`的方式来new一个Java对象 +(Date.) ; + +; 用`.`操作符来调用方法,或者用`.method`的简化方式。 +(. (Date.) getTime) ; +(.getTime (Date.)) ; 和上例一样。 + +; 用`/`调用静态方法 +(System/currentTimeMillis) ; (system is always present) + +; 用`doto`来更方便的使用(可变)类。 +(import java.util.Calendar) +(doto (Calendar/getInstance) + (.set 2000 1 1 0 0 0) + .getTime) ; => A Date. set to 2000-01-01 00:00:00 + +; STM +;;;;;;;;;;;;;;;;; + +; 软件内存事务(Software Transactional Memory)被clojure用来处理持久化的状态。clojure里内置了一些结构来使用STM。 +; atom是最简单的。给它传一个初始值 +(def my-atom (atom {})) + +; 用`swap!`更新atom。 +; `swap!`会以atom的当前值为第一个参数来调用一个指定的函数,`swap`其余的参数作为该函数的第二个参数。 +(swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2) + +; 用`@`读取atom的值 +my-atom ;=> Atom<#...> (返回Atom对象) +@my-atom ; => {:a 1 :b 2} + +; 下例是一个使用atom实现的简单计数器 +(def counter (atom 0)) +(defn inc-counter [] + (swap! counter inc)) + +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) + +@counter ; => 5 + +; 其他STM相关的结构是ref和agent. +; Refs: http://clojure.org/refs +; Agents: http://clojure.org/agents +``` + +### 进阶读物 + +本文肯定不足以讲述关于clojure的一切,但是希望足以让你迈出第一步。 + +Clojure.org官网有很多文章: +[http://clojure.org/](http://clojure.org/) + +Clojuredocs.org有大多数核心函数的文档,还带了示例哦: +[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) + +4Clojure是个很赞的用来练习clojure/FP技能的地方: +[http://www.4clojure.com/](http://www.4clojure.com/) + +Clojure-doc.org (你没看错)有很多入门级的文章: +[http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From ca5671a5209336241885eeeed3543c06ea9e2517 Mon Sep 17 00:00:00 2001 From: lidashuang Date: Sun, 5 Jan 2014 04:23:58 +0800 Subject: Update go-cn.html.markdown --- zh-cn/go-cn.html.markdown | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 7cc9c171..4a87dc21 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -5,6 +5,8 @@ filename: learngo-cn.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["pantaovay", "https://github.com/pantaovay"] + - ["lidashuang", "https://github.com/lidashuang"] + --- 发明Go语言是出于更好地完成工作的需要。Go不是计算机科学的最新发展潮流,但它却提供了解决现实问题的最新最快的方法。 @@ -30,7 +32,7 @@ import ( ) // 函数声明:Main是程序执行的入口。 -// 不管你喜欢还是不喜欢,反正G就用了花括号来包住函数体。 +// 不管你喜欢还是不喜欢,反正Go就用了花括号来包住函数体。 func main() { // 往标准输出打印一行。 // 用包名fmt限制打印函数。 @@ -47,7 +49,7 @@ func beyondHello() { x = 3 // 变量赋值。 // 可以用:=来偷懒,它自动把变量类型、声明和赋值都搞定了。 y := 4 - sum, prod := learnMultiple(x, y) // 多个返回变量的函数 + sum, prod := learnMultiple(x, y) // 返回多个变量的函数 fmt.Println("sum:", sum, "prod:", prod) // 简单输出 learnTypes() // 少于y分钟,学的更多! } @@ -82,7 +84,7 @@ can include line breaks.` // 同样是String类型 var a4 [4] int // 有4个int变量的数组,初始为0 a3 := [...]int{3, 1, 5} // 有3个int变量的数组,同时进行了初始化 - // Slice 有动态大小。Array和Slice各有千秋,但是使用slice的地方更多些。 + // Slice 可以动态的增删。Array和Slice各有千秋,但是使用slice的地方更多些。 s3 := []int{4, 5, 9} // 和a3相比,这里没有省略号 s4 := make([]int, 4) // 分配一个有4个int型变量的slice,全部被初始化为0 @@ -114,7 +116,7 @@ func learnMemory() (p, q *int) { s := make([]int, 20) // 给20个int变量分配一块内存 s[3] = 7 // 赋值 r := -2 // 声明另一个局部变量 - return &s[3], &r // & 取址 + return &s[3], &r // & 取地址 } func expensiveComputation() int { @@ -149,7 +151,7 @@ func learnFlowControl() { // x在这里还是1。为什么? // for 是go里唯一的循环关键字,不过它有很多变种 - for { // 无限循环 + for { // 死循环 break // 骗你的 continue // 不会运行的 } @@ -239,7 +241,7 @@ func learnConcurrency() { go inc(-805, c) // 从channel中独处结果并打印。 // 打印出什么东西是不可预知的。 - fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是接收操作。 + fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是读操作。 cs := make(chan string) // 操作string的channel cc := make(chan chan string) // 操作channel的channel @@ -255,7 +257,7 @@ func learnConcurrency() { case <-cc: // 空的,还没作好通讯的准备 fmt.Println("didn't happen.") } - // 上面c或者cs的值被取到,其中一个goroutine结束,另外一个保持阻塞。 + // 上面c或者cs的值被取到,其中一个goroutine结束,另外一个一直阻塞。 learnWebProgramming() // Go很适合web编程,我知道你也想学! } -- cgit v1.2.3 From a8f49bb1889cf96904a99af7458229d860e1e248 Mon Sep 17 00:00:00 2001 From: lidashuang Date: Sun, 5 Jan 2014 04:35:23 +0800 Subject: Update ruby-cn.html.markdown --- zh-cn/ruby-cn.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 619e6e92..3c47f3f9 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -6,6 +6,7 @@ contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["lidashuang", "https://github.com/lidashuang"] translators: - ["Lin Xiangyu", "https://github.com/oa414"] --- @@ -173,7 +174,7 @@ new_hash = { defcon: 3, action: true} new_hash.keys #=> [:defcon, :action] # 小贴士:数组和哈希表都是可枚举的 -# 它们可以共享一些有用的方法,比如each, map, count, 和more +# 它们可以共享一些有用的方法,比如each, map, count 等等 # 控制流 -- cgit v1.2.3 From 283f3d4089e566ead35fe6dae0a239ed9071007d Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 4 Jan 2014 16:56:24 -0800 Subject: Updated git-es to us lang:, not language: --- es-es/git-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 0623b29b..5c9d3378 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -6,7 +6,7 @@ contributors: translator: - ["Raúl Ascencio", "http://rscnt.github.io"] filename: LearnGit.txt -language: es-es +lang: es-es --- -- cgit v1.2.3 From f542ed357d6057ee0cf54efea32590c9f29a442b Mon Sep 17 00:00:00 2001 From: "Duong H. Nguyen" Date: Sun, 5 Jan 2014 21:25:12 +0700 Subject: Add input/output section for Racket --- racket.html.markdown | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/racket.html.markdown b/racket.html.markdown index adacd91d..8c15d447 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -6,6 +6,7 @@ contributors: - ["th3rac25", "https://github.com/voila"] - ["Eli Barzilay", "https://github.com/elibarzilay"] - ["Gustavo Schmidt", "https://github.com/gustavoschmidt"] + - ["Duong H. Nguyen", "https://github.com/cmpitg"] --- Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family. @@ -600,6 +601,45 @@ vec ; => #(1 2 3 4) ;; expected: positive? ;; given: -5 ;; more details.... + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 11. Input & output +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Racket has this concept of "port", which is very similar to file descriptor +;; in other languages + +;; Open "/tmp/tmp.txt" and write "Hello World" +;; This would trigger an error if the file's already existed +(define out-port (open-output-file "/tmp/tmp.txt")) +(displayln "Hello World" out-port) +(close-output-port out-port) + +;; Append to "/tmp/tmp.txt" +(define out-port (open-output-file "/tmp/tmp.txt" + #:exists 'append)) +(displayln "Hola mundo" out-port) +(close-output-port out-port) + +;; Read from the file again +(define in-port (open-input-file "/tmp/tmp.txt")) +(displayln (read-line in-port)) +; => "Hello World" +(displayln (read-line in-port)) +; => "Hola mundo" +(close-input-port in-port) + +;; Alternatively, with call-with-output-file you don't need to explicitly +;; close the file +(call-with-output-file "/tmp/tmp.txt" + #:exists 'update ; Rewrite the content + (λ (out-port) + (displayln "World Hello!" out-port))) + +;; And call-with-input-file does the same thing for input +(call-with-input-file "/tmp/tmp.txt" + (λ (in-port) + (displayln (read-line in-port)))) ``` ## Further Reading -- cgit v1.2.3 From 17f4ff8588acfa4a0306f01b56de7abe4d9d9c89 Mon Sep 17 00:00:00 2001 From: "Duong H. Nguyen" Date: Sun, 5 Jan 2014 21:29:27 +0700 Subject: Fix Racket style --- racket.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/racket.html.markdown b/racket.html.markdown index 8c15d447..856fa75c 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -617,7 +617,7 @@ vec ; => #(1 2 3 4) ;; Append to "/tmp/tmp.txt" (define out-port (open-output-file "/tmp/tmp.txt" - #:exists 'append)) + #:exists 'append)) (displayln "Hola mundo" out-port) (close-output-port out-port) -- cgit v1.2.3 From 755c987deca2ceb1aae680fd9b9d73865157a64a Mon Sep 17 00:00:00 2001 From: lidashuang Date: Sun, 5 Jan 2014 22:32:37 +0800 Subject: Update javascript-cn.html.markdown --- zh-cn/javascript-cn.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 89fc256e..86ad1d07 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -401,8 +401,6 @@ if (Object.create === undefined){ // 如果存在则不覆盖 [Mozilla 开发者 网络](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 提供了很好的 Javascript文档,并且由于是wiki,所以你也可以自行编辑来分享你的知识。 -wiki, so as you learn more you can help others out by sharing your own -knowledge. MDN的 [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -- cgit v1.2.3 From 6801c7056d0e2d2eac269ff81a969c29775f6e4a Mon Sep 17 00:00:00 2001 From: "Duong H. Nguyen" Date: Sun, 5 Jan 2014 21:37:35 +0700 Subject: Improve language usage in Racket guide --- racket.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/racket.html.markdown b/racket.html.markdown index 856fa75c..eddc00bf 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -606,8 +606,8 @@ vec ; => #(1 2 3 4) ;; 11. Input & output ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Racket has this concept of "port", which is very similar to file descriptor -;; in other languages +;; Racket has this concept of "port", which is very similar to file +;; descriptors in other languages ;; Open "/tmp/tmp.txt" and write "Hello World" ;; This would trigger an error if the file's already existed -- cgit v1.2.3 From 72de48f9e2a371f28deb7bd41d328d5c41c8e245 Mon Sep 17 00:00:00 2001 From: jingege Date: Mon, 6 Jan 2014 09:30:18 +0800 Subject: [clojure/cn]Wrap some lines to fit the view. --- zh-cn/clojure-cn.html.markdown | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/zh-cn/clojure-cn.html.markdown b/zh-cn/clojure-cn.html.markdown index f65dda9d..d5d8232b 100644 --- a/zh-cn/clojure-cn.html.markdown +++ b/zh-cn/clojure-cn.html.markdown @@ -81,7 +81,7 @@ Clojure是运行在JVM上的Lisp家族中的一员。她比Common Lisp更强调 (seq? '(1 2 3)) ; => true (seq? [1 2 3]) ; => false -; 序列被访问时只需要提供一个值,所以序列可以被懒加载 —— 也就意味着可以定义一个无限序列: +; 序列被访问时只需要提供一个值,所以序列可以被懒加载——也就意味着可以定义一个无限序列: (range 4) ; => (0 1 2 3) (range) ; => (0 1 2 3 4 ...) (无限序列) (take 4 (range)) ; (0 1 2 3) @@ -163,11 +163,13 @@ x ; => 1 ; 哈希表 ;;;;;;;;;; -; 基于hash的map和基于数组的map(即arraymap)实现了相同的接口,hashmap查询起来比较快,但不保证元素的顺序。 +; 基于hash的map和基于数组的map(即arraymap)实现了相同的接口,hashmap查询起来比较快, +; 但不保证元素的顺序。 (class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap (class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap -; arraymap在足够大的时候,大多数操作会将其自动转换成hashmap,所以不用担心(对大的arraymap的查询性能)。 +; arraymap在足够大的时候,大多数操作会将其自动转换成hashmap, +; 所以不用担心(对大的arraymap的查询性能)。 ; map支持很多类型的key,但推荐使用keyword类型 ; keyword类型和字符串类似,但做了一些优化。 @@ -275,7 +277,7 @@ keymap ; => {:a 1, :b 2, :c 3} (str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." ; (#""用来表示一个正则表达式) -; 你可以在一个namespace定义里用`:require`的方式来require(或者use,但最好不要用)模块。 +; 你可以在一个namespace定义里用:require的方式来require(或use,但最好不要用)模块。 ; 这样的话你无需引用模块列表。 (ns test (:require @@ -314,12 +316,14 @@ keymap ; => {:a 1, :b 2, :c 3} ; STM ;;;;;;;;;;;;;;;;; -; 软件内存事务(Software Transactional Memory)被clojure用来处理持久化的状态。clojure里内置了一些结构来使用STM。 +; 软件内存事务(Software Transactional Memory)被clojure用来处理持久化的状态。 +; clojure里内置了一些结构来使用STM。 ; atom是最简单的。给它传一个初始值 (def my-atom (atom {})) ; 用`swap!`更新atom。 -; `swap!`会以atom的当前值为第一个参数来调用一个指定的函数,`swap`其余的参数作为该函数的第二个参数。 +; `swap!`会以atom的当前值为第一个参数来调用一个指定的函数, +; `swap`其余的参数作为该函数的第二个参数。 (swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1) (swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2) -- cgit v1.2.3 From d935f8fd4e09a2e72a679d75b732d18e451eaf8a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 6 Jan 2014 19:16:47 -0600 Subject: Edit code for all snippets to compile properly. Re-word some descriptions. --- objective-c.html.markdown | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 248e132e..53f155a6 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -76,16 +76,16 @@ int main (int argc, const char * argv[]) short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 NSLog(@"%hi", fortyTwoShort); - NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:41]; - unsigned short fortyTwoUnsigned = [fortyTwoShortNumber unsignedShortValue]; // or 41 - NSLog(@"%hu", fortyTwoUnsigned); + NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41]; + unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41 + NSLog(@"%u", fortyOneUnsigned); NSNumber *fortyTwoLongNumber = @42L; long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 NSLog(@"%li", fortyTwoLong); - NSNumber *fortyTwoLongNumber = @53L; - unsigned long fiftyThreeUnsigned = [fortyTwoLongNumber unsignedLongValue]; // or 53 + NSNumber *fiftyThreeLongNumber = @53L; + unsigned long fiftyThreeUnsigned = [fiftyThreeLongNumber unsignedLongValue]; // or 53 NSLog(@"%lu", fiftyThreeUnsigned); // Floating point literals @@ -118,6 +118,7 @@ int main (int argc, const char * argv[]) NSLog(@"%i", yesBool); // prints => 1 // Array object + // May contain different data types, but must be an Objective-C object. NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" @@ -148,10 +149,6 @@ int main (int argc, const char * argv[]) [mutableSet addObject:@"Hello"]; NSLog(@"%@", mutableSet); // prints => {(Hello)} - // Set object - NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; - NSLog(@"%@", set); // prints => {(Hello, World)} - /////////////////////////////////////// // Operators /////////////////////////////////////// @@ -299,9 +296,9 @@ int main (int argc, const char * argv[]) } // Convenient notation for public access variables to auto generate a setter method. // By default, setter method name is 'set' followed by @property variable name. -@property int count; // Setter name = 'setCount' +@property int count; // Setter method name = 'setCount' @property (copy) NSString *name; // (copy) => Copy the object during assignment. -@property (readonly) id data; // (readonly) => Declare only a getter method. +@property (readonly) id data; // (readonly) => Cannot set value outside interface. // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; @@ -322,7 +319,7 @@ int main (int argc, const char * argv[]) // automatically. Method name is 'set' followed by @property variable name: MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. [myClass setCount:10]; -NSLog(@"%@", [myClass count]); // prints => 10 +NSLog(@"%d", [myClass count]); // prints => 10 // Or using the custom getter and setter method defined in @interface: [myClass lengthSet:32]; NSLog(@"%i", [myClass lengthGet]); // prints => 32 @@ -349,7 +346,7 @@ NSLog(@"%li", distance); // prints => 18 } // Constructors are a way of creating classes -// This is a default constructor which is called when the object is creating +// This is a default constructor which is called when the object is initialized. - (id)init { if ((self = [super init])) @@ -410,31 +407,34 @@ With all object interactions, follow the pattern of: (1) create the object, (2) use the object, (3) then free the object from memory. */ -MyClass *classVar = [MyClass alloc]; // alloc sets classVar's reference count to one. Returns pointer to object. +MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object. [classVar release]; // Decrements classVar's reference count. -// retain claims ownership of existing object instance and increments reference count. Returns pointer to object. +// 'retain' claims ownership of existing object instance and increments reference count. Returns pointer to object. MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner. [classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object. -// @property can use retain or assign as well for small convenient definitions. +// @property can use 'retain' and 'assign' as well for small convenient definitions. @property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). @property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). +// Automatic Reference Counting (ARC) // Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). // ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, // you must not use retain, relase, or autorelease. -MyClass *arcMyClass = [[MyClass alloc] init]; // Without ARC, you will need to call: [arcMyClass release] after -// you're done using arcMyClass. But with ARC, there is no need. It will insert this release statement for you. +MyClass *arcMyClass = [[MyClass alloc] init]; +// ... code using arcMyClass +// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, +// there is no need. It will insert this release statement for you. -// As for the "assign" and "retain" @property attributes, with ARC you use "weak" and "strong". -@property (weak) MyClass *weakVar; // weak does not take ownership of object. If original instance's reference count +// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'. +@property (weak) MyClass *weakVar; // 'weak' does not take ownership of object. If original instance's reference count // is set to zero, weakVar will automatically receive value of nil to avoid application crashing. -@property (strong) MyClass *strongVar; // strong takes ownership of object. Ensures object will stay in memory to use. +@property (strong) MyClass *strongVar; // 'strong' takes ownership of object. Ensures object will stay in memory to use. // For regular variables (not @property declared variables), use the following: __strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope. __weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil. -__unsafe_unretained NSArray *unsafeArray; // Like __weak but unsafeArray not set to nil when existing object is released. +__unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not set to nil when existing object is released. ``` ## Further Reading -- cgit v1.2.3 From dcf6331eec9faeefc91eb53f90f17408b7d01857 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 6 Jan 2014 20:21:29 -0600 Subject: Add name and github page to contributors list. --- objective-c.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 53f155a6..98179f97 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -4,6 +4,7 @@ language: Objective-C contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] + - ["Levi Bostian", "https://github.com/levibostian"] filename: LearnObjectiveC.m --- -- cgit v1.2.3 From bfa623ac4997cadf132676c49cb92975173ce741 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 6 Jan 2014 20:28:42 -0600 Subject: Removed NSLog() statements inside @implementation where not allowed. --- objective-c.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 98179f97..886f80e2 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -336,10 +336,8 @@ NSLog(@"%i", myClass.count); // prints => 45 // To access public variable from the interface file, use '_' followed by variable name: _count = 5; // References "int count" from MyClass interface. -NSLog(@"%d", _count); // prints => 5 // Access variables defined in implementation file: distance = 18; // References "long distance" from MyClass implementation. -NSLog(@"%li", distance); // prints => 18 // Call when the object is releasing - (void)dealloc -- cgit v1.2.3 From afa93d54ad7d370b9b05434c2cf4a09c5b695ddf Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 7 Jan 2014 08:41:07 -0600 Subject: Fix typos. --- ...o-laptop's conflicted copy 2014-01-07).markdown | 446 +++++++++++++++++++++ objective-c.html.markdown | 4 +- 2 files changed, 448 insertions(+), 2 deletions(-) create mode 100644 objective-c.html (levi-dell-banno-laptop's conflicted copy 2014-01-07).markdown diff --git a/objective-c.html (levi-dell-banno-laptop's conflicted copy 2014-01-07).markdown b/objective-c.html (levi-dell-banno-laptop's conflicted copy 2014-01-07).markdown new file mode 100644 index 00000000..490fefee --- /dev/null +++ b/objective-c.html (levi-dell-banno-laptop's conflicted copy 2014-01-07).markdown @@ -0,0 +1,446 @@ +--- + +language: Objective-C +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] +filename: LearnObjectiveC.m + +--- + +Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. +It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. + +```cpp +// Single-line comments start with // + +/* +Multi-line comments look like this. +*/ + +// Imports the Foundation headers with #import +#import +#import "MyClass.h" + +// Your program's entry point is a function called +// main with an integer return type. +int main (int argc, const char * argv[]) +{ + // Create an autorelease pool to manage the memory into the program + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + // If using automatic reference counting (ARC), use @autoreleasepool instead: + @autoreleasepool { + + // Use NSLog to print lines to the console + NSLog(@"Hello World!"); // Print the string "Hello World!" + + /////////////////////////////////////// + // Types & Variables + /////////////////////////////////////// + + // Primitive declarations + int myPrimitive1 = 1; + long myPrimitive2 = 234554664565; + + // Object declarations + // Put the * in front of the variable names for strongly-typed object declarations + MyClass *myObject1 = nil; // Strong typing + id myObject2 = nil; // Weak typing + // %@ is an object + // 'description' is a convention to display the value of the Objects + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // Print "(null) and (null)" + + // String + NSString *worldString = @"World"; + NSLog(@"Hello %@!", worldString); // prints => "Hello World!" + // NSMutableString is a mutable version of the NSString object. + NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; + [mutableString appendString:@" World!"]; + NSLog(@"%@", mutableString); // prints => "Hello World!" + + // Character literals + NSNumber *theLetterZNumber = @'Z'; + char theLetterZ = [theLetterZNumber charValue]; // or 'Z' + NSLog(@"%c", theLetterZ); + + // Integral literals + NSNumber *fortyTwoNumber = @42; + int fortyTwo = [fortyTwoNumber intValue]; // or 42 + NSLog(@"%i", fortyTwo); + + NSNumber *fortyTwoUnsignedNumber = @42U; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42 + NSLog(@"%u", fortyTwoUnsigned); + + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 + NSLog(@"%hi", fortyTwoShort); + + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:41]; + unsigned short fortyTwoUnsigned = [fortyTwoShortNumber unsignedShortValue]; // or 41 + NSLog(@"%hu", fortyTwoUnsigned); + + NSNumber *fortyTwoLongNumber = @42L; + long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 + NSLog(@"%li", fortyTwoLong); + + NSNumber *fortyTwoLongNumber = @53L; + unsigned long fiftyThreeUnsigned = [fortyTwoLongNumber unsignedLongValue]; // or 53 + NSLog(@"%lu", fiftyThreeUnsigned); + + // Floating point literals + NSNumber *piFloatNumber = @3.141592654F; + float piFloat = [piFloatNumber floatValue]; // or 3.141592654f + NSLog(@"%f", piFloat); // prints => 3.141592654 + NSLog(@"%5.2f", piFloat); // prints => " 3.14" + + NSNumber *piDoubleNumber = @3.1415926535; + double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 + NSLog(@"%f", piDouble); + NSLog(@"%4.2f", piDouble); // prints => "3.14" + + // NSDecimalNumber is a fixed-point class that's more precise then float or double + NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; + NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; + // NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own: + [oneDecNum decimalNumberByAdding:twoDecNum]; + [oneDecNum decimalNumberBySubtracting:twoDecNum]; + [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; + [oneDecNum decimalNumberByDividingBy:twoDecNum]; + NSLog(@"%@", oneDecNum); // prints => 10.99 as NSDecimalNumber is immutable. + + // BOOL literals + NSNumber *yesNumber = @YES; + NSNumber *noNumber = @NO; + // or + BOOL yesBool = YES; + BOOL noBool = NO; + NSLog(@"%i", yesBool); // prints => 1 + + // Array object + NSArray *anArray = @[@1, @2, @3, @4]; + NSNumber *thirdNumber = anArray[2]; + NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" + // NSMutableArray is mutable version of NSArray allowing to change items in array + // and extend or shrink array object. Convenient, but not as efficient as NSArray. + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; + [mutableArray addObject:@"Hello"]; + [mutableArray addObject:@"World"]; + [mutableArray removeObjectAtIndex:0]; + NSLog(@"%@", [mutableArray objectAtIndex:0]); // prints => "World" + + // Dictionary object + NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSObject *valueObject = aDictionary[@"A Key"]; + NSLog(@"Object = %@", valueObject); // Print "Object = (null)" + // NSMutableDictionary also available as a mutable dictionary object. + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; + [mutableDictionary setObject:@"value1" forKey:@"key1"]; + [mutableDictionary setObject:@"value2" forKey:@"key2"]; + [mutableDictionary removeObjectForKey:@"key1"]; + + // Set object + NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; + NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) + // NSMutableSet also available as a mutable set object. + NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; + [mutableSet addObject:@"Hello"]; + [mutableSet addObject:@"Hello"]; + NSLog(@"%@", mutableSet); // prints => {(Hello)} + + // Set object + NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; + NSLog(@"%@", set); // prints => {(Hello, World)} + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + + // The operators works like in the C language + // For example: + 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)) + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + + // If-Else statement + if (NO) + { + NSLog(@"I am never run"); + } else if (0) + { + NSLog(@"I am also never run"); + } else + { + NSLog(@"I print"); + } + + // Switch statement + 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 loops statements + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value. + } // => prints "0," + // "1," + // "2," + // "3," + + // For loops statements + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", jj); + } // => prints "0," + // "1," + // "2," + // "3," + + // Foreach statements + NSArray *values = @[@0, @1, @2, @3]; + for (NSNumber *value in values) + { + NSLog(@"%@,", value); + } // => prints "0," + // "1," + // "2," + // "3," + + // Object for loop statement. Can be used with any Objective-C object type. + for (id item in values) { + NSLog(@"%@,", item); + } // => prints "0," + // "1," + // "2," + // "3," + + // Try-Catch-Finally statements + @try + { + // Your statements here + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"File Not Found on System" userInfo:nil]; + } @catch (NSException * e) + { + NSLog(@"Exception: %@", e); + } @finally + { + NSLog(@"Finally"); + } // => prints "Exception: File Not Found on System" + // "Finally" + + /////////////////////////////////////// + // Objects + /////////////////////////////////////// + + // Create an object instance by allocating memory and initializing it. + // An object is not fully functional until both steps have been completed. + MyClass *myObject = [[MyClass alloc] init]; + + // The Objective-C model of object-oriented programming is based on message + // passing to object instances. + // In Objective-C one does not simply call a method; one sends a message. + [myObject instanceMethodWithParameter:@"Steve Jobs"]; + + // Clean up the memory you used into your program + [pool drain]; + + // End of @autoreleasepool. + } + + // End the program + return 0; +} + +/////////////////////////////////////// +// Classes And Functions +/////////////////////////////////////// + +// Declare your class in a header file (MyClass.h): +// Class declaration syntax: +// @interface ClassName : ParentClassName +// { +// type name; <= variable declarations; +// } +// @property type name; <= property declarations. +// -/+ (type) Method declarations; <= Method declarations. +// @end +@interface MyClass : NSObject // NSObject is Objective-C's base object class. +{ + // Instance variable declarations (can exist in either interface or implementation file). + int count; // Protected access by default. + @private id data; // Private access. (More convenient to declare in implementation file). + NSString *name; +} +// Convenient notation for public access variables to auto generate a setter method. +// By default, setter method name is 'set' followed by @property variable name. +@property int count; // Setter name = 'setCount' +@property (copy) NSString *name; // (copy) => Copy the object during assignment. +@property (readonly) id data; // (readonly) => Declare only a getter method. +// You can customize the getter and setter names instead of using default 'set' name: +@property (getter=lengthGet, setter=lengthSet:) int length; + +// Methods ++/- (return type)methodSignature:(Parameter Type *)parameterName; + +// + for class method ++ (NSString *)classMethod; + +// - for instance method +- (NSString *)instanceMethodWithParameter:(NSString *)string; +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; + +@end // States the end of the interface. + + +// To access public variables from the implementation file, @property generates a setter method +// automatically. Method name is 'set' followed by @property variable name: +MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. +[myClass setCount:10]; +NSLog(@"%@", [myClass count]); // prints => 10 +// Or using the custom getter and setter method defined in @interface: +[myClass lengthSet:32]; +NSLog(@"%i", [myClass lengthGet]); // prints => 32 +// For convenience, you may use dot notation to set and access object instance variables: +myClass.count = 45; +NSLog(@"%i", myClass.count); // prints => 45 + + +// Implement the methods in an implementation (MyClass.m) file: +@implementation MyClass { + long distance; // Private access instance variable. +} + +// To access public variable from the interface file, use '_' followed by variable name: +_count = 5; // References "int count" from MyClass interface. +NSLog(@"%d", _count); // prints => 5 +// Access variables defined in implementation file: +distance = 18; // References "long distance" from MyClass implementation. +NSLog(@"%li", distance); // prints => 18 + +// Call when the object is releasing +- (void)dealloc +{ +} + +// Constructors are a way of creating classes +// This is a default constructor which is called when the object is creating +- (id)init +{ + if ((self = [super init])) + { + self.count = 1; + } + return self; +} + ++ (NSString *)classMethod +{ + return [[self alloc] init]; +} + +- (NSString *)instanceMethodWithParameter:(NSString *)string +{ + return @"New string"; +} + +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number +{ + return @42; +} + +// Methods declared into MyProtocol +- (void)myProtocolMethod +{ + // statements +} + +@end // States the end of the implementation. + +/* + * A protocol declares methods that can be implemented by any class. + * Protocols are not classes themselves. They simply define an interface + * that other objects are responsible for implementing. + */ +@protocol MyProtocol + - (void)myProtocolMethod; +@end + + +/////////////////////////////////////// +// Memory Management +/////////////////////////////////////// +/* +For each object used in an application, memory must be allocated for that object. When the application +is done using that object, memory must be deallocated to ensure application efficiency. +Objective-C does not use garbage collection and instead uses reference counting. As long as +there is at least one reference to an object (also called "owning" an object), then the object +will be available to use (known as "ownership"). + +When an instance owns an object, its reference counter is increments by one. When the +object is released, the reference counter decrements by one. When reference count is zero, +the object is removed from memory. + +With all object interactions, follow the pattern of: +(1) create the object, (2) use the object, (3) then free the object from memory. +*/ + +MyClass *classVar = [MyClass alloc]; // alloc sets classVar's reference count to one. Returns pointer to object. +[classVar release]; // Decrements classVar's reference count. +// retain claims ownership of existing object instance and increments reference count. Returns pointer to object. +MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner. +[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object. + +// @property can use retain or assign as well for small convenient definitions. +@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). +@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). + +// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). +// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, +// you must not use retain, relase, or autorelease. +MyClass *arcMyClass = [[MyClass alloc] init]; // Without ARC, you will need to call: [arcMyClass release] after +// you're done using arcMyClass. But with ARC, there is no need. It will insert this release statement for you. + +// As for the "assign" and "retain" @property attributes, with ARC you use "weak" and "strong". +@property (weak) MyClass *weakVar; // weak does not take ownership of object. If original instance's reference count +// is set to zero, weakVar will automatically receive value of nil to avoid application crashing. +@property (strong) MyClass *strongVar; // strong takes ownership of object. Ensures object will stay in memory to use. + +// For regular variables (not @property declared variables), use the following: +__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope. +__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil. +__unsafe_unretained NSArray *unsafeArray; // Like __weak but unsafeArray not set to nil when existing object is released. + +``` +## Further Reading + +[Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) + +[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) + +[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 886f80e2..a70351b5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -288,7 +288,7 @@ int main (int argc, const char * argv[]) // @property type name; <= property declarations. // -/+ (type) Method declarations; <= Method declarations. // @end -@interface MyClass : NSObject // NSObject is Objective-C base object class. +@interface MyClass : NSObject // NSObject is Objective-C's base object class. { // Instance variable declarations (can exist in either interface or implementation file). int count; // Protected access by default. @@ -334,7 +334,7 @@ NSLog(@"%i", myClass.count); // prints => 45 long distance; // Private access instance variable. } -// To access public variable from the interface file, use '_' followed by variable name: +// To access a public variable from the interface file, use '_' followed by variable name: _count = 5; // References "int count" from MyClass interface. // Access variables defined in implementation file: distance = 18; // References "long distance" from MyClass implementation. -- cgit v1.2.3 From 18b9cde0327b5384c4c9cd14106ddaa41b0f3673 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 7 Jan 2014 08:56:34 -0600 Subject: Remove unwanted Dropbox conflict file. Sorry. --- ...o-laptop's conflicted copy 2014-01-07).markdown | 446 --------------------- 1 file changed, 446 deletions(-) delete mode 100644 objective-c.html (levi-dell-banno-laptop's conflicted copy 2014-01-07).markdown diff --git a/objective-c.html (levi-dell-banno-laptop's conflicted copy 2014-01-07).markdown b/objective-c.html (levi-dell-banno-laptop's conflicted copy 2014-01-07).markdown deleted file mode 100644 index 490fefee..00000000 --- a/objective-c.html (levi-dell-banno-laptop's conflicted copy 2014-01-07).markdown +++ /dev/null @@ -1,446 +0,0 @@ ---- - -language: Objective-C -contributors: - - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - - ["Yannick Loriot", "https://github.com/YannickL"] -filename: LearnObjectiveC.m - ---- - -Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. -It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. - -```cpp -// Single-line comments start with // - -/* -Multi-line comments look like this. -*/ - -// Imports the Foundation headers with #import -#import -#import "MyClass.h" - -// Your program's entry point is a function called -// main with an integer return type. -int main (int argc, const char * argv[]) -{ - // Create an autorelease pool to manage the memory into the program - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - // If using automatic reference counting (ARC), use @autoreleasepool instead: - @autoreleasepool { - - // Use NSLog to print lines to the console - NSLog(@"Hello World!"); // Print the string "Hello World!" - - /////////////////////////////////////// - // Types & Variables - /////////////////////////////////////// - - // Primitive declarations - int myPrimitive1 = 1; - long myPrimitive2 = 234554664565; - - // Object declarations - // Put the * in front of the variable names for strongly-typed object declarations - MyClass *myObject1 = nil; // Strong typing - id myObject2 = nil; // Weak typing - // %@ is an object - // 'description' is a convention to display the value of the Objects - NSLog(@"%@ and %@", myObject1, [myObject2 description]); // Print "(null) and (null)" - - // String - NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // prints => "Hello World!" - // NSMutableString is a mutable version of the NSString object. - NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; - [mutableString appendString:@" World!"]; - NSLog(@"%@", mutableString); // prints => "Hello World!" - - // Character literals - NSNumber *theLetterZNumber = @'Z'; - char theLetterZ = [theLetterZNumber charValue]; // or 'Z' - NSLog(@"%c", theLetterZ); - - // Integral literals - NSNumber *fortyTwoNumber = @42; - int fortyTwo = [fortyTwoNumber intValue]; // or 42 - NSLog(@"%i", fortyTwo); - - NSNumber *fortyTwoUnsignedNumber = @42U; - unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42 - NSLog(@"%u", fortyTwoUnsigned); - - NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; - short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 - NSLog(@"%hi", fortyTwoShort); - - NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:41]; - unsigned short fortyTwoUnsigned = [fortyTwoShortNumber unsignedShortValue]; // or 41 - NSLog(@"%hu", fortyTwoUnsigned); - - NSNumber *fortyTwoLongNumber = @42L; - long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 - NSLog(@"%li", fortyTwoLong); - - NSNumber *fortyTwoLongNumber = @53L; - unsigned long fiftyThreeUnsigned = [fortyTwoLongNumber unsignedLongValue]; // or 53 - NSLog(@"%lu", fiftyThreeUnsigned); - - // Floating point literals - NSNumber *piFloatNumber = @3.141592654F; - float piFloat = [piFloatNumber floatValue]; // or 3.141592654f - NSLog(@"%f", piFloat); // prints => 3.141592654 - NSLog(@"%5.2f", piFloat); // prints => " 3.14" - - NSNumber *piDoubleNumber = @3.1415926535; - double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 - NSLog(@"%f", piDouble); - NSLog(@"%4.2f", piDouble); // prints => "3.14" - - // NSDecimalNumber is a fixed-point class that's more precise then float or double - NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; - NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; - // NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own: - [oneDecNum decimalNumberByAdding:twoDecNum]; - [oneDecNum decimalNumberBySubtracting:twoDecNum]; - [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; - [oneDecNum decimalNumberByDividingBy:twoDecNum]; - NSLog(@"%@", oneDecNum); // prints => 10.99 as NSDecimalNumber is immutable. - - // BOOL literals - NSNumber *yesNumber = @YES; - NSNumber *noNumber = @NO; - // or - BOOL yesBool = YES; - BOOL noBool = NO; - NSLog(@"%i", yesBool); // prints => 1 - - // Array object - NSArray *anArray = @[@1, @2, @3, @4]; - NSNumber *thirdNumber = anArray[2]; - NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" - // NSMutableArray is mutable version of NSArray allowing to change items in array - // and extend or shrink array object. Convenient, but not as efficient as NSArray. - NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; - [mutableArray addObject:@"Hello"]; - [mutableArray addObject:@"World"]; - [mutableArray removeObjectAtIndex:0]; - NSLog(@"%@", [mutableArray objectAtIndex:0]); // prints => "World" - - // Dictionary object - NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; - NSObject *valueObject = aDictionary[@"A Key"]; - NSLog(@"Object = %@", valueObject); // Print "Object = (null)" - // NSMutableDictionary also available as a mutable dictionary object. - NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; - [mutableDictionary setObject:@"value1" forKey:@"key1"]; - [mutableDictionary setObject:@"value2" forKey:@"key2"]; - [mutableDictionary removeObjectForKey:@"key1"]; - - // Set object - NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; - NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) - // NSMutableSet also available as a mutable set object. - NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; - [mutableSet addObject:@"Hello"]; - [mutableSet addObject:@"Hello"]; - NSLog(@"%@", mutableSet); // prints => {(Hello)} - - // Set object - NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; - NSLog(@"%@", set); // prints => {(Hello, World)} - - /////////////////////////////////////// - // Operators - /////////////////////////////////////// - - // The operators works like in the C language - // For example: - 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)) - - /////////////////////////////////////// - // Control Structures - /////////////////////////////////////// - - // If-Else statement - if (NO) - { - NSLog(@"I am never run"); - } else if (0) - { - NSLog(@"I am also never run"); - } else - { - NSLog(@"I print"); - } - - // Switch statement - 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 loops statements - int ii = 0; - while (ii < 4) - { - NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value. - } // => prints "0," - // "1," - // "2," - // "3," - - // For loops statements - int jj; - for (jj=0; jj < 4; jj++) - { - NSLog(@"%d,", jj); - } // => prints "0," - // "1," - // "2," - // "3," - - // Foreach statements - NSArray *values = @[@0, @1, @2, @3]; - for (NSNumber *value in values) - { - NSLog(@"%@,", value); - } // => prints "0," - // "1," - // "2," - // "3," - - // Object for loop statement. Can be used with any Objective-C object type. - for (id item in values) { - NSLog(@"%@,", item); - } // => prints "0," - // "1," - // "2," - // "3," - - // Try-Catch-Finally statements - @try - { - // Your statements here - @throw [NSException exceptionWithName:@"FileNotFoundException" - reason:@"File Not Found on System" userInfo:nil]; - } @catch (NSException * e) - { - NSLog(@"Exception: %@", e); - } @finally - { - NSLog(@"Finally"); - } // => prints "Exception: File Not Found on System" - // "Finally" - - /////////////////////////////////////// - // Objects - /////////////////////////////////////// - - // Create an object instance by allocating memory and initializing it. - // An object is not fully functional until both steps have been completed. - MyClass *myObject = [[MyClass alloc] init]; - - // The Objective-C model of object-oriented programming is based on message - // passing to object instances. - // In Objective-C one does not simply call a method; one sends a message. - [myObject instanceMethodWithParameter:@"Steve Jobs"]; - - // Clean up the memory you used into your program - [pool drain]; - - // End of @autoreleasepool. - } - - // End the program - return 0; -} - -/////////////////////////////////////// -// Classes And Functions -/////////////////////////////////////// - -// Declare your class in a header file (MyClass.h): -// Class declaration syntax: -// @interface ClassName : ParentClassName -// { -// type name; <= variable declarations; -// } -// @property type name; <= property declarations. -// -/+ (type) Method declarations; <= Method declarations. -// @end -@interface MyClass : NSObject // NSObject is Objective-C's base object class. -{ - // Instance variable declarations (can exist in either interface or implementation file). - int count; // Protected access by default. - @private id data; // Private access. (More convenient to declare in implementation file). - NSString *name; -} -// Convenient notation for public access variables to auto generate a setter method. -// By default, setter method name is 'set' followed by @property variable name. -@property int count; // Setter name = 'setCount' -@property (copy) NSString *name; // (copy) => Copy the object during assignment. -@property (readonly) id data; // (readonly) => Declare only a getter method. -// You can customize the getter and setter names instead of using default 'set' name: -@property (getter=lengthGet, setter=lengthSet:) int length; - -// Methods -+/- (return type)methodSignature:(Parameter Type *)parameterName; - -// + for class method -+ (NSString *)classMethod; - -// - for instance method -- (NSString *)instanceMethodWithParameter:(NSString *)string; -- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; - -@end // States the end of the interface. - - -// To access public variables from the implementation file, @property generates a setter method -// automatically. Method name is 'set' followed by @property variable name: -MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. -[myClass setCount:10]; -NSLog(@"%@", [myClass count]); // prints => 10 -// Or using the custom getter and setter method defined in @interface: -[myClass lengthSet:32]; -NSLog(@"%i", [myClass lengthGet]); // prints => 32 -// For convenience, you may use dot notation to set and access object instance variables: -myClass.count = 45; -NSLog(@"%i", myClass.count); // prints => 45 - - -// Implement the methods in an implementation (MyClass.m) file: -@implementation MyClass { - long distance; // Private access instance variable. -} - -// To access public variable from the interface file, use '_' followed by variable name: -_count = 5; // References "int count" from MyClass interface. -NSLog(@"%d", _count); // prints => 5 -// Access variables defined in implementation file: -distance = 18; // References "long distance" from MyClass implementation. -NSLog(@"%li", distance); // prints => 18 - -// Call when the object is releasing -- (void)dealloc -{ -} - -// Constructors are a way of creating classes -// This is a default constructor which is called when the object is creating -- (id)init -{ - if ((self = [super init])) - { - self.count = 1; - } - return self; -} - -+ (NSString *)classMethod -{ - return [[self alloc] init]; -} - -- (NSString *)instanceMethodWithParameter:(NSString *)string -{ - return @"New string"; -} - -- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number -{ - return @42; -} - -// Methods declared into MyProtocol -- (void)myProtocolMethod -{ - // statements -} - -@end // States the end of the implementation. - -/* - * A protocol declares methods that can be implemented by any class. - * Protocols are not classes themselves. They simply define an interface - * that other objects are responsible for implementing. - */ -@protocol MyProtocol - - (void)myProtocolMethod; -@end - - -/////////////////////////////////////// -// Memory Management -/////////////////////////////////////// -/* -For each object used in an application, memory must be allocated for that object. When the application -is done using that object, memory must be deallocated to ensure application efficiency. -Objective-C does not use garbage collection and instead uses reference counting. As long as -there is at least one reference to an object (also called "owning" an object), then the object -will be available to use (known as "ownership"). - -When an instance owns an object, its reference counter is increments by one. When the -object is released, the reference counter decrements by one. When reference count is zero, -the object is removed from memory. - -With all object interactions, follow the pattern of: -(1) create the object, (2) use the object, (3) then free the object from memory. -*/ - -MyClass *classVar = [MyClass alloc]; // alloc sets classVar's reference count to one. Returns pointer to object. -[classVar release]; // Decrements classVar's reference count. -// retain claims ownership of existing object instance and increments reference count. Returns pointer to object. -MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner. -[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object. - -// @property can use retain or assign as well for small convenient definitions. -@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). -@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). - -// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). -// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, -// you must not use retain, relase, or autorelease. -MyClass *arcMyClass = [[MyClass alloc] init]; // Without ARC, you will need to call: [arcMyClass release] after -// you're done using arcMyClass. But with ARC, there is no need. It will insert this release statement for you. - -// As for the "assign" and "retain" @property attributes, with ARC you use "weak" and "strong". -@property (weak) MyClass *weakVar; // weak does not take ownership of object. If original instance's reference count -// is set to zero, weakVar will automatically receive value of nil to avoid application crashing. -@property (strong) MyClass *strongVar; // strong takes ownership of object. Ensures object will stay in memory to use. - -// For regular variables (not @property declared variables), use the following: -__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope. -__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil. -__unsafe_unretained NSArray *unsafeArray; // Like __weak but unsafeArray not set to nil when existing object is released. - -``` -## Further Reading - -[Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) - -[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) - -[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From c07cb9560cc32f316ce484683ec1f0c00a75a626 Mon Sep 17 00:00:00 2001 From: Jongmin Kim Date: Wed, 8 Jan 2014 15:48:33 +0900 Subject: Added Go translation in Korean --- ko-kr/go-kr.html.markdown | 318 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 318 insertions(+) create mode 100644 ko-kr/go-kr.html.markdown diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown new file mode 100644 index 00000000..df0dea8b --- /dev/null +++ b/ko-kr/go-kr.html.markdown @@ -0,0 +1,318 @@ +--- +name: Go +category: language +language: Go +filename: learngo.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] +translators: + - ["Jongmin Kim", "http://github.com/atomaths"] +lang: ko-kr +--- + +Go는 일을 잘 끝낼 필요에 의해 만들어졌다. Go가 잘 알려진 최신의 +트렌드는 아니지만, 실세계의 문제들을 해결하기 위해서는 가장 +새롭고 빠른 방법이다. + +Go는 정적 타이핑(static typing)의 명령형 언어들(imperative languages)이 +갖고 있는 특징과 유사한 개념들을 가지고 있다. Go는 컴파일과 실행속도가 +빠르며, 오늘날의 멀티코어 CPU를 위해 이해하기 쉬운 동시성(concurrency) +기능이 추가되었다. 그리고 큰 스케일의 프로그래밍에도 도움이 되는 +기능들을 가지고 있다. + +또한 Go에는 훌륭한 표준 라이브러리와 열정적인 커뮤니티가 있다. + +```go +// 한 줄 주석 +/* 여러 줄 + 주석 */ + +// 모든 Go 소스 파일은 `package`로 시작한다. +// 패키지 이름 중 `main`은 라이브러리가 아닌 실행파일을 선언하는 특별한 이름이다. +package main + +// `import`는 이 Go 소스 파일 내에서 참조하는 라이브러리 패키지들을 선언한다. +import ( + "fmt" // Go 표준 라이브러리에 있는 패키지 + "net/http" // 표준 라이브러리에는 웹 서버 패키지도 있다! (클라이언트도 있음) + "strconv" // 문자열 변환 패키지 +) + +// 함수 선언. `main`은 실행 프로그램에서 시작점이 되는 특별한 함수다. +// 중괄호를 사용한다. +func main() { + // `Println`은 표준 출력으로 개행을 출력한다. + // fmt 패키지를 통해 이용할 수 있다. + fmt.Println("Hello world!") + + // 다른 함수를 호출한다. + beyondHello() +} + +// 함수에 파라미터가 없더라도 빈 괄호는 있어야 한다. +func beyondHello() { + var x int // 변수 선언. 변수는 사용하기 전에 선언해야 한다. + x = 3 // 변수에 값 할당. + // 짧은 선언(short declaration)으로 `:=` 를 사용하는데, + // 이렇게 값을 할당하면 값의 타입에 따라 변수의 타입이 결정된다. + y := 4 + sum, prod := learnMultiple(x, y) // 함수는 두 개 이상의 리턴 값을 줄 수 있다. + fmt.Println("sum:", sum, "prod:", prod) // 간단한 출력 + learnTypes() // 잠시 후에 좀더 자세히! +} + +// 함수는 파라미터들을 가질 수 있고, 복수개의 값을 리턴할 수 있다. +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // 두 개의 값을 리턴. +} + +// 내장 타입과 리터럴 +func learnTypes() { + // 짧은 선언은 유용하다. + s := "Learn Go!" // string 타입 + + s2 := `역따옴표 안의 string 리터럴은 +개행을 포함할 수 있다.` // 같은 string 타입 + + // non-ASCII 리터럴. Go 소스는 UTF-8로 작성해야 한다. + g := 'Σ' // 유니코드 코드 포인트를 담고 있고, uint32 타입의 가칭(alias)인 rune 타입 + + f := 3.14195 // float64, an IEEE-754 64-bit 부동소수 타입 + c := 3 + 4i // complex128, 내부적으로는 두 개의 float64 타입으로 표현됨 + + // 초기값과 함께 사용하는 var 키워드. + var u uint = 7 // unsigned, 하지만 int에 따른 구현의존적인 크기 + var pi float32 = 22. / 7 + + // 짧은 선언으로 변환(conversion)하는 문법. + // Go에서는 type casting 이라고 하지않고 type conversion 이라고 함. + n := byte('\n') // byte는 uint8의 가칭(alias) + + // 배열은 컴파일 시에 크기가 정해진다. + var a4 [4]int // 모두 0으로 초기화되는 int 타입 4개짜리 배열 + a3 := [...]int{3, 1, 5} // 3, 1, 5로 초기화되는 int 타입 3개짜리 배열 + + // 슬라이스(slice)라고 하는 타입은 배열에 대한 가변 크기를 가진다. + // 배열, 슬라이스 각자 장점이 있지만, 슬라이스가 더 많이 사용된다. + s3 := []int{4, 5, 9} // 위의 a3와 비교해보면 생략부호(...)가 없다. + s4 := make([]int, 4) // 모두 0으로 초기화되는 int 4개에 대한 슬라이스를 할당. + var d2 [][]float64 // 여기에서는 선언만 있고 할당은 없다. + bs := []byte("a slice") // string 타입을 byte 슬라이스 타입으로 형변환(type conversion) + + p, q := learnMemory() // int에 대한 포인터 타입인 p와 q를 선언 + fmt.Println(*p, *q) // C에서처럼 *는 포인터를 따라가 값을 참조한다. 여기서는 두 개의 int를 출력. + + // 맵(map)은 다른 언어의 해시(hash)나 딕셔너리(dictionary)처럼 가변의 연관배열 타입. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // 선언만 하고 사용하지 않는 변수가 있다면 Go에서는 컴파일 시 에러가 난다. + // 언더바를 이용해서 변수를 사용한 것처럼 하고 그 값은 무시해버릴 수 있다. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // 물론 출력을 하면 변수로 취급한다. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // 잠시 후에 다시 나옴 +} + +// Go는 가비지 컬렉션 기능을 JVM 같은 곳이 아닌 실행파일 런타임에 포함하고 있다. +// 그리고 포인터는 있지만, 포인터 연산(*p++ 같은)은 없다. +// 그래서 `nil` 포인터 접근같은 것 때문에 실수를 할 수는 있지만 +// 포인터 연산으로 인한 실수는 없게 된다. +func learnMemory() (p, q *int) { + // 지명된 리턴 값(named return value)인 p와 q는 int에 대한 포인터 타입이다. + p = new(int) // 내장함수인 `new`는 메모리를 할당해준다. + // 메모리 할당된 int는 0으로 초기화 되고, p는 이제 `nil`이 아니다. + s := make([]int, 20) // 메모리의 단일 블록으로 20개의 int 공간을 할당한다. + s[3] = 7 // 그중 하나에 값을 준다. + r := -2 // 또다른 로컬 변수를 선언한다. + return &s[3], &r // `&`는 어떤 대상체의 메모리 주소를 가져오게 된다. +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // `if`문에 중괄호는 필요하지만, 조건이 들어갈 곳에 소괄호는 쓰지 않는다. + if true { + fmt.Println("told ya") + } + // 모든 Go 소스의 코드 포맷팅은 `go fmt` 커맨드라인 명령으로 규격을 맞춘다. + if false { + // pout + } else { + // gloat + } + // if-else 체인 형태보다 `switch` 사용이 권장된다. + x := 1 + switch x { + case 0: + case 1: + // case 안에서는 `break`가 없어도 자동으로 다음 case로 내려가지 않는다. + // 자동으로 내려가게 하려면 `fallthrough` 키워드를 사용한다. + case 2: + // x는 1이므로 여기는 실행되지 않음. + } + // `if`에서처럼 `for`에서도 양쪽에 소괄호를 쓰지 않는다. + for x := 0; x < 3; x++ { // `++`은 실행을 제어하는 하나의 구문(statement)이다. + fmt.Println("iteration", x) + } + // 여기서 x는 1이다. 위 for에서 x는 for 안의 블록 범위에 있기 때문. + + // For is the only loop statement in Go, but it has alternate forms. + // `for`는 Go에서 유일한 루프 구문이지만 다양한 형태로 조건을 주거나 while + // 처럼 쓸 수도 있다. + for { // 무한루프 + break // 여기서 곧바로 break를 한 건 단지 + continue // break, continue를 루프 안에서 쓸 수 있다는 것을 보여주기 위함. + } + // `for`에서처럼 `if`에서 `:=`를 사용하는 것은 y에 먼저 값을 대입하고, + // 그리고 y > x를 검사한다는 의미. + if y := expensiveComputation(); y > x { + x = y + } + // 함수 리터럴은 클로저다. + xBig := func() bool { + return x > 100 // 위 switch 문 바로 위에 있는 x를 참조한다. + } + fmt.Println("xBig:", xBig()) // true (x에 1e6를 대입했었다.) + x /= 1e5 // x는 10이 된다. + fmt.Println("xBig:", xBig()) // 이제 xBig()의 결과는 false가 된다. + + // `goto`가 필요하다면, 좋아하게 될지도... + goto love +love: + + learnInterfaces() // 곧이어서 좋은 기능에 대한 설명이 나올 거다. +} + +// String 이라는 메서드 하나를 가진 Stringer 라는 인터페이스 타입을 정의하자. +type Stringer interface { + String() string +} + +// x와 y라는 이름의 int 타입 필드를 가진 pair라는 struct를 정의하자. +type pair struct { + x, y int +} + +// Define a method on type pair. Pair now implements Stringer. +// pair 타입에 메서드 String을 정의하자. +// 이제 pair는 Stringer 인터페이스를 구현(implement)한 것이 되었다. +func (p pair) String() string { // 여기서 p는 리시버(receiver)라고 부른다. + // Sprintf는 fmt 패키지 안에 있는 외부로 공개된(exported) 함수다. + // 점(.)으로 p의 필드들을 참조할 수 있다. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // 중괄호 문법은 "구조체 리터럴(struct literal)"인데, 초기화된 구조체로 + // 취급하게 해준다. := 문법으로 p를 이 구조체로 선언하고 초기화한다. + p := pair{3, 4} + fmt.Println(p.String()) // 타입 pair인 p의 String 메서드를 호출. + var i Stringer // Stringer 인터페이스 타입 i를 선언. + i = p // pair는 Stringer를 구현했기 때문에 이 대입은 유효하다. + // 타입 Stringer인 i의 String 메서드 호출. 결과는 위와 같다. + fmt.Println(i.String()) + + // fmt 패키지의 함수들을 통해 어떤 객체를 출력해보려고 할 때, + // fmt 패키지 내에서는 그 객체가 가진 String 메서드를 호출하도록 되어 있다. + fmt.Println(p) // 결과는 위와 같다. Println은 String 메서드를 호출한다. + fmt.Println(i) // 결과는 위와 같다. + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" (comma okay)표현은 무언가가 맞는 것인지 아닌지 확인하는데 사용된다. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // 이 map 안에 키가 1인 것은 없으므로 ok는 false가 된다. + fmt.Println("no one there") + } else { + fmt.Print(x) // 만일 1이 map에 있었다면 x는 키 1의 값이 들어가게 된다. + } + // An error value communicates not just "ok" but more about the problem. + + // Go에서는 함수가 복수 개의 리턴 값을 줄 수 있다는 점을 활용해 함수의 두 번째 리턴 + // 값으로 error를 리턴해주고 그 error가 nil 인지 아닌지 확인하는 관례가 있다. + // 이때 이 error 값은 단지 위에서처럼 함수의 결과가 성공했는지 실패했는지를 확인하는 + // 것뿐만 아니라 실패 시 어떤 문제가 있었는지 확인할 수 있는 수단도 된다. + if _, err := strconv.Atoi("non-int"); err != nil { // _ 는 값을 안 쓰고 버린다는 의미. + // "strconv.ParseInt: parsing "non-int": invalid syntax" 이런 에러가 출력된다. + fmt.Println(err) + } + // 인터페이스에 대해 잠시 후에 다시 잠깐 볼 것이다. + learnConcurrency() +} + +// c는 goroutine 간의 통신을 위한 채널(channel)이다. +func inc(i int, c chan int) { + c <- i + 1 // 채널이 <- 이 연산자 왼쪽에 온다면 그 채널로 데이터를 보낸다는 의미다. +} + +// We'll use inc to increment some numbers concurrently. +func learnConcurrency() { + // Same make function used earlier to make a slice. Make allocates and + // initializes slices, maps, and channels. + c := make(chan int) + // Start three concurrent goroutines. Numbers will be incremented + // concurrently, perhaps in parallel if the machine is capable and + // properly configured. All three send to the same channel. + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) + // Read three results from the channel and print them out. + // There is no telling in what order the results will arrive! + fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. + + cs := make(chan string) // another channel, this one handles strings. + cc := make(chan chan string) // a channel of string channels. + go func() { c <- 84 }() // start a new goroutine just to send a value + go func() { cs <- "wordy" }() // again, for cs this time + // Select has syntax like a switch statement but each case involves + // a channel operation. It selects a case at random out of the cases + // that are ready to communicate. + select { + case i := <-c: // the value received can be assigned to a variable + fmt.Printf("it's a %T", i) + case <-cs: // or the value received can be discarded + fmt.Println("it's a string") + case <-cc: // empty channel, not ready for communication. + fmt.Println("didn't happen.") + } + // At this point a value was taken from either c or cs. One of the two + // goroutines started above has completed, the other will remain blocked. + + learnWebProgramming() // Go does it. You want to do it too. +} + +// http 패키지의 함수 하나로 웹 서버를 실행시킨다. +func learnWebProgramming() { + // ListenAndServe의 첫 번째 파라미터는 listen 하기 위한 TCP 주소고, + // 두 번째 파라미터는 http.Handler 인터페이스다. + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // don't ignore errors +} + +// http.Handler의 하나 뿐인 메서드, ServeHTTP를 pair에서 구현한다. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // http.ResponseWriter의 메서드로 클라이언트에게 데이터를 보낸다. + w.Write([]byte("You learned Go in Y minutes!")) +} +``` + +## 더 읽어볼 것들 + +The root of all things Go is the [official Go web site](http://golang.org/). +There you can follow the tutorial, play interactively, and read lots. + +The language definition itself is highly recommended. It's easy to read +and amazingly short (as language definitions go these days.) + +On the reading list for students of Go is the [source code to the standard +library](http://golang.org/src/pkg/). Comprehensively documented, it +demonstrates the best of readable and understandable Go, Go style, and Go +idioms. Or you can click on a function name in [the +documentation](http://golang.org/pkg/) and the source code comes up! + -- cgit v1.2.3 From 9b3ce954b17fa433ea74de9fd2125c52cadd5143 Mon Sep 17 00:00:00 2001 From: Jongmin Kim Date: Wed, 8 Jan 2014 16:44:30 +0900 Subject: Complete Korean translation --- ko-kr/go-kr.html.markdown | 110 ++++++++++++++++++++++------------------------ 1 file changed, 53 insertions(+), 57 deletions(-) diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown index df0dea8b..7404572c 100644 --- a/ko-kr/go-kr.html.markdown +++ b/ko-kr/go-kr.html.markdown @@ -10,7 +10,7 @@ translators: lang: ko-kr --- -Go는 일을 잘 끝낼 필요에 의해 만들어졌다. Go가 잘 알려진 최신의 +Go는 어떤 일을 잘 끝낼 수 있도록 하기위해 만들어졌다. Go가 잘 알려진 최신의 트렌드는 아니지만, 실세계의 문제들을 해결하기 위해서는 가장 새롭고 빠른 방법이다. @@ -27,21 +27,21 @@ Go는 정적 타이핑(static typing)의 명령형 언어들(imperative language /* 여러 줄 주석 */ -// 모든 Go 소스 파일은 `package`로 시작한다. -// 패키지 이름 중 `main`은 라이브러리가 아닌 실행파일을 선언하는 특별한 이름이다. +// 모든 Go 소스 파일은 package로 시작한다. +// 패키지 이름 중 main은 라이브러리가 아닌 실행파일을 선언하는 특별한 이름이다. package main -// `import`는 이 Go 소스 파일 내에서 참조하는 라이브러리 패키지들을 선언한다. +// import는 이 Go 소스 파일 내에서 참조하는 라이브러리 패키지들을 선언한다. import ( "fmt" // Go 표준 라이브러리에 있는 패키지 "net/http" // 표준 라이브러리에는 웹 서버 패키지도 있다! (클라이언트도 있음) "strconv" // 문자열 변환 패키지 ) -// 함수 선언. `main`은 실행 프로그램에서 시작점이 되는 특별한 함수다. +// 함수 선언. main은 실행 프로그램에서 시작점이 되는 특별한 함수다. // 중괄호를 사용한다. func main() { - // `Println`은 표준 출력으로 개행을 출력한다. + // Println은 표준 출력으로 개행을 출력한다. // fmt 패키지를 통해 이용할 수 있다. fmt.Println("Hello world!") @@ -53,7 +53,7 @@ func main() { func beyondHello() { var x int // 변수 선언. 변수는 사용하기 전에 선언해야 한다. x = 3 // 변수에 값 할당. - // 짧은 선언(short declaration)으로 `:=` 를 사용하는데, + // 짧은 선언(short declaration)으로 := 를 사용하는데, // 이렇게 값을 할당하면 값의 타입에 따라 변수의 타입이 결정된다. y := 4 sum, prod := learnMultiple(x, y) // 함수는 두 개 이상의 리턴 값을 줄 수 있다. @@ -117,16 +117,16 @@ func learnTypes() { // Go는 가비지 컬렉션 기능을 JVM 같은 곳이 아닌 실행파일 런타임에 포함하고 있다. // 그리고 포인터는 있지만, 포인터 연산(*p++ 같은)은 없다. -// 그래서 `nil` 포인터 접근같은 것 때문에 실수를 할 수는 있지만 +// 그래서 nil 포인터 접근같은 것 때문에 실수를 할 수는 있지만 // 포인터 연산으로 인한 실수는 없게 된다. func learnMemory() (p, q *int) { // 지명된 리턴 값(named return value)인 p와 q는 int에 대한 포인터 타입이다. - p = new(int) // 내장함수인 `new`는 메모리를 할당해준다. - // 메모리 할당된 int는 0으로 초기화 되고, p는 이제 `nil`이 아니다. + p = new(int) // 내장함수인 new는 메모리를 할당해준다. + // 메모리 할당된 int는 0으로 초기화 되고, p는 이제 nil이 아니다. s := make([]int, 20) // 메모리의 단일 블록으로 20개의 int 공간을 할당한다. s[3] = 7 // 그중 하나에 값을 준다. r := -2 // 또다른 로컬 변수를 선언한다. - return &s[3], &r // `&`는 어떤 대상체의 메모리 주소를 가져오게 된다. + return &s[3], &r // &는 어떤 대상체의 메모리 주소를 가져오게 된다. } func expensiveComputation() int { @@ -134,40 +134,40 @@ func expensiveComputation() int { } func learnFlowControl() { - // `if`문에 중괄호는 필요하지만, 조건이 들어갈 곳에 소괄호는 쓰지 않는다. + // if문에 중괄호는 필요하지만, 조건이 들어갈 곳에 소괄호는 쓰지 않는다. if true { fmt.Println("told ya") } - // 모든 Go 소스의 코드 포맷팅은 `go fmt` 커맨드라인 명령으로 규격을 맞춘다. + // 모든 Go 소스의 코드 포맷팅은 "go fmt" 커맨드라인 명령으로 소스코드의 포맷을 맞춘다. if false { // pout } else { // gloat } - // if-else 체인 형태보다 `switch` 사용이 권장된다. + // if-else 체인 형태보다 switch 사용이 권장된다. x := 1 switch x { case 0: case 1: - // case 안에서는 `break`가 없어도 자동으로 다음 case로 내려가지 않는다. - // 자동으로 내려가게 하려면 `fallthrough` 키워드를 사용한다. + // case 안에서는 break가 없어도 자동으로 다음 case로 내려가지 않는다. + // 자동으로 내려가게 하려면 fallthrough 키워드를 사용한다. case 2: // x는 1이므로 여기는 실행되지 않음. } - // `if`에서처럼 `for`에서도 양쪽에 소괄호를 쓰지 않는다. - for x := 0; x < 3; x++ { // `++`은 실행을 제어하는 하나의 구문(statement)이다. + // if 에서처럼 for 에서도 양쪽에 소괄호를 쓰지 않는다. + for x := 0; x < 3; x++ { // ++ 은 실행을 제어하는 하나의 구문(statement)이다. fmt.Println("iteration", x) } // 여기서 x는 1이다. 위 for에서 x는 for 안의 블록 범위에 있기 때문. // For is the only loop statement in Go, but it has alternate forms. - // `for`는 Go에서 유일한 루프 구문이지만 다양한 형태로 조건을 주거나 while + // for 는 Go에서 유일한 루프 구문이지만 다양한 형태로 조건을 주거나 while // 처럼 쓸 수도 있다. for { // 무한루프 break // 여기서 곧바로 break를 한 건 단지 continue // break, continue를 루프 안에서 쓸 수 있다는 것을 보여주기 위함. } - // `for`에서처럼 `if`에서 `:=`를 사용하는 것은 y에 먼저 값을 대입하고, + // for 에서처럼 if 에서 := 를 사용하는것은 y에 먼저 값을 대입하고, // 그리고 y > x를 검사한다는 의미. if y := expensiveComputation(); y > x { x = y @@ -177,7 +177,7 @@ func learnFlowControl() { return x > 100 // 위 switch 문 바로 위에 있는 x를 참조한다. } fmt.Println("xBig:", xBig()) // true (x에 1e6를 대입했었다.) - x /= 1e5 // x는 10이 된다. + x /= 1e5 // x는 10이 된다. fmt.Println("xBig:", xBig()) // 이제 xBig()의 결과는 false가 된다. // `goto`가 필요하다면, 좋아하게 될지도... @@ -197,7 +197,6 @@ type pair struct { x, y int } -// Define a method on type pair. Pair now implements Stringer. // pair 타입에 메서드 String을 정의하자. // 이제 pair는 Stringer 인터페이스를 구현(implement)한 것이 되었다. func (p pair) String() string { // 여기서 p는 리시버(receiver)라고 부른다. @@ -232,7 +231,6 @@ func learnErrorHandling() { } else { fmt.Print(x) // 만일 1이 map에 있었다면 x는 키 1의 값이 들어가게 된다. } - // An error value communicates not just "ok" but more about the problem. // Go에서는 함수가 복수 개의 리턴 값을 줄 수 있다는 점을 활용해 함수의 두 번째 리턴 // 값으로 error를 리턴해주고 그 error가 nil 인지 아닌지 확인하는 관례가 있다. @@ -251,40 +249,40 @@ func inc(i int, c chan int) { c <- i + 1 // 채널이 <- 이 연산자 왼쪽에 온다면 그 채널로 데이터를 보낸다는 의미다. } -// We'll use inc to increment some numbers concurrently. +// 우리는 어떤 숫자들을 동시에 증가시키기 위해 inc 함수를 사용할 것이다. func learnConcurrency() { - // Same make function used earlier to make a slice. Make allocates and - // initializes slices, maps, and channels. + // make는 slice, map, channel 타입들에 대해 메모리를 할당하고 초기화를 한다. + // Go에는 메모리 할당 방법으로 new와 make가 있다. c := make(chan int) - // Start three concurrent goroutines. Numbers will be incremented - // concurrently, perhaps in parallel if the machine is capable and - // properly configured. All three send to the same channel. - go inc(0, c) // go is a statement that starts a new goroutine. + // 3개의 동시에 실행되는 goroutine를 시작한다. 만약 실행하고 있는 머신이 + // 멀티코어 CPU를 가지고 있고 올바르게 설정되어(GOMAXPROCS) 있다면 + // 숫자가 정말로 병렬적으로 증가하게 될 것이다. + go inc(0, c) // go는 새로운 goroutine을 시작하는 구문이다. go inc(10, c) go inc(-805, c) - // Read three results from the channel and print them out. - // There is no telling in what order the results will arrive! - fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. - - cs := make(chan string) // another channel, this one handles strings. - cc := make(chan chan string) // a channel of string channels. - go func() { c <- 84 }() // start a new goroutine just to send a value - go func() { cs <- "wordy" }() // again, for cs this time - // Select has syntax like a switch statement but each case involves - // a channel operation. It selects a case at random out of the cases - // that are ready to communicate. + // 채널로부터 3개의 결과를 읽어 출력한다. + // 결과가 어떤 순서로 오는지는 알 수 없다. + fmt.Println(<-c, <-c, <-c) // 채널이 <- 연산자 오른쪽에 있는 건, 채널로부터 데이터를 받는 연산이다. + + cs := make(chan string) // string을 다루는 또 다른 채널 + cc := make(chan chan string) // string 채널의 채널 + go func() { c <- 84 }() // c 채널로 값을 보내는 goroutine 시작. + go func() { cs <- "wordy" }() // cs 채널로 값을 보내느 goroutine 시작. + // select 구문은 switch 문과 비슷하지만, case에서 채널 연산에 관한 일을 한다. + // select의 case들은 채널통신을 할 준비가 된 case 하나가 무작위로 선택되어 + // 그 부분이 실행된다. select { - case i := <-c: // the value received can be assigned to a variable + case i := <-c: // 채널로부터 받아진 값은 변수에 대입할 수 있다. fmt.Printf("it's a %T", i) - case <-cs: // or the value received can be discarded + case <-cs: // 또는 받은 값을 그냥 버릴 수도 있다. fmt.Println("it's a string") - case <-cc: // empty channel, not ready for communication. + case <-cc: // 통신할 준비가 되어 있지 않은 비어있는 채널. fmt.Println("didn't happen.") } - // At this point a value was taken from either c or cs. One of the two - // goroutines started above has completed, the other will remain blocked. + // 여기서는 c나 cs 채널로부터 값 하나를 받을 수 있다. 위에서 실행한 두 개의 + // goroutine 중 하나가 완료되면 다른 하나는 블락된 상태로 있게 된다. - learnWebProgramming() // Go does it. You want to do it too. + learnWebProgramming() // Go에서는 웹 서버쪽 개발도 쉽게 할 수 있다. } // http 패키지의 함수 하나로 웹 서버를 실행시킨다. @@ -304,15 +302,13 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ## 더 읽어볼 것들 -The root of all things Go is the [official Go web site](http://golang.org/). -There you can follow the tutorial, play interactively, and read lots. +Go에 대한 모든 것들은 [Go 공식 웹 사이트](http://golang.org/)를 참고하자. +여기에는 따라해볼 튜토리얼, 웹 기반의 인터랙티브 실행환경과 많은 읽을거리들이 있다. -The language definition itself is highly recommended. It's easy to read -and amazingly short (as language definitions go these days.) - -On the reading list for students of Go is the [source code to the standard -library](http://golang.org/src/pkg/). Comprehensively documented, it -demonstrates the best of readable and understandable Go, Go style, and Go -idioms. Or you can click on a function name in [the -documentation](http://golang.org/pkg/) and the source code comes up! +Go 언어 자체에 대한 스펙도 읽어보기를 적극 추천한다. 읽기 쉽게 되어있고 +그리 길지는 않다. +Go 소스코드에 대해 좀더 알아보고 싶다면 [Go 표준 라이브러리](http://golang.org/src/pkg/)를 +분석해보기 바란다. 이해하기 쉽게 문서화되어 있고, Go 스타일 그리고 Go에서의 +관례 배우기에 가장 좋은 방법일 것이다. 또는 [문서](http://golang.org/pkg/) 안에서 +함수 이름 하나를 클릭해보면 소스코드를 브라우저에서 살펴볼 수도 있다. -- cgit v1.2.3 From 5ad738af38b4642257f5036ac5ed7dbc27f4e187 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 1 Jan 2014 17:20:23 -0600 Subject: Add example of calling instance and class methods. --- objective-c.html.markdown | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index a70351b5..e1834bf8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -306,10 +306,11 @@ int main (int argc, const char * argv[]) // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; -// + for class method +// + for class method. + (NSString *)classMethod; ++ (MyClass *)myClassFromName:(NSString *)name; -// - for instance method +// - for instance methods. - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; @@ -329,6 +330,14 @@ myClass.count = 45; NSLog(@"%i", myClass.count); // prints => 45 +// Call class methods: +NSString *classMethodString = [MyClass classMethod]; +MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; + +// Call instance methods: +MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance. +NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; + // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { long distance; // Private access instance variable. -- cgit v1.2.3 From 7496526cf447c6f5459a9b32448d2ba6e0f60dc0 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 6 Jan 2014 20:18:45 -0600 Subject: Add more examples of methods available to objects. --- objective-c.html.markdown | 49 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index e1834bf8..cdf89338 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -297,9 +297,10 @@ int main (int argc, const char * argv[]) } // Convenient notation for public access variables to auto generate a setter method. // By default, setter method name is 'set' followed by @property variable name. -@property int count; // Setter method name = 'setCount' -@property (copy) NSString *name; // (copy) => Copy the object during assignment. -@property (readonly) id data; // (readonly) => Cannot set value outside interface. +@property int propInt; // Setter method name = 'setCount' +@property (copy) id copyId; // (copy) => Copy the object during assignment. +// (readonly) => Cannot set value outside interface. +@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor. // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; @@ -308,12 +309,15 @@ int main (int argc, const char * argv[]) // + for class method. + (NSString *)classMethod; -+ (MyClass *)myClassFromName:(NSString *)name; ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight; // - for instance methods. - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; +// Constructor methods with arguments: +- (id)initWithDistance:(int)defaultDistance; + @end // States the end of the interface. @@ -341,6 +345,7 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { long distance; // Private access instance variable. + NSNumber height; } // To access a public variable from the interface file, use '_' followed by variable name: @@ -348,27 +353,49 @@ _count = 5; // References "int count" from MyClass interface. // Access variables defined in implementation file: distance = 18; // References "long distance" from MyClass implementation. -// Call when the object is releasing +// Called before calling any class methods or instantiating any objects. ++ (void)initialize +{ + if (self == [MyClass class]) { + distance = 0; + } +} + +// Counterpart to initialize method. Called when an object's reference count is zero. - (void)dealloc { + [height release]; // If not using ARC, make sure to release class variable objects + [super dealloc]; // and call parent class dealloc. } -// Constructors are a way of creating classes +// Constructors are a way of creating instances of classes. // This is a default constructor which is called when the object is initialized. - (id)init { - if ((self = [super init])) + if ((self = [super init])) // 'super' used to access methods from parent class. { - self.count = 1; + self.count = 1; // 'self' used for object to send messages to itself. } return self; } +// Can create constructors that contain arguments: +- (id)initWithDistance:(int)defaultDistance +{ + distance = defaultDistance; + return self; +} + (NSString *)classMethod { return [[self alloc] init]; } ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight +{ + height = defaultHeight; + return [[self alloc] init]; +} + - (NSString *)instanceMethodWithParameter:(NSString *)string { return @"New string"; @@ -379,6 +406,12 @@ distance = 18; // References "long distance" from MyClass implementation. return @42; } +// If you create a method in @implementation but do not include in @interface, it is private. +- (NSNumber *)secretPrivateMethod { + return @72; +} +[self secretPrivateMethod]; // Calls private method. + // Methods declared into MyProtocol - (void)myProtocolMethod { -- cgit v1.2.3 From a16841e0497d033af29257233b2c3e8e93b7987f Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 6 Jan 2014 22:18:54 -0600 Subject: Add selector and @synthesize examples. --- objective-c.html.markdown | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index cdf89338..38b2cc52 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -333,6 +333,20 @@ NSLog(@"%i", [myClass lengthGet]); // prints => 32 myClass.count = 45; NSLog(@"%i", myClass.count); // prints => 45 +// Selectors. +// Way of dynamically represent methods. Used to call methods of a class, pass methods +// through functions to tell other classes they should call it, and save to methods +// as a variable. +// SEL is data type. @selector() returns a selector from method name provided. +// methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method. + // Must put method arguments into one object to send to performSelector. + NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; + [myClass performSelector:selectorVar withObject:arguments]; // Calls the method +} else { + NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar)); +} // Call class methods: NSString *classMethodString = [MyClass classMethod]; @@ -352,6 +366,8 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell _count = 5; // References "int count" from MyClass interface. // Access variables defined in implementation file: distance = 18; // References "long distance" from MyClass implementation. +// To use @property variable in implementation, use @synthesize to create accessor variable: +@synthesize roString = _roString; // _roString available now in @implementation. // Called before calling any class methods or instantiating any objects. + (void)initialize -- cgit v1.2.3 From eab35e826eb86744d98a3fc424ebca6ccf432390 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 8 Jan 2014 13:03:31 -0600 Subject: Organize branch changes. --- objective-c.html.markdown | 42 ++++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 38b2cc52..f2787649 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -297,9 +297,9 @@ int main (int argc, const char * argv[]) } // Convenient notation for public access variables to auto generate a setter method. // By default, setter method name is 'set' followed by @property variable name. -@property int propInt; // Setter method name = 'setCount' +@property int propInt; // Setter method name = 'setPropInt' @property (copy) id copyId; // (copy) => Copy the object during assignment. -// (readonly) => Cannot set value outside interface. +// (readonly) => Cannot set value outside @interface. @property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor. // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; @@ -307,16 +307,17 @@ int main (int argc, const char * argv[]) // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; -// + for class method. +// + for class methods: + (NSString *)classMethod; + (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight; -// - for instance methods. +// - for instance methods: - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; // Constructor methods with arguments: - (id)initWithDistance:(int)defaultDistance; +// Objective-C method names are very descriptive. Always name methods according to their arguments. @end // States the end of the interface. @@ -333,29 +334,30 @@ NSLog(@"%i", [myClass lengthGet]); // prints => 32 myClass.count = 45; NSLog(@"%i", myClass.count); // prints => 45 +// Call class methods: +NSString *classMethodString = [MyClass classMethod]; +MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; + +// Call instance methods: +MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance. +NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; + // Selectors. -// Way of dynamically represent methods. Used to call methods of a class, pass methods -// through functions to tell other classes they should call it, and save to methods +// Way to dynamically represent methods. Used to call methods of a class, pass methods +// through functions to tell other classes they should call it, and to save methods // as a variable. -// SEL is data type. @selector() returns a selector from method name provided. +// SEL is the data type. @selector() returns a selector from method name provided. // methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method. - // Must put method arguments into one object to send to performSelector. + // Must put all method arguments into one object to send to performSelector function. NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; - [myClass performSelector:selectorVar withObject:arguments]; // Calls the method + [myClass performSelector:selectorVar withObject:arguments]; // Calls the method. } else { + // NSStringFromSelector() returns a NSString of the method name of a given selector. NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar)); } -// Call class methods: -NSString *classMethodString = [MyClass classMethod]; -MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; - -// Call instance methods: -MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance. -NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; - // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { long distance; // Private access instance variable. @@ -384,13 +386,13 @@ distance = 18; // References "long distance" from MyClass implementation. [super dealloc]; // and call parent class dealloc. } -// Constructors are a way of creating instances of classes. +// Constructors are a way of creating instances of a class. // This is a default constructor which is called when the object is initialized. - (id)init { if ((self = [super init])) // 'super' used to access methods from parent class. { - self.count = 1; // 'self' used for object to send messages to itself. + self.count = 1; // 'self' used for object to call itself. } return self; } @@ -422,7 +424,7 @@ distance = 18; // References "long distance" from MyClass implementation. return @42; } -// If you create a method in @implementation but do not include in @interface, it is private. +// To create a private method, create the method in the @implementation but not in the @interface. - (NSNumber *)secretPrivateMethod { return @72; } -- cgit v1.2.3 From c8b12bd824659879038d5d752b13d5c91fad8303 Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Fri, 10 Jan 2014 18:14:35 +0100 Subject: Added verb ("is") where it was missing --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 84856b32..99ff0d27 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -92,7 +92,7 @@ int main() { printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) - // If the argument of the `sizeof` operator an expression, then its argument + // If the argument of the `sizeof` operator is an expression, then its argument // is not evaluated (except VLAs (see below)). // The value it yields in this case is a compile-time constant. int a = 1; -- cgit v1.2.3 From c9a32b08e72a4c219a549497e24675e700870f26 Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Fri, 10 Jan 2014 18:28:34 +0100 Subject: Added missing comma in printf --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 99ff0d27..e55ff148 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -376,7 +376,7 @@ int main() { // or when it's the argument of the `sizeof` or `alignof` operator: int arr[10]; int *ptr = arr; // equivalent with int *ptr = &arr[0]; - printf("%zu %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8" + printf("%zu, %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8" // Pointers are incremented and decremented based on their type -- cgit v1.2.3 From f273c5183235330e06eeab63a66ed9fbe549e4f2 Mon Sep 17 00:00:00 2001 From: Abhishek L Date: Sat, 11 Jan 2014 12:06:24 +0530 Subject: [hy/en] Introductory tutorial to hy language * hy.html.markdown: This is an introductory tutorial to hy language, http://hylang.org which is a dialect of lisp built on top of python --- hy.html.markdown | 174 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 hy.html.markdown diff --git a/hy.html.markdown b/hy.html.markdown new file mode 100644 index 00000000..04bd05c9 --- /dev/null +++ b/hy.html.markdown @@ -0,0 +1,174 @@ +--- +language: hy +filename: learnhy.hy +contributors: + - ["Abhishek L", "http://twitter.com/abhishekl"] +--- + +Hy is a lisp dialect built on top of python. This is achieved by +converting hy code to python's abstract syntax tree (ast). This allows +hy to call native python code or python to call native hy code as well + +This tutorial works for hy ≥ 0.9.12 + +```clojure +;; this gives an gentle introduction to hy for a quick trial head to +;; http://try-hy.appspot.com +;; +; Semicolon comments, like other LISPS + +;; s-expression basics +; lisp programs are made of symbolic expressions or sexps which +; resemble +(some-function args) +; now the quintessential hello world +(print "hello world") + +;; simple data types +; All simple data types are exactly similar to their python counterparts +; which +42 ; => 42 +3.14 ; => 3.14 +True ; => True +4+10j ; => (4+10j) a complex number + +; lets start with some really simple arithmetic +(+ 4 1) ;=> 5 +; the operator is applied to all arguments, like other lisps +(+ 4 1 2 3) ;=> 10 +(- 2 1) ;=> 1 +(* 4 2) ;=> 8 +(/ 4 1) ;=> 4 +(% 4 2) ;=> 0 the modulo operator +; power is represented by ** operator like python +(** 3 2) ;=> 9 +; nesting forms will do the expected thing +(+ 2 (* 4 2)) ;=> 10 +; also logical operators and or not and equal to etc. do as expected +(= 5 4) ;=> False +(not (= 5 4)) ;=> True + +;; variables +; variables are set using setv, variable names can use utf-8 except +; for ()[]{}",'`;#| +(setv a 42) +(setv π 3.14159) +(def *foo* 42) +;; other container data types +; strings, lists, tuples & dicts +; these are exactly same as python's container types +"hello world" ;=> "hello world" +; string operations work similar to python +(+ "hello " "world") ;=> "hello world" +; lists are created using [], indexing starts at 0 +(setv mylist [1 2 3 4]) +; tuples are immutable data structures +(setv mytuple (, 1 2)) +; dictionaries are key value pairs +(setv dict1 {"key1" 42 "key2" 21}) +; :name can be used to define keywords in hy which can be used for keys +(setv dict2 {:key1 41 :key2 20}) +; use `get' to get the element at an index/key +(get mylist 1) ;=> 2 +(get dict1 "key1") ;=> 42 +; Alternatively if keywords were used they can directly be called +(:key1 dict2) ;=> 41 + +;; functions and other program constructs +; functions are defined using defn, the last sexp is returned by default +(defn greet [name] + "A simple greeting" ; an optional docstring + (print "hello " name)) + +(greet "bilbo") ;=> "hello bilbo" + +; functions can take optional arguments as well as keyword arguments +(defn foolist [arg1 &optional [arg2 2]] + [arg1 arg2]) + +(foolists 3) ;=> [3 2] +(foolists 10 3) ;=> [10 3] + +; anonymous functions are created using `fn' or `lambda' constructs +; which are similiar to `defn' +(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16] + +;; Sequence operations +; hy has some builtin utils for sequence operations etc. +; retrieve the first element using `first' or `car' +(setv mylist [1 2 3 4]) +(setv mydict {"a" 1 "b" 2}) +(first mylist) ;=> 1 + +; slice lists using slice +(slice mylist 1 3) ;=> [2 3] + +; get elements from a list or dict using `get' +(get mylist 1) ;=> 2 +(get mydict "b") ;=> 2 +; list indexing starts from 0 same as python +; assoc can set elements at keys/indexes +(assoc mylist 2 10) ; makes mylist [1 2 10 4] +(assoc mydict "c" 3) ; makes mydict {"a" 1 "b" 2 "c" 3} +; there are a whole lot of other core functions which makes working with +; sequences fun + +;; Python interop +;; import works just like in python +(import datetime) +(import [functools [partial reduce]]) ; imports fun1 and fun2 from module1 +(import [matplotlib.pyplot :as plt]) ; doing an import foo as bar +; all builtin python methods etc. are accessible from hy +; a.foo(arg) is called as (.foo a arg) +(.split (.strip "hello world ")) ;=> ["hello" "world"] + +;; Conditionals +; (if condition (body-if-true) (body-if-false) +(if (= passcode "moria") + (print "welcome") + (print "Speak friend, and Enter!")) + +; nest multiple if else if clauses with cond +(cond + [(= someval 42) + (print "Life, universe and everything else!")] + [(> someval 42) + (print "val too large")] + [(< someval 42) + (print "val too small")]) + +; group statements with do, these are executed sequentially +; forms like defn have an implicit do +(do + (setv someval 10) + (print "someval is set to " someval)) ;=> 10 + +; create lexical bindings with `let', all variables defined thusly +; have local scope +(let [[nemesis {"superman" "lex luther" + "sherlock" "moriarty" + "seinfeld" "newman"}]] + (for [(, h v) (.items nemesis)] + (print (.format "{0}'s nemesis was {1}" h v)))) + +;; classes +; classes are defined in the following way +(defclass Wizard [object] + [[--init-- (fn [self spell] + (setv self.spell spell) ; init the spell attr + None)] + [get-spell (fn [self] + self.spell)]]) + +;; do checkout hylang.org +``` + +### Further Reading + +This tutorial is just a very basic introduction to hy/lisp/python. + +Hy docs are here: [http://hy.readthedocs.org](http://hy.readthedocs.org) + +Hy's Github repo: [http://github.com/hylang/hy](http://github.com/hylang/hy) + +On freenode irc #hy, twitter hashtag #hylang -- cgit v1.2.3 From b7b43c3fffad76bca45962e6f508c7d696281828 Mon Sep 17 00:00:00 2001 From: Yannick Date: Sat, 11 Jan 2014 19:27:47 +0100 Subject: [UPDATE] Import Details --- objective-c.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index f2787649..bbfc6126 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -12,7 +12,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```cpp +```objective-c // Single-line comments start with // /* @@ -20,9 +20,15 @@ Multi-line comments look like this. */ // Imports the Foundation headers with #import +// Use <> to import global files (in general frameworks) +// Use "" to import local files (from project) #import #import "MyClass.h" +// If you enable modules for iOS >= 7.0 or Mac OSX >= 10.9 projects in +// Xcode 5 you can import frameworks like that: +@import Foundation; + // Your program's entry point is a function called // main with an integer return type. int main (int argc, const char * argv[]) -- cgit v1.2.3 From 01e3455d90e7e542d0b38c9e46865a06ea018237 Mon Sep 17 00:00:00 2001 From: Yannick Date: Sat, 11 Jan 2014 19:27:47 +0100 Subject: [UPDATE] Import Details --- objective-c.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index f2787649..3390c69b 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -12,7 +12,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```cpp +```objective-c // Single-line comments start with // /* @@ -20,9 +20,15 @@ Multi-line comments look like this. */ // Imports the Foundation headers with #import +// Use <> to import global files (in general frameworks) +// Use "" to import local files (from project) #import #import "MyClass.h" +// If you enable modules for iOS >= 7.0 or OS X >= 10.9 projects in +// Xcode 5 you can import frameworks like that: +@import Foundation; + // Your program's entry point is a function called // main with an integer return type. int main (int argc, const char * argv[]) -- cgit v1.2.3 From d5c4e851da8e5cf58279941af81531e3fd8b1035 Mon Sep 17 00:00:00 2001 From: Yannick Date: Sat, 11 Jan 2014 19:51:41 +0100 Subject: [REMOVE] dots at the end of the comments --- objective-c.html.markdown | 130 +++++++++++++++++++++++----------------------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 3390c69b..453a42a5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -16,7 +16,7 @@ It is a general-purpose, object-oriented programming language that adds Smalltal // Single-line comments start with // /* -Multi-line comments look like this. +Multi-line comments look like this */ // Imports the Foundation headers with #import @@ -30,7 +30,7 @@ Multi-line comments look like this. @import Foundation; // Your program's entry point is a function called -// main with an integer return type. +// main with an integer return type int main (int argc, const char * argv[]) { // Create an autorelease pool to manage the memory into the program @@ -60,7 +60,7 @@ int main (int argc, const char * argv[]) // String NSString *worldString = @"World"; NSLog(@"Hello %@!", worldString); // prints => "Hello World!" - // NSMutableString is a mutable version of the NSString object. + // NSMutableString is a mutable version of the NSString object NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; [mutableString appendString:@" World!"]; NSLog(@"%@", mutableString); // prints => "Hello World!" @@ -114,7 +114,7 @@ int main (int argc, const char * argv[]) [oneDecNum decimalNumberBySubtracting:twoDecNum]; [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; [oneDecNum decimalNumberByDividingBy:twoDecNum]; - NSLog(@"%@", oneDecNum); // prints => 10.99 as NSDecimalNumber is immutable. + NSLog(@"%@", oneDecNum); // prints => 10.99 as NSDecimalNumber is immutable // BOOL literals NSNumber *yesNumber = @YES; @@ -125,12 +125,12 @@ int main (int argc, const char * argv[]) NSLog(@"%i", yesBool); // prints => 1 // Array object - // May contain different data types, but must be an Objective-C object. + // May contain different data types, but must be an Objective-C object NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" // NSMutableArray is mutable version of NSArray allowing to change items in array - // and extend or shrink array object. Convenient, but not as efficient as NSArray. + // and extend or shrink array object. Convenient, but not as efficient as NSArray NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; [mutableArray addObject:@"Hello"]; [mutableArray addObject:@"World"]; @@ -141,7 +141,7 @@ int main (int argc, const char * argv[]) NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // Print "Object = (null)" - // NSMutableDictionary also available as a mutable dictionary object. + // NSMutableDictionary also available as a mutable dictionary object NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; [mutableDictionary setObject:@"value1" forKey:@"key1"]; [mutableDictionary setObject:@"value2" forKey:@"key2"]; @@ -150,7 +150,7 @@ int main (int argc, const char * argv[]) // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) - // NSMutableSet also available as a mutable set object. + // NSMutableSet also available as a mutable set object NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; [mutableSet addObject:@"Hello"]; [mutableSet addObject:@"Hello"]; @@ -209,7 +209,7 @@ int main (int argc, const char * argv[]) int ii = 0; while (ii < 4) { - NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value. + NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value } // => prints "0," // "1," // "2," @@ -235,7 +235,7 @@ int main (int argc, const char * argv[]) // "2," // "3," - // Object for loop statement. Can be used with any Objective-C object type. + // Object for loop statement. Can be used with any Objective-C object type for (id item in values) { NSLog(@"%@,", item); } // => prints "0," @@ -262,19 +262,19 @@ int main (int argc, const char * argv[]) // Objects /////////////////////////////////////// - // Create an object instance by allocating memory and initializing it. - // An object is not fully functional until both steps have been completed. + // Create an object instance by allocating memory and initializing it + // An object is not fully functional until both steps have been completed MyClass *myObject = [[MyClass alloc] init]; // The Objective-C model of object-oriented programming is based on message - // passing to object instances. - // In Objective-C one does not simply call a method; one sends a message. + // passing to object instances + // In Objective-C one does not simply call a method; one sends a message [myObject instanceMethodWithParameter:@"Steve Jobs"]; // Clean up the memory you used into your program [pool drain]; - // End of @autoreleasepool. + // End of @autoreleasepool } // End the program @@ -291,22 +291,22 @@ int main (int argc, const char * argv[]) // { // type name; <= variable declarations; // } -// @property type name; <= property declarations. -// -/+ (type) Method declarations; <= Method declarations. +// @property type name; <= property declarations +// -/+ (type) Method declarations; <= Method declarations // @end @interface MyClass : NSObject // NSObject is Objective-C's base object class. { - // Instance variable declarations (can exist in either interface or implementation file). + // Instance variable declarations (can exist in either interface or implementation file) int count; // Protected access by default. - @private id data; // Private access. (More convenient to declare in implementation file). + @private id data; // Private access (More convenient to declare in implementation file) NSString *name; } -// Convenient notation for public access variables to auto generate a setter method. -// By default, setter method name is 'set' followed by @property variable name. +// Convenient notation for public access variables to auto generate a setter method +// By default, setter method name is 'set' followed by @property variable name @property int propInt; // Setter method name = 'setPropInt' -@property (copy) id copyId; // (copy) => Copy the object during assignment. -// (readonly) => Cannot set value outside @interface. -@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor. +@property (copy) id copyId; // (copy) => Copy the object during assignment +// (readonly) => Cannot set value outside @interface +@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; @@ -323,14 +323,14 @@ int main (int argc, const char * argv[]) // Constructor methods with arguments: - (id)initWithDistance:(int)defaultDistance; -// Objective-C method names are very descriptive. Always name methods according to their arguments. +// Objective-C method names are very descriptive. Always name methods according to their arguments -@end // States the end of the interface. +@end // States the end of the interface // To access public variables from the implementation file, @property generates a setter method // automatically. Method name is 'set' followed by @property variable name: -MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. +MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance [myClass setCount:10]; NSLog(@"%d", [myClass count]); // prints => 10 // Or using the custom getter and setter method defined in @interface: @@ -345,39 +345,39 @@ NSString *classMethodString = [MyClass classMethod]; MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; // Call instance methods: -MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance. +MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; -// Selectors. +// Selectors // Way to dynamically represent methods. Used to call methods of a class, pass methods // through functions to tell other classes they should call it, and to save methods -// as a variable. -// SEL is the data type. @selector() returns a selector from method name provided. +// as a variable +// SEL is the data type. @selector() returns a selector from method name provided // methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); -if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method. - // Must put all method arguments into one object to send to performSelector function. +if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method + // Must put all method arguments into one object to send to performSelector function NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; - [myClass performSelector:selectorVar withObject:arguments]; // Calls the method. + [myClass performSelector:selectorVar withObject:arguments]; // Calls the method } else { - // NSStringFromSelector() returns a NSString of the method name of a given selector. + // NSStringFromSelector() returns a NSString of the method name of a given selector NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar)); } // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { - long distance; // Private access instance variable. + long distance; // Private access instance variable NSNumber height; } // To access a public variable from the interface file, use '_' followed by variable name: -_count = 5; // References "int count" from MyClass interface. +_count = 5; // References "int count" from MyClass interface // Access variables defined in implementation file: -distance = 18; // References "long distance" from MyClass implementation. +distance = 18; // References "long distance" from MyClass implementation // To use @property variable in implementation, use @synthesize to create accessor variable: -@synthesize roString = _roString; // _roString available now in @implementation. +@synthesize roString = _roString; // _roString available now in @implementation -// Called before calling any class methods or instantiating any objects. +// Called before calling any class methods or instantiating any objects + (void)initialize { if (self == [MyClass class]) { @@ -385,20 +385,20 @@ distance = 18; // References "long distance" from MyClass implementation. } } -// Counterpart to initialize method. Called when an object's reference count is zero. +// Counterpart to initialize method. Called when an object's reference count is zero - (void)dealloc { [height release]; // If not using ARC, make sure to release class variable objects - [super dealloc]; // and call parent class dealloc. + [super dealloc]; // and call parent class dealloc } -// Constructors are a way of creating instances of a class. -// This is a default constructor which is called when the object is initialized. +// Constructors are a way of creating instances of a class +// This is a default constructor which is called when the object is initialized. - (id)init { - if ((self = [super init])) // 'super' used to access methods from parent class. + if ((self = [super init])) // 'super' used to access methods from parent class { - self.count = 1; // 'self' used for object to call itself. + self.count = 1; // 'self' used for object to call itself } return self; } @@ -430,11 +430,11 @@ distance = 18; // References "long distance" from MyClass implementation. return @42; } -// To create a private method, create the method in the @implementation but not in the @interface. +// To create a private method, create the method in the @implementation but not in the @interface - (NSNumber *)secretPrivateMethod { return @72; } -[self secretPrivateMethod]; // Calls private method. +[self secretPrivateMethod]; // Calls private method // Methods declared into MyProtocol - (void)myProtocolMethod @@ -442,7 +442,7 @@ distance = 18; // References "long distance" from MyClass implementation. // statements } -@end // States the end of the implementation. +@end // States the end of the implementation /* * A protocol declares methods that can be implemented by any class. @@ -472,34 +472,34 @@ With all object interactions, follow the pattern of: (1) create the object, (2) use the object, (3) then free the object from memory. */ -MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object. -[classVar release]; // Decrements classVar's reference count. -// 'retain' claims ownership of existing object instance and increments reference count. Returns pointer to object. -MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner. -[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object. +MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object +[classVar release]; // Decrements classVar's reference count +// 'retain' claims ownership of existing object instance and increments reference count. Returns pointer to object +MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner +[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object -// @property can use 'retain' and 'assign' as well for small convenient definitions. -@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). -@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). +// @property can use 'retain' and 'assign' as well for small convenient definitions +@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference) +@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference) // Automatic Reference Counting (ARC) // Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). // ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, -// you must not use retain, relase, or autorelease. +// you must not use retain, relase, or autorelease MyClass *arcMyClass = [[MyClass alloc] init]; // ... code using arcMyClass // Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, -// there is no need. It will insert this release statement for you. +// there is no need. It will insert this release statement for you -// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'. +// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong' @property (weak) MyClass *weakVar; // 'weak' does not take ownership of object. If original instance's reference count -// is set to zero, weakVar will automatically receive value of nil to avoid application crashing. -@property (strong) MyClass *strongVar; // 'strong' takes ownership of object. Ensures object will stay in memory to use. +// is set to zero, weakVar will automatically receive value of nil to avoid application crashing +@property (strong) MyClass *strongVar; // 'strong' takes ownership of object. Ensures object will stay in memory to use // For regular variables (not @property declared variables), use the following: -__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope. -__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil. -__unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not set to nil when existing object is released. +__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope +__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil +__unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not set to nil when existing object is released ``` ## Further Reading -- cgit v1.2.3 From 84b7e2ccd6ac9f9641edeb30f2c0ed22e18b0666 Mon Sep 17 00:00:00 2001 From: Yannick Date: Sat, 11 Jan 2014 22:31:22 +0100 Subject: [ADD] Translation in french of the first part --- fr-fr/objective-c.html.markdown | 509 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 509 insertions(+) create mode 100644 fr-fr/objective-c.html.markdown diff --git a/fr-fr/objective-c.html.markdown b/fr-fr/objective-c.html.markdown new file mode 100644 index 00000000..b6567382 --- /dev/null +++ b/fr-fr/objective-c.html.markdown @@ -0,0 +1,509 @@ +--- + +language: Objective-C +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] + - ["Levi Bostian", "https://github.com/levibostian"] +translators: + - ["Yannick Loriot", "https://github.com/YannickL"] +filename: LearnObjectiveC.m + +--- + +L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs framworks respectifs, Cocoa et Cocoa Touch. + +```objective-c +// Les commentaires unilignes commencent par // + +/* +Les commentaires multilignes ressemblent à ça +*/ + +// Importe les en-têtes en utilisant #import +// Utilisez <> pour importer des fichiers globaux (en général des frameworks) +// Utilisez "" pour importer des fichiers locaux (du projet) +#import +#import "MaClasse.h" + +// Si vous activez les modules pour les projects iOS >= 7 ou Mac OS X >= 10.9 +// dans Xcode 5 vous pouvez importer les frameworks comme cela : +@import Foundation; + +// Le point d'entrée de votre programme est une fonction qui s'appelle main +// et qui return un entier comme type +int main (int argc, const char * argv[]) +{ + // Créer un groupe de libération automatique de la mémoire pour l'ensemble + // du programme + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + // Si vous utilisez le comptage de référence automatique (ARC), utilisez + // @autoreleasepool à la place : + @autoreleasepool { + + // Utilisez NSLog pour afficher les lignes sur la console + // Affiche la chaine de caractères "Bonjour Tous Le Monde !" + NSLog(@"Bonjour tous le Monde !"); + + /////////////////////////////////////// + // Les Types & Les Variables + /////////////////////////////////////// + + // Déclarations de primitive + int maPrimitive1 = 1; + long maPrimitive2 = 234554664565; + + // Declarations d'objets + // Il faut mettre l'* devant la déclaration d'objets fortement typés + MaClasse *monObject1 = nil; // Typage fort + id monObject2 = nil; // Typage faible + // %@ est un objet + // 'description' est une convention pour afficher la valeur des objets + NSLog(@"%@ and %@", monObject1, [monObject2 description]); // Affiche "(null) et (null)" + + // Chaines de caractères + NSString *chaineMonde = @"Monde"; + NSLog(@"Bonjour tous le %@ !", chaineMonde); // affiche => "Bonjour Tous Le Monde !" + // NSMutableString est une chaine mutable + NSMutableString *chaineMutable = [NSMutableString stringWithString:@"Bonjour tous le"]; + [chaineMutable appendString:@" Monde !"]; + NSLog(@"%@", chaineMutable); // affiche => "Bonjour Tous Le Monde !" + + // Les littéraux pour les caratères + NSNumber *laLettreZSousFormeDeNombre = @'Z'; + char laLettreZ = [laLettreZSousFormeDeNombre charValue]; // ou 'Z' + NSLog(@"%c", laLettreZ); + + // Les littéraux pour les nombres + NSNumber *nombreQuaranteDeux = @42; + int quaranteDeux = [nombreQuaranteDeux intValue]; // ou 42 + NSLog(@"%i", quaranteDeux); + + NSNumber *nombreQuaranteDeuxnonSigne = @42U; + unsigned int quaranteDeuxnonSigne = [nombreQuaranteDeuxnonSigne unsignedIntValue]; + NSLog(@"%u", fortyTwoUnsigned); + + NSNumber *nombreQuaranteDeuxCourt = [NSNumber numberWithShort:42]; + short quaranteDeuxCourt = [nombreQuaranteDeuxCourt shortValue]; // ou 42 + NSLog(@"%hi", fortyTwoShort); + + NSNumber *nombreQuaranteDeuxLong = @42L; + long quaranteDeuxLong = [nombreQuaranteDeuxLong longValue]; // ou 42 + NSLog(@"%li", fortyTwoLong); + + // Les littéraux pour les flottans + NSNumber *nombrePiFlottan = @3.141592654F; + float piFlottan = [nombrePiFlottan floatValue]; // ou 3.141592654f + NSLog(@"%f", piFlottan); // affiche => 3.141592654 + NSLog(@"%5.2f", piFlottan); // affiche => " 3.14" + + NSNumber *nombrePiDouble = @3.1415926535; + double piDouble = [nombrePiDouble doubleValue]; // ou 3.1415926535 + NSLog(@"%f", piDouble); + NSLog(@"%4.2f", piDouble); // affiche => "3.14" + + // NSDecimalNumber est une classe pour avoir plus de précision sur les flottans + // et les doubles + NSDecimalNumber *decNumUn = [NSDecimalNumber decimalNumberWithString:@"10.99"]; + NSDecimalNumber *decNumDeux = [NSDecimalNumber decimalNumberWithString:@"5.002"]; + // NSDecimalNumber n'est pas capable d'utiliser les opérations standards : + // +, -, *, /, il utilise donc ses propres fonctions : + [decNumUn decimalNumberByAdding:decNumDeux]; + [decNumUn decimalNumberBySubtracting:decNumDeux]; + [decNumUn decimalNumberByMultiplyingBy:decNumDeux]; + [decNumUn decimalNumberByDividingBy:decNumDeux]; + NSLog(@"%@", decNumUn); // affiche => 10.99 comme NSDecimalNumber is immuable + + // Les littéraux pour les booléens + NSNumber *ouiNumber = @YES; + NSNumber *nonNumber = @NO; + // ou + BOOL ouiBool = YES; + BOOL nonBool = NO; + NSLog(@"%i", ouiBool); // affiche => 1 + + // Les listes + // Ils peuvent contenir différents types de données, mais ils doivent absolument + // être des objets + NSArray *uneListe = @[@1, @2, @3, @4]; + NSNumber *troisiemeNombre = uneListe[2]; + NSLog(@"Troisième nombre = %@", troisiemeNombre); // affiche "Troisième nombre = 3" + // NSMutableArray est une version mutable de NSArray qui permet de changer les + // objets dans la liste et l'étendre ou la réduire + // C'est très pratique, mais pas aussi performant que l'utilsation de la classe + // NSArray + NSMutableArray *listeMutable = [NSMutableArray arrayWithCapacity:2]; + [listeMutable addObject:@"Bonjour tous le"]; + [listeMutable addObject:@"Monde"]; + [listeMutable removeObjectAtIndex:0]; + NSLog(@"%@", [listeMutable objectAtIndex:0]); // affiche => "Monde" + + // Les dictionnaires + NSDictionary *unDictionnaire = @{ @"cle1" : @"valeur1", @"cle2" : @"valeur2" }; + NSObject *valeur = unDictionnaire[@"Une clé"]; + NSLog(@"Objet = %@", valeur); // affiche "Objet = (null)" + // NSMutableDictionary est un dictionnaire mutable + NSMutableDictionary *dictionnaireMutable = [NSMutableDictionary dictionaryWithCapacity:2]; + [dictionnaireMutable setObject:@"valeur1" forKey:@"cle1"]; + [dictionnaireMutable setObject:@"valeur2" forKey:@"cle2"]; + [dictionnaireMutable removeObjectForKey:@"cle1"]; + + // Les ensembles + NSSet *ensemble = [NSSet setWithObjects:@"Salut", @"Salut", @"Monde", nil]; + NSLog(@"%@", ensemble); // affiche => {(Salut, Monde)} (peut être dans un ordre différente) + // NSMutableSet est un ensemble mutable + NSMutableSet *ensembleMutable = [NSMutableSet setWithCapacity:2]; + [ensembleMutable addObject:@"Salut"]; + [ensembleMutable addObject:@"Salut"]; + NSLog(@"%@", ensembleMutable); // affiche => {(Salut)} + + /////////////////////////////////////// + // Operateurs + /////////////////////////////////////// + + // Les opérateurs sont les mêmes que ceux du langage C + // Par exemple : + 2 + 5; // => 7 + 4.2f + 5.1f; // => 9.3f + 3 == 2; // => 0 (NO) + 3 != 2; // => 1 (YES) + 1 && 1; // => 1 (et logique) + 0 || 1; // => 1 (ou logique) + ~0x0F; // => 0xF0 (négation bit à bit) + 0x0F & 0xF0; // => 0x00 (et bit à bit) + 0x01 << 1; // => 0x02 (décale à gauche (par 1)) + + /////////////////////////////////////// + // Structures de controle + /////////////////////////////////////// + + // Expression If-Else + if (NO) + { + NSLog(@"Je ne suis jamais affiché"); + } else if (0) + { + NSLog(@"Je ne suis jamais affiché aussi"); + } else + { + NSLog(@"Je suis affiché"); + } + + // Expression Switch + switch (2) + { + case 0: + { + NSLog(@"Je ne suis jamais affiché"); + } break; + case 1: + { + NSLog(@"Je ne suis jamais affiché aussi"); + } break; + default: + { + NSLog(@"Je suis affiché"); + } break; + } + + // Expression de boucle While + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++ incrémente ii après avoir utilisé sa valeure + } // => affiche "0," + // "1," + // "2," + // "3," + + // Expression de boucle For loops + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", jj); + } // => affiche "0," + // "1," + // "2," + // "3," + + // Expression de boucle Foreach + NSArray *valeurs = @[@0, @1, @2, @3]; + for (NSNumber *valeur in valeurs) + { + NSLog(@"%@,", valeur); + } // => affiche "0," + // "1," + // "2," + // "3," + + // Expressions Try-Catch-Finally + @try + { + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"Fichier non trouvé" userInfo:nil]; + } @catch (NSException * e) + { + NSLog(@"Exception : %@", e); + } @finally + { + NSLog(@"Finalement"); + } // => affiche "Exceptio : Fichier non trouvé" + // "Finalement" + + /////////////////////////////////////// + // Objets + /////////////////////////////////////// + + // Créez une instance d'objet en allouant un espace mémoire puis en l'initialisant + // Un objet n'est pas complétement fonctionnel jusqu'à ce que les deux étapes précédente + // ne sont pas fini + MaClass *monObjet = [[MaClass alloc] init]; + + // Le modèle Objective-C est basé sur l'envoie de message et non sur les appels de + // méthodes comme la plupart des autres langage de programmation + [myObject instanceMethodWithParameter:@"Steve Jobs"]; + + // Nettoie la mémoire que vous avez utilisé dans votre programme + [pool drain]; + + // Fin the l'@autoreleasepool + } + + // Fin du programme + return 0; +} + +/////////////////////////////////////// +// Classes et Fonctions +/////////////////////////////////////// + +// Déclarez votre classe dans une en-tête de fichier (MaClasse.h) : +// La syntaxe de déclaration : +// @interface NomDeLaClasse : NomDeLaClasseParent +// { +// type nom; <= declarations de variable; +// } +// @property type nom; <= declarations de propriété. +// -/+ (type) Methode declarations; <= Declarations de methodes. +// @end +// NSObject est la classe de base de l'Objective-C +@interface MaClasse : NSObject +{ + // Déclaration des variables d'instances (peut existé soit dans l'interface soir dans + // l'implémentation) + int nombre; // Accès protégé par défaut + @private id donnee; // Accès privé (il est plus pratique de le faire dans l'implémentation) + NSString *nom; +} +// Notation pratique pour l'accès aux variable public et pour générrer les +// accésseurs/affecteurs +// Par défaut, le nom de l'affecteur vaut 'set' suivi par le nom de la @property +@property int propInt; // Nom du setter = 'setPropInt' +@property (copy) id copyId; // (copy) => Copie l'objet pendant l'affectation +// (readonly) => Ne peut pas affecté la variable en dehors de l'@interface +// Utilisez @synthesize dans l'@implementation pour créer l'accésseur +@property (readonly) NSString *roString; +// Vous pouvez personnaliser les noms des accésseurs et des affecteurs au lieu d'utiliser les +// noms par défauts +@property (getter=longeurGet, setter=longeurSet:) int longeur; + +// Methodes ++/- (type de retour)signatureDeLaMethode:(Type Du Parametre *)nomDuParametre; + +// + pour les méthodes de classe : ++ (NSString *)methodeDeClasse; ++ (MaClasse *)maClasseDepuisLaHauteur:(NSNumber *)hauteurParDefaut; + +// - pour les méthodes d'instances : +- (NSString *)methodeInstanceAvecUnParametre:(NSString *)string; +- (NSNumber *)methodeInstanceAvecUnParametre:(NSString*)string puisUnDeuxieme:(NSNumber *)number; + +// Contructeur avec des arguments : +- (id)initAvecDistance:(int)distanceParDefault; +// Les méthodes en Objective-C sont très descriptive + +@end // Définit la fin de l'interface + + +// Exemple d'utilisation de MaClasse +MaClasse *maClasse = [[MaClasse alloc] init]; // créer une instance de MaClasse +[maClasse setNombre:10]; +NSLog(@"%d", [maClasse nombre]); // affiche => 10 +[myClass longeurSet:32]; +NSLog(@"%i", [maClasse longeurGet]); // affiche => 32 +// Pour des raisons pratiques vous pouvez aussi utiliser la notation en point pour accéder aux +// variables d'instances : +maClasse.nombre = 45; +NSLog(@"%i", maClasse.nombre); // maClasse => 45 + +// Appeler un méthode de classe : +NSString *s1 = [MaClasse methodeDeClasse]; +MaClasse *m2 = [MaClasse maClasseDepuisLaHauteur:38]; + +// Appeler un méthode d'instance : +MaClasse *maClasse = [[MaClasse alloc] init]; // Créer une instance de MaClasse +NSString *stringDepuisUneInstanceDeMethode = [maClasse methodeInstanceAvecUnParametre:@"Salut"]; + +// Sélecteurs sont un moyen de représenté les méthodes dynamiquement +// Ils sont utilisé pour appeller des méthodes de classe, passer des methodes au travers de fonctions +// pour notifier les autres classes qu'elle peuvent les appellé, et pour sauvegarder les méthodes en +// tant que variables +// SEL est un type de donnée. @selected retourne un selecteur à partir d'un nom de methode +SEL selecteur = @selector(methodeInstanceAvecUnParametre:puisUnDeuxieme:); +if ([maClasse respondsToSelector:selecteur]) { // Vérifie si la classe contient la méthode + // Doit mettre tous les arguments de la méthode dans un seul objet pour l'envoyer via la fonction + // performSelector:withObject: + NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; + [myClass performSelector:selectorVar withObject:arguments]; // Appele la méthode +} else { + // NSStringFromSelector() retourne une chaine de charactères à partir d'un sélecteur + NSLog(@"MaClasse ne possède pas de méthode : %@", NSStringFromSelector(selecteur)); +} + +// Implement la méthode dans le fichier d'impémentation (MaClasse.m) +@implementation MaClasse { + long distance; // Variable d'instance privé + NSNumber hauteur; +} + +// Pour accéder à une variable depuis le fichier d'implémentation on peut utiliser le _ devant le nom +// de la variable : +_nombre = 5; +// Accès d'une variable définit dans le fichier d'implémentation : +distance = 18; +// Pour utiliser la varible @property dans l'implémentation, utiliser @synthesize qui créer les +// accésseurs : +@synthesize roString = _roString; // _roString est disponible dans l'@implementation + +// Première méthode appelé ++ (void)initialize +{ + if (self == [MaClasse class]) { + distance = 0; + } +} + +// Counterpart to initialize method. Called when an object's reference count is zero. +- (void)dealloc +{ + [height release]; // If not using ARC, make sure to release class variable objects + [super dealloc]; // and call parent class dealloc. +} + +// Constructors are a way of creating instances of a class. +// This is a default constructor which is called when the object is initialized. +- (id)init +{ + if ((self = [super init])) // 'super' used to access methods from parent class. + { + self.count = 1; // 'self' used for object to call itself. + } + return self; +} +// Can create constructors that contain arguments: +- (id)initWithDistance:(int)defaultDistance +{ + distance = defaultDistance; + return self; +} + ++ (NSString *)classMethod +{ + return [[self alloc] init]; +} + ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight +{ + height = defaultHeight; + return [[self alloc] init]; +} + +- (NSString *)instanceMethodWithParameter:(NSString *)string +{ + return @"New string"; +} + +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number +{ + return @42; +} + +// To create a private method, create the method in the @implementation but not in the @interface. +- (NSNumber *)secretPrivateMethod { + return @72; +} +[self secretPrivateMethod]; // Calls private method. + +// Methods declared into MyProtocol +- (void)myProtocolMethod +{ + // statements +} + +@end // States the end of the implementation. + +/* + * A protocol declares methods that can be implemented by any class. + * Protocols are not classes themselves. They simply define an interface + * that other objects are responsible for implementing. + */ +@protocol MyProtocol + - (void)myProtocolMethod; +@end + + +/////////////////////////////////////// +// Memory Management +/////////////////////////////////////// +/* +For each object used in an application, memory must be allocated for that object. When the application +is done using that object, memory must be deallocated to ensure application efficiency. +Objective-C does not use garbage collection and instead uses reference counting. As long as +there is at least one reference to an object (also called "owning" an object), then the object +will be available to use (known as "ownership"). + +When an instance owns an object, its reference counter is increments by one. When the +object is released, the reference counter decrements by one. When reference count is zero, +the object is removed from memory. + +With all object interactions, follow the pattern of: +(1) create the object, (2) use the object, (3) then free the object from memory. +*/ + +MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object. +[classVar release]; // Decrements classVar's reference count. +// 'retain' claims ownership of existing object instance and increments reference count. Returns pointer to object. +MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner. +[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object. + +// @property can use 'retain' and 'assign' as well for small convenient definitions. +@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). +@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). + +// Automatic Reference Counting (ARC) +// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). +// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, +// you must not use retain, relase, or autorelease. +MyClass *arcMyClass = [[MyClass alloc] init]; +// ... code using arcMyClass +// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, +// there is no need. It will insert this release statement for you. + +// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'. +@property (weak) MyClass *weakVar; // 'weak' does not take ownership of object. If original instance's reference count +// is set to zero, weakVar will automatically receive value of nil to avoid application crashing. +@property (strong) MyClass *strongVar; // 'strong' takes ownership of object. Ensures object will stay in memory to use. + +// For regular variables (not @property declared variables), use the following: +__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope. +__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil. +__unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not set to nil when existing object is released. + +``` +## Further Reading + +[La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C) + +[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) + +[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From 42a5b7d305610a98d57c7ad9d576b22f33aeff75 Mon Sep 17 00:00:00 2001 From: Yannick Date: Sun, 12 Jan 2014 22:43:53 +0100 Subject: [NEW] french translation --- fr-fr/objective-c.html.markdown | 73 ++++++++++++++++++++--------------------- 1 file changed, 36 insertions(+), 37 deletions(-) diff --git a/fr-fr/objective-c.html.markdown b/fr-fr/objective-c.html.markdown index b6567382..730687db 100644 --- a/fr-fr/objective-c.html.markdown +++ b/fr-fr/objective-c.html.markdown @@ -375,80 +375,79 @@ distance = 18; // accésseurs : @synthesize roString = _roString; // _roString est disponible dans l'@implementation -// Première méthode appelé -+ (void)initialize -{ - if (self == [MaClasse class]) { - distance = 0; - } -} - -// Counterpart to initialize method. Called when an object's reference count is zero. +// En contre-partie de l'initialisation, la fonction dealloc est appelé quand l'objet est n'est plus +// utilisé - (void)dealloc { - [height release]; // If not using ARC, make sure to release class variable objects - [super dealloc]; // and call parent class dealloc. + [hauteur release]; // Si vous n'utilisez par l'ARC, pensez bien à supprimer l'objet + [super dealloc]; // et à appeler la méthode de la classe parent } -// Constructors are a way of creating instances of a class. -// This is a default constructor which is called when the object is initialized. +// Les constructeurs sont une manière de créer des instances de classes +// Ceci est le constructeur par défaut; il est appelé quand l'objet est créé - (id)init { - if ((self = [super init])) // 'super' used to access methods from parent class. + if ((self = [super init])) // 'super' est utilisé pour appeler la méthode de la classe parent { - self.count = 1; // 'self' used for object to call itself. + self.count = 1; // 'self' est utilisé pour appeler la méthodes de l'objet courrant } return self; } -// Can create constructors that contain arguments: -- (id)initWithDistance:(int)defaultDistance + +// Vous pouvez créer des constructeurs qui possèdent des arguments : +- (id)initAvecUneDistance:(int)distanceParDefault { - distance = defaultDistance; - return self; + if ((self = [super init])) + { + distance = distanceParDefault; + return self; + } } -+ (NSString *)classMethod ++ (NSString *)methodDeClasse { return [[self alloc] init]; } -+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight ++ (MaClasse *)maClasseDepuisUneHauteur:(NSNumber *)hauteurParDefaut { - height = defaultHeight; + hauteur = hauteurParDefaut; return [[self alloc] init]; } -- (NSString *)instanceMethodWithParameter:(NSString *)string +- (NSString *)methodeInstanceAvecUnParametre:(NSString *)string { - return @"New string"; + return @"Ma chaine de charactère"; } -- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number +- (NSNumber *)methodeInstanceAvecUnParametre:(NSString*)string puisUnDeuxieme:(NSNumber *)number { return @42; } -// To create a private method, create the method in the @implementation but not in the @interface. -- (NSNumber *)secretPrivateMethod { +// Pour créer une méthode privée, il faut la définir dans l'@implementation et non pas dans +// l'@interface +- (NSNumber *)methodePrivee +{ return @72; } -[self secretPrivateMethod]; // Calls private method. -// Methods declared into MyProtocol -- (void)myProtocolMethod +[self methodePrivee]; // Appel de la méthode privée + +// Méthode déclarée dans MonProtocole +- (void)methodeDuProtocole { - // statements + // expressions } -@end // States the end of the implementation. +@end // Fin de l'implémentation /* - * A protocol declares methods that can be implemented by any class. - * Protocols are not classes themselves. They simply define an interface - * that other objects are responsible for implementing. + * Un protocole déclare les méthodes qu'ils doivent implémenter afin de se conformer celui-ci + * Un protocole n'est pas une classe, c'est juste une interface */ -@protocol MyProtocol - - (void)myProtocolMethod; +@protocol MonProtocole + - (void)methodeDuProtocole; @end -- cgit v1.2.3 From ae892c802cbd2d62cd205fabe36f303f326683b9 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Fri, 17 Jan 2014 14:38:24 +0800 Subject: php: typo --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index c3317d59..e1bb86a0 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -212,7 +212,7 @@ assert($c >= $d); // The following will only be true if the values match and are the same type. assert($c === $d); assert($a !== $d); -assert(1 == '1'); +assert(1 === '1'); assert(1 !== '1'); // Variables can be converted between types, depending on their usage. -- cgit v1.2.3 From d2a34d3390e131f738f6f54b95a1101966f4ea5d Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Fri, 17 Jan 2014 14:47:54 +0800 Subject: php: typo --- zh-cn/php-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/php-cn.html.markdown b/zh-cn/php-cn.html.markdown index c6ebb515..c22d8e12 100644 --- a/zh-cn/php-cn.html.markdown +++ b/zh-cn/php-cn.html.markdown @@ -180,7 +180,7 @@ assert($c >= $d); // 下面的比较只有在类型相同、值相同的情况下才为真 assert($c === $d); assert($a !== $d); -assert(1 == '1'); +assert(1 === '1'); assert(1 !== '1'); // 变量可以根据其使用来进行类型转换 -- cgit v1.2.3 From 6c2210e92172b0a5cb5ab9eaf09cbd60a6d73c13 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Fri, 17 Jan 2014 14:50:29 +0800 Subject: php: typo --- zh-cn/php-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/php-cn.html.markdown b/zh-cn/php-cn.html.markdown index c6ebb515..9c344ef6 100644 --- a/zh-cn/php-cn.html.markdown +++ b/zh-cn/php-cn.html.markdown @@ -243,7 +243,7 @@ if ($x === '0') { -// 下面的语法常用语模板中: +// 下面的语法常用于模板中: ?> -- cgit v1.2.3 From f47de5a0972de32050cd1fbc7be0ec8eb9f51636 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Fri, 17 Jan 2014 15:12:05 +0800 Subject: php:typo --- zh-cn/php-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/php-cn.html.markdown b/zh-cn/php-cn.html.markdown index c6ebb515..e29b6771 100644 --- a/zh-cn/php-cn.html.markdown +++ b/zh-cn/php-cn.html.markdown @@ -333,7 +333,7 @@ function my_function () { echo my_function(); // => "Hello" // 函数名需要以字母或者下划线开头, -// 后面可以跟着任意的字幕、下划线、数字. +// 后面可以跟着任意的字母、下划线、数字. function add ($x, $y = 1) { // $y 是可选参数,默认值为 1 $result = $x + $y; -- cgit v1.2.3 From c43c033646f87b735246bb5c681945b72cc4855c Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sun, 19 Jan 2014 16:10:58 +1030 Subject: Fixed `) {` vs `){` inconsistency --- javascript.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 7fb7ba55..a9d73cf1 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -175,14 +175,14 @@ myObj.myFourthKey; // = undefined var count = 1; if (count == 3){ // evaluated if count is 3 -} else if (count == 4) { +} else if (count == 4){ // evaluated if count is 4 } else { // evaluated if it's not either 3 or 4 } // As does while. -while (true) { +while (true){ // An infinite loop! } @@ -327,7 +327,7 @@ var anotherFunc = function(s){ } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" -// The 'apply' function is nearly identical, but takes an array for an argument list. +// The 'apply' function is nearly identical, but takes an array for an argument list. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" -- cgit v1.2.3 From b0755aa7058f6c062f2888bd1774ab5ffe885f96 Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 19 Jan 2014 20:33:06 -0800 Subject: Added Clojure macros --- clojure-macros.html.markdown | 152 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 clojure-macros.html.markdown diff --git a/clojure-macros.html.markdown b/clojure-macros.html.markdown new file mode 100644 index 00000000..8e671936 --- /dev/null +++ b/clojure-macros.html.markdown @@ -0,0 +1,152 @@ +--- +language: "clojure macros" +filename: learnclojuremacros.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +--- + +As with all Lisps, Clojure's inherent [homoiconicity](https://en.wikipedia.org/wiki/Homoiconic) +gives you access to the full extent of the language to write code-generation routines +called "macros". Macros provide a powerful way to tailor the language to your needs. + +Be careful though. It's considered bad form to write a macro when a function will do. +Use a macro only when you need control over when or if the arguments to a form will +be evaluated. + +You'll want to be familiar with Clojure. Make sure you understand everything in +[Clojure in Y Minutes](/docs/clojure/). + +```clojure +;; Define a macro using defmacro. Your macro should output a list that can +;; be evaluated as clojure code. +;; +;; This macro is the same as if you wrote (reverse "Hello World") +(defmacro my-first-macro [] + (list reverse "Hello World")) + +;; Inspect the result of a macro using macroexpand or macroexpand-1. +;; +;; Note that the call must be quoted. +(macroexpand '(my-first-macro)) +;; -> (# "Hello World") + +;; You can eval the result of macroexpand directly: +(eval (macroexpand '(my-first-macro))) +; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; But you should use this more succinct, function-like syntax: +(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; You can make things easier on yourself by using the more succinct quote syntax +;; to create lists in your macros: +(defmacro my-first-quoted-macro [] + '(reverse "Hello World")) + +(macroexpand '(my-first-quoted-macro)) +;; -> (reverse "Hello World") +;; Notice that reverse is no longer function object, but a symbol. + +;; Macros can take arguments. +(defmacro inc2 [arg] + (list + 2 arg)) + +(inc2 2) ; -> 4 + +;; But, if you try to do this with a quoted list, you'll get an error, because +;; the argument will be quoted too. To get around this, clojure provides a +;; way of quoting macros: `. Inside `, you can use ~ to get at the outer scope +(defmacro inc2-quoted [arg] + `(+ 2 ~arg)) + +(inc2-quoted 2) + +;; You can use the usual destructuring args. Expand list variables using ~@ +(defmacro unless [arg & body] + `(if (not ~arg) + (do ~@body))) ; Remember the do! + +(macroexpand '(unless true (reverse "Hello World"))) +;; -> +;; (if (clojure.core/not true) (do (reverse "Hello World"))) + +;; (unless) evaluates and returns its body if the first argument is false. +;; Otherwise, it returns nil + +(unless true "Hello") ; -> nil +(unless false "Hello") ; -> "Hello" + +;; Used without care, macros can do great evil by clobbering your vars +(defmacro define-x [] + '(do + (def x 2) + (list x))) + +(def x 4) +(define-x) ; -> (2) +(list x) ; -> (2) + +;; To avoid this, use gensym to get a unique identifier +(gensym 'x) ; -> x1281 (or some such thing) + +(defmacro define-x-safely [] + (let [sym (gensym 'x)] + `(do + (def ~sym 2) + (list ~sym)))) + +(def x 4) +(define-x-safely) ; -> (2) +(list x) ; -> (4) + +;; You can use # within ` to produce a gensym for each symbol automatically +(defmacro define-x-hygenically [] + `(do + (def x# 2) + (list x#))) + +(def x 4) +(define-x-hygenically) ; -> (2) +(list x) ; -> (4) + +;; It's typical to use helper functions with macros. Let's create a few to +;; help us support a (dumb) inline arithmatic syntax +(declare inline-2-helper) +(defn clean-arg [arg] + (if (seq? arg) + (inline-2-helper arg) + arg)) + +(defn apply-arg + "Given args [x (+ y)], return (+ x y)" + [val [op arg]] + (list op val (clean-arg arg))) + +(defn inline-2-helper + [[arg1 & ops-and-args]] + (let [ops (partition 2 ops-and-args)] + (reduce apply-arg (clean-arg arg1) ops))) + +;; We can test it immediately, without creating a macro +(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5)) + +; However, we'll need to make it a macro if we want it to be run at compile time +(defmacro inline-2 [form] + (inline-2-helper form))) + +(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) +; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) + +(inline-2 (1 + (3 / 2) - (1 / 2) + 1)) +; -> 3 (actually, 3N, since the number got cast to a rational fraction with /) +``` + +### Further Reading + +Writing Macros from [Clojure for the Brave and True](http://www.braveclojure.com/) +[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/) + +Official docs +[http://clojure.org/macros](http://clojure.org/macros) + +When to use macros? +[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html) -- cgit v1.2.3 From a35126f22e481fa154c6cc7252bf4d91dced2607 Mon Sep 17 00:00:00 2001 From: Yannick Date: Mon, 20 Jan 2014 22:42:23 +0100 Subject: [UPDATE] MRC section --- fr-fr/objective-c.html.markdown | 44 ++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/fr-fr/objective-c.html.markdown b/fr-fr/objective-c.html.markdown index 730687db..610283aa 100644 --- a/fr-fr/objective-c.html.markdown +++ b/fr-fr/objective-c.html.markdown @@ -452,32 +452,32 @@ distance = 18; /////////////////////////////////////// -// Memory Management +// Gestion de la mémoire /////////////////////////////////////// /* -For each object used in an application, memory must be allocated for that object. When the application -is done using that object, memory must be deallocated to ensure application efficiency. -Objective-C does not use garbage collection and instead uses reference counting. As long as -there is at least one reference to an object (also called "owning" an object), then the object -will be available to use (known as "ownership"). - -When an instance owns an object, its reference counter is increments by one. When the -object is released, the reference counter decrements by one. When reference count is zero, -the object is removed from memory. - -With all object interactions, follow the pattern of: -(1) create the object, (2) use the object, (3) then free the object from memory. +Pour chaque objet utilisé dans une application, la mémoire doit être alloué pour chacun d'entre eux. +Quand l'application en a fini avec cet objet, la mémoire doit être libéré pour assurer la performane. +Il n'y a pas de ramasse-miettes en Objective-C, il utilise à la place le comptage de référence à la +place. Tant que le compteur de référence est supérieur à 1 sur un objet, l'objet ne sera pas supprimé. + +Quand une instance détient un objet, le compteur de référence est incrémenté de un. Quand l'objet est +libéré, le compteur est décrémenté de un. Quand le compteur est égale à zéro, l'objet est supprimé de +la mémoire. + +Une bonne pratique à suivre quand on travaille avec des objets est la suivante : +(1) créer un objet, (2) utiliser l'objet, (3) supprimer l'objet de la mémoire. */ -MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object. -[classVar release]; // Decrements classVar's reference count. -// 'retain' claims ownership of existing object instance and increments reference count. Returns pointer to object. -MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner. -[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object. +MaClasse *classeVar = [MyClass alloc]; // 'alloc' incrémente le compteur de référence +[classeVar release]; // Décrémente le compteur de rérence +// 'retain' incrémente le compteur de référence +// Si 'classeVar' est libéré, l'objet reste en mémoire car le compteur de référence est non nulle +MaClasse *nouvelleVar = [classVar retain]; +[classeVar autorelease]; // Supprime l'appartenance de l'objet à la fin du block -// @property can use 'retain' and 'assign' as well for small convenient definitions. -@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). -@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). +// @property peuvent utiliser 'retain' et 'assign' +@property (retain) MaClasse *instance; // Libère l'ancienne valeur et retient la nouvelle +@property (assign) NSSet *set; // Pointeur vers la valeur sans retenir/libérer l'ancienne valeur // Automatic Reference Counting (ARC) // Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). @@ -499,7 +499,7 @@ __weak NSSet *weakSet; // Weak reference to existing object. When existing objec __unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not set to nil when existing object is released. ``` -## Further Reading +## Lectures Complémentaires [La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C) -- cgit v1.2.3 From 08107bef21fad628b617bbc4a5e2e79d5638da72 Mon Sep 17 00:00:00 2001 From: Renjith G R Date: Wed, 22 Jan 2014 10:52:24 +0530 Subject: Fixed capitalization in the word JavaScript Changed Javascript to JavaScript in the first paragraph. --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index a9d73cf1..cef5b4b9 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -5,7 +5,7 @@ contributors: filename: javascript.js --- -Javascript was created by Netscape's Brendan Eich in 1995. It was originally +JavaScript was created by Netscape's Brendan Eich in 1995. It was originally intended as a simpler scripting language for websites, complimenting the use of Java for more complex web applications, but its tight integration with Web pages and built-in support in browsers has caused it to become far more common than -- cgit v1.2.3 From 845dc497adbfe2ec149f7ba7e62a25b146dd8e23 Mon Sep 17 00:00:00 2001 From: Renjith G R Date: Wed, 22 Jan 2014 11:22:07 +0530 Subject: Fix capitalization in the word JavaScript There were two more other places where JavaScript was written as Javascript. --- javascript.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index cef5b4b9..85c5d817 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -37,7 +37,7 @@ doStuff() /////////////////////////////////// // 1. Numbers, Strings and Operators -// Javascript has one number type (which is a 64-bit IEEE 754 double). +// JavaScript has one number type (which is a 64-bit IEEE 754 double). // As with Lua, don't freak out about the lack of ints: doubles have a 52-bit // mantissa, which is enough to store integers up to about 9✕10¹⁵ precisely. 3; // = 3 @@ -116,7 +116,7 @@ undefined; // used to indicate a value is not currently present (although /////////////////////////////////// // 2. Variables, Arrays and Objects -// Variables are declared with the var keyword. Javascript is dynamically typed, +// Variables are declared with the var keyword. JavaScript is dynamically typed, // so you don't need to specify type. Assignment uses a single = character. var someVar = 5; @@ -477,7 +477,7 @@ more about how to use JavaScript in web pages, start by learning about the [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) -[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth guide of all the counter-intuitive parts of the language. In addition to direct contributors to this article, some content is adapted -- cgit v1.2.3 From 400b00aa87a98f0601a566f94038d2b2197aae1a Mon Sep 17 00:00:00 2001 From: Laban Kimotho Date: Fri, 24 Jan 2014 10:59:53 +0200 Subject: typo fixes + view generated low level code --- julia.html.markdown | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 77 insertions(+), 2 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 4b946d46..58ff7608 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -427,7 +427,7 @@ end keyword_args(name2="ness") #=> ["name2"=>"ness","k1"=>4] keyword_args(k1="mine") #=> ["k1"=>"mine","name2"=>"hello"] -keyword_args() #=> ["name2"=>"hello","k2"=>4] +keyword_args() #=> ["name2"=>"hello","k1"=>4] # You can combine all kinds of arguments in the same function function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") @@ -560,7 +560,7 @@ type Panther <: Cat # Panther is also a subtype of Cat Panther() = new("green") # Panthers will only have this constructor, and no default constructor. end -# Using inner constructors, like Panter does, gives you control +# Using inner constructors, like Panther does, gives you control # over how values of the type can be created. # When possible, you should use outer constructors rather than inner ones. @@ -657,6 +657,81 @@ fight(Lion("RAR"),Lion("brown","rarrr")) #=> prints The victorious cat says rarr fight(l::Lion,l2::Lion) = println("The lions come to a tie") fight(Lion("RAR"),Lion("brown","rarrr")) #=> prints The lions come to a tie + +# Under the hood +# You can take a look at the llvm intermediate code and the assembly code generated. + +square_area(l) = l * l # square_area (generic function with 1 method) + +square_area(5) #25 + +code_native(square_area, (Int32,)) # What happens when we feed square_area an integer? + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 # Prologue + # push RBP + # mov RBP, RSP + # Source line: 1 + # movsxd RAX, EDI # Fetch l from memory? + # imul RAX, RAX # 32bit square of l and store the result in RAX + # pop RBP # Restore old base pointer + # ret # Result will still be in RAX + +code_native(square_area, (Float32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiplication (AVX) (in this case square the number) + # pop RBP + # ret + +code_native(square_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiplacation (AVX) + # pop RBP + # ret + # +# Note that julia will use floating point instructions if any of the arguements are floats. +# Let's calculate the area of a circle +circle_area(r) = pi * r * r # circle_area (generic function with 1 method) +circle_area(5) # 78.53981633974483 + +code_native(circle_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory + # movabs RAX, 4593140240 # Load pi + # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r + # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r + # pop RBP + # ret + # + +code_native(circle_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # movabs RAX, 4593140496 + # Source line: 1 + # vmulsd XMM1, XMM0, QWORD PTR [RAX] + # vmulsd XMM0, XMM1, XMM0 + # pop RBP + # ret + # ``` ## Further Reading -- cgit v1.2.3 From c705d16a3e0b49f274564b3e61faa219ab63bd78 Mon Sep 17 00:00:00 2001 From: Laban Kimotho Date: Fri, 24 Jan 2014 11:06:41 +0200 Subject: style fixes --- julia.html.markdown | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 58ff7608..3bc660cf 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -659,23 +659,24 @@ fight(Lion("RAR"),Lion("brown","rarrr")) #=> prints The lions come to a tie # Under the hood -# You can take a look at the llvm intermediate code and the assembly code generated. +# You can take a look at the llvm and the assembly code generated. square_area(l) = l * l # square_area (generic function with 1 method) square_area(5) #25 -code_native(square_area, (Int32,)) # What happens when we feed square_area an integer? +# What happens when we feed square_area an integer? +code_native(square_area, (Int32,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none - # Source line: 1 # Prologue + # Source line: 1 # Prologue # push RBP # mov RBP, RSP # Source line: 1 - # movsxd RAX, EDI # Fetch l from memory? - # imul RAX, RAX # 32bit square of l and store the result in RAX - # pop RBP # Restore old base pointer - # ret # Result will still be in RAX + # movsxd RAX, EDI # Fetch l from memory? + # imul RAX, RAX # Square l and store the result in RAX + # pop RBP # Restore old base pointer + # ret # Result will still be in RAX code_native(square_area, (Float32,)) # .section __TEXT,__text,regular,pure_instructions @@ -684,7 +685,7 @@ code_native(square_area, (Float32,)) # push RBP # mov RBP, RSP # Source line: 1 - # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiplication (AVX) (in this case square the number) + # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) # pop RBP # ret @@ -695,11 +696,12 @@ code_native(square_area, (Float64,)) # push RBP # mov RBP, RSP # Source line: 1 - # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiplacation (AVX) + # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) # pop RBP # ret # -# Note that julia will use floating point instructions if any of the arguements are floats. +# Note that julia will use floating point instructions if any of the +# arguements are floats. # Let's calculate the area of a circle circle_area(r) = pi * r * r # circle_area (generic function with 1 method) circle_area(5) # 78.53981633974483 @@ -711,10 +713,10 @@ code_native(circle_area, (Int32,)) # push RBP # mov RBP, RSP # Source line: 1 - # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory - # movabs RAX, 4593140240 # Load pi - # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r - # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r + # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory + # movabs RAX, 4593140240 # Load pi + # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r + # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r # pop RBP # ret # -- cgit v1.2.3 From 15dcc4a6ce1d7df54292925f4d0af4a8af87eea8 Mon Sep 17 00:00:00 2001 From: Yannick Date: Fri, 24 Jan 2014 18:36:30 +0100 Subject: [UPDATE] French Translation --- fr-fr/objective-c.html.markdown | 46 +++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/fr-fr/objective-c.html.markdown b/fr-fr/objective-c.html.markdown index 610283aa..e6a8abfb 100644 --- a/fr-fr/objective-c.html.markdown +++ b/fr-fr/objective-c.html.markdown @@ -458,14 +458,14 @@ distance = 18; Pour chaque objet utilisé dans une application, la mémoire doit être alloué pour chacun d'entre eux. Quand l'application en a fini avec cet objet, la mémoire doit être libéré pour assurer la performane. Il n'y a pas de ramasse-miettes en Objective-C, il utilise à la place le comptage de référence à la -place. Tant que le compteur de référence est supérieur à 1 sur un objet, l'objet ne sera pas supprimé. +place. Tant que le compteur de référence est supérieur à 1 sur un objet, l'objet ne sera pas supprimé Quand une instance détient un objet, le compteur de référence est incrémenté de un. Quand l'objet est libéré, le compteur est décrémenté de un. Quand le compteur est égale à zéro, l'objet est supprimé de -la mémoire. +la mémoire Une bonne pratique à suivre quand on travaille avec des objets est la suivante : -(1) créer un objet, (2) utiliser l'objet, (3) supprimer l'objet de la mémoire. +(1) créer un objet, (2) utiliser l'objet, (3) supprimer l'objet de la mémoire */ MaClasse *classeVar = [MyClass alloc]; // 'alloc' incrémente le compteur de référence @@ -480,29 +480,31 @@ MaClasse *nouvelleVar = [classVar retain]; @property (assign) NSSet *set; // Pointeur vers la valeur sans retenir/libérer l'ancienne valeur // Automatic Reference Counting (ARC) -// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). -// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, -// you must not use retain, relase, or autorelease. -MyClass *arcMyClass = [[MyClass alloc] init]; -// ... code using arcMyClass -// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, -// there is no need. It will insert this release statement for you. - -// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'. -@property (weak) MyClass *weakVar; // 'weak' does not take ownership of object. If original instance's reference count -// is set to zero, weakVar will automatically receive value of nil to avoid application crashing. -@property (strong) MyClass *strongVar; // 'strong' takes ownership of object. Ensures object will stay in memory to use. - -// For regular variables (not @property declared variables), use the following: -__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope. -__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil. -__unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not set to nil when existing object is released. +// La gestion de la mémoire étant pénible, depuis iOS 4 et Xcode 4.2, Apple a introduit le comptage de référence +// automatique (Automatic Reference Counting en anglais). +// ARC est une fonctionnalité du compilateur qui lui permet d'ajouter les 'retain', 'release' et 'autorelease' +// automatiquement. Donc quand utilisez ARC vous de devez plus utiliser ces mots clés +MaClasse *arcMaClasse = [[MaClasse alloc] init]; +// ... code utilisant arcMaClasse +// Sans ARC, vous auriez dû appeler [arcMaClasse release] après avoir utilisé l'objet. Mais avec ARC il n'y a plus +// besoin car le compilateur ajoutera l'expréssion automatiquement pour vous + +// Les mots clés 'assign' et 'retain', avec ARC sont respectivement remplacé par 'weak' et 'strong' +@property (weak) MaClasse *weakVar; // 'weak' ne retient pas l'objet. Si l'instance original descend à zero, weakVar +// sera automatiquement mis à nil +@property (strong) MaClasse *strongVar; // 'strong' prend posséssion de l'objet comme le ferai le mot clé 'retain' + +// Pour l'instanciation des variables (en dehors de @property), vous pouvez utiliser les instructions suivantes : +__strong NSString *strongString; // Par defaut. La variable est retenu en mémoire jusqu'à la fin de sa portée +__weak NSSet *weakSet; // Réfère la variable en utilisant le mot clé '__weak' +__unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais quand la variable n'est pas mis à nil quand l'objet +// est supprimé ailleurs ``` ## Lectures Complémentaires [La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C) -[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) +[iOS pour les écoliers : Votre première app iOS](http://www.raywenderlich.com/fr/39272/ios-pour-les-ecoliers-votre-premiere-app-ios-partie-12) -[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) +[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) \ No newline at end of file -- cgit v1.2.3 From 3dae1ab745c2f3e5eae0a9d47c0b848f3ed44730 Mon Sep 17 00:00:00 2001 From: Yannick Date: Fri, 24 Jan 2014 18:43:22 +0100 Subject: [FIX] Objective-C French Translation Filename --- fr-fr/objective-c-fr.html.markdown | 510 +++++++++++++++++++++++++++++++++++++ fr-fr/objective-c.html.markdown | 510 ------------------------------------- 2 files changed, 510 insertions(+), 510 deletions(-) create mode 100644 fr-fr/objective-c-fr.html.markdown delete mode 100644 fr-fr/objective-c.html.markdown diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown new file mode 100644 index 00000000..e6a8abfb --- /dev/null +++ b/fr-fr/objective-c-fr.html.markdown @@ -0,0 +1,510 @@ +--- + +language: Objective-C +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] + - ["Levi Bostian", "https://github.com/levibostian"] +translators: + - ["Yannick Loriot", "https://github.com/YannickL"] +filename: LearnObjectiveC.m + +--- + +L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs framworks respectifs, Cocoa et Cocoa Touch. + +```objective-c +// Les commentaires unilignes commencent par // + +/* +Les commentaires multilignes ressemblent à ça +*/ + +// Importe les en-têtes en utilisant #import +// Utilisez <> pour importer des fichiers globaux (en général des frameworks) +// Utilisez "" pour importer des fichiers locaux (du projet) +#import +#import "MaClasse.h" + +// Si vous activez les modules pour les projects iOS >= 7 ou Mac OS X >= 10.9 +// dans Xcode 5 vous pouvez importer les frameworks comme cela : +@import Foundation; + +// Le point d'entrée de votre programme est une fonction qui s'appelle main +// et qui return un entier comme type +int main (int argc, const char * argv[]) +{ + // Créer un groupe de libération automatique de la mémoire pour l'ensemble + // du programme + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + // Si vous utilisez le comptage de référence automatique (ARC), utilisez + // @autoreleasepool à la place : + @autoreleasepool { + + // Utilisez NSLog pour afficher les lignes sur la console + // Affiche la chaine de caractères "Bonjour Tous Le Monde !" + NSLog(@"Bonjour tous le Monde !"); + + /////////////////////////////////////// + // Les Types & Les Variables + /////////////////////////////////////// + + // Déclarations de primitive + int maPrimitive1 = 1; + long maPrimitive2 = 234554664565; + + // Declarations d'objets + // Il faut mettre l'* devant la déclaration d'objets fortement typés + MaClasse *monObject1 = nil; // Typage fort + id monObject2 = nil; // Typage faible + // %@ est un objet + // 'description' est une convention pour afficher la valeur des objets + NSLog(@"%@ and %@", monObject1, [monObject2 description]); // Affiche "(null) et (null)" + + // Chaines de caractères + NSString *chaineMonde = @"Monde"; + NSLog(@"Bonjour tous le %@ !", chaineMonde); // affiche => "Bonjour Tous Le Monde !" + // NSMutableString est une chaine mutable + NSMutableString *chaineMutable = [NSMutableString stringWithString:@"Bonjour tous le"]; + [chaineMutable appendString:@" Monde !"]; + NSLog(@"%@", chaineMutable); // affiche => "Bonjour Tous Le Monde !" + + // Les littéraux pour les caratères + NSNumber *laLettreZSousFormeDeNombre = @'Z'; + char laLettreZ = [laLettreZSousFormeDeNombre charValue]; // ou 'Z' + NSLog(@"%c", laLettreZ); + + // Les littéraux pour les nombres + NSNumber *nombreQuaranteDeux = @42; + int quaranteDeux = [nombreQuaranteDeux intValue]; // ou 42 + NSLog(@"%i", quaranteDeux); + + NSNumber *nombreQuaranteDeuxnonSigne = @42U; + unsigned int quaranteDeuxnonSigne = [nombreQuaranteDeuxnonSigne unsignedIntValue]; + NSLog(@"%u", fortyTwoUnsigned); + + NSNumber *nombreQuaranteDeuxCourt = [NSNumber numberWithShort:42]; + short quaranteDeuxCourt = [nombreQuaranteDeuxCourt shortValue]; // ou 42 + NSLog(@"%hi", fortyTwoShort); + + NSNumber *nombreQuaranteDeuxLong = @42L; + long quaranteDeuxLong = [nombreQuaranteDeuxLong longValue]; // ou 42 + NSLog(@"%li", fortyTwoLong); + + // Les littéraux pour les flottans + NSNumber *nombrePiFlottan = @3.141592654F; + float piFlottan = [nombrePiFlottan floatValue]; // ou 3.141592654f + NSLog(@"%f", piFlottan); // affiche => 3.141592654 + NSLog(@"%5.2f", piFlottan); // affiche => " 3.14" + + NSNumber *nombrePiDouble = @3.1415926535; + double piDouble = [nombrePiDouble doubleValue]; // ou 3.1415926535 + NSLog(@"%f", piDouble); + NSLog(@"%4.2f", piDouble); // affiche => "3.14" + + // NSDecimalNumber est une classe pour avoir plus de précision sur les flottans + // et les doubles + NSDecimalNumber *decNumUn = [NSDecimalNumber decimalNumberWithString:@"10.99"]; + NSDecimalNumber *decNumDeux = [NSDecimalNumber decimalNumberWithString:@"5.002"]; + // NSDecimalNumber n'est pas capable d'utiliser les opérations standards : + // +, -, *, /, il utilise donc ses propres fonctions : + [decNumUn decimalNumberByAdding:decNumDeux]; + [decNumUn decimalNumberBySubtracting:decNumDeux]; + [decNumUn decimalNumberByMultiplyingBy:decNumDeux]; + [decNumUn decimalNumberByDividingBy:decNumDeux]; + NSLog(@"%@", decNumUn); // affiche => 10.99 comme NSDecimalNumber is immuable + + // Les littéraux pour les booléens + NSNumber *ouiNumber = @YES; + NSNumber *nonNumber = @NO; + // ou + BOOL ouiBool = YES; + BOOL nonBool = NO; + NSLog(@"%i", ouiBool); // affiche => 1 + + // Les listes + // Ils peuvent contenir différents types de données, mais ils doivent absolument + // être des objets + NSArray *uneListe = @[@1, @2, @3, @4]; + NSNumber *troisiemeNombre = uneListe[2]; + NSLog(@"Troisième nombre = %@", troisiemeNombre); // affiche "Troisième nombre = 3" + // NSMutableArray est une version mutable de NSArray qui permet de changer les + // objets dans la liste et l'étendre ou la réduire + // C'est très pratique, mais pas aussi performant que l'utilsation de la classe + // NSArray + NSMutableArray *listeMutable = [NSMutableArray arrayWithCapacity:2]; + [listeMutable addObject:@"Bonjour tous le"]; + [listeMutable addObject:@"Monde"]; + [listeMutable removeObjectAtIndex:0]; + NSLog(@"%@", [listeMutable objectAtIndex:0]); // affiche => "Monde" + + // Les dictionnaires + NSDictionary *unDictionnaire = @{ @"cle1" : @"valeur1", @"cle2" : @"valeur2" }; + NSObject *valeur = unDictionnaire[@"Une clé"]; + NSLog(@"Objet = %@", valeur); // affiche "Objet = (null)" + // NSMutableDictionary est un dictionnaire mutable + NSMutableDictionary *dictionnaireMutable = [NSMutableDictionary dictionaryWithCapacity:2]; + [dictionnaireMutable setObject:@"valeur1" forKey:@"cle1"]; + [dictionnaireMutable setObject:@"valeur2" forKey:@"cle2"]; + [dictionnaireMutable removeObjectForKey:@"cle1"]; + + // Les ensembles + NSSet *ensemble = [NSSet setWithObjects:@"Salut", @"Salut", @"Monde", nil]; + NSLog(@"%@", ensemble); // affiche => {(Salut, Monde)} (peut être dans un ordre différente) + // NSMutableSet est un ensemble mutable + NSMutableSet *ensembleMutable = [NSMutableSet setWithCapacity:2]; + [ensembleMutable addObject:@"Salut"]; + [ensembleMutable addObject:@"Salut"]; + NSLog(@"%@", ensembleMutable); // affiche => {(Salut)} + + /////////////////////////////////////// + // Operateurs + /////////////////////////////////////// + + // Les opérateurs sont les mêmes que ceux du langage C + // Par exemple : + 2 + 5; // => 7 + 4.2f + 5.1f; // => 9.3f + 3 == 2; // => 0 (NO) + 3 != 2; // => 1 (YES) + 1 && 1; // => 1 (et logique) + 0 || 1; // => 1 (ou logique) + ~0x0F; // => 0xF0 (négation bit à bit) + 0x0F & 0xF0; // => 0x00 (et bit à bit) + 0x01 << 1; // => 0x02 (décale à gauche (par 1)) + + /////////////////////////////////////// + // Structures de controle + /////////////////////////////////////// + + // Expression If-Else + if (NO) + { + NSLog(@"Je ne suis jamais affiché"); + } else if (0) + { + NSLog(@"Je ne suis jamais affiché aussi"); + } else + { + NSLog(@"Je suis affiché"); + } + + // Expression Switch + switch (2) + { + case 0: + { + NSLog(@"Je ne suis jamais affiché"); + } break; + case 1: + { + NSLog(@"Je ne suis jamais affiché aussi"); + } break; + default: + { + NSLog(@"Je suis affiché"); + } break; + } + + // Expression de boucle While + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++ incrémente ii après avoir utilisé sa valeure + } // => affiche "0," + // "1," + // "2," + // "3," + + // Expression de boucle For loops + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", jj); + } // => affiche "0," + // "1," + // "2," + // "3," + + // Expression de boucle Foreach + NSArray *valeurs = @[@0, @1, @2, @3]; + for (NSNumber *valeur in valeurs) + { + NSLog(@"%@,", valeur); + } // => affiche "0," + // "1," + // "2," + // "3," + + // Expressions Try-Catch-Finally + @try + { + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"Fichier non trouvé" userInfo:nil]; + } @catch (NSException * e) + { + NSLog(@"Exception : %@", e); + } @finally + { + NSLog(@"Finalement"); + } // => affiche "Exceptio : Fichier non trouvé" + // "Finalement" + + /////////////////////////////////////// + // Objets + /////////////////////////////////////// + + // Créez une instance d'objet en allouant un espace mémoire puis en l'initialisant + // Un objet n'est pas complétement fonctionnel jusqu'à ce que les deux étapes précédente + // ne sont pas fini + MaClass *monObjet = [[MaClass alloc] init]; + + // Le modèle Objective-C est basé sur l'envoie de message et non sur les appels de + // méthodes comme la plupart des autres langage de programmation + [myObject instanceMethodWithParameter:@"Steve Jobs"]; + + // Nettoie la mémoire que vous avez utilisé dans votre programme + [pool drain]; + + // Fin the l'@autoreleasepool + } + + // Fin du programme + return 0; +} + +/////////////////////////////////////// +// Classes et Fonctions +/////////////////////////////////////// + +// Déclarez votre classe dans une en-tête de fichier (MaClasse.h) : +// La syntaxe de déclaration : +// @interface NomDeLaClasse : NomDeLaClasseParent +// { +// type nom; <= declarations de variable; +// } +// @property type nom; <= declarations de propriété. +// -/+ (type) Methode declarations; <= Declarations de methodes. +// @end +// NSObject est la classe de base de l'Objective-C +@interface MaClasse : NSObject +{ + // Déclaration des variables d'instances (peut existé soit dans l'interface soir dans + // l'implémentation) + int nombre; // Accès protégé par défaut + @private id donnee; // Accès privé (il est plus pratique de le faire dans l'implémentation) + NSString *nom; +} +// Notation pratique pour l'accès aux variable public et pour générrer les +// accésseurs/affecteurs +// Par défaut, le nom de l'affecteur vaut 'set' suivi par le nom de la @property +@property int propInt; // Nom du setter = 'setPropInt' +@property (copy) id copyId; // (copy) => Copie l'objet pendant l'affectation +// (readonly) => Ne peut pas affecté la variable en dehors de l'@interface +// Utilisez @synthesize dans l'@implementation pour créer l'accésseur +@property (readonly) NSString *roString; +// Vous pouvez personnaliser les noms des accésseurs et des affecteurs au lieu d'utiliser les +// noms par défauts +@property (getter=longeurGet, setter=longeurSet:) int longeur; + +// Methodes ++/- (type de retour)signatureDeLaMethode:(Type Du Parametre *)nomDuParametre; + +// + pour les méthodes de classe : ++ (NSString *)methodeDeClasse; ++ (MaClasse *)maClasseDepuisLaHauteur:(NSNumber *)hauteurParDefaut; + +// - pour les méthodes d'instances : +- (NSString *)methodeInstanceAvecUnParametre:(NSString *)string; +- (NSNumber *)methodeInstanceAvecUnParametre:(NSString*)string puisUnDeuxieme:(NSNumber *)number; + +// Contructeur avec des arguments : +- (id)initAvecDistance:(int)distanceParDefault; +// Les méthodes en Objective-C sont très descriptive + +@end // Définit la fin de l'interface + + +// Exemple d'utilisation de MaClasse +MaClasse *maClasse = [[MaClasse alloc] init]; // créer une instance de MaClasse +[maClasse setNombre:10]; +NSLog(@"%d", [maClasse nombre]); // affiche => 10 +[myClass longeurSet:32]; +NSLog(@"%i", [maClasse longeurGet]); // affiche => 32 +// Pour des raisons pratiques vous pouvez aussi utiliser la notation en point pour accéder aux +// variables d'instances : +maClasse.nombre = 45; +NSLog(@"%i", maClasse.nombre); // maClasse => 45 + +// Appeler un méthode de classe : +NSString *s1 = [MaClasse methodeDeClasse]; +MaClasse *m2 = [MaClasse maClasseDepuisLaHauteur:38]; + +// Appeler un méthode d'instance : +MaClasse *maClasse = [[MaClasse alloc] init]; // Créer une instance de MaClasse +NSString *stringDepuisUneInstanceDeMethode = [maClasse methodeInstanceAvecUnParametre:@"Salut"]; + +// Sélecteurs sont un moyen de représenté les méthodes dynamiquement +// Ils sont utilisé pour appeller des méthodes de classe, passer des methodes au travers de fonctions +// pour notifier les autres classes qu'elle peuvent les appellé, et pour sauvegarder les méthodes en +// tant que variables +// SEL est un type de donnée. @selected retourne un selecteur à partir d'un nom de methode +SEL selecteur = @selector(methodeInstanceAvecUnParametre:puisUnDeuxieme:); +if ([maClasse respondsToSelector:selecteur]) { // Vérifie si la classe contient la méthode + // Doit mettre tous les arguments de la méthode dans un seul objet pour l'envoyer via la fonction + // performSelector:withObject: + NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; + [myClass performSelector:selectorVar withObject:arguments]; // Appele la méthode +} else { + // NSStringFromSelector() retourne une chaine de charactères à partir d'un sélecteur + NSLog(@"MaClasse ne possède pas de méthode : %@", NSStringFromSelector(selecteur)); +} + +// Implement la méthode dans le fichier d'impémentation (MaClasse.m) +@implementation MaClasse { + long distance; // Variable d'instance privé + NSNumber hauteur; +} + +// Pour accéder à une variable depuis le fichier d'implémentation on peut utiliser le _ devant le nom +// de la variable : +_nombre = 5; +// Accès d'une variable définit dans le fichier d'implémentation : +distance = 18; +// Pour utiliser la varible @property dans l'implémentation, utiliser @synthesize qui créer les +// accésseurs : +@synthesize roString = _roString; // _roString est disponible dans l'@implementation + +// En contre-partie de l'initialisation, la fonction dealloc est appelé quand l'objet est n'est plus +// utilisé +- (void)dealloc +{ + [hauteur release]; // Si vous n'utilisez par l'ARC, pensez bien à supprimer l'objet + [super dealloc]; // et à appeler la méthode de la classe parent +} + +// Les constructeurs sont une manière de créer des instances de classes +// Ceci est le constructeur par défaut; il est appelé quand l'objet est créé +- (id)init +{ + if ((self = [super init])) // 'super' est utilisé pour appeler la méthode de la classe parent + { + self.count = 1; // 'self' est utilisé pour appeler la méthodes de l'objet courrant + } + return self; +} + +// Vous pouvez créer des constructeurs qui possèdent des arguments : +- (id)initAvecUneDistance:(int)distanceParDefault +{ + if ((self = [super init])) + { + distance = distanceParDefault; + return self; + } +} + ++ (NSString *)methodDeClasse +{ + return [[self alloc] init]; +} + ++ (MaClasse *)maClasseDepuisUneHauteur:(NSNumber *)hauteurParDefaut +{ + hauteur = hauteurParDefaut; + return [[self alloc] init]; +} + +- (NSString *)methodeInstanceAvecUnParametre:(NSString *)string +{ + return @"Ma chaine de charactère"; +} + +- (NSNumber *)methodeInstanceAvecUnParametre:(NSString*)string puisUnDeuxieme:(NSNumber *)number +{ + return @42; +} + +// Pour créer une méthode privée, il faut la définir dans l'@implementation et non pas dans +// l'@interface +- (NSNumber *)methodePrivee +{ + return @72; +} + +[self methodePrivee]; // Appel de la méthode privée + +// Méthode déclarée dans MonProtocole +- (void)methodeDuProtocole +{ + // expressions +} + +@end // Fin de l'implémentation + +/* + * Un protocole déclare les méthodes qu'ils doivent implémenter afin de se conformer celui-ci + * Un protocole n'est pas une classe, c'est juste une interface + */ +@protocol MonProtocole + - (void)methodeDuProtocole; +@end + + +/////////////////////////////////////// +// Gestion de la mémoire +/////////////////////////////////////// +/* +Pour chaque objet utilisé dans une application, la mémoire doit être alloué pour chacun d'entre eux. +Quand l'application en a fini avec cet objet, la mémoire doit être libéré pour assurer la performane. +Il n'y a pas de ramasse-miettes en Objective-C, il utilise à la place le comptage de référence à la +place. Tant que le compteur de référence est supérieur à 1 sur un objet, l'objet ne sera pas supprimé + +Quand une instance détient un objet, le compteur de référence est incrémenté de un. Quand l'objet est +libéré, le compteur est décrémenté de un. Quand le compteur est égale à zéro, l'objet est supprimé de +la mémoire + +Une bonne pratique à suivre quand on travaille avec des objets est la suivante : +(1) créer un objet, (2) utiliser l'objet, (3) supprimer l'objet de la mémoire +*/ + +MaClasse *classeVar = [MyClass alloc]; // 'alloc' incrémente le compteur de référence +[classeVar release]; // Décrémente le compteur de rérence +// 'retain' incrémente le compteur de référence +// Si 'classeVar' est libéré, l'objet reste en mémoire car le compteur de référence est non nulle +MaClasse *nouvelleVar = [classVar retain]; +[classeVar autorelease]; // Supprime l'appartenance de l'objet à la fin du block + +// @property peuvent utiliser 'retain' et 'assign' +@property (retain) MaClasse *instance; // Libère l'ancienne valeur et retient la nouvelle +@property (assign) NSSet *set; // Pointeur vers la valeur sans retenir/libérer l'ancienne valeur + +// Automatic Reference Counting (ARC) +// La gestion de la mémoire étant pénible, depuis iOS 4 et Xcode 4.2, Apple a introduit le comptage de référence +// automatique (Automatic Reference Counting en anglais). +// ARC est une fonctionnalité du compilateur qui lui permet d'ajouter les 'retain', 'release' et 'autorelease' +// automatiquement. Donc quand utilisez ARC vous de devez plus utiliser ces mots clés +MaClasse *arcMaClasse = [[MaClasse alloc] init]; +// ... code utilisant arcMaClasse +// Sans ARC, vous auriez dû appeler [arcMaClasse release] après avoir utilisé l'objet. Mais avec ARC il n'y a plus +// besoin car le compilateur ajoutera l'expréssion automatiquement pour vous + +// Les mots clés 'assign' et 'retain', avec ARC sont respectivement remplacé par 'weak' et 'strong' +@property (weak) MaClasse *weakVar; // 'weak' ne retient pas l'objet. Si l'instance original descend à zero, weakVar +// sera automatiquement mis à nil +@property (strong) MaClasse *strongVar; // 'strong' prend posséssion de l'objet comme le ferai le mot clé 'retain' + +// Pour l'instanciation des variables (en dehors de @property), vous pouvez utiliser les instructions suivantes : +__strong NSString *strongString; // Par defaut. La variable est retenu en mémoire jusqu'à la fin de sa portée +__weak NSSet *weakSet; // Réfère la variable en utilisant le mot clé '__weak' +__unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais quand la variable n'est pas mis à nil quand l'objet +// est supprimé ailleurs + +``` +## Lectures Complémentaires + +[La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C) + +[iOS pour les écoliers : Votre première app iOS](http://www.raywenderlich.com/fr/39272/ios-pour-les-ecoliers-votre-premiere-app-ios-partie-12) + +[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) \ No newline at end of file diff --git a/fr-fr/objective-c.html.markdown b/fr-fr/objective-c.html.markdown deleted file mode 100644 index e6a8abfb..00000000 --- a/fr-fr/objective-c.html.markdown +++ /dev/null @@ -1,510 +0,0 @@ ---- - -language: Objective-C -contributors: - - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - - ["Yannick Loriot", "https://github.com/YannickL"] - - ["Levi Bostian", "https://github.com/levibostian"] -translators: - - ["Yannick Loriot", "https://github.com/YannickL"] -filename: LearnObjectiveC.m - ---- - -L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs framworks respectifs, Cocoa et Cocoa Touch. - -```objective-c -// Les commentaires unilignes commencent par // - -/* -Les commentaires multilignes ressemblent à ça -*/ - -// Importe les en-têtes en utilisant #import -// Utilisez <> pour importer des fichiers globaux (en général des frameworks) -// Utilisez "" pour importer des fichiers locaux (du projet) -#import -#import "MaClasse.h" - -// Si vous activez les modules pour les projects iOS >= 7 ou Mac OS X >= 10.9 -// dans Xcode 5 vous pouvez importer les frameworks comme cela : -@import Foundation; - -// Le point d'entrée de votre programme est une fonction qui s'appelle main -// et qui return un entier comme type -int main (int argc, const char * argv[]) -{ - // Créer un groupe de libération automatique de la mémoire pour l'ensemble - // du programme - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - // Si vous utilisez le comptage de référence automatique (ARC), utilisez - // @autoreleasepool à la place : - @autoreleasepool { - - // Utilisez NSLog pour afficher les lignes sur la console - // Affiche la chaine de caractères "Bonjour Tous Le Monde !" - NSLog(@"Bonjour tous le Monde !"); - - /////////////////////////////////////// - // Les Types & Les Variables - /////////////////////////////////////// - - // Déclarations de primitive - int maPrimitive1 = 1; - long maPrimitive2 = 234554664565; - - // Declarations d'objets - // Il faut mettre l'* devant la déclaration d'objets fortement typés - MaClasse *monObject1 = nil; // Typage fort - id monObject2 = nil; // Typage faible - // %@ est un objet - // 'description' est une convention pour afficher la valeur des objets - NSLog(@"%@ and %@", monObject1, [monObject2 description]); // Affiche "(null) et (null)" - - // Chaines de caractères - NSString *chaineMonde = @"Monde"; - NSLog(@"Bonjour tous le %@ !", chaineMonde); // affiche => "Bonjour Tous Le Monde !" - // NSMutableString est une chaine mutable - NSMutableString *chaineMutable = [NSMutableString stringWithString:@"Bonjour tous le"]; - [chaineMutable appendString:@" Monde !"]; - NSLog(@"%@", chaineMutable); // affiche => "Bonjour Tous Le Monde !" - - // Les littéraux pour les caratères - NSNumber *laLettreZSousFormeDeNombre = @'Z'; - char laLettreZ = [laLettreZSousFormeDeNombre charValue]; // ou 'Z' - NSLog(@"%c", laLettreZ); - - // Les littéraux pour les nombres - NSNumber *nombreQuaranteDeux = @42; - int quaranteDeux = [nombreQuaranteDeux intValue]; // ou 42 - NSLog(@"%i", quaranteDeux); - - NSNumber *nombreQuaranteDeuxnonSigne = @42U; - unsigned int quaranteDeuxnonSigne = [nombreQuaranteDeuxnonSigne unsignedIntValue]; - NSLog(@"%u", fortyTwoUnsigned); - - NSNumber *nombreQuaranteDeuxCourt = [NSNumber numberWithShort:42]; - short quaranteDeuxCourt = [nombreQuaranteDeuxCourt shortValue]; // ou 42 - NSLog(@"%hi", fortyTwoShort); - - NSNumber *nombreQuaranteDeuxLong = @42L; - long quaranteDeuxLong = [nombreQuaranteDeuxLong longValue]; // ou 42 - NSLog(@"%li", fortyTwoLong); - - // Les littéraux pour les flottans - NSNumber *nombrePiFlottan = @3.141592654F; - float piFlottan = [nombrePiFlottan floatValue]; // ou 3.141592654f - NSLog(@"%f", piFlottan); // affiche => 3.141592654 - NSLog(@"%5.2f", piFlottan); // affiche => " 3.14" - - NSNumber *nombrePiDouble = @3.1415926535; - double piDouble = [nombrePiDouble doubleValue]; // ou 3.1415926535 - NSLog(@"%f", piDouble); - NSLog(@"%4.2f", piDouble); // affiche => "3.14" - - // NSDecimalNumber est une classe pour avoir plus de précision sur les flottans - // et les doubles - NSDecimalNumber *decNumUn = [NSDecimalNumber decimalNumberWithString:@"10.99"]; - NSDecimalNumber *decNumDeux = [NSDecimalNumber decimalNumberWithString:@"5.002"]; - // NSDecimalNumber n'est pas capable d'utiliser les opérations standards : - // +, -, *, /, il utilise donc ses propres fonctions : - [decNumUn decimalNumberByAdding:decNumDeux]; - [decNumUn decimalNumberBySubtracting:decNumDeux]; - [decNumUn decimalNumberByMultiplyingBy:decNumDeux]; - [decNumUn decimalNumberByDividingBy:decNumDeux]; - NSLog(@"%@", decNumUn); // affiche => 10.99 comme NSDecimalNumber is immuable - - // Les littéraux pour les booléens - NSNumber *ouiNumber = @YES; - NSNumber *nonNumber = @NO; - // ou - BOOL ouiBool = YES; - BOOL nonBool = NO; - NSLog(@"%i", ouiBool); // affiche => 1 - - // Les listes - // Ils peuvent contenir différents types de données, mais ils doivent absolument - // être des objets - NSArray *uneListe = @[@1, @2, @3, @4]; - NSNumber *troisiemeNombre = uneListe[2]; - NSLog(@"Troisième nombre = %@", troisiemeNombre); // affiche "Troisième nombre = 3" - // NSMutableArray est une version mutable de NSArray qui permet de changer les - // objets dans la liste et l'étendre ou la réduire - // C'est très pratique, mais pas aussi performant que l'utilsation de la classe - // NSArray - NSMutableArray *listeMutable = [NSMutableArray arrayWithCapacity:2]; - [listeMutable addObject:@"Bonjour tous le"]; - [listeMutable addObject:@"Monde"]; - [listeMutable removeObjectAtIndex:0]; - NSLog(@"%@", [listeMutable objectAtIndex:0]); // affiche => "Monde" - - // Les dictionnaires - NSDictionary *unDictionnaire = @{ @"cle1" : @"valeur1", @"cle2" : @"valeur2" }; - NSObject *valeur = unDictionnaire[@"Une clé"]; - NSLog(@"Objet = %@", valeur); // affiche "Objet = (null)" - // NSMutableDictionary est un dictionnaire mutable - NSMutableDictionary *dictionnaireMutable = [NSMutableDictionary dictionaryWithCapacity:2]; - [dictionnaireMutable setObject:@"valeur1" forKey:@"cle1"]; - [dictionnaireMutable setObject:@"valeur2" forKey:@"cle2"]; - [dictionnaireMutable removeObjectForKey:@"cle1"]; - - // Les ensembles - NSSet *ensemble = [NSSet setWithObjects:@"Salut", @"Salut", @"Monde", nil]; - NSLog(@"%@", ensemble); // affiche => {(Salut, Monde)} (peut être dans un ordre différente) - // NSMutableSet est un ensemble mutable - NSMutableSet *ensembleMutable = [NSMutableSet setWithCapacity:2]; - [ensembleMutable addObject:@"Salut"]; - [ensembleMutable addObject:@"Salut"]; - NSLog(@"%@", ensembleMutable); // affiche => {(Salut)} - - /////////////////////////////////////// - // Operateurs - /////////////////////////////////////// - - // Les opérateurs sont les mêmes que ceux du langage C - // Par exemple : - 2 + 5; // => 7 - 4.2f + 5.1f; // => 9.3f - 3 == 2; // => 0 (NO) - 3 != 2; // => 1 (YES) - 1 && 1; // => 1 (et logique) - 0 || 1; // => 1 (ou logique) - ~0x0F; // => 0xF0 (négation bit à bit) - 0x0F & 0xF0; // => 0x00 (et bit à bit) - 0x01 << 1; // => 0x02 (décale à gauche (par 1)) - - /////////////////////////////////////// - // Structures de controle - /////////////////////////////////////// - - // Expression If-Else - if (NO) - { - NSLog(@"Je ne suis jamais affiché"); - } else if (0) - { - NSLog(@"Je ne suis jamais affiché aussi"); - } else - { - NSLog(@"Je suis affiché"); - } - - // Expression Switch - switch (2) - { - case 0: - { - NSLog(@"Je ne suis jamais affiché"); - } break; - case 1: - { - NSLog(@"Je ne suis jamais affiché aussi"); - } break; - default: - { - NSLog(@"Je suis affiché"); - } break; - } - - // Expression de boucle While - int ii = 0; - while (ii < 4) - { - NSLog(@"%d,", ii++); // ii++ incrémente ii après avoir utilisé sa valeure - } // => affiche "0," - // "1," - // "2," - // "3," - - // Expression de boucle For loops - int jj; - for (jj=0; jj < 4; jj++) - { - NSLog(@"%d,", jj); - } // => affiche "0," - // "1," - // "2," - // "3," - - // Expression de boucle Foreach - NSArray *valeurs = @[@0, @1, @2, @3]; - for (NSNumber *valeur in valeurs) - { - NSLog(@"%@,", valeur); - } // => affiche "0," - // "1," - // "2," - // "3," - - // Expressions Try-Catch-Finally - @try - { - @throw [NSException exceptionWithName:@"FileNotFoundException" - reason:@"Fichier non trouvé" userInfo:nil]; - } @catch (NSException * e) - { - NSLog(@"Exception : %@", e); - } @finally - { - NSLog(@"Finalement"); - } // => affiche "Exceptio : Fichier non trouvé" - // "Finalement" - - /////////////////////////////////////// - // Objets - /////////////////////////////////////// - - // Créez une instance d'objet en allouant un espace mémoire puis en l'initialisant - // Un objet n'est pas complétement fonctionnel jusqu'à ce que les deux étapes précédente - // ne sont pas fini - MaClass *monObjet = [[MaClass alloc] init]; - - // Le modèle Objective-C est basé sur l'envoie de message et non sur les appels de - // méthodes comme la plupart des autres langage de programmation - [myObject instanceMethodWithParameter:@"Steve Jobs"]; - - // Nettoie la mémoire que vous avez utilisé dans votre programme - [pool drain]; - - // Fin the l'@autoreleasepool - } - - // Fin du programme - return 0; -} - -/////////////////////////////////////// -// Classes et Fonctions -/////////////////////////////////////// - -// Déclarez votre classe dans une en-tête de fichier (MaClasse.h) : -// La syntaxe de déclaration : -// @interface NomDeLaClasse : NomDeLaClasseParent -// { -// type nom; <= declarations de variable; -// } -// @property type nom; <= declarations de propriété. -// -/+ (type) Methode declarations; <= Declarations de methodes. -// @end -// NSObject est la classe de base de l'Objective-C -@interface MaClasse : NSObject -{ - // Déclaration des variables d'instances (peut existé soit dans l'interface soir dans - // l'implémentation) - int nombre; // Accès protégé par défaut - @private id donnee; // Accès privé (il est plus pratique de le faire dans l'implémentation) - NSString *nom; -} -// Notation pratique pour l'accès aux variable public et pour générrer les -// accésseurs/affecteurs -// Par défaut, le nom de l'affecteur vaut 'set' suivi par le nom de la @property -@property int propInt; // Nom du setter = 'setPropInt' -@property (copy) id copyId; // (copy) => Copie l'objet pendant l'affectation -// (readonly) => Ne peut pas affecté la variable en dehors de l'@interface -// Utilisez @synthesize dans l'@implementation pour créer l'accésseur -@property (readonly) NSString *roString; -// Vous pouvez personnaliser les noms des accésseurs et des affecteurs au lieu d'utiliser les -// noms par défauts -@property (getter=longeurGet, setter=longeurSet:) int longeur; - -// Methodes -+/- (type de retour)signatureDeLaMethode:(Type Du Parametre *)nomDuParametre; - -// + pour les méthodes de classe : -+ (NSString *)methodeDeClasse; -+ (MaClasse *)maClasseDepuisLaHauteur:(NSNumber *)hauteurParDefaut; - -// - pour les méthodes d'instances : -- (NSString *)methodeInstanceAvecUnParametre:(NSString *)string; -- (NSNumber *)methodeInstanceAvecUnParametre:(NSString*)string puisUnDeuxieme:(NSNumber *)number; - -// Contructeur avec des arguments : -- (id)initAvecDistance:(int)distanceParDefault; -// Les méthodes en Objective-C sont très descriptive - -@end // Définit la fin de l'interface - - -// Exemple d'utilisation de MaClasse -MaClasse *maClasse = [[MaClasse alloc] init]; // créer une instance de MaClasse -[maClasse setNombre:10]; -NSLog(@"%d", [maClasse nombre]); // affiche => 10 -[myClass longeurSet:32]; -NSLog(@"%i", [maClasse longeurGet]); // affiche => 32 -// Pour des raisons pratiques vous pouvez aussi utiliser la notation en point pour accéder aux -// variables d'instances : -maClasse.nombre = 45; -NSLog(@"%i", maClasse.nombre); // maClasse => 45 - -// Appeler un méthode de classe : -NSString *s1 = [MaClasse methodeDeClasse]; -MaClasse *m2 = [MaClasse maClasseDepuisLaHauteur:38]; - -// Appeler un méthode d'instance : -MaClasse *maClasse = [[MaClasse alloc] init]; // Créer une instance de MaClasse -NSString *stringDepuisUneInstanceDeMethode = [maClasse methodeInstanceAvecUnParametre:@"Salut"]; - -// Sélecteurs sont un moyen de représenté les méthodes dynamiquement -// Ils sont utilisé pour appeller des méthodes de classe, passer des methodes au travers de fonctions -// pour notifier les autres classes qu'elle peuvent les appellé, et pour sauvegarder les méthodes en -// tant que variables -// SEL est un type de donnée. @selected retourne un selecteur à partir d'un nom de methode -SEL selecteur = @selector(methodeInstanceAvecUnParametre:puisUnDeuxieme:); -if ([maClasse respondsToSelector:selecteur]) { // Vérifie si la classe contient la méthode - // Doit mettre tous les arguments de la méthode dans un seul objet pour l'envoyer via la fonction - // performSelector:withObject: - NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; - [myClass performSelector:selectorVar withObject:arguments]; // Appele la méthode -} else { - // NSStringFromSelector() retourne une chaine de charactères à partir d'un sélecteur - NSLog(@"MaClasse ne possède pas de méthode : %@", NSStringFromSelector(selecteur)); -} - -// Implement la méthode dans le fichier d'impémentation (MaClasse.m) -@implementation MaClasse { - long distance; // Variable d'instance privé - NSNumber hauteur; -} - -// Pour accéder à une variable depuis le fichier d'implémentation on peut utiliser le _ devant le nom -// de la variable : -_nombre = 5; -// Accès d'une variable définit dans le fichier d'implémentation : -distance = 18; -// Pour utiliser la varible @property dans l'implémentation, utiliser @synthesize qui créer les -// accésseurs : -@synthesize roString = _roString; // _roString est disponible dans l'@implementation - -// En contre-partie de l'initialisation, la fonction dealloc est appelé quand l'objet est n'est plus -// utilisé -- (void)dealloc -{ - [hauteur release]; // Si vous n'utilisez par l'ARC, pensez bien à supprimer l'objet - [super dealloc]; // et à appeler la méthode de la classe parent -} - -// Les constructeurs sont une manière de créer des instances de classes -// Ceci est le constructeur par défaut; il est appelé quand l'objet est créé -- (id)init -{ - if ((self = [super init])) // 'super' est utilisé pour appeler la méthode de la classe parent - { - self.count = 1; // 'self' est utilisé pour appeler la méthodes de l'objet courrant - } - return self; -} - -// Vous pouvez créer des constructeurs qui possèdent des arguments : -- (id)initAvecUneDistance:(int)distanceParDefault -{ - if ((self = [super init])) - { - distance = distanceParDefault; - return self; - } -} - -+ (NSString *)methodDeClasse -{ - return [[self alloc] init]; -} - -+ (MaClasse *)maClasseDepuisUneHauteur:(NSNumber *)hauteurParDefaut -{ - hauteur = hauteurParDefaut; - return [[self alloc] init]; -} - -- (NSString *)methodeInstanceAvecUnParametre:(NSString *)string -{ - return @"Ma chaine de charactère"; -} - -- (NSNumber *)methodeInstanceAvecUnParametre:(NSString*)string puisUnDeuxieme:(NSNumber *)number -{ - return @42; -} - -// Pour créer une méthode privée, il faut la définir dans l'@implementation et non pas dans -// l'@interface -- (NSNumber *)methodePrivee -{ - return @72; -} - -[self methodePrivee]; // Appel de la méthode privée - -// Méthode déclarée dans MonProtocole -- (void)methodeDuProtocole -{ - // expressions -} - -@end // Fin de l'implémentation - -/* - * Un protocole déclare les méthodes qu'ils doivent implémenter afin de se conformer celui-ci - * Un protocole n'est pas une classe, c'est juste une interface - */ -@protocol MonProtocole - - (void)methodeDuProtocole; -@end - - -/////////////////////////////////////// -// Gestion de la mémoire -/////////////////////////////////////// -/* -Pour chaque objet utilisé dans une application, la mémoire doit être alloué pour chacun d'entre eux. -Quand l'application en a fini avec cet objet, la mémoire doit être libéré pour assurer la performane. -Il n'y a pas de ramasse-miettes en Objective-C, il utilise à la place le comptage de référence à la -place. Tant que le compteur de référence est supérieur à 1 sur un objet, l'objet ne sera pas supprimé - -Quand une instance détient un objet, le compteur de référence est incrémenté de un. Quand l'objet est -libéré, le compteur est décrémenté de un. Quand le compteur est égale à zéro, l'objet est supprimé de -la mémoire - -Une bonne pratique à suivre quand on travaille avec des objets est la suivante : -(1) créer un objet, (2) utiliser l'objet, (3) supprimer l'objet de la mémoire -*/ - -MaClasse *classeVar = [MyClass alloc]; // 'alloc' incrémente le compteur de référence -[classeVar release]; // Décrémente le compteur de rérence -// 'retain' incrémente le compteur de référence -// Si 'classeVar' est libéré, l'objet reste en mémoire car le compteur de référence est non nulle -MaClasse *nouvelleVar = [classVar retain]; -[classeVar autorelease]; // Supprime l'appartenance de l'objet à la fin du block - -// @property peuvent utiliser 'retain' et 'assign' -@property (retain) MaClasse *instance; // Libère l'ancienne valeur et retient la nouvelle -@property (assign) NSSet *set; // Pointeur vers la valeur sans retenir/libérer l'ancienne valeur - -// Automatic Reference Counting (ARC) -// La gestion de la mémoire étant pénible, depuis iOS 4 et Xcode 4.2, Apple a introduit le comptage de référence -// automatique (Automatic Reference Counting en anglais). -// ARC est une fonctionnalité du compilateur qui lui permet d'ajouter les 'retain', 'release' et 'autorelease' -// automatiquement. Donc quand utilisez ARC vous de devez plus utiliser ces mots clés -MaClasse *arcMaClasse = [[MaClasse alloc] init]; -// ... code utilisant arcMaClasse -// Sans ARC, vous auriez dû appeler [arcMaClasse release] après avoir utilisé l'objet. Mais avec ARC il n'y a plus -// besoin car le compilateur ajoutera l'expréssion automatiquement pour vous - -// Les mots clés 'assign' et 'retain', avec ARC sont respectivement remplacé par 'weak' et 'strong' -@property (weak) MaClasse *weakVar; // 'weak' ne retient pas l'objet. Si l'instance original descend à zero, weakVar -// sera automatiquement mis à nil -@property (strong) MaClasse *strongVar; // 'strong' prend posséssion de l'objet comme le ferai le mot clé 'retain' - -// Pour l'instanciation des variables (en dehors de @property), vous pouvez utiliser les instructions suivantes : -__strong NSString *strongString; // Par defaut. La variable est retenu en mémoire jusqu'à la fin de sa portée -__weak NSSet *weakSet; // Réfère la variable en utilisant le mot clé '__weak' -__unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais quand la variable n'est pas mis à nil quand l'objet -// est supprimé ailleurs - -``` -## Lectures Complémentaires - -[La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C) - -[iOS pour les écoliers : Votre première app iOS](http://www.raywenderlich.com/fr/39272/ios-pour-les-ecoliers-votre-premiere-app-ios-partie-12) - -[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) \ No newline at end of file -- cgit v1.2.3 From a759407f0b0da9784cf6c0f3865452d546c03da7 Mon Sep 17 00:00:00 2001 From: Yannick Date: Fri, 24 Jan 2014 20:00:45 +0100 Subject: [FIX] Typing Errors In The First Part --- fr-fr/objective-c-fr.html.markdown | 174 ++++++++++++++++++------------------- 1 file changed, 87 insertions(+), 87 deletions(-) diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index e6a8abfb..ca0b2391 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -11,27 +11,32 @@ filename: LearnObjectiveC.m --- -L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs framworks respectifs, Cocoa et Cocoa Touch. +L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch. ```objective-c -// Les commentaires unilignes commencent par // +// Les commentaires sur une seule ligne commencent par // /* -Les commentaires multilignes ressemblent à ça +Les +commentaires +multi-lignes +ressemblent +à +ceci */ -// Importe les en-têtes en utilisant #import +// #import permet d'importer les en-têtes d'autres fichiers // Utilisez <> pour importer des fichiers globaux (en général des frameworks) // Utilisez "" pour importer des fichiers locaux (du projet) #import #import "MaClasse.h" -// Si vous activez les modules pour les projects iOS >= 7 ou Mac OS X >= 10.9 -// dans Xcode 5 vous pouvez importer les frameworks comme cela : +// Si vous activez les modules dans les projets iOS >= 7 ou Mac OS X >= 10.9 +// dans Xcode 5, vous pouvez importer les frameworks comme cela : @import Foundation; // Le point d'entrée de votre programme est une fonction qui s'appelle main -// et qui return un entier comme type +// et qui retourne un entier comme type int main (int argc, const char * argv[]) { // Créer un groupe de libération automatique de la mémoire pour l'ensemble @@ -41,7 +46,7 @@ int main (int argc, const char * argv[]) // @autoreleasepool à la place : @autoreleasepool { - // Utilisez NSLog pour afficher les lignes sur la console + // NSLog() permet d'afficher une chaine de caractères dans la console // Affiche la chaine de caractères "Bonjour Tous Le Monde !" NSLog(@"Bonjour tous le Monde !"); @@ -49,19 +54,19 @@ int main (int argc, const char * argv[]) // Les Types & Les Variables /////////////////////////////////////// - // Déclarations de primitive + // La déclaration de primitive int maPrimitive1 = 1; long maPrimitive2 = 234554664565; - // Declarations d'objets - // Il faut mettre l'* devant la déclaration d'objets fortement typés + // La déclaration d'objet + // Il faut mettre un astérisque devant la déclaration d'objet fortement typé MaClasse *monObject1 = nil; // Typage fort id monObject2 = nil; // Typage faible - // %@ est un objet - // 'description' est une convention pour afficher la valeur des objets + // 'description' est une méthode qui permet d'afficher un aperçut de l'objet + // La méthode 'description' est appelée par défaut quand on utilise le paramètre '%@' NSLog(@"%@ and %@", monObject1, [monObject2 description]); // Affiche "(null) et (null)" - // Chaines de caractères + // Les chaines de caractères NSString *chaineMonde = @"Monde"; NSLog(@"Bonjour tous le %@ !", chaineMonde); // affiche => "Bonjour Tous Le Monde !" // NSMutableString est une chaine mutable @@ -69,12 +74,12 @@ int main (int argc, const char * argv[]) [chaineMutable appendString:@" Monde !"]; NSLog(@"%@", chaineMutable); // affiche => "Bonjour Tous Le Monde !" - // Les littéraux pour les caratères + // Les caractères NSNumber *laLettreZSousFormeDeNombre = @'Z'; char laLettreZ = [laLettreZSousFormeDeNombre charValue]; // ou 'Z' NSLog(@"%c", laLettreZ); - // Les littéraux pour les nombres + // Les nombres NSNumber *nombreQuaranteDeux = @42; int quaranteDeux = [nombreQuaranteDeux intValue]; // ou 42 NSLog(@"%i", quaranteDeux); @@ -91,7 +96,7 @@ int main (int argc, const char * argv[]) long quaranteDeuxLong = [nombreQuaranteDeuxLong longValue]; // ou 42 NSLog(@"%li", fortyTwoLong); - // Les littéraux pour les flottans + // Les nombres flottans NSNumber *nombrePiFlottan = @3.141592654F; float piFlottan = [nombrePiFlottan floatValue]; // ou 3.141592654f NSLog(@"%f", piFlottan); // affiche => 3.141592654 @@ -102,19 +107,19 @@ int main (int argc, const char * argv[]) NSLog(@"%f", piDouble); NSLog(@"%4.2f", piDouble); // affiche => "3.14" - // NSDecimalNumber est une classe pour avoir plus de précision sur les flottans - // et les doubles + // NSDecimalNumber est une classe pour avoir plus de précision sur les nombres + // flottans et les doubles NSDecimalNumber *decNumUn = [NSDecimalNumber decimalNumberWithString:@"10.99"]; NSDecimalNumber *decNumDeux = [NSDecimalNumber decimalNumberWithString:@"5.002"]; - // NSDecimalNumber n'est pas capable d'utiliser les opérations standards : - // +, -, *, /, il utilise donc ses propres fonctions : + // NSDecimalNumber n'est pas capable d'utiliser les opérations standards (+, -, *, /) + // Il faut utiliser les méthodes suivantes : [decNumUn decimalNumberByAdding:decNumDeux]; [decNumUn decimalNumberBySubtracting:decNumDeux]; [decNumUn decimalNumberByMultiplyingBy:decNumDeux]; [decNumUn decimalNumberByDividingBy:decNumDeux]; - NSLog(@"%@", decNumUn); // affiche => 10.99 comme NSDecimalNumber is immuable + NSLog(@"%@", decNumUn); // affiche => 10.99 comme NSDecimalNumber est immuable - // Les littéraux pour les booléens + // Les booléens NSNumber *ouiNumber = @YES; NSNumber *nonNumber = @NO; // ou @@ -123,15 +128,13 @@ int main (int argc, const char * argv[]) NSLog(@"%i", ouiBool); // affiche => 1 // Les listes - // Ils peuvent contenir différents types de données, mais ils doivent absolument - // être des objets + // Une liste peut contenir uniquement des objets NSArray *uneListe = @[@1, @2, @3, @4]; NSNumber *troisiemeNombre = uneListe[2]; NSLog(@"Troisième nombre = %@", troisiemeNombre); // affiche "Troisième nombre = 3" - // NSMutableArray est une version mutable de NSArray qui permet de changer les - // objets dans la liste et l'étendre ou la réduire - // C'est très pratique, mais pas aussi performant que l'utilsation de la classe - // NSArray + // NSMutableArray est une version mutable de NSArray + // Cela permet de modifier la liste en ajoutant/supprimant/modifiant des objets + // C'est très pratique, mais pas aussi performant que l'utilisation de la classe NSArray NSMutableArray *listeMutable = [NSMutableArray arrayWithCapacity:2]; [listeMutable addObject:@"Bonjour tous le"]; [listeMutable addObject:@"Monde"]; @@ -139,18 +142,20 @@ int main (int argc, const char * argv[]) NSLog(@"%@", [listeMutable objectAtIndex:0]); // affiche => "Monde" // Les dictionnaires + // Un dictionnaire est un ensemble de { clé: valeur } NSDictionary *unDictionnaire = @{ @"cle1" : @"valeur1", @"cle2" : @"valeur2" }; NSObject *valeur = unDictionnaire[@"Une clé"]; NSLog(@"Objet = %@", valeur); // affiche "Objet = (null)" - // NSMutableDictionary est un dictionnaire mutable + // NSMutableDictionary est un dictionnaire mutable, c-à-d que l'on peut modifier NSMutableDictionary *dictionnaireMutable = [NSMutableDictionary dictionaryWithCapacity:2]; [dictionnaireMutable setObject:@"valeur1" forKey:@"cle1"]; [dictionnaireMutable setObject:@"valeur2" forKey:@"cle2"]; [dictionnaireMutable removeObjectForKey:@"cle1"]; // Les ensembles + // Un ensemble peut ne peut contenir que des objets uniques contrairement aux NSArray NSSet *ensemble = [NSSet setWithObjects:@"Salut", @"Salut", @"Monde", nil]; - NSLog(@"%@", ensemble); // affiche => {(Salut, Monde)} (peut être dans un ordre différente) + NSLog(@"%@", ensemble); // affiche => {(Salut, Monde)} (Pas forcément dans le même ordre) // NSMutableSet est un ensemble mutable NSMutableSet *ensembleMutable = [NSMutableSet setWithCapacity:2]; [ensembleMutable addObject:@"Salut"]; @@ -158,7 +163,7 @@ int main (int argc, const char * argv[]) NSLog(@"%@", ensembleMutable); // affiche => {(Salut)} /////////////////////////////////////// - // Operateurs + // Les Operateurs /////////////////////////////////////// // Les opérateurs sont les mêmes que ceux du langage C @@ -174,10 +179,10 @@ int main (int argc, const char * argv[]) 0x01 << 1; // => 0x02 (décale à gauche (par 1)) /////////////////////////////////////// - // Structures de controle + // Les Structures de Controle /////////////////////////////////////// - // Expression If-Else + // Expression "Si-Sinon" (If-Else) if (NO) { NSLog(@"Je ne suis jamais affiché"); @@ -189,7 +194,7 @@ int main (int argc, const char * argv[]) NSLog(@"Je suis affiché"); } - // Expression Switch + // Expression "Selon" (Switch) switch (2) { case 0: @@ -206,17 +211,17 @@ int main (int argc, const char * argv[]) } break; } - // Expression de boucle While + // Expression de boucle "Tant Que" (While) int ii = 0; while (ii < 4) { - NSLog(@"%d,", ii++); // ii++ incrémente ii après avoir utilisé sa valeure + NSLog(@"%d,", ii++); // ii++ incrémente ii après avoir utilisé sa valeur } // => affiche "0," // "1," // "2," // "3," - // Expression de boucle For loops + // Expression de boucle "Pour" (For) int jj; for (jj=0; jj < 4; jj++) { @@ -226,7 +231,7 @@ int main (int argc, const char * argv[]) // "2," // "3," - // Expression de boucle Foreach + // Expression de boucle "Pour Chaque" (Foreach) NSArray *valeurs = @[@0, @1, @2, @3]; for (NSNumber *valeur in valeurs) { @@ -236,37 +241,37 @@ int main (int argc, const char * argv[]) // "2," // "3," - // Expressions Try-Catch-Finally + // Expression "Essayer-Attraper-Finalement" (Try-Catch-Finally) @try { @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"Fichier non trouvé" userInfo:nil]; } @catch (NSException * e) { - NSLog(@"Exception : %@", e); + NSLog(@"Une exception est survenue : %@", e); } @finally { NSLog(@"Finalement"); - } // => affiche "Exceptio : Fichier non trouvé" + } // => affiche "Une exception est survenue : Fichier non trouvé" // "Finalement" /////////////////////////////////////// - // Objets + // Les Objets /////////////////////////////////////// - // Créez une instance d'objet en allouant un espace mémoire puis en l'initialisant - // Un objet n'est pas complétement fonctionnel jusqu'à ce que les deux étapes précédente - // ne sont pas fini + // Définis et créé une instance d'objet en allouant un espace mémoire puis en + // l'initialisant. Un objet n'est pas complétement fonctionnel tant que les deux + // étapes précédentes ne sont pas terminées MaClass *monObjet = [[MaClass alloc] init]; - // Le modèle Objective-C est basé sur l'envoie de message et non sur les appels de - // méthodes comme la plupart des autres langage de programmation + // L'Objective-C est basé sur le principe d'envoie de message et non sur celui + // d'appel de méthode comme la plupart des autres langages de programmation [myObject instanceMethodWithParameter:@"Steve Jobs"]; - // Nettoie la mémoire que vous avez utilisé dans votre programme + // Nettoie la mémoire qui a été utilisée dans le programme [pool drain]; - // Fin the l'@autoreleasepool + // Fin de l'@autoreleasepool } // Fin du programme @@ -274,58 +279,54 @@ int main (int argc, const char * argv[]) } /////////////////////////////////////// -// Classes et Fonctions +// Les Classes et Les Fonctions /////////////////////////////////////// -// Déclarez votre classe dans une en-tête de fichier (MaClasse.h) : -// La syntaxe de déclaration : -// @interface NomDeLaClasse : NomDeLaClasseParent +// Déclaration d'une classe dans un en-tête de fichier (MaClasse.h) : +// La déclaration d'une classe en Objective-C commence par la déclaration de son interface : +// @interface NomDeLaClasse : NomDeLaClasseParent // { -// type nom; <= declarations de variable; +// type nom; // declaration d'une variable; // } -// @property type nom; <= declarations de propriété. -// -/+ (type) Methode declarations; <= Declarations de methodes. -// @end -// NSObject est la classe de base de l'Objective-C +// @property type nom; // declaration d'une propriété +// -/+ (type)nomDeLaMethode; // Declaration d'une methode +// @end // Termine la déclaration +// NSObject est la classe de base (super classe) en Objective-C @interface MaClasse : NSObject { - // Déclaration des variables d'instances (peut existé soit dans l'interface soir dans - // l'implémentation) - int nombre; // Accès protégé par défaut + int nombre; // Accès protégé par défaut (équivalent à '@protected int nombre;') @private id donnee; // Accès privé (il est plus pratique de le faire dans l'implémentation) NSString *nom; } -// Notation pratique pour l'accès aux variable public et pour générrer les -// accésseurs/affecteurs -// Par défaut, le nom de l'affecteur vaut 'set' suivi par le nom de la @property -@property int propInt; // Nom du setter = 'setPropInt' +// Les propriétés permettent de générrer les accésseurs/affecteurs publiques à la compilation +// Par défaut, le nom de l'affecteur est la chaine 'set' suivi par le nom de la @property +@property int propInt; // Nom de l'affecteur = 'setPropInt' @property (copy) id copyId; // (copy) => Copie l'objet pendant l'affectation // (readonly) => Ne peut pas affecté la variable en dehors de l'@interface -// Utilisez @synthesize dans l'@implementation pour créer l'accésseur +// Il faut utiliser le mot clé '@synthesize' dans l'@implementation pour créer l'accésseur @property (readonly) NSString *roString; -// Vous pouvez personnaliser les noms des accésseurs et des affecteurs au lieu d'utiliser les -// noms par défauts +// Vous pouvez aussi personnaliser les noms des accésseurs ou des affecteurs @property (getter=longeurGet, setter=longeurSet:) int longeur; // Methodes -+/- (type de retour)signatureDeLaMethode:(Type Du Parametre *)nomDuParametre; ++/- (TypeDeRetour)signatureDeLaMethode:(TypeDuParametre *)nomDuParametre; -// + pour les méthodes de classe : +// '+' signifie que c'est une méthode de classe (statique) : + (NSString *)methodeDeClasse; + (MaClasse *)maClasseDepuisLaHauteur:(NSNumber *)hauteurParDefaut; -// - pour les méthodes d'instances : +// '-' pour les méthodes d'instances (classe) : - (NSString *)methodeInstanceAvecUnParametre:(NSString *)string; - (NSNumber *)methodeInstanceAvecUnParametre:(NSString*)string puisUnDeuxieme:(NSNumber *)number; // Contructeur avec des arguments : - (id)initAvecDistance:(int)distanceParDefault; -// Les méthodes en Objective-C sont très descriptive +// Les méthodes en Objective-C sont très descriptives -@end // Définit la fin de l'interface +@end // Fin de l'interface -// Exemple d'utilisation de MaClasse +// Voici un exemple d'utilisation de MaClasse MaClasse *maClasse = [[MaClasse alloc] init]; // créer une instance de MaClasse [maClasse setNombre:10]; NSLog(@"%d", [maClasse nombre]); // affiche => 10 @@ -336,27 +337,26 @@ NSLog(@"%i", [maClasse longeurGet]); // affiche => 32 maClasse.nombre = 45; NSLog(@"%i", maClasse.nombre); // maClasse => 45 -// Appeler un méthode de classe : +// Pour appeler une méthode de classe : NSString *s1 = [MaClasse methodeDeClasse]; MaClasse *m2 = [MaClasse maClasseDepuisLaHauteur:38]; -// Appeler un méthode d'instance : +// Pour appeler une méthode d'instance : MaClasse *maClasse = [[MaClasse alloc] init]; // Créer une instance de MaClasse NSString *stringDepuisUneInstanceDeMethode = [maClasse methodeInstanceAvecUnParametre:@"Salut"]; -// Sélecteurs sont un moyen de représenté les méthodes dynamiquement -// Ils sont utilisé pour appeller des méthodes de classe, passer des methodes au travers de fonctions -// pour notifier les autres classes qu'elle peuvent les appellé, et pour sauvegarder les méthodes en -// tant que variables -// SEL est un type de donnée. @selected retourne un selecteur à partir d'un nom de methode +// les sélecteurs sont un moyen de décrire les méthodes dynamiquement +// Ils sont utilisés pour appeler des méthodes de classe et avoir des pointeurs de fonctions +// facilement manipulable +// SEL est un type de donnée et @selector retourne un selecteur à partir d'un nom de methode SEL selecteur = @selector(methodeInstanceAvecUnParametre:puisUnDeuxieme:); -if ([maClasse respondsToSelector:selecteur]) { // Vérifie si la classe contient la méthode - // Doit mettre tous les arguments de la méthode dans un seul objet pour l'envoyer via la fonction +if ([maClasse respondsToSelector:selecteur]) { // Vérifie si la classe possède la méthode + // Met les arguments de la méthode dans un seul objet pour l'envoyer via la fonction // performSelector:withObject: NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; - [myClass performSelector:selectorVar withObject:arguments]; // Appele la méthode + [myClass performSelector:selectorVar withObject:arguments]; // Appele la méthode via le sélecteur } else { - // NSStringFromSelector() retourne une chaine de charactères à partir d'un sélecteur + // NSStringFromSelector() retourne une chaine de caractères à partir d'un sélecteur NSLog(@"MaClasse ne possède pas de méthode : %@", NSStringFromSelector(selecteur)); } @@ -417,7 +417,7 @@ distance = 18; - (NSString *)methodeInstanceAvecUnParametre:(NSString *)string { - return @"Ma chaine de charactère"; + return @"Ma chaine de caractère"; } - (NSNumber *)methodeInstanceAvecUnParametre:(NSString*)string puisUnDeuxieme:(NSNumber *)number -- cgit v1.2.3 From 409317cf25c28dc9a034e0b23b7e284d73dd97e6 Mon Sep 17 00:00:00 2001 From: Yannick Date: Fri, 24 Jan 2014 20:19:22 +0100 Subject: [FIX] Typing Errors In The Second Part --- fr-fr/objective-c-fr.html.markdown | 63 +++++++++++++++++++++----------------- 1 file changed, 35 insertions(+), 28 deletions(-) diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index ca0b2391..d0e6f3eb 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -315,7 +315,7 @@ int main (int argc, const char * argv[]) + (NSString *)methodeDeClasse; + (MaClasse *)maClasseDepuisLaHauteur:(NSNumber *)hauteurParDefaut; -// '-' pour les méthodes d'instances (classe) : +// '-' pour les méthodes d'instances : - (NSString *)methodeInstanceAvecUnParametre:(NSString *)string; - (NSNumber *)methodeInstanceAvecUnParametre:(NSString*)string puisUnDeuxieme:(NSNumber *)number; @@ -355,46 +355,48 @@ if ([maClasse respondsToSelector:selecteur]) { // Vérifie si la classe possède // performSelector:withObject: NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; [myClass performSelector:selectorVar withObject:arguments]; // Appele la méthode via le sélecteur -} else { +} +else { // NSStringFromSelector() retourne une chaine de caractères à partir d'un sélecteur NSLog(@"MaClasse ne possède pas de méthode : %@", NSStringFromSelector(selecteur)); } -// Implement la méthode dans le fichier d'impémentation (MaClasse.m) +// Le fichier d'implémentation de la classe MaClasse (MaClasse.m) doit commencer comme ceci : @implementation MaClasse { - long distance; // Variable d'instance privé + long distance; // Variable d'instance privé (équivalent à @private dans l'interface) NSNumber hauteur; } -// Pour accéder à une variable depuis le fichier d'implémentation on peut utiliser le _ devant le nom +// Pour accéder à une variable depuis l'implémentation on peut utiliser le _ (tiret bas) devant le nom // de la variable : _nombre = 5; -// Accès d'une variable définit dans le fichier d'implémentation : +// Accès d'une variable défini dans le fichier d'implémentation : distance = 18; -// Pour utiliser la varible @property dans l'implémentation, utiliser @synthesize qui créer les -// accésseurs : -@synthesize roString = _roString; // _roString est disponible dans l'@implementation +// Pour utiliser la variable défini par l'intermédiaire de @property, il faut utiliser @synthesize +// qui permet de créer les affecteurs et les accésseurs : +@synthesize roString = _roString; // _roString est maintenant disponible dans l'implementation -// En contre-partie de l'initialisation, la fonction dealloc est appelé quand l'objet est n'est plus -// utilisé +// En contre-partie de l'appel de la fonction 'init' lors de la création d'un objet, la fonction +// 'dealloc' est appelée quand l'objet est supprimé - (void)dealloc { - [hauteur release]; // Si vous n'utilisez par l'ARC, pensez bien à supprimer l'objet - [super dealloc]; // et à appeler la méthode de la classe parent + [hauteur release]; // Si vous n'utilisez pas ARC, pensez bien à supprimer l'objet + [super dealloc]; // et à appeler la méthode 'dealloc' de la classe parent } // Les constructeurs sont une manière de créer des instances de classes -// Ceci est le constructeur par défaut; il est appelé quand l'objet est créé +// 'init' est le constructeur par défaut; il est appelé quand l'objet est créé - (id)init { if ((self = [super init])) // 'super' est utilisé pour appeler la méthode de la classe parent { - self.count = 1; // 'self' est utilisé pour appeler la méthodes de l'objet courrant + self.count = 1; // 'self' est utilisé pour appeler la méthodes de l'instance courante } return self; } -// Vous pouvez créer des constructeurs qui possèdent des arguments : +// Vous pouvez aussi créer des constructeurs qui possèdent des arguments +// Attention : chaque nom de constructeur doit absolument commencer par 'init' - (id)initAvecUneDistance:(int)distanceParDefault { if ((self = [super init])) @@ -404,6 +406,7 @@ distance = 18; } } +// Implémentation d'une méthode de classe + (NSString *)methodDeClasse { return [[self alloc] init]; @@ -415,6 +418,7 @@ distance = 18; return [[self alloc] init]; } +// Implémentation d'une méthode d'instance - (NSString *)methodeInstanceAvecUnParametre:(NSString *)string { return @"Ma chaine de caractère"; @@ -425,8 +429,8 @@ distance = 18; return @42; } -// Pour créer une méthode privée, il faut la définir dans l'@implementation et non pas dans -// l'@interface +// Pour créer une méthode privée, il faut la définir dans l'implementation et non pas dans +// l'interface - (NSNumber *)methodePrivee { return @72; @@ -434,7 +438,7 @@ distance = 18; [self methodePrivee]; // Appel de la méthode privée -// Méthode déclarée dans MonProtocole +// Implémentation d'une méthode qui est déclarée dans - (void)methodeDuProtocole { // expressions @@ -443,7 +447,8 @@ distance = 18; @end // Fin de l'implémentation /* - * Un protocole déclare les méthodes qu'ils doivent implémenter afin de se conformer celui-ci + * Un protocole déclare des méthodes que chaque objet respectant celui-ci doit implémenter + * afin de se conformer celui-ci * Un protocole n'est pas une classe, c'est juste une interface */ @protocol MonProtocole @@ -455,14 +460,16 @@ distance = 18; // Gestion de la mémoire /////////////////////////////////////// /* -Pour chaque objet utilisé dans une application, la mémoire doit être alloué pour chacun d'entre eux. -Quand l'application en a fini avec cet objet, la mémoire doit être libéré pour assurer la performane. -Il n'y a pas de ramasse-miettes en Objective-C, il utilise à la place le comptage de référence à la -place. Tant que le compteur de référence est supérieur à 1 sur un objet, l'objet ne sera pas supprimé - -Quand une instance détient un objet, le compteur de référence est incrémenté de un. Quand l'objet est -libéré, le compteur est décrémenté de un. Quand le compteur est égale à zéro, l'objet est supprimé de -la mémoire +A chaque fois qu'un objet est créé dans l'application, un bloque mémoire doit être alloué. +Quand l'application en a fini avec cet objet, la mémoire doit être libéré pour assurer la bonne +réactivité du programme (éviter les fuites mémoires) +Il n'y a pas de ramasse-miettes en Objective-C contrairement à Java par example. L'Objective-C repose +sur le comptage de référence. A chaque objet est assigné un compteur qui permet de connaitre son état. + +Le principe est le suivant : +Lorsque l'objet est créé, le compteur est initialisé à 1. Quand une instance détient un objet, le +compteur est incrémenté de un. Quand l'objet est libéré, le compteur est décrémenté de un. Enfin +quand le compteur arrive à zéro, l'objet est supprimé de la mémoire Une bonne pratique à suivre quand on travaille avec des objets est la suivante : (1) créer un objet, (2) utiliser l'objet, (3) supprimer l'objet de la mémoire -- cgit v1.2.3 From dc8f3cbe30a8271f4be809ce17d68d146ee53f88 Mon Sep 17 00:00:00 2001 From: Yannick Date: Fri, 24 Jan 2014 22:07:09 +0100 Subject: [FIX] typo with the help of @Nami-Doc --- fr-fr/objective-c-fr.html.markdown | 138 ++++++++++++++++++++----------------- 1 file changed, 74 insertions(+), 64 deletions(-) diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index d0e6f3eb..b14b3a52 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -62,7 +62,7 @@ int main (int argc, const char * argv[]) // Il faut mettre un astérisque devant la déclaration d'objet fortement typé MaClasse *monObject1 = nil; // Typage fort id monObject2 = nil; // Typage faible - // 'description' est une méthode qui permet d'afficher un aperçut de l'objet + // 'description' est une méthode qui permet de retourner un aperçut de l'objet sous forme textuelle // La méthode 'description' est appelée par défaut quand on utilise le paramètre '%@' NSLog(@"%@ and %@", monObject1, [monObject2 description]); // Affiche "(null) et (null)" @@ -96,11 +96,11 @@ int main (int argc, const char * argv[]) long quaranteDeuxLong = [nombreQuaranteDeuxLong longValue]; // ou 42 NSLog(@"%li", fortyTwoLong); - // Les nombres flottans - NSNumber *nombrePiFlottan = @3.141592654F; - float piFlottan = [nombrePiFlottan floatValue]; // ou 3.141592654f - NSLog(@"%f", piFlottan); // affiche => 3.141592654 - NSLog(@"%5.2f", piFlottan); // affiche => " 3.14" + // Les nombres flottants + NSNumber *nombrePiFlottant = @3.141592654F; + float piFlottant = [nombrePiFlottant floatValue]; // ou 3.141592654f + NSLog(@"%f", piFlottant); // affiche => 3.141592654 + NSLog(@"%5.2f", piFlottant); // affiche => " 3.14" NSNumber *nombrePiDouble = @3.1415926535; double piDouble = [nombrePiDouble doubleValue]; // ou 3.1415926535 @@ -108,11 +108,11 @@ int main (int argc, const char * argv[]) NSLog(@"%4.2f", piDouble); // affiche => "3.14" // NSDecimalNumber est une classe pour avoir plus de précision sur les nombres - // flottans et les doubles + // flottants et les doubles NSDecimalNumber *decNumUn = [NSDecimalNumber decimalNumberWithString:@"10.99"]; NSDecimalNumber *decNumDeux = [NSDecimalNumber decimalNumberWithString:@"5.002"]; - // NSDecimalNumber n'est pas capable d'utiliser les opérations standards (+, -, *, /) - // Il faut utiliser les méthodes suivantes : + // NSDecimalNumber ne permet pas d'utiliser les opérations standards (+, -, *, /) + // Il faut utiliser les méthodes suivantes à la place : [decNumUn decimalNumberByAdding:decNumDeux]; [decNumUn decimalNumberBySubtracting:decNumDeux]; [decNumUn decimalNumberByMultiplyingBy:decNumDeux]; @@ -133,7 +133,8 @@ int main (int argc, const char * argv[]) NSNumber *troisiemeNombre = uneListe[2]; NSLog(@"Troisième nombre = %@", troisiemeNombre); // affiche "Troisième nombre = 3" // NSMutableArray est une version mutable de NSArray - // Cela permet de modifier la liste en ajoutant/supprimant/modifiant des objets + // Cela permet de modifier la liste en ajoutant de nouveaux éléments et en supprimant ou + // changeant de place des objets déjà présent // C'est très pratique, mais pas aussi performant que l'utilisation de la classe NSArray NSMutableArray *listeMutable = [NSMutableArray arrayWithCapacity:2]; [listeMutable addObject:@"Bonjour tous le"]; @@ -142,7 +143,7 @@ int main (int argc, const char * argv[]) NSLog(@"%@", [listeMutable objectAtIndex:0]); // affiche => "Monde" // Les dictionnaires - // Un dictionnaire est un ensemble de { clé: valeur } + // Un dictionnaire est un ensemble de clés : valeurs NSDictionary *unDictionnaire = @{ @"cle1" : @"valeur1", @"cle2" : @"valeur2" }; NSObject *valeur = unDictionnaire[@"Une clé"]; NSLog(@"Objet = %@", valeur); // affiche "Objet = (null)" @@ -153,7 +154,7 @@ int main (int argc, const char * argv[]) [dictionnaireMutable removeObjectForKey:@"cle1"]; // Les ensembles - // Un ensemble peut ne peut contenir que des objets uniques contrairement aux NSArray + // Un ensemble ne peut contenir de duplicatas contrairement aux NSArray NSSet *ensemble = [NSSet setWithObjects:@"Salut", @"Salut", @"Monde", nil]; NSLog(@"%@", ensemble); // affiche => {(Salut, Monde)} (Pas forcément dans le même ordre) // NSMutableSet est un ensemble mutable @@ -166,7 +167,7 @@ int main (int argc, const char * argv[]) // Les Operateurs /////////////////////////////////////// - // Les opérateurs sont les mêmes que ceux du langage C + // Les opérateurs sont pareil qu'en C // Par exemple : 2 + 5; // => 7 4.2f + 5.1f; // => 9.3f @@ -176,13 +177,13 @@ int main (int argc, const char * argv[]) 0 || 1; // => 1 (ou logique) ~0x0F; // => 0xF0 (négation bit à bit) 0x0F & 0xF0; // => 0x00 (et bit à bit) - 0x01 << 1; // => 0x02 (décale à gauche (par 1)) + 0x01 << 1; // => 0x02 (décalage à gauche (par 1)) /////////////////////////////////////// - // Les Structures de Controle + // Les Structures de Contrôle /////////////////////////////////////// - // Expression "Si-Sinon" (If-Else) + // Structure "Si-Sinon" (If-Else) if (NO) { NSLog(@"Je ne suis jamais affiché"); @@ -194,7 +195,7 @@ int main (int argc, const char * argv[]) NSLog(@"Je suis affiché"); } - // Expression "Selon" (Switch) + // Structure "Selon" (Switch) switch (2) { case 0: @@ -211,7 +212,7 @@ int main (int argc, const char * argv[]) } break; } - // Expression de boucle "Tant Que" (While) + // Structure de boucle "Tant Que" (While) int ii = 0; while (ii < 4) { @@ -221,7 +222,7 @@ int main (int argc, const char * argv[]) // "2," // "3," - // Expression de boucle "Pour" (For) + // Structure de boucle "Pour" (For) int jj; for (jj=0; jj < 4; jj++) { @@ -231,7 +232,7 @@ int main (int argc, const char * argv[]) // "2," // "3," - // Expression de boucle "Pour Chaque" (Foreach) + // Structure de boucle "Pour Chaque" (Foreach) NSArray *valeurs = @[@0, @1, @2, @3]; for (NSNumber *valeur in valeurs) { @@ -241,7 +242,7 @@ int main (int argc, const char * argv[]) // "2," // "3," - // Expression "Essayer-Attraper-Finalement" (Try-Catch-Finally) + // Structure "Essayer-Attraper-Finalement" (Try-Catch-Finally) @try { @throw [NSException exceptionWithName:@"FileNotFoundException" @@ -264,8 +265,11 @@ int main (int argc, const char * argv[]) // étapes précédentes ne sont pas terminées MaClass *monObjet = [[MaClass alloc] init]; - // L'Objective-C est basé sur le principe d'envoie de message et non sur celui - // d'appel de méthode comme la plupart des autres langages de programmation + // L'Objet en Objective-C est basé sur le principe d'envoie de message et non sur + // celui d'appel de méthode comme la plupart des autres langages + // C'est un détail important car cela veut dire que l'on peut envoyer un message + // à un objet qui ne possède pas la méthode demandée sans aucune incidence sur le + // fonctionnement du programme (aucune exception ne sera levée) [myObject instanceMethodWithParameter:@"Steve Jobs"]; // Nettoie la mémoire qui a été utilisée dans le programme @@ -286,10 +290,10 @@ int main (int argc, const char * argv[]) // La déclaration d'une classe en Objective-C commence par la déclaration de son interface : // @interface NomDeLaClasse : NomDeLaClasseParent // { -// type nom; // declaration d'une variable; +// type nom; // Déclaration d'une variable; // } -// @property type nom; // declaration d'une propriété -// -/+ (type)nomDeLaMethode; // Declaration d'une methode +// @property type nom; // Déclaration d'une propriété +// -/+ (type)nomDeLaMethode; // Déclaration d'une methode // @end // Termine la déclaration // NSObject est la classe de base (super classe) en Objective-C @interface MaClasse : NSObject @@ -298,7 +302,7 @@ int main (int argc, const char * argv[]) @private id donnee; // Accès privé (il est plus pratique de le faire dans l'implémentation) NSString *nom; } -// Les propriétés permettent de générrer les accésseurs/affecteurs publiques à la compilation +// Les propriétés permettent de générer les accésseurs/affecteurs publiques à la compilation // Par défaut, le nom de l'affecteur est la chaine 'set' suivi par le nom de la @property @property int propInt; // Nom de l'affecteur = 'setPropInt' @property (copy) id copyId; // (copy) => Copie l'objet pendant l'affectation @@ -345,7 +349,7 @@ MaClasse *m2 = [MaClasse maClasseDepuisLaHauteur:38]; MaClasse *maClasse = [[MaClasse alloc] init]; // Créer une instance de MaClasse NSString *stringDepuisUneInstanceDeMethode = [maClasse methodeInstanceAvecUnParametre:@"Salut"]; -// les sélecteurs sont un moyen de décrire les méthodes dynamiquement +// Les sélecteurs sont un moyen de décrire les méthodes dynamiquement // Ils sont utilisés pour appeler des méthodes de classe et avoir des pointeurs de fonctions // facilement manipulable // SEL est un type de donnée et @selector retourne un selecteur à partir d'un nom de methode @@ -363,20 +367,20 @@ else { // Le fichier d'implémentation de la classe MaClasse (MaClasse.m) doit commencer comme ceci : @implementation MaClasse { - long distance; // Variable d'instance privé (équivalent à @private dans l'interface) + long distance; // Variable d'instance privée (équivalent à @private dans l'interface) NSNumber hauteur; } // Pour accéder à une variable depuis l'implémentation on peut utiliser le _ (tiret bas) devant le nom // de la variable : _nombre = 5; -// Accès d'une variable défini dans le fichier d'implémentation : +// Accès d'une variable définie dans le fichier d'implémentation : distance = 18; -// Pour utiliser la variable défini par l'intermédiaire de @property, il faut utiliser @synthesize -// qui permet de créer les affecteurs et les accésseurs : +// Pour utiliser la variable définie par l'intermédiaire de @property, il faut utiliser @synthesize +// qui permet de créer les affecteurs et les accésseurs correspondants : @synthesize roString = _roString; // _roString est maintenant disponible dans l'implementation -// En contre-partie de l'appel de la fonction 'init' lors de la création d'un objet, la fonction +// A l'inverse dela méthode 'init' qui est appelée lors de la création d'un objet, la fonction // 'dealloc' est appelée quand l'objet est supprimé - (void)dealloc { @@ -384,18 +388,18 @@ distance = 18; [super dealloc]; // et à appeler la méthode 'dealloc' de la classe parent } -// Les constructeurs sont une manière de créer des instances de classes -// 'init' est le constructeur par défaut; il est appelé quand l'objet est créé +// Les constructeurs sont des fonctions qui permettent d'instancier un objet +// 'init' est le constructeur par défaut en Objective-C - (id)init { if ((self = [super init])) // 'super' est utilisé pour appeler la méthode de la classe parent { - self.count = 1; // 'self' est utilisé pour appeler la méthodes de l'instance courante + self.count = 1; // 'self' permet d'appeler la méthode de l'instance courante } return self; } -// Vous pouvez aussi créer des constructeurs qui possèdent des arguments +// Vous pouvez aussi créer des constructeurs avec des arguments // Attention : chaque nom de constructeur doit absolument commencer par 'init' - (id)initAvecUneDistance:(int)distanceParDefault { @@ -447,8 +451,8 @@ distance = 18; @end // Fin de l'implémentation /* - * Un protocole déclare des méthodes que chaque objet respectant celui-ci doit implémenter - * afin de se conformer celui-ci + * Un protocole déclare des méthodes et propriétés que chaque implémentation doit avoir afin de se + * conformer à celui-ci * Un protocole n'est pas une classe, c'est juste une interface */ @protocol MonProtocole @@ -460,16 +464,17 @@ distance = 18; // Gestion de la mémoire /////////////////////////////////////// /* -A chaque fois qu'un objet est créé dans l'application, un bloque mémoire doit être alloué. -Quand l'application en a fini avec cet objet, la mémoire doit être libéré pour assurer la bonne -réactivité du programme (éviter les fuites mémoires) -Il n'y a pas de ramasse-miettes en Objective-C contrairement à Java par example. L'Objective-C repose -sur le comptage de référence. A chaque objet est assigné un compteur qui permet de connaitre son état. +À chaque fois qu'un objet est créé dans l'application, un bloc mémoire doit être alloué. +Quand l'application en a fini avec cet objet, la mémoire doit être libérée afin d'éviter les fuites +mémoires +Il n'y a pas de ramasse-miettes en Objective-C contrairement à Java par exemple. La gestion de la +mémoire repose sur le comptage de référence qui, pour chaque objet, assigne un compteur qui permet +de connaitre le nombre de référence qui l'utilise. Le principe est le suivant : Lorsque l'objet est créé, le compteur est initialisé à 1. Quand une instance détient un objet, le -compteur est incrémenté de un. Quand l'objet est libéré, le compteur est décrémenté de un. Enfin -quand le compteur arrive à zéro, l'objet est supprimé de la mémoire +compteur est incrémenté de un. Quand l'objet est libéré, le compteur est décrémenté de un. Au moment +où le compteur arrive à zéro, l'objet est supprimé de la mémoire Une bonne pratique à suivre quand on travaille avec des objets est la suivante : (1) créer un objet, (2) utiliser l'objet, (3) supprimer l'objet de la mémoire @@ -478,34 +483,39 @@ Une bonne pratique à suivre quand on travaille avec des objets est la suivante MaClasse *classeVar = [MyClass alloc]; // 'alloc' incrémente le compteur de référence [classeVar release]; // Décrémente le compteur de rérence // 'retain' incrémente le compteur de référence -// Si 'classeVar' est libéré, l'objet reste en mémoire car le compteur de référence est non nulle +// Si 'classeVar' est libéré, l'objet reste en mémoire car le compteur de référence est non nul MaClasse *nouvelleVar = [classVar retain]; -[classeVar autorelease]; // Supprime l'appartenance de l'objet à la fin du block +[classeVar autorelease]; // Supprime l'appartenance de l'objet à la fin du bloc -// @property peuvent utiliser 'retain' et 'assign' +// Les @property peuvent utiliser 'retain' et 'assign' @property (retain) MaClasse *instance; // Libère l'ancienne valeur et retient la nouvelle @property (assign) NSSet *set; // Pointeur vers la valeur sans retenir/libérer l'ancienne valeur // Automatic Reference Counting (ARC) -// La gestion de la mémoire étant pénible, depuis iOS 4 et Xcode 4.2, Apple a introduit le comptage de référence -// automatique (Automatic Reference Counting en anglais). -// ARC est une fonctionnalité du compilateur qui lui permet d'ajouter les 'retain', 'release' et 'autorelease' -// automatiquement. Donc quand utilisez ARC vous de devez plus utiliser ces mots clés +// La gestion de la mémoire étant pénible, depuis iOS 4 et Xcode 4.2, Apple a introduit le comptage de +// référence automatique (Automatic Reference Counting en anglais) +// ARC est une fonctionnalité du compilateur qui permet d'ajouter les 'retain', 'release' et 'autorelease' +// automatiquement. Cela veut dire que lorsque vous utilisez ARC vous ne devez plus utiliser ces mot-clés MaClasse *arcMaClasse = [[MaClasse alloc] init]; // ... code utilisant arcMaClasse -// Sans ARC, vous auriez dû appeler [arcMaClasse release] après avoir utilisé l'objet. Mais avec ARC il n'y a plus -// besoin car le compilateur ajoutera l'expréssion automatiquement pour vous +// Sans ARC, vous auriez dû appeler [arcMaClasse release] après avoir utilisé l'objet. Mais avec ARC +// activé il n'est plus nécessaire de le faire car le compilateur ajoutera l'expréssion automatiquement +// pour vous // Les mots clés 'assign' et 'retain', avec ARC sont respectivement remplacé par 'weak' et 'strong' -@property (weak) MaClasse *weakVar; // 'weak' ne retient pas l'objet. Si l'instance original descend à zero, weakVar -// sera automatiquement mis à nil -@property (strong) MaClasse *strongVar; // 'strong' prend posséssion de l'objet comme le ferai le mot clé 'retain' - -// Pour l'instanciation des variables (en dehors de @property), vous pouvez utiliser les instructions suivantes : -__strong NSString *strongString; // Par defaut. La variable est retenu en mémoire jusqu'à la fin de sa portée -__weak NSSet *weakSet; // Réfère la variable en utilisant le mot clé '__weak' -__unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais quand la variable n'est pas mis à nil quand l'objet -// est supprimé ailleurs +@property (weak) MaClasse *weakVar; // 'weak' ne retient pas l'objet. Si le compteur de référence +// descend à zero, weakVar sera automatiquement mis à nil +@property (strong) MaClasse *strongVar; // 'strong' prend possession de l'objet comme le ferait avec +// le mot-clé 'retain' + +// Pour l'instanciation des variables (en dehors de @property), vous pouvez utiliser les instructions +// suivantes : +__strong NSString *strongString; // Par défaut. La variable est retenue en mémoire jusqu'à la fin +// de sa portée +__weak NSSet *weakSet; // Maintient une référence vers l'objet sans incrémenter son compteur de référence : +// Lorsque l'objet sera supprimé, weakSet sera mis à nil automatiquement +__unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais la variable n'est pas mis à nil quand +// l'objet est supprimé ``` ## Lectures Complémentaires -- cgit v1.2.3 From 863194a89aa98fd446910246980e7c4ba8954cfa Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Fri, 24 Jan 2014 15:30:11 -0600 Subject: - add variadic function example --- go.html.markdown | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index ee41642a..d68ba51b 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -5,6 +5,7 @@ language: Go filename: learngo.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] --- Go was created out of the need to get work done. It's not the latest trend @@ -175,7 +176,20 @@ func learnFlowControl() { goto love love: - learnInterfaces() // Good stuff coming up! + // Good stuff coming up! + learnVariadicParams("great", "learning", "here!") + learnInterfaces() +} + +// Functions can have variadic parameters +func learnVariadicParams(myStrings ...string) { + // iterate each value of the variadic + for _, param := range myStrings { + fmt.Println("param:", param) + } + + // pass variadic value as a variadic parameter + fmt.Println("params:", fmt.Sprintln(myStrings...)) } // Define Stringer as an interface type with one method, String. -- cgit v1.2.3 From ef8ed1834c24159ff951192985b00886b78c5342 Mon Sep 17 00:00:00 2001 From: skovorodkin Date: Tue, 31 Dec 2013 04:28:30 +0300 Subject: [julia/ru] Add first version --- ru-ru/julia-ru.html.markdown | 749 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 749 insertions(+) create mode 100644 ru-ru/julia-ru.html.markdown diff --git a/ru-ru/julia-ru.html.markdown b/ru-ru/julia-ru.html.markdown new file mode 100644 index 00000000..51654cfe --- /dev/null +++ b/ru-ru/julia-ru.html.markdown @@ -0,0 +1,749 @@ +--- +language: julia +contributors: + - ["Leah Hanson", "http://leahhanson.us"] +translators: + - ["Sergey Skovorodkin", "https://github.com/skovorodkin"] +filename: learnjulia.jl +--- + +Julia — гомоиконный функциональный язык программирования для технических расчётов. +Несмотря на полную поддержку гомоиконных макросов, функций первого класса и конструкций управления низкого уровня, этот язык так же прост в изучении и применении, как и Python. + +Документ описывает текущую dev-версию Julia от 18-о октября 2013 года. + +```ruby + +# Однострочные комментарии начинаются со знака решётки. + +#################################################### +## 1. Примитивные типы данных и операторы +#################################################### + +# Всё в Julia — выражение. + +# Простые численные типы +3 #=> 3 (Int64) +3.2 #=> 3.2 (Float64) +2 + 1im #=> 2 + 1im (Complex{Int64}) +2//3 #=> 2//3 (Rational{Int64}) + +# Доступны все привычные инфиксные операторы +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7.0 +5 / 2 #=> 2.5 # деление Int на Int всегда возвращает Float +div(5, 2) #=> 2 # для округления к нулю используется div +5 \ 35 #=> 7.0 +2 ^ 2 #=> 4 # возведение в степень +12 % 10 #=> 2 + +# С помощью скобок можно изменить приоритет операций +(1 + 3) * 2 #=> 8 + +# Побитовые операторы +~2 #=> -3 # НЕ (NOT) +3 & 5 #=> 1 # И (AND) +2 | 4 #=> 6 # ИЛИ (OR) +2 $ 4 #=> 6 # сложение по модулю 2 (XOR) +2 >>> 1 #=> 1 # логический сдвиг вправо +2 >> 1 #=> 1 # арифметический сдвиг вправо +2 << 1 #=> 4 # логический/арифметический сдвиг влево + +# Функция bits возвращает бинарное представление числа +bits(12345) +#=> "0000000000000000000000000000000000000000000000000011000000111001" +bits(12345.0) +#=> "0100000011001000000111001000000000000000000000000000000000000000" + +# Логические значения являются примитивами +true +false + +# Булевы операторы +!true #=> false +!false #=> true +1 == 1 #=> true +2 == 1 #=> false +1 != 1 #=> false +2 != 1 #=> true +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true +# Сравнения можно объединять цепочкой +1 < 2 < 3 #=> true +2 < 3 < 2 #=> false + +# Строки объявляются с помощью двойных кавычек — " +"This is a string." + +# Символьные литералы создаются с помощью одинарных кавычек — ' +'a' + +# Строки индексируются как массивы символов +"This is a string"[1] #=> 'T' # Индексы начинаются с единицы +# Индексирование не всегда правильно работает для UTF8-строк, +# поэтому рекомендуется использовать итерирование (map, for-циклы и т.п.). + +# Для строковой интерполяции используется знак доллара ($): +"2 + 2 = $(2 + 2)" #=> "2 + 2 = 4" +# В скобках можно использовать любое выражение языка. + +# Другой способ форматирования строк — макрос printf +@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 + +#################################################### +## 2. Переменные и коллекции +#################################################### + +# Вывод +println("I'm Julia. Nice to meet you!") + +# Переменные инициализируются без предварительного объявления +some_var = 5 #=> 5 +some_var #=> 5 + +# Попытка доступа к переменной до инициализации вызывает ошибку +try + some_other_var #=> ERROR: some_other_var not defined +catch e + println(e) +end + +# Имена переменных начинаются с букв. +# После первого символа можно использовать буквы, цифры, +# символы подчёркивания и восклицательные знаки. +SomeOtherVar123! = 6 #=> 6 + +# Допустимо использование unicode-символов +☃ = 8 #=> 8 +# Это особенно удобно для математических обозначений +2 * π #=> 6.283185307179586 + +# Рекомендации по именованию: +# * имена переменных в нижнем регистре, слова разделяются символом +# подчёркивания ('\_'); +# +# * для имён типов используется CamelCase; +# +# * имена функций и макросов в нижнем регистре +# без разделения слов символом подчёркивания; +# +# * имя функции, изменяющей переданные ей аргументы (in-place function), +# оканчивается восклицательным знаком. + +# Массив хранит последовательность значений, индексируемых с единицы до n: +a = Int64[] #=> пустой массив Int64-элементов + +# Одномерный массив объявляется разделёнными запятой значениями. +b = [4, 5, 6] #=> массив из трёх Int64-элементов: [4, 5, 6] +b[1] #=> 4 +b[end] #=> 6 + +# Строки двумерного массива разделяются точкой с запятой. +# Элементы строк разделяются пробелами. +matrix = [1 2; 3 4] #=> 2x2 Int64 Array: [1 2; 3 4] + +# push! и append! добавляют в список новые элементы +push!(a,1) #=> [1] +push!(a,2) #=> [1,2] +push!(a,4) #=> [1,2,4] +push!(a,3) #=> [1,2,4,3] +append!(a,b) #=> [1,2,4,3,4,5,6] + +# pop! удаляет из списка последний элемент +pop!(b) #=> возвращает 6; массив b снова равен [4,5] + +# Вернём 6 обратно +push!(b,6) # b снова [4,5,6]. + +a[1] #=> 1 # индексы начинаются с единицы! + +# Последний элемент можно получить с помощью end +a[end] #=> 6 + +# Операции сдвига +shift!(a) #=> 1 and a is now [2,4,3,4,5,6] +unshift!(a,7) #=> [7,2,4,3,4,5,6] + +# Восклицательный знак на конце названия функции означает, +# что функция изменяет переданные ей аргументы. +arr = [5,4,6] #=> массив из 3 Int64-элементов: [5,4,6] +sort(arr) #=> [4,5,6]; но arr равен [5,4,6] +sort!(arr) #=> [4,5,6]; а теперь arr — [4,5,6] + +# Попытка доступа за пределами массива выбрасывает BoundsError +try + a[0] #=> ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] #=> ERROR: BoundsError() in getindex at array.jl:270 +catch e + println(e) +end + +# Вывод ошибок содержит строку и файл, где произошла ошибка, +# даже если это случилось в стандартной библиотеке. +# Если вы собрали Julia из исходных кодов, +# то найти эти файлы можно в директории base. + +# Создавать массивы можно из последовательности +a = [1:5] #=> массив из 5 Int64-элементов: [1,2,3,4,5] + +# Срезы +a[1:3] #=> [1, 2, 3] +a[2:] #=> [2, 3, 4, 5] +a[2:end] #=> [2, 3, 4, 5] + +# splice! удаляет элемент из массива +# Remove elements from an array by index with splice! +arr = [3,4,5] +splice!(arr,2) #=> 4 ; arr теперь равен [3,5] + +# append! объединяет списки +b = [1,2,3] +append!(a,b) # теперь a равен [1, 2, 3, 4, 5, 1, 2, 3] + +# Проверка на вхождение +in(1, a) #=> true + +# Длина списка +length(a) #=> 8 + +# Кортеж — неизменяемая структура. +tup = (1, 2, 3) #=> (1,2,3) # кортеж (Int64,Int64,Int64). +tup[1] #=> 1 +try: + tup[1] = 3 #=> ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +catch e + println(e) +end + +# Многие функции над списками работают и для кортежей +length(tup) #=> 3 +tup[1:2] #=> (1,2) +in(2, tup) #=> true + +# Кортежи можно распаковывать в переменные +a, b, c = (1, 2, 3) #=> (1,2,3) # a = 1, b = 2 и c = 3 + +# Скобки из предыдущего примера можно опустить +d, e, f = 4, 5, 6 #=> (4,5,6) + +# Кортеж из одного элемента не равен значению этого элемента +(1,) == 1 #=> false +(1) == 1 #=> true + +# Обмен значений +e, d = d, e #=> (5,4) # d = 5, e = 4 + + +# Словари содержат ассоциативные массивы +empty_dict = Dict() #=> Dict{Any,Any}() + +# Для создания словаря можно использовать литерал +filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +# => Dict{ASCIIString,Int64} + +# Значения ищутся по ключу с помощью оператора [] +filled_dict["one"] #=> 1 + +# Получить все ключи +keys(filled_dict) +#=> KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# Заметьте, словарь не запоминает порядок, в котором добавляются ключи. + +# Получить все значения. +values(filled_dict) +#=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# То же касается и порядка значений. + +# Проверка вхождения ключа в словарь +in(("one", 1), filled_dict) #=> true +in(("two", 3), filled_dict) #=> false +haskey(filled_dict, "one") #=> true +haskey(filled_dict, 1) #=> false + +# Попытка обратиться к несуществующему ключу выбросит ошибку +try + filled_dict["four"] #=> ERROR: key not found: four in getindex at dict.jl:489 +catch e + println(e) +end + +# Используйте метод get со значением по умолчанию, чтобы избежать этой ошибки +# get(dictionary,key,default_value) +get(filled_dict,"one",4) #=> 1 +get(filled_dict,"four",4) #=> 4 + +# Для коллекций неотсортированных уникальных элементов используйте Set +empty_set = Set() #=> Set{Any}() +# Инициализация множества +filled_set = Set(1,2,2,3,4) #=> Set{Int64}(1,2,3,4) + +# Добавление элементов +push!(filled_set,5) #=> Set{Int64}(5,4,2,3,1) + +# Проверка вхождения элементов во множество +in(2, filled_set) #=> true +in(10, filled_set) #=> false + +# Функции для получения пересечения, объединения и разницы. +other_set = Set(3, 4, 5, 6) #=> Set{Int64}(6,4,5,3) +intersect(filled_set, other_set) #=> Set{Int64}(3,4,5) +union(filled_set, other_set) #=> Set{Int64}(1,2,3,4,5,6) +setdiff(Set(1,2,3,4),Set(2,3,5)) #=> Set{Int64}(1,4) + + +#################################################### +## 3. Поток управления +#################################################### + +# Создадим переменную +some_var = 5 + +# Выражение if. Отступы не имеют значения. +if some_var > 10 + println("some_var is totally bigger than 10.") +elseif some_var < 10 # Необязательная ветка elseif. + println("some_var is smaller than 10.") +else # else-ветка также опциональна. + println("some_var is indeed 10.") +end +#=> prints "some var is smaller than 10" + + +# Цикл for проходит по итерируемым объектам +# Примеры итерируемых типов: Range, Array, Set, Dict и String. +for animal=["dog", "cat", "mouse"] + println("$animal is a mammal") + # Для вставки значения переменной или выражения в строку используется $ +end +# Выведет: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# Другой вариант записи. +for animal in ["dog", "cat", "mouse"] + println("$animal is a mammal") +end +# Выведет: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$(a[1]) is a $(a[2])") +end +# Выведет: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$k is a $v") +end +# Выведет: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# Цикл while выполняется до тех пор, пока верно условие +x = 0 +while x < 4 + println(x) + x += 1 # Короткая запись x = x + 1 +end +# Выведет: +# 0 +# 1 +# 2 +# 3 + +# Обработка исключений +try + error("help") +catch e + println("caught it $e") +end +#=> caught it ErrorException("help") + + +#################################################### +## 4. Функции +#################################################### + +# Для определения новой функции используется ключевое слово 'function' +#function имя(аргументы) +# тело... +#end +function add(x, y) + println("x is $x and y is $y") + + # Функция возвращает значение последнего выражения + x + y +end + +add(5, 6) #=> Вернёт 11, напечатав "x is 5 and y is 6" + +# Функция может принимать переменное количество позиционных аргументов. +function varargs(args...) + return args + # для возвращения из функции в любом месте используется 'return' +end +#=> varargs (generic function with 1 method) + +varargs(1,2,3) #=> (1,2,3) + +# Многоточие (...) — это splat. +# Мы только что воспользовались им в определении функции. +# Также его можно использовать при вызове функции, +# где он преобразует содержимое массива или кортежа в список аргументов. +Set([1,2,3]) #=> Set{Array{Int64,1}}([1,2,3]) # формирует множество массивов +Set([1,2,3]...) #=> Set{Int64}(1,2,3) # эквивалентно Set(1,2,3) + +x = (1,2,3) #=> (1,2,3) +Set(x) #=> Set{(Int64,Int64,Int64)}((1,2,3)) # множество кортежей +Set(x...) #=> Set{Int64}(2,3,1) + + +# Опциональные позиционные аргументы +function defaults(a,b,x=5,y=6) + return "$a $b and $x $y" +end + +defaults('h','g') #=> "h g and 5 6" +defaults('h','g','j') #=> "h g and j 6" +defaults('h','g','j','k') #=> "h g and j k" +try + defaults('h') #=> ERROR: no method defaults(Char,) + defaults() #=> ERROR: no methods defaults() +catch e + println(e) +end + +# Именованные аргументы +function keyword_args(;k1=4,name2="hello") # обратите внимание на ; + return ["k1"=>k1,"name2"=>name2] +end + +keyword_args(name2="ness") #=> ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") #=> ["k1"=>"mine","name2"=>"hello"] +keyword_args() #=> ["name2"=>"hello","k2"=>4] + +# В одной функции можно совмещать все виды аргументов +function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") + println("normal arg: $normal_arg") + println("optional arg: $optional_positional_arg") + println("keyword arg: $keyword_arg") +end + +all_the_args(1, 3, keyword_arg=4) +# Выведет: +# normal arg: 1 +# optional arg: 3 +# keyword arg: 4 + +# Функции в Julia первого класса +function create_adder(x) + adder = function (y) + return x + y + end + return adder +end + +# Анонимная функция +(x -> x > 2)(3) #=> true + +# Эта функция идентичная предыдущей версии create_adder +function create_adder(x) + y -> x + y +end + +# Если есть желание, можно воспользоваться полным вариантом +function create_adder(x) + function adder(y) + x + y + end + adder +end + +add_10 = create_adder(10) +add_10(3) #=> 13 + + +# Встроенные функции высшего порядка +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Списковые сборки +[add_10(i) for i=[1, 2, 3]] #=> [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] + +#################################################### +## 5. Типы +#################################################### + +# Julia has a type system. +# Каждое значение имеет тип, но переменные не определяют тип значения. +# Функция `typeof` возвращает тип значения. +typeof(5) #=> Int64 + +# Types are first-class values +# Типы являются значениями первого класса +typeof(Int64) #=> DataType +typeof(DataType) #=> DataType +# Тип DataType представляет типы, включая себя самого. + +# Типы используются в качестве документации, для оптимизации и организации. +# Статически типы не проверяются. + +# Пользователь может определять свои типы +# Типы похожи на структуры в других языках +# Новые типы определяются с помощью ключевого слова `type` + +# type Name +# field::OptionalType +# ... +# end +type Tiger + taillength::Float64 + coatcolor # отсутствие типа равносильно `::Any` +end + +# Аргументы конструктора по умолчанию — свойства типа +# в порядке их определения. +tigger = Tiger(3.5,"orange") #=> Tiger(3.5,"orange") + +# Тип объекта по сути является конструктором значений такого типа +sherekhan = typeof(tigger)(5.6,"fire") #=> Tiger(5.6,"fire") + +# Эти типы, похожие на структуры, называются конкретными. +# Можно создавать объекты таких типов, но не их подтипы. +# Другой вид типов — абстрактные типы. + +# abstract Name +abstract Cat # просто имя и точка в иерархии типов + +# Объекты абстрактных типов создавать нельзя, +# но зато от них можно наследовать подтипы. +# Например, Number — это абстрактный тип. +subtypes(Number) #=> 6 элементов в массиве Array{Any,1}: + # Complex{Float16} + # Complex{Float32} + # Complex{Float64} + # Complex{T<:Real} + # ImaginaryUnit + # Real +subtypes(Cat) #=> пустой массив Array{Any,1} + +# У всех типов есть супертип. Для его определения есть функция `super`. +typeof(5) #=> Int64 +super(Int64) #=> Signed +super(Signed) #=> Real +super(Real) #=> Number +super(Number) #=> Any +super(super(Signed)) #=> Number +super(Any) #=> Any +# Все эти типы, за исключением Int64, абстрактные. + +# Для создания подтипа используется оператор <: +type Lion <: Cat # Lion — это подтип Cat + mane_color + roar::String +end + +# У типа может быть несколько конструкторов. +# Для создания нового определите функцию с именем, как у типа, +# и вызовите имеющийся конструктор. +Lion(roar::String) = Lion("green",roar) +# Мы создали внешний (т.к. он находится вне определения типа) конструктор. + +type Panther <: Cat # Panther — это тоже подтип Cat + eye_color + + # Определим свой конструктор вместо конструктора по умолчанию + Panther() = new("green") +end +# Использование внутренних конструкторов позволяет +# определять, как будут создаваться объекты типов. +# Но по возможности стоит пользоваться внешними конструкторами. + +#################################################### +## 6. Мультиметоды +#################################################### + +# Все именованные функции являются generic-функциями, +# т.е. все они состоят из разных методов. +# Каждый конструктор типа Lion — это метод generic-функции Lion. + +# Приведём пример без использования конструкторов, создадим функцию meow + +# Определения Lion, Panther и Tiger +function meow(animal::Lion) + animal.roar # доступ к свойству типа через точку +end + +function meow(animal::Panther) + "grrr" +end + +function meow(animal::Tiger) + "rawwwr" +end + +# Проверка +meow(tigger) #=> "rawwr" +meow(Lion("brown","ROAAR")) #=> "ROAAR" +meow(Panther()) #=> "grrr" + +# Вспомним иерархию типов +issubtype(Tiger,Cat) #=> false +issubtype(Lion,Cat) #=> true +issubtype(Panther,Cat) #=> true + +# Определим функцию, принимающую на вход объекты типа Cat +function pet_cat(cat::Cat) + println("The cat says $(meow(cat))") +end + +pet_cat(Lion("42")) #=> выведет "The cat says 42" +try + pet_cat(tigger) #=> ERROR: no method pet_cat(Tiger,) +catch e + println(e) +end + +# В объектно-ориентированных языках распространена одиночная диспетчеризация — +# подходящий метод выбирается на основе типа первого аргумента. +# В Julia все аргументы участвуют в выборе нужного метода. + +# Чтобы понять разницу, определим функцию с несколькими аргументами. +function fight(t::Tiger,c::Cat) + println("The $(t.coatcolor) tiger wins!") +end +#=> fight (generic function with 1 method) + +fight(tigger,Panther()) #=> выведет The orange tiger wins! +fight(tigger,Lion("ROAR")) #=> выведет The orange tiger wins! + +# Переопределим поведение функции, если Cat-объект является Lion-объектом +fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") +#=> fight (generic function with 2 methods) + +fight(tigger,Panther()) #=> выведет The orange tiger wins! +fight(tigger,Lion("ROAR")) #=> выведет The green-maned lion wins! + +# Драться можно не только с тиграми! +fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +#=> fight (generic function with 3 methods) + +fight(Lion("balooga!"),Panther()) #=> выведет The victorious cat says grrr +try + fight(Panther(),Lion("RAWR")) #=> ERROR: no method fight(Panther,Lion) +catch +end + +# Вообще, пускай кошачьи могут первыми проявлять агрессию +fight(c::Cat,l::Lion) = println("The cat beats the Lion") +#=> Warning: New definition +# fight(Cat,Lion) at none:1 +# is ambiguous with +# fight(Lion,Cat) at none:2. +# Make sure +# fight(Lion,Lion) +# is defined first. +#fight (generic function with 4 methods) + +# Предупреждение говорит, что неясно, какой из методов вызывать: +fight(Lion("RAR"),Lion("brown","rarrr")) #=> выведет The victorious cat says rarrr +# Результат может оказаться разным в разных версиях Julia + +fight(l::Lion,l2::Lion) = println("The lions come to a tie") +fight(Lion("RAR"),Lion("brown","rarrr")) #=> выведет The lions come to a tie + + +# Под капотом +# Язык позволяет посмотреть на сгенерированные ассемблерный и LLVM-код. + +square_area(l) = l * l # square_area (generic function with 1 method) + +square_area(5) #25 + +# Что происходит, когда мы передаём функции square_area целое число? +code_native(square_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 # Вводная часть + # push RBP + # mov RBP, RSP + # Source line: 1 + # movsxd RAX, EDI # + # imul RAX, RAX # + # pop RBP # + # ret # + +code_native(square_area, (Float32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulss XMM0, XMM0, XMM0 # Произведение чисел одинарной точности (AVX) + # pop RBP + # ret + +code_native(square_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulsd XMM0, XMM0, XMM0 # Произведение чисел двойной точности (AVX) + # pop RBP + # ret + # +# Если хотя бы один из аргументов является числом с плавающей запятой, +# то Julia будет использовать соответствующие инструкции. +# Вычислим площать круга +circle_area(r) = pi * r * r # circle_area (generic function with 1 method) +circle_area(5) # 78.53981633974483 + +code_native(circle_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vcvtsi2sd XMM0, XMM0, EDI # Загрузить целое число (r) + # movabs RAX, 4593140240 # Загрузить pi + # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r + # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r + # pop RBP + # ret + # + +code_native(circle_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # movabs RAX, 4593140496 + # Source line: 1 + # vmulsd XMM1, XMM0, QWORD PTR [RAX] + # vmulsd XMM0, XMM1, XMM0 + # pop RBP + # ret + # +``` + +## Что дальше? + +Для более подробной информации читайте [документацию по языку](http://docs.julialang.org/en/latest/manual/) + +Если вам нужна помощь, задавайте вопросы в [списке рассылки](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From 5aa542280e58ddaabd84f75665702c25f11cc27d Mon Sep 17 00:00:00 2001 From: iArnold Date: Wed, 29 Jan 2014 16:14:56 +0100 Subject: Create red.html.markdown --- red.html.markdown | 143 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 red.html.markdown diff --git a/red.html.markdown b/red.html.markdown new file mode 100644 index 00000000..cfe14c9b --- /dev/null +++ b/red.html.markdown @@ -0,0 +1,143 @@ +--- +name: Red +category: language +language: Red +filename: learnred.red +contributors: + - ["Arnold van Hofwegen", "https://github.com/iArnold"] +--- + + +Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks. +It was not Open Sourced at that time and it is an interpreted language, what means that it is on average slow compared to a compiled language. + +Red, together with its C-level dialect Red/System, provides a language that covers the entire programming space you ever need to program something in. +Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon, +Red/System, covers the more basic needs of programming like C can, being closer to the metal. + +Red will be the worlds first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level +from the metal to the meta without the aid of other stack tools. +Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain +from any platform to any other platform. And it will do this all from a binary executable that is supposed to stay under 1 MB. + +Ready to learn your first Red? + +``` +Red + +; Single-line comments start with a semicolon ';' + +comment { + Multi-line comments + look like this. +} + +; Import files with #include and filenames start with a % sign +#include %includefile.red + +; Your program's entry point is the first executable code that is found +; no need to restrict this to a 'main' function. + +; Valid variable names start with a letter and can contain numbers, +; variables containing only capital A thru F and numbers and ending with 'h' are +; forbidden, because that is how hexadecimal numbers are expressed in Red and +; Red/System. + +; assign a value to a variable using a colon ':' +my-name: "Red" +reason-for-using-the-colon: {This makes the equality sign '=' exclusively usable for comparisons purposes, thus speeding up the original Rebol interpreter.} +is-this-name-valid?: true + +; print output using print, or prin for printing without a newline or linefeed at the ; end of the printed text. + +prin " My name is " print my-name +My name is Red + +print ["My name is " my-name lf] +My name is Red + +; In case you haven't already noticed: statements do NOT end with a semicolon ;-) + +; +; Datatypes +; +; If you know Rebol, you probably have noticed it has lots of datatypes. Red +; does not have yet all those types, but as Red want to be close to Rebol it +; will have a lot of datatypes. +; You can recognize types by the exclamation sign at the end. But beware +; names ending with an exclamation sign are allowed. +; Some of the available types are integer! string! block! + +; Declaring variables before using them? +; Red knows by itself what variable is best to use for the data you want to use it +; for. +; A variable declaration is not always necessary. +; It is considered good coding practise to declare your variables, +; but it is not forced upon you by Red. +; You can declare a variable and specify its type. a variable's type determines its +; size in bytes. + +; Variables of integer! type are usually 4 bytes or 32 bits +my-integer: 0 +; Red's integers are signed. No support for unsigned atm but that will come. + +; To find out the type of variable use type? +type? my-integer +integer! + +; chars are guaranteed to be 1 byte +; A string can be cast to a character +empty-string: "" +a-string: to-string #"a" + +i2: 1 + i1: 1 + +; Arithmetic is straightforward +i1 + i2 ; result 3 +i2 - i1 ; result 1 +i2 * i1 ; result 2 +i1 / i2 ; result 0 (0.5, but truncated towards 0) + +; Comparison operators are probably familiar, and unlike in other languages you +; only need a single '=' sign for comparison. +; There is a boolean like type in Red. It has values true and false, but also the +; values on/off or yes/no can be used + +3 = 2 ; => false +3 != 2 ; => true +3 > 2 ; => true +3 < 2 ; => false +2 <= 2 ; => true +2 >= 2 ; => true + +; +; Control Structures +; @TBD + +; +; Functions +; +; In Red almost everything can be seen as a function. Even the IF returns a value. + +; Function declaration syntax: +; function-name: function [][] +twice: function [a [integer!] /one return: [integer!]][ + c: 2 + a: a * c + either one [a + 1][a] +] + + + +``` + +## Further Reading + +The main source for information about Red is [the Red language homepage](http://www.red-lang.org). + +To learn more about Rebol and Red join the [chat on StackOverflow](http://chat.stackoverflow.com/rooms/291/rebol-and-red). +(You will need 20 points to chat but if you ask questions about Red or Rebol we will help you get those points). + +Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl). + +You can also learn Red by learning [Rebol](http://www.rebol.com/docs.html). -- cgit v1.2.3 From d1376f0152f96073dd9ce754e3fac3ae2a89da69 Mon Sep 17 00:00:00 2001 From: iArnold Date: Wed, 29 Jan 2014 17:23:11 +0100 Subject: Update red.html.markdown --- red.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 70 insertions(+), 14 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index cfe14c9b..b0165693 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -22,19 +22,18 @@ from any platform to any other platform. And it will do this all from a binary e Ready to learn your first Red? -``` -Red +```Red + +;this is a commented line -; Single-line comments start with a semicolon ';' +print "hello world" ; this is another comment comment { - Multi-line comments - look like this. + This is a + multiline + comment } -; Import files with #include and filenames start with a % sign -#include %includefile.red - ; Your program's entry point is the first executable code that is found ; no need to restrict this to a 'main' function. @@ -85,10 +84,6 @@ my-integer: 0 type? my-integer integer! -; chars are guaranteed to be 1 byte -; A string can be cast to a character -empty-string: "" -a-string: to-string #"a" i2: 1 + i1: 1 @@ -112,7 +107,63 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0) ; ; Control Structures -; @TBD +; +; if +; Execute a block of code if a given condition is true. IF does not return any value, +; so cannot be used in an expression. +if a < 0 [print "a is negative"] + +; either +; Execute a block of code if a given condition is true, else execute an alternative block of code. +; If last expressions in both blocks have the same type, EITHER can be used inside an expression. +either a < 0 [ + either a = 0 [ + msg: "zero" + ][ + msg: "negative" + ] +][ + msg: "positive" +] + +print ["a is " msg lf] + +; An alternative way to write it (allowed because all code paths return a value of the same type): + +msg: either a < 0 [ + either a = 0 [ + "zero" + ][ + "negative" + ] + ][ + "positive" +] +print ["a is " msg lf] + +; until +; Loop over a block of code until the condition at end of block, is met. UNTIL does not return any value, +; so cannot be used in an expression. +c: 5 +until [ + prin "o" + c: c - 1 + c = 0 +] +; will output: +ooooo +; Note that the loop will always be executed at least once, even if the condition is not met from the beginning. + +; while +; While a given condition is met, execute a block of code. WHILE does not return any value, +; so cannot be used in an expression. +c: 5 +while [c > 0][ + prin "o" + c: c - 1 +] +; will output: +ooooo ; ; Functions @@ -128,6 +179,9 @@ twice: function [a [integer!] /one return: [integer!]][ ] +; Import external files with #include and filenames start with a % sign +#include %includefile.red + ``` @@ -135,9 +189,11 @@ twice: function [a [integer!] /one return: [integer!]][ The main source for information about Red is [the Red language homepage](http://www.red-lang.org). +The Red/System language specification can be found [here](http://static.red-lang.org/red-system-specs-light.html). + To learn more about Rebol and Red join the [chat on StackOverflow](http://chat.stackoverflow.com/rooms/291/rebol-and-red). (You will need 20 points to chat but if you ask questions about Red or Rebol we will help you get those points). Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl). -You can also learn Red by learning [Rebol](http://www.rebol.com/docs.html). +You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html). -- cgit v1.2.3 From 22ebe9a9b4d474341882aee8cbc82f63119e42e0 Mon Sep 17 00:00:00 2001 From: iArnold Date: Wed, 29 Jan 2014 21:27:53 +0100 Subject: Update red.html.markdown Equality sign means equal --- red.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index b0165693..f91b324b 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -42,9 +42,10 @@ comment { ; forbidden, because that is how hexadecimal numbers are expressed in Red and ; Red/System. -; assign a value to a variable using a colon ':' +; assign a value to a variable using a colon ":" my-name: "Red" -reason-for-using-the-colon: {This makes the equality sign '=' exclusively usable for comparisons purposes, thus speeding up the original Rebol interpreter.} +reason-for-using-the-colon: {Assigning values using the colon makes the equality sign "=" exclusively usable for comparisons purposes, exactly what "=" was intended for in the first place! Remember this y = x + 1 and x = 1 => y = 2 stuff from school? +} is-this-name-valid?: true ; print output using print, or prin for printing without a newline or linefeed at the ; end of the printed text. -- cgit v1.2.3 From 9a4a3c084fe34dcade067a6b3582d43b850757dc Mon Sep 17 00:00:00 2001 From: iArnold Date: Wed, 29 Jan 2014 21:30:53 +0100 Subject: Update red.html.markdown minor indentation --- red.html.markdown | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index f91b324b..ceaaf80f 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -44,11 +44,15 @@ comment { ; assign a value to a variable using a colon ":" my-name: "Red" -reason-for-using-the-colon: {Assigning values using the colon makes the equality sign "=" exclusively usable for comparisons purposes, exactly what "=" was intended for in the first place! Remember this y = x + 1 and x = 1 => y = 2 stuff from school? +reason-for-using-the-colon: {Assigning values using the colon makes + the equality sign "=" exclusively usable for comparisons purposes, + exactly what "=" was intended for in the first place! + Remember this y = x + 1 and x = 1 => y = 2 stuff from school? } is-this-name-valid?: true -; print output using print, or prin for printing without a newline or linefeed at the ; end of the printed text. +; print output using print, or prin for printing without a newline or linefeed at the +; end of the printed text. prin " My name is " print my-name My name is Red -- cgit v1.2.3 From ade0d072c00f68175dae50395e7d045e566c1a55 Mon Sep 17 00:00:00 2001 From: iArnold Date: Wed, 29 Jan 2014 21:35:28 +0100 Subject: Update red.html.markdown --- red.html.markdown | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index ceaaf80f..f277dd64 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -103,12 +103,12 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0) ; There is a boolean like type in Red. It has values true and false, but also the ; values on/off or yes/no can be used -3 = 2 ; => false -3 != 2 ; => true -3 > 2 ; => true -3 < 2 ; => false -2 <= 2 ; => true -2 >= 2 ; => true +3 = 2 ; result false +3 != 2 ; result true +3 > 2 ; result true +3 < 2 ; result false +2 <= 2 ; result true +2 >= 2 ; result true ; ; Control Structures @@ -153,7 +153,7 @@ c: 5 until [ prin "o" c: c - 1 - c = 0 + c = 0 ; the condition to end the until loop ] ; will output: ooooo @@ -173,10 +173,7 @@ ooooo ; ; Functions ; -; In Red almost everything can be seen as a function. Even the IF returns a value. - -; Function declaration syntax: -; function-name: function [][] +; function example twice: function [a [integer!] /one return: [integer!]][ c: 2 a: a * c -- cgit v1.2.3 From ce005d7fdb9a6a6815f88b08ab42ee6fbf689abb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rory=20O=E2=80=99Kane?= Date: Wed, 29 Jan 2014 21:34:56 -0500 Subject: Link to CoffeeScript official website --- coffeescript.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index 429f10b5..c61cad67 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -5,6 +5,8 @@ contributors: filename: coffeescript.coffee --- +See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript. + ``` coffeescript # CoffeeScript is a hipster language. # It goes with the trends of many modern languages. -- cgit v1.2.3 From e3b20c7e26cdbe77932a344a19402c4431a35f92 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 8 Jan 2014 21:27:42 -0600 Subject: Add categories description and Car example. --- objective-c.html.markdown | 95 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 90 insertions(+), 5 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 453a42a5..b6b378d5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -444,11 +444,96 @@ distance = 18; // References "long distance" from MyClass implementation @end // States the end of the implementation -/* - * A protocol declares methods that can be implemented by any class. - * Protocols are not classes themselves. They simply define an interface - * that other objects are responsible for implementing. - */ +// Categories +// A category is a group of methods designed to extend a class. They allow you to add new methods +// to an existing class for organizational purposes. This is not to be mistaken with subclasses. +// Subclasses are meant to CHANGE functionality of an object while categories instead ADD +// functionality to an object. +// Categories allow you to: +// -- Add methods to an existing class for organizational purposes. +// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods. +// -- Add ability to create protected and private methods to classes. +// NOTE: Do not override methods of the base class in a category even though you have the ability +// to. Overriding methods may cause compiler errors later between different categories and it +// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods. + +// Here is a simple Car base class. +@interface Car : NSObject + +@property NSString *make; +@property NSString *color; + +- (void)turnOn; +- (void)accelerate; + +@end + +// And the simple Car base class implementation: +#import "Car.h" + +@implementation Car + +@synthesize make = _make; +@synthesize color = _color; + +- (void)turnOn { + NSLog(@"Car is on."); +} +- (void)accelerate { + NSLog(@"Accelerating."); +} + +@end + +// Now, if we wanted to create a Truck object, we would create a subclass of Car instead as it would +// be changing the functionality of the Car to behave like a truck. But lets say we want to just add +// functionality to this existing Car. A good example would be to clean the car. So we would create +// a category to add these cleaning methods: +// @interface filename: Car+Clean.h +#import "Car.h" // Make sure to import base class to extend. + +@interface Car (Clean) // The category name is inside () following the name of the base class. + +- (void)washWindows; // Names of the new methods we are adding to our Car object. +- (void)wax; + +@end + +// @implementation filename: Car+Clean.m +#import "Car+Clean.h" + +@implementation Car (Clean) + +- (void)washWindows { + NSLog(@"Windows washed."); +} +- (void)wax { + NSLog(@"Waxed."); +} + +@end + +// Any Car object instance has the ability to use a category. All they need to do is import it: +#import "Car+Clean.h" // Import as many different categories as you want to use. +#import "Car.h" // Also need to import base class to use it's original functionality. + +int main(int argc, const char *argv[]) { + @autoreleasepool { + Car *mustang = [[Car alloc] init]; + mustang.color = @"Red"; + mustang.make = @"Ford"; + + [mustang turnOn]; // Use methods from base Car class. + [mustang washWindows]; // Use methods from Car's Clean category. + } + return 0; +} + + +// Protocols +// A protocol declares methods that can be implemented by any class. +// Protocols are not classes themselves. They simply define an interface +// that other objects are responsible for implementing. @protocol MyProtocol - (void)myProtocolMethod; @end -- cgit v1.2.3 From e3853e564bea5a1463ee7b1ec4b9beaaae295d0c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 8 Jan 2014 21:55:20 -0600 Subject: Add description and example of how to simulate protected methods. --- objective-c.html.markdown | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index b6b378d5..33200b63 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -430,7 +430,12 @@ distance = 18; // References "long distance" from MyClass implementation return @42; } +<<<<<<< HEAD // To create a private method, create the method in the @implementation but not in the @interface +======= +// Objective-C does not have private method declarations, but you can simulate them. +// To simulate a private method, create the method in the @implementation but not in the @interface. +>>>>>>> 421f48c... Add description and example of how to simulate protected methods. - (NSNumber *)secretPrivateMethod { return @72; } @@ -485,11 +490,11 @@ distance = 18; // References "long distance" from MyClass implementation @end -// Now, if we wanted to create a Truck object, we would create a subclass of Car instead as it would +// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would // be changing the functionality of the Car to behave like a truck. But lets say we want to just add // functionality to this existing Car. A good example would be to clean the car. So we would create // a category to add these cleaning methods: -// @interface filename: Car+Clean.h +// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h) #import "Car.h" // Make sure to import base class to extend. @interface Car (Clean) // The category name is inside () following the name of the base class. @@ -499,8 +504,8 @@ distance = 18; // References "long distance" from MyClass implementation @end -// @implementation filename: Car+Clean.m -#import "Car+Clean.h" +// @implementation filename: Car+Clean.m (BaseClassName+CategoryName.m) +#import "Car+Clean.h" // Import the Clean category's @interface file. @implementation Car (Clean) @@ -511,13 +516,13 @@ distance = 18; // References "long distance" from MyClass implementation NSLog(@"Waxed."); } -@end +@end // Any Car object instance has the ability to use a category. All they need to do is import it: #import "Car+Clean.h" // Import as many different categories as you want to use. #import "Car.h" // Also need to import base class to use it's original functionality. -int main(int argc, const char *argv[]) { +int main (int argc, const char * argv[]) { @autoreleasepool { Car *mustang = [[Car alloc] init]; mustang.color = @"Red"; @@ -529,6 +534,24 @@ int main(int argc, const char *argv[]) { return 0; } +// Objective-C does not have protected method declarations but you can simulate them. +// Create a category containing all of the protected methods, then import it ONLY into the +// @implementation file of a class belonging to the Car class: +@interface Car (Protected) // Naming category 'Protected' to remember methods are protected. + +- (void)lockCar; // Methods listed here may only be created by Car objects. + +@end +//To use protected methods, import the category, then implement the methods: +#import "Car+Protected.h" // Remember, import in the @implementation file only. + +@implementation Car + +- (void)lockCar { + NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. +} + +@end // Protocols // A protocol declares methods that can be implemented by any class. -- cgit v1.2.3 From 4b44b03a07bf6ffc1f265fa0f08e8ef8ceeae8d3 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 8 Jan 2014 23:37:43 -0600 Subject: Add extensions description with example. --- objective-c.html.markdown | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 33200b63..47af5ae8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -553,6 +553,42 @@ int main (int argc, const char * argv[]) { @end +// Extensions +// Extensions allow you to override public access property attributes and methods of an @interface. +// @interface filename: Shape.h +@interface Shape : NSObject // Base Shape class extension overrides below. + +@property (readonly) NSNumber *numOfSides; + +- (int)getNumOfSides; + +@end +// You can override numOfSides variable or getNumOfSides method to edit them with an extension: +// @implementation filename: Shape.m +#import "Shape.h" +// Extensions live in the same file as the class @implementation. +@interface Shape () // () after base class name declares an extension. + +@property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly. +-(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int. +-(void)privateMethod; // You can also create new private methods inside of extensions. + +@end +// The main @implementation: +@implementation Shape + +@synthesize numOfSides = _numOfSides; + +-(NSNumber)getNumOfSides { // All statements inside of extension must be in the @implementation. + return _numOfSides; +} +-(void)privateMethod { + NSLog(@"Private method created by extension. Shape instances cannot call me."); +} + +@end + + // Protocols // A protocol declares methods that can be implemented by any class. // Protocols are not classes themselves. They simply define an interface -- cgit v1.2.3 From 718c2289e54fb707e49ca373b8083d7e85bf8dde Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 9 Jan 2014 19:56:23 -0600 Subject: Add much more to the protocols section. --- objective-c.html.markdown | 70 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 3 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 47af5ae8..9e41e135 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -449,7 +449,9 @@ distance = 18; // References "long distance" from MyClass implementation @end // States the end of the implementation +/////////////////////////////////////// // Categories +/////////////////////////////////////// // A category is a group of methods designed to extend a class. They allow you to add new methods // to an existing class for organizational purposes. This is not to be mistaken with subclasses. // Subclasses are meant to CHANGE functionality of an object while categories instead ADD @@ -553,7 +555,9 @@ int main (int argc, const char * argv[]) { @end +/////////////////////////////////////// // Extensions +/////////////////////////////////////// // Extensions allow you to override public access property attributes and methods of an @interface. // @interface filename: Shape.h @interface Shape : NSObject // Base Shape class extension overrides below. @@ -588,15 +592,75 @@ int main (int argc, const char * argv[]) { @end - +/////////////////////////////////////// // Protocols +/////////////////////////////////////// // A protocol declares methods that can be implemented by any class. // Protocols are not classes themselves. They simply define an interface // that other objects are responsible for implementing. -@protocol MyProtocol - - (void)myProtocolMethod; + // @protocol filename: "CarUtilities.h" +@protocol CarUtilities // => Name of another protocol this protocol includes. + @property BOOL engineOn; // Adopting class must @synthesize all defined @properties and + - (void)turnOnEngine; // all defined methods. +@end +// Below is an example class implementing the protocol. +#import "CarUtilities.h" // Import the @protocol file. + +@interface Car : NSObject // Name of protocol goes inside <> + // You don't need the @property or method names here for CarUtilities. Only @implementation does. +- (void)turnOnEngineWithUtilities:(id )car; // You can use protocols as data too. +@end +// The @implementation needs to implement the @properties and methods for the protocol. +@implementation Car : NSObject + +@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property. + +- (void)turnOnEngine { // Implement turnOnEngine however you would like. Protocols do not define + _engineOn = YES; // how you implement a method, it just requires that you do implement it. +} +// You may use a protocol as data as you know what methods and variables it has implemented. +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { + [objectOfSomeKind engineOn]; // You have access to object variables + [objectOfSomeKind turnOnEngine]; // and the methods inside. + [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants. +} + @end +// Instances of Car now have access to the protocol. +Car *carInstance = [[Car alloc] init]; +[[carInstance setEngineOn:NO]; +[carInstance turnOnEngine]; +if ([carInstance engineOn]) { + NSLog(@"Car engine is on."); // prints => "Car engine is on." +} +// Make sure to check if an object of type 'id' implements a protocol before calling protocol methods: +if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); +} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does run as the Car class implements the CarUtilities protocol."); +} +// Categories may implement protocols as well: @interface Car (CarCategory) +// You may implement many protocols: @interface Car : NSObject +// NOTE: If two or more protocols rely on each other, make sure to forward-declare them: +#import "Brother.h" + +@protocol Brother; // Forward-declare statement. Without it, compiler would through error. + +@protocol Sister + +- (void)beNiceToBrother:(id )brother; +@end +// See the problem is that Sister relies on Brother, and Brother relies on Sister. +#import "Sister.h" + +@protocol Sister; // These lines stop the recursion, resolving the issue. + +@protocol Brother + +- (void)beNiceToSister:(id )sister; + +@end /////////////////////////////////////// // Memory Management -- cgit v1.2.3 From 57c16ffb5ca3c91d163479f3d0d6eaddf51fb123 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 9 Jan 2014 19:56:23 -0600 Subject: Add much more to the protocols section. --- objective-c.html.markdown | 74 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 67 insertions(+), 7 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 47af5ae8..781cdd3e 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -430,12 +430,8 @@ distance = 18; // References "long distance" from MyClass implementation return @42; } -<<<<<<< HEAD -// To create a private method, create the method in the @implementation but not in the @interface -======= // Objective-C does not have private method declarations, but you can simulate them. // To simulate a private method, create the method in the @implementation but not in the @interface. ->>>>>>> 421f48c... Add description and example of how to simulate protected methods. - (NSNumber *)secretPrivateMethod { return @72; } @@ -449,7 +445,9 @@ distance = 18; // References "long distance" from MyClass implementation @end // States the end of the implementation +/////////////////////////////////////// // Categories +/////////////////////////////////////// // A category is a group of methods designed to extend a class. They allow you to add new methods // to an existing class for organizational purposes. This is not to be mistaken with subclasses. // Subclasses are meant to CHANGE functionality of an object while categories instead ADD @@ -553,7 +551,9 @@ int main (int argc, const char * argv[]) { @end +/////////////////////////////////////// // Extensions +/////////////////////////////////////// // Extensions allow you to override public access property attributes and methods of an @interface. // @interface filename: Shape.h @interface Shape : NSObject // Base Shape class extension overrides below. @@ -588,15 +588,75 @@ int main (int argc, const char * argv[]) { @end - +/////////////////////////////////////// // Protocols +/////////////////////////////////////// // A protocol declares methods that can be implemented by any class. // Protocols are not classes themselves. They simply define an interface // that other objects are responsible for implementing. -@protocol MyProtocol - - (void)myProtocolMethod; + // @protocol filename: "CarUtilities.h" +@protocol CarUtilities // => Name of another protocol this protocol includes. + @property BOOL engineOn; // Adopting class must @synthesize all defined @properties and + - (void)turnOnEngine; // all defined methods. +@end +// Below is an example class implementing the protocol. +#import "CarUtilities.h" // Import the @protocol file. + +@interface Car : NSObject // Name of protocol goes inside <> + // You don't need the @property or method names here for CarUtilities. Only @implementation does. +- (void)turnOnEngineWithUtilities:(id )car; // You can use protocols as data too. +@end +// The @implementation needs to implement the @properties and methods for the protocol. +@implementation Car : NSObject + +@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property. + +- (void)turnOnEngine { // Implement turnOnEngine however you would like. Protocols do not define + _engineOn = YES; // how you implement a method, it just requires that you do implement it. +} +// You may use a protocol as data as you know what methods and variables it has implemented. +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { + [objectOfSomeKind engineOn]; // You have access to object variables + [objectOfSomeKind turnOnEngine]; // and the methods inside. + [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants. +} + @end +// Instances of Car now have access to the protocol. +Car *carInstance = [[Car alloc] init]; +[[carInstance setEngineOn:NO]; +[carInstance turnOnEngine]; +if ([carInstance engineOn]) { + NSLog(@"Car engine is on."); // prints => "Car engine is on." +} +// Make sure to check if an object of type 'id' implements a protocol before calling protocol methods: +if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); +} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does run as the Car class implements the CarUtilities protocol."); +} +// Categories may implement protocols as well: @interface Car (CarCategory) +// You may implement many protocols: @interface Car : NSObject +// NOTE: If two or more protocols rely on each other, make sure to forward-declare them: +#import "Brother.h" + +@protocol Brother; // Forward-declare statement. Without it, compiler would through error. + +@protocol Sister + +- (void)beNiceToBrother:(id )brother; +@end +// See the problem is that Sister relies on Brother, and Brother relies on Sister. +#import "Sister.h" + +@protocol Sister; // These lines stop the recursion, resolving the issue. + +@protocol Brother + +- (void)beNiceToSister:(id )sister; + +@end /////////////////////////////////////// // Memory Management -- cgit v1.2.3 From a257b3bfbae6ab17237f89c44b0ad79514ba5b53 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 29 Jan 2014 21:55:11 -0800 Subject: Updated russian julia --- ru-ru/julia-ru.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ru-ru/julia-ru.html.markdown b/ru-ru/julia-ru.html.markdown index 51654cfe..b8890a93 100644 --- a/ru-ru/julia-ru.html.markdown +++ b/ru-ru/julia-ru.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Sergey Skovorodkin", "https://github.com/skovorodkin"] filename: learnjulia.jl +lang: ru-ru --- Julia — гомоиконный функциональный язык программирования для технических расчётов. -- cgit v1.2.3 From 5ab214be7270c9b0d0b7d394ebf05f8b75457a76 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 29 Jan 2014 22:01:30 -0800 Subject: Added lang to objc fr --- fr-fr/objective-c-fr.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index b14b3a52..0aeb5082 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -8,6 +8,7 @@ contributors: translators: - ["Yannick Loriot", "https://github.com/YannickL"] filename: LearnObjectiveC.m +lang: fr-fr --- @@ -524,4 +525,4 @@ __unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais la variable n'es [iOS pour les écoliers : Votre première app iOS](http://www.raywenderlich.com/fr/39272/ios-pour-les-ecoliers-votre-premiere-app-ios-partie-12) -[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) \ No newline at end of file +[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) -- cgit v1.2.3 From 4a9b80d5f5a0b2618bf7b7f5b4a6b603f6f7d7f0 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 29 Jan 2014 22:05:08 -0800 Subject: No objc highlighting, use cpp to fix errors --- fr-fr/objective-c-fr.html.markdown | 2 +- objective-c.html.markdown | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index 0aeb5082..d48bcc5e 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -14,7 +14,7 @@ lang: fr-fr L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch. -```objective-c +```cpp // Les commentaires sur une seule ligne commencent par // /* diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 453a42a5..6f48c155 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -12,7 +12,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```objective-c +```cpp // Single-line comments start with // /* -- cgit v1.2.3 From 50158e3b02624b55b7e5dca85efe8358bb535d57 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 29 Jan 2014 22:25:15 -0800 Subject: juliavonovich --- ru-ru/julia-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/julia-ru.html.markdown b/ru-ru/julia-ru.html.markdown index b8890a93..c9213a42 100644 --- a/ru-ru/julia-ru.html.markdown +++ b/ru-ru/julia-ru.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Leah Hanson", "http://leahhanson.us"] translators: - ["Sergey Skovorodkin", "https://github.com/skovorodkin"] -filename: learnjulia.jl +filename: learnjulia-ru.jl lang: ru-ru --- -- cgit v1.2.3 From 8185f5e033c74f2ff9c7be0af117c8d296fe55f9 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 29 Jan 2014 23:20:11 -0800 Subject: Updated learngo filenames --- es-es/go-es.html.markdown | 2 +- ko-kr/go-kr.html.markdown | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 434f6713..661a7dad 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -2,7 +2,7 @@ name: Go category: language language: Go -filename: learngo.go +filename: learngo-es.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] translators: diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown index 7404572c..e6ebe097 100644 --- a/ko-kr/go-kr.html.markdown +++ b/ko-kr/go-kr.html.markdown @@ -2,7 +2,7 @@ name: Go category: language language: Go -filename: learngo.go +filename: learngo-kr.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] translators: -- cgit v1.2.3 From 0b2a283db4bc622aaca3c23daa3c39dfd9297db1 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 29 Jan 2014 23:30:28 -0800 Subject: Updated a lot of filenames --- css.html.markdown | 1 + de-de/css-de.html.markdown | 1 + fa-ir/javascript.html.markdown | 2 +- fr-fr/haskell.html.markdown | 1 + fr-fr/objective-c-fr.html.markdown | 2 +- ko-kr/coffeescript-kr.html.markdown | 2 +- ko-kr/javascript-kr.html.markdown | 1 + ko-kr/lua-kr.html.markdown | 1 + ko-kr/php-kr.html.markdown | 2 +- pt-br/java-pt.html.markdown | 2 +- pt-br/ruby-pt.html.markdown | 4 ++-- ru-ru/c-ru.html.markdown | 4 ++-- zh-cn/r-cn.html.markdown | 2 +- zh-cn/racket-cn.html.markdown | 2 +- zh-cn/scala-cn.html.markdown | 1 - 15 files changed, 16 insertions(+), 12 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index b16b364d..26eaae53 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -2,6 +2,7 @@ language: css contributors: - ["Mohammad Valipour", "https://github.com/mvalipour"] +filename: learncss.css --- In early days of web there was no visual elements, just pure text. But with the diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown index e03b3174..8909b251 100644 --- a/de-de/css-de.html.markdown +++ b/de-de/css-de.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Kyr", "http://github.com/kyrami"] lang: de-de +filename: learncss-de.css --- In den frühen Tagen des Internets gab es keine visuellen Elemente, alles war nur reiner Text. Aber mit der Weiterentwickliung von Browsern wurden auch vollständig visuelle Webseiten zu einem Standard. diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown index f1beae87..922fe416 100644 --- a/fa-ir/javascript.html.markdown +++ b/fa-ir/javascript.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] translators: - ["Mohammad Valipour", "https://github.com/mvalipour"] -filename: javascript.js +filename: javascript-fa.js lang: fa-ir --- diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown index 9d0cec99..989db1d5 100644 --- a/fr-fr/haskell.html.markdown +++ b/fr-fr/haskell.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["David Baumgartner", "http://davidbaumgartner.ch"] lang: fr-fr +filename: learnhaskell-fr.hs --- Haskell a été conçu pour être un langage fonctionnel pur et maniable. Il est connu pour ses monades et son système de types, mais je n'ai cesse d'y revenir pour son élégance. Pour moi, Haskell fait de la programmation une joie. diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index d48bcc5e..b98d161e 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -7,7 +7,7 @@ contributors: - ["Levi Bostian", "https://github.com/levibostian"] translators: - ["Yannick Loriot", "https://github.com/YannickL"] -filename: LearnObjectiveC.m +filename: LearnObjectiveC-fr.m lang: fr-fr --- diff --git a/ko-kr/coffeescript-kr.html.markdown b/ko-kr/coffeescript-kr.html.markdown index 7d00a0fe..f8ac8069 100644 --- a/ko-kr/coffeescript-kr.html.markdown +++ b/ko-kr/coffeescript-kr.html.markdown @@ -3,7 +3,7 @@ language: coffeescript category: language contributors: - ["Tenor Biel", "http://github.com/L8D"] -filename: coffeescript.coffee +filename: coffeescript-kr.coffee translators: - ["wikibook", "http://wikibook.co.kr"] lang: ko-kr diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index e5517aa8..f651fbe7 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] translators: - ["wikibook", "http://wikibook.co.kr"] +filename: javascript-kr.js lang: ko-kr --- diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index 862c47a7..850587a0 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -6,6 +6,7 @@ contributors: translators: - ["wikibook", "http://wikibook.co.kr"] lang: ko-kr +filename: learnlua-kr.lua --- ```lua diff --git a/ko-kr/php-kr.html.markdown b/ko-kr/php-kr.html.markdown index 2382a8fb..80f324f3 100644 --- a/ko-kr/php-kr.html.markdown +++ b/ko-kr/php-kr.html.markdown @@ -4,7 +4,7 @@ category: language contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] -filename: learnphp.php +filename: learnphp-kr.php translators: - ["wikibook", "http://wikibook.co.kr"] lang: ko-kr diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index e8d5a538..a884f273 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -8,7 +8,7 @@ translators: - ["Victor Kléber Santos L. Melo", "http://victormelo.com.br/blog"] - ["Renê Douglas N. de Morais", "mailto:rene.douglas.bsi@gmail.com"] lang: pt-br -filename: LearnJava.java +filename: LearnJava-pt.java --- diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index a2f40c3b..4a8a1b5c 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -1,7 +1,7 @@ --- language: ruby -lang: br-pt -filename: learnruby.rb +lang: pt-br +filename: learnruby-pt.rb contributors: - ["Bruno Henrique - Garu", "http://garulab.com"] translators: diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index 874e0821..5988b159 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -1,6 +1,6 @@ --- language: c -filename: learnc.c +filename: learnc-ru.c contributors: - ["Adam Bard", "http://adambard.com/"] - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] @@ -480,4 +480,4 @@ void str_reverse_through_pointer(char *str_in) { Также не забывайте, что [Google](http://google.com) и [Яндекс](http://yandex.ru) – ваши хорошие друзья. -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown index ed8c43b6..19c5f25d 100644 --- a/zh-cn/r-cn.html.markdown +++ b/zh-cn/r-cn.html.markdown @@ -6,7 +6,7 @@ contributors: translators: - ["小柒", "http://weibo.com/u/2328126220"] - ["alswl", "https://github.com/alswl"] -filename: learnr.r +filename: learnr-zh.r lang: zh-cn --- diff --git a/zh-cn/racket-cn.html.markdown b/zh-cn/racket-cn.html.markdown index d43511ea..8ef3671f 100644 --- a/zh-cn/racket-cn.html.markdown +++ b/zh-cn/racket-cn.html.markdown @@ -2,7 +2,7 @@ language: racket lang: zh-cn -filename: learnracket.rkt +filename: learnracket-zh.rkt contributors: - ["th3rac25", "https://github.com/voila"] - ["Eli Barzilay", "https://github.com/elibarzilay"] diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 1ce41ac6..24f73bb5 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -6,7 +6,6 @@ contributors: - ["Dominic Bou-Samra", "http://dbousamra.github.com"] translators: - ["Peiyong Lin", ""] -filename: learn.scala lang: zh-cn --- -- cgit v1.2.3 From 2793e0bd48afdf809923ac0bf461fb4153f120ad Mon Sep 17 00:00:00 2001 From: iArnold Date: Thu, 30 Jan 2014 09:32:58 +0100 Subject: Update red.html.markdown Added header info and completed Hello World program with the header. --- red.html.markdown | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index f277dd64..6e31eee9 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -23,15 +23,22 @@ from any platform to any other platform. And it will do this all from a binary e Ready to learn your first Red? ```Red +All text before the Red header will be treated as comment +The Red header is the word "Red" followed by a whitespace character followed by a block of square brackets []. +The block of brackets can be filled in with useful information about the script or program, the author, the version, the license, what the program does or needs. +The Red/System header is just like the Red header, only saying "Red/System" and not "Red". + +Red [] ;this is a commented line -print "hello world" ; this is another comment +print "Hello Red World" ; this is another comment comment { This is a multiline - comment + comment. + You just saw the Red version of the "Hello World" program. } ; Your program's entry point is the first executable code that is found -- cgit v1.2.3 From 026dcf7b2f9a5a3159d9d35c0da82b6180034e45 Mon Sep 17 00:00:00 2001 From: iArnold Date: Thu, 30 Jan 2014 09:57:20 +0100 Subject: Update red.html.markdown minor edits --- red.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index 6e31eee9..43fe03a6 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -23,9 +23,10 @@ from any platform to any other platform. And it will do this all from a binary e Ready to learn your first Red? ```Red -All text before the Red header will be treated as comment +All text before the Red header will be treated as comment. The Red header is the word "Red" followed by a whitespace character followed by a block of square brackets []. -The block of brackets can be filled in with useful information about the script or program, the author, the version, the license, what the program does or needs. +The block of brackets can be filled in with useful information about the script or program, the author, +the filename, the version, the license, what the program does or needs. The Red/System header is just like the Red header, only saying "Red/System" and not "Red". Red [] @@ -35,9 +36,7 @@ Red [] print "Hello Red World" ; this is another comment comment { - This is a - multiline - comment. + This is a multiline comment. You just saw the Red version of the "Hello World" program. } -- cgit v1.2.3 From c285bf758365107af78ce9a99c7f0d1e1f52421f Mon Sep 17 00:00:00 2001 From: iArnold Date: Thu, 30 Jan 2014 10:33:19 +0100 Subject: Update red.html.markdown completed function twice example --- red.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index 43fe03a6..55251e4e 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -185,17 +185,18 @@ twice: function [a [integer!] /one return: [integer!]][ a: a * c either one [a + 1][a] ] - +b: 3 +print twice b ; will output 6. ; Import external files with #include and filenames start with a % sign #include %includefile.red - +; Now the functions in the included file can be used too. ``` ## Further Reading -The main source for information about Red is [the Red language homepage](http://www.red-lang.org). +The main source for information about Red is the [Red language homepage](http://www.red-lang.org). The Red/System language specification can be found [here](http://static.red-lang.org/red-system-specs-light.html). -- cgit v1.2.3 From 28db2323b7e160de651cd4f62ef9b5cea089ae7f Mon Sep 17 00:00:00 2001 From: iArnold Date: Thu, 30 Jan 2014 11:05:00 +0100 Subject: Update red.html.markdown added giuthub source link and mailinglist --- red.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index 55251e4e..8060536d 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -198,10 +198,11 @@ print twice b ; will output 6. The main source for information about Red is the [Red language homepage](http://www.red-lang.org). +The source can be found on [github](https://github.com/red/red). + The Red/System language specification can be found [here](http://static.red-lang.org/red-system-specs-light.html). -To learn more about Rebol and Red join the [chat on StackOverflow](http://chat.stackoverflow.com/rooms/291/rebol-and-red). -(You will need 20 points to chat but if you ask questions about Red or Rebol we will help you get those points). +To learn more about Rebol and Red join the [chat on StackOverflow](http://chat.stackoverflow.com/rooms/291/rebol-and-red). You will need 20 points to chat but if you ask or answer questions about Red or Rebol we will help you get those points. And if that is not working for you drop a mail to us on the [Red mailing list](mailto: red-langNO_SPAM@googlegroups.com) (remove NO_SPAM). Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl). -- cgit v1.2.3 From 1e0d5abebac015808e2ac22ac8ba741b05dc8f6f Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Thu, 30 Jan 2014 12:36:19 -0600 Subject: Issue#163 https://github.com/adambard/learnxinyminutes-docs/issues/163 --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index b4624d5e..1fbf6a21 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -191,7 +191,7 @@ public class LearnJava { { //System.out.println(fooWhile); //Increment the counter - //Iterated 99 times, fooWhile 0->99 + //Iterated 100 times, fooWhile 0,1,2...99 fooWhile++; } System.out.println("fooWhile Value: " + fooWhile); -- cgit v1.2.3 From f1894bdd004cb1d19873da4f67eae6f314b1263a Mon Sep 17 00:00:00 2001 From: iArnold Date: Thu, 30 Jan 2014 20:47:29 +0100 Subject: Update red.html.markdown Avoid "Red" in the pre-header text --- red.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index 8060536d..ffcead51 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -23,11 +23,11 @@ from any platform to any other platform. And it will do this all from a binary e Ready to learn your first Red? ```Red -All text before the Red header will be treated as comment. -The Red header is the word "Red" followed by a whitespace character followed by a block of square brackets []. -The block of brackets can be filled in with useful information about the script or program, the author, +All text before the header will be treated as comment, as long as you avoid using the word "red" starting with a capital "R" in this pre-header text. Most of the time you start your script with the header itself. +The header of a redscript is the capitalized word "red" followed by a whitespace character followed by a block of square brackets []. +The block of brackets can be filled with useful information about the script or program, the author, the filename, the version, the license, what the program does or needs. -The Red/System header is just like the Red header, only saying "Red/System" and not "Red". +The red/System header is just like the red header, only saying "red/System" and not "red". Red [] -- cgit v1.2.3 From 471f67379ca4fc7ff421fc6de8824be30f35feeb Mon Sep 17 00:00:00 2001 From: iArnold Date: Thu, 30 Jan 2014 20:49:42 +0100 Subject: Update red.html.markdown --- red.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index ffcead51..c2e81b71 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -23,8 +23,10 @@ from any platform to any other platform. And it will do this all from a binary e Ready to learn your first Red? ```Red -All text before the header will be treated as comment, as long as you avoid using the word "red" starting with a capital "R" in this pre-header text. Most of the time you start your script with the header itself. -The header of a redscript is the capitalized word "red" followed by a whitespace character followed by a block of square brackets []. +All text before the header will be treated as comment, as long as you avoid using the word "red" +starting with a capital "R" in this pre-header text. Most of the time you start your script with +the header itself. The header of a redscript is the capitalized word "red" followed by a +whitespace character followed by a block of square brackets []. The block of brackets can be filled with useful information about the script or program, the author, the filename, the version, the license, what the program does or needs. The red/System header is just like the red header, only saying "red/System" and not "red". -- cgit v1.2.3 From 88492baf332c100e52512bd755e9e2bcfa6726f6 Mon Sep 17 00:00:00 2001 From: Jesse Johnson Date: Thu, 30 Jan 2014 18:45:42 -0500 Subject: [go/es] Update translation, format comments. --- es-es/go-es.html.markdown | 193 ++++++++++++++++++++++++++-------------------- 1 file changed, 110 insertions(+), 83 deletions(-) diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 661a7dad..a7166dc1 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -7,16 +7,20 @@ contributors: - ["Sonia Keys", "https://github.com/soniakeys"] translators: - ["Adrian Espinosa", "http://www.adrianespinosa.com"] + - ["Jesse Johnson, "https://github.com/holocronweaver"] lang: es-es - - --- -Go fue creado por la necesidad de hacer el trabajo rápidamente. No es la última -tendencia en informática, pero es la forma nueva y más rápida de resolver problemas reales. +Go fue creado por la necesidad de hacer el trabajo rápidamente. No es +la última tendencia en informática, pero es la forma nueva y más +rápida de resolver problemas reales. + +Tiene conceptos familiares de lenguajes imperativos con tipado +estático. Es rápido compilando y rápido al ejecutar, añade una +concurrencia fácil de entender para las CPUs de varios núcleos de hoy +en día, y tiene características que ayudan con la programación a gran +escala. -Tiene conceptos familiares de lenguajes imperativos con tipado estático. -Es rápido compilando y rápido al ejecutar, añade una concurrencia fácil de entender para las CPUs de varios núcleos de hoy en día, y tiene características que ayudan con la programación a gran escala. Go viene con una librería estándar muy buena y una comunidad entusiasta. ```go @@ -28,15 +32,17 @@ Go viene con una librería estándar muy buena y una comunidad entusiasta. // Main es un nombre especial que declara un ejecutable en vez de una librería. package main -// La declaración Import declara los paquetes de librerías referenciados en este archivo. +// La declaración Import declara los paquetes de librerías +// referenciados en este archivo. import ( - "fmt" // Un paquete en la librería estándar de Go + "fmt" // Un paquete en la librería estándar de Go. "net/http" // Sí, un servidor web! - "strconv" // Conversiones de cadenas + "strconv" // Conversiones de cadenas. + m "math" // Librería matemáticas con alias local m. ) -// Definición de una función. Main es especial. Es el punto de entrada para el ejecutable. -// Te guste o no, Go utiliza llaves. +// Definición de una función. Main es especial. Es el punto de +// entrada para el ejecutable. Te guste o no, Go utiliza llaves. func main() { // Println imprime una línea a stdout. // Cualificalo con el nombre del paquete, fmt. @@ -49,19 +55,19 @@ func main() { // Las funciones llevan parámetros entre paréntesis. // Si no hay parámetros, los paréntesis siguen siendo obligatorios. func beyondHello() { - var x int // Declaración de una variable. Las variables se deben declarar antes de - // utilizarlas. + var x int // Declaración de una variable. + // Las variables se deben declarar antes de utilizarlas. x = 3 // Asignación de variables. // Declaración "corta" con := para inferir el tipo, declarar y asignar. y := 4 - sum, prod := learnMultiple(x, y) // función devuelve dos valores - fmt.Println("sum:", sum, "prod:", prod) // simple salida + sum, prod := learnMultiple(x, y) // Función devuelve dos valores. + fmt.Println("sum:", sum, "prod:", prod) // Simple salida. learnTypes() // < y minutes, learn more! } // Las funciones pueden tener parámetros y (múltiples!) valores de retorno. func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // devolver dos valores + return x + y, x * y // Devolver dos valores. } // Algunos tipos incorporados y literales. @@ -73,32 +79,33 @@ func learnTypes() { saltos de línea.` // mismo tipo cadena // Literal no ASCII. Los fuentes de Go son UTF-8. - g := 'Σ' // tipo rune, un alias de uint32, alberga un punto unicode. - f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit - c := 3 + 4i // complex128, representado internamente por dos float64 + g := 'Σ' // Tipo rune, un alias de uint32, alberga un punto unicode. + f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit. + c := 3 + 4i // complex128, representado internamente por dos float64. // Sintaxis Var con inicializadores. - var u uint = 7 // sin signo, pero la implementación depende del tamaño como en int + var u uint = 7 // Sin signo, pero la implementación depende del + // tamaño como en int. var pi float32 = 22. / 7 // Sintáxis de conversión con una declaración corta. - n := byte('\n') // byte es un alias de uint8 + n := byte('\n') // byte es un alias de uint8. // Los Arrays tienen un tamaño fijo a la hora de compilar. - var a4 [4]int // un array de 4 ints, inicializados a 0 - a3 := [...]int{3, 1, 5} // un array de 3 ints, inicializados como se indica + var a4 [4]int // Un array de 4 ints, inicializados a 0. + a3 := [...]int{3, 1, 5} // Un array de 3 ints, inicializados como se indica. // Los Slices tienen tamaño dinámico. Los arrays y slices tienen sus ventajas // y desventajas pero los casos de uso para los slices son más comunes. - s3 := []int{4, 5, 9} // Comparar con a3. No hay puntos suspensivos - s4 := make([]int, 4) // Asigna slices de 4 ints, inicializados a 0 - var d2 [][]float64 // solo declaración, sin asignación - bs := []byte("a slice") // sintaxis de conversión de tipo + s3 := []int{4, 5, 9} // Comparar con a3. No hay puntos suspensivos. + s4 := make([]int, 4) // Asigna slices de 4 ints, inicializados a 0. + var d2 [][]float64 // Solo declaración, sin asignación. + bs := []byte("a slice") // Sintaxis de conversión de tipo. - p, q := learnMemory() // declara p, q para ser un tipo puntero a int. + p, q := learnMemory() // Declara p, q para ser un tipo puntero a int. fmt.Println(*p, *q) // * sigue un puntero. Esto imprime dos ints. - // Los Maps son arrays asociativos dinámicos, como los hash o diccionarios - // de otros lenguajes + // Los Maps son arrays asociativos dinámicos, como los hash o + // diccionarios de otros lenguajes. m := map[string]int{"three": 3, "four": 4} m["one"] = 1 @@ -108,23 +115,24 @@ saltos de línea.` // mismo tipo cadena // Esto cuenta como utilización de variables. fmt.Println(s, c, a4, s3, d2, m) - learnFlowControl() // vuelta al flujo + learnFlowControl() // Vuelta al flujo. } -// Go posee recolector de basura. Tiene puntero pero no aritmética de punteros. -// Puedes cometer un errores con un puntero nil, pero no incrementando un puntero. +// Go posee recolector de basura. Tiene puntero pero no aritmética de +// punteros. Puedes cometer un errores con un puntero nil, pero no +// incrementando un puntero. func learnMemory() (p, q *int) { // q y p tienen un tipo puntero a int. - p = new(int) // función incorporada que asigna memoria. + p = new(int) // Función incorporada que asigna memoria. // La asignación de int se inicializa a 0, p ya no es nil. - s := make([]int, 20) // asigna 20 ints a un solo bloque de memoria. - s[3] = 7 // asignar uno de ellos - r := -2 // declarar otra variable local + s := make([]int, 20) // Asigna 20 ints a un solo bloque de memoria. + s[3] = 7 // Asignar uno de ellos. + r := -2 // Declarar otra variable local. return &s[3], &r // & toma la dirección de un objeto. } -func expensiveComputation() int { - return 1e6 +func expensiveComputation() float64 { + return m.Exp(10) } func learnFlowControl() { @@ -134,29 +142,31 @@ func learnFlowControl() { } // El formato está estandarizado por el comando "go fmt." if false { - // pout + // Pout. } else { - // gloat + // Gloat. } // Utiliza switch preferiblemente para if encadenados. - x := 1 + x := 42.0 switch x { case 0: case 1: - // los cases no se mezclan, no requieren de "break" - case 2: - // no llega + case 42: + // Los cases no se mezclan, no requieren de "break". + case 43: + // No llega. } // Como if, for no utiliza paréntesis tampoco. - for x := 0; x < 3; x++ { // ++ es una sentencia + // Variables declaradas en for y if son locales de su ámbito local. + for x := 0; x < 3; x++ { // ++ es una sentencia. fmt.Println("iteration", x) } - // x == 1 aqui. + // x == 42 aqui. // For es la única sentencia de bucle en Go, pero tiene formas alternativas. - for { // bucle infinito - break // solo bromeaba! - continue // no llega + for { // Bucle infinito. + break // Solo bromeaba! + continue // No llega. } // Como en for, := en una sentencia if significa declarar y asignar primero, // luego comprobar y > x. @@ -165,11 +175,11 @@ func learnFlowControl() { } // Los literales de funciones son "closures". xBig := func() bool { - return x > 100 // referencia a x declarada encima de la sentencia switch. + return x > 100 // Referencia a x declarada encima de la sentencia switch. } - fmt.Println("xBig:", xBig()) // verdadero (la última vez asignamos 1e6 a x) - x /= 1e5 // esto lo hace == 10 - fmt.Println("xBig:", xBig()) // ahora es falso + fmt.Println("xBig:", xBig()) // verdadero (la última vez asignamos 1e6 a x). + x /= m.Exp(9) // Esto lo hace x == e. + fmt.Println("xBig:", xBig()) // Ahora es falso. // Cuando lo necesites, te encantará. goto love @@ -199,16 +209,29 @@ func learnInterfaces() { // La sintaxis de llaves es un "literal struct". Evalúa a un struct // inicializado. La sintaxis := declara e inicializa p a este struct. p := pair{3, 4} - fmt.Println(p.String()) // llamar al método String de p, de tipo pair. - var i Stringer // declarar i como interfaz tipo Stringer. - i = p // válido porque pair implementa Stringer - // Llamar al metodo String de i, de tipo Stringer. Misma salida que arriba + fmt.Println(p.String()) // Llamar al método String de p, de tipo pair. + var i Stringer // Declarar i como interfaz tipo Stringer. + i = p // Válido porque pair implementa Stringer. + // Llamar al metodo String de i, de tipo Stringer. Misma salida que arriba. fmt.Println(i.String()) - // Las funciones en el paquete fmt llaman al método String para preguntar a un objeto - // por una versión imprimible de si mismo - fmt.Println(p) // salida igual que arriba. Println llama al método String. - fmt.Println(i) // salida igual que arriba. + // Las funciones en el paquete fmt llaman al método String para + // preguntar a un objeto por una versión imprimible de si mismo. + fmt.Println(p) // Salida igual que arriba. Println llama al método String. + fmt.Println(i) // Salida igual que arriba. + + learnVariadicParams("great", "learning", "here!") +} + +// Las funciones pueden tener número variable de argumentos. +func learnVariadicParams(myStrings ...interface{}) { + // Iterar cada valor de la variadic. + for _, param := range myStrings { + fmt.Println("param:", param) + } + + // Pasar valor variadic como parámetro variadic. + fmt.Println("params:", fmt.Sprintln(myStrings...)) learnErrorHandling() } @@ -223,7 +246,7 @@ func learnErrorHandling() { } // Un valor de error comunica más información sobre el problema aparte de "ok". if _, err := strconv.Atoi("non-int"); err != nil { // _ descarta el valor - // imprime "strconv.ParseInt: parsing "non-int": invalid syntax" + // Imprime "strconv.ParseInt: parsing "non-int": invalid syntax". fmt.Println(err) } // Revisarmeos las interfaces más tarde. Mientras tanto, @@ -248,25 +271,28 @@ func learnConcurrency() { go inc(-805, c) // Leer los tres resultados del channel e imprimirlos. // No se puede saber en que orden llegarán los resultados! - fmt.Println(<-c, <-c, <-c) // channel a la derecha, <- es el operador "recibir". - - cs := make(chan string) // otro channel, este gestiona cadenas. - cc := make(chan chan string) // un channel de cadenas de channels. - go func() { c <- 84 }() // iniciar una nueva goroutine solo para enviar un valor. - go func() { cs <- "wordy" }() // otra vez, para cs en esta ocasión - // Select tiene una sintáxis parecida a la sentencia switch pero cada caso involucra - // una operacion de channels. Selecciona un caso de forma aleatoria de los casos - // que están listos para comunicarse. + fmt.Println(<-c, <-c, <-c) // Channel a la derecha, <- es el operador "recibir". + + cs := make(chan string) // Otro channel, este gestiona cadenas. + ccs := make(chan chan string) // Un channel de cadenas de channels. + go func() { c <- 84 }() // Iniciar una nueva goroutine solo para + // enviar un valor. + go func() { cs <- "wordy" }() // Otra vez, para cs en esta ocasión. + // Select tiene una sintáxis parecida a la sentencia switch pero + // cada caso involucra una operacion de channels. Selecciona un caso + // de forma aleatoria de los casos que están listos para comunicarse. select { - case i := <-c: // el valor recibido puede ser asignado a una variable + case i := <-c: // El valor recibido puede ser asignado a una variable, fmt.Printf("it's a %T", i) - case <-cs: // o el valor puede ser descartado + case <-cs: // o el valor puede ser descartado. fmt.Println("it's a string") - case <-cc: // channel vacío, no está listo para la comunicación. + case <-ccs: // Channel vacío, no está listo para la comunicación. fmt.Println("didn't happen.") } + // En este punto un valor fue devuelvto de c o cs. Uno de las dos - // goroutines que se iniciaron se ha completado, la otrá permancerá bloqueada. + // goroutines que se iniciaron se ha completado, la otrá permancerá + // bloqueada. learnWebProgramming() // Go lo hace. Tu también quieres hacerlo. } @@ -281,7 +307,7 @@ func learnWebProgramming() { // Haz pair un http.Handler implementando su único método, ServeHTTP. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Servir datos con un método de http.ResponseWriter + // Servir datos con un método de http.ResponseWriter. w.Write([]byte("You learned Go in Y minutes!")) } ``` @@ -291,11 +317,12 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { La raíz de todas las cosas de Go es la [web oficial de Go](http://golang.org/). Ahí puedes seguir el tutorial, jugar interactivamente y leer mucho. -La propia definición del lenguaje también está altamente recomendada. Es fácil de leer -e increíblemente corta (como otras definiciones de lenguajes hoy en día) +La propia definición del lenguaje también está altamente +recomendada. Es fácil de leer e increíblemente corta (como otras +definiciones de lenguajes hoy en día) -En la lista de lectura de estudiantes de Go está el código fuente de la -librería estándar. Muy bien documentada, demuestra lo mejor de Go leíble, comprendible, -estilo Go y formas Go. Pincha en el nombre de una función en la documentación -y te aparecerá el código fuente! +En la lista de lectura de estudiantes de Go está el código fuente de +la librería estándar. Muy bien documentada, demuestra lo mejor de Go +leíble, comprendible, estilo Go y formas Go. Pincha en el nombre de +una función en la documentación y te aparecerá el código fuente! -- cgit v1.2.3 From 2655b4d056d9757f5edeee571d82c86629f1f862 Mon Sep 17 00:00:00 2001 From: Jesse Johnson Date: Thu, 30 Jan 2014 18:47:55 -0500 Subject: [go/en] Fix veriadic function bug; format and clarify comments. --- go.html.markdown | 146 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 75 insertions(+), 71 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index d68ba51b..d1a0ae34 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -6,6 +6,7 @@ filename: learngo.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] --- Go was created out of the need to get work done. It's not the latest trend @@ -30,9 +31,10 @@ package main // Import declaration declares library packages referenced in this file. import ( - "fmt" // A package in the Go standard library + "fmt" // A package in the Go standard library. "net/http" // Yes, a web server! - "strconv" // String conversions + "strconv" // String conversions. + m "math" // Math library with local alias m. ) // A function definition. Main is special. It is the entry point for the @@ -53,49 +55,49 @@ func beyondHello() { x = 3 // Variable assignment. // "Short" declarations use := to infer the type, declare, and assign. y := 4 - sum, prod := learnMultiple(x, y) // function returns two values - fmt.Println("sum:", sum, "prod:", prod) // simple output + sum, prod := learnMultiple(x, y) // Function returns two values. + fmt.Println("sum:", sum, "prod:", prod) // Simple output. learnTypes() // < y minutes, learn more! } // Functions can have parameters and (multiple!) return values. func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // return two values + return x + y, x * y // Return two values. } // Some built-in types and literals. func learnTypes() { // Short declaration usually gives you what you want. - s := "Learn Go!" // string type + s := "Learn Go!" // string type. s2 := `A "raw" string literal -can include line breaks.` // same string type +can include line breaks.` // Same string type. - // non-ASCII literal. Go source is UTF-8. - g := 'Σ' // rune type, an alias for uint32, holds a unicode code point + // Non-ASCII literal. Go source is UTF-8. + g := 'Σ' // rune type, an alias for uint32, holds a unicode code point. - f := 3.14195 // float64, an IEEE-754 64-bit floating point number - c := 3 + 4i // complex128, represented internally with two float64s + f := 3.14195 // float64, an IEEE-754 64-bit floating point number. + c := 3 + 4i // complex128, represented internally with two float64's. // Var syntax with an initializers. - var u uint = 7 // unsigned, but implementation dependent size as with int + var u uint = 7 // Unsigned, but implementation dependent size as with int. var pi float32 = 22. / 7 // Conversion syntax with a short declaration. - n := byte('\n') // byte is an alias for uint8 + n := byte('\n') // byte is an alias for uint8. // Arrays have size fixed at compile time. - var a4 [4]int // an array of 4 ints, initialized to all 0 - a3 := [...]int{3, 1, 5} // an array of 3 ints, initialized as shown + var a4 [4]int // An array of 4 ints, initialized to all 0. + a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown. // Slices have dynamic size. Arrays and slices each have advantages // but use cases for slices are much more common. - s3 := []int{4, 5, 9} // compare to a3. no ellipsis here - s4 := make([]int, 4) // allocates slice of 4 ints, initialized to all 0 - var d2 [][]float64 // declaration only, nothing allocated here - bs := []byte("a slice") // type conversion syntax + s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. + s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0. + var d2 [][]float64 // Declaration only, nothing allocated here. + bs := []byte("a slice") // Type conversion syntax. - p, q := learnMemory() // declares p, q to be type pointer to int. + p, q := learnMemory() // Declares p, q to be type pointer to int. fmt.Println(*p, *q) // * follows a pointer. This prints two ints. // Maps are a dynamically growable associative array type, like the @@ -109,23 +111,23 @@ can include line breaks.` // same string type // Output of course counts as using a variable. fmt.Println(s, c, a4, s3, d2, m) - learnFlowControl() // back in the flow + learnFlowControl() // Back in the flow. } // Go is fully garbage collected. It has pointers but no pointer arithmetic. // You can make a mistake with a nil pointer, but not by incrementing a pointer. func learnMemory() (p, q *int) { // Named return values p and q have type pointer to int. - p = new(int) // built-in function new allocates memory. + p = new(int) // Built-in function new allocates memory. // The allocated int is initialized to 0, p is no longer nil. - s := make([]int, 20) // allocate 20 ints as a single block of memory - s[3] = 7 // assign one of them - r := -2 // declare another local variable + s := make([]int, 20) // Allocate 20 ints as a single block of memory. + s[3] = 7 // Assign one of them. + r := -2 // Declare another local variable. return &s[3], &r // & takes the address of an object. } -func expensiveComputation() int { - return 1e6 +func expensiveComputation() float64 { + return m.Exp(10) } func learnFlowControl() { @@ -135,29 +137,31 @@ func learnFlowControl() { } // Formatting is standardized by the command line command "go fmt." if false { - // pout + // Pout. } else { - // gloat + // Gloat. } // Use switch in preference to chained if statements. - x := 1 + x := 42.0 switch x { case 0: case 1: - // cases don't "fall through" - case 2: - // unreached + case 42: + // Cases don't "fall through". + case 43: + // Unreached. } // Like if, for doesn't use parens either. - for x := 0; x < 3; x++ { // ++ is a statement + // Variables declared in for and if are local to their scope. + for x := 0; x < 3; x++ { // ++ is a statement. fmt.Println("iteration", x) } - // x == 1 here. + // x == 42 here. // For is the only loop statement in Go, but it has alternate forms. - for { // infinite loop - break // just kidding - continue // unreached + for { // Infinite loop. + break // Just kidding. + continue // Unreached. } // As with for, := in an if statement means to declare and assign y first, // then test y > x. @@ -166,30 +170,17 @@ func learnFlowControl() { } // Function literals are closures. xBig := func() bool { - return x > 100 // references x declared above switch statement. + return x > 100 // References x declared above switch statement. } - fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x) - x /= 1e5 // this makes it == 10 - fmt.Println("xBig:", xBig()) // false now + fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x). + x /= m.Exp(9) // This makes x == e. + fmt.Println("xBig:", xBig()) // false now. // When you need it, you'll love it. goto love love: - // Good stuff coming up! - learnVariadicParams("great", "learning", "here!") - learnInterfaces() -} - -// Functions can have variadic parameters -func learnVariadicParams(myStrings ...string) { - // iterate each value of the variadic - for _, param := range myStrings { - fmt.Println("param:", param) - } - - // pass variadic value as a variadic parameter - fmt.Println("params:", fmt.Sprintln(myStrings...)) + learnInterfaces() // Good stuff coming up! } // Define Stringer as an interface type with one method, String. @@ -213,16 +204,29 @@ func learnInterfaces() { // Brace syntax is a "struct literal." It evaluates to an initialized // struct. The := syntax declares and initializes p to this struct. p := pair{3, 4} - fmt.Println(p.String()) // call String method of p, of type pair. - var i Stringer // declare i of interface type Stringer. - i = p // valid because pair implements Stringer + fmt.Println(p.String()) // Call String method of p, of type pair. + var i Stringer // Declare i of interface type Stringer. + i = p // Valid because pair implements Stringer // Call String method of i, of type Stringer. Output same as above. fmt.Println(i.String()) // Functions in the fmt package call the String method to ask an object // for a printable representation of itself. - fmt.Println(p) // output same as above. Println calls String method. - fmt.Println(i) // output same as above + fmt.Println(p) // Output same as above. Println calls String method. + fmt.Println(i) // Output same as above. + + learnVariadicParams("great", "learning", "here!") +} + +// Functions can have variadic parameters. +func learnVariadicParams(myStrings ...interface{}) { + // Iterate each value of the variadic. + for _, param := range myStrings { + fmt.Println("param:", param) + } + + // Pass variadic value as a variadic parameter. + fmt.Println("params:", fmt.Sprintln(myStrings...)) learnErrorHandling() } @@ -237,7 +241,7 @@ func learnErrorHandling() { } // An error value communicates not just "ok" but more about the problem. if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value - // prints "strconv.ParseInt: parsing "non-int": invalid syntax" + // prints 'strconv.ParseInt: parsing "non-int": invalid syntax' fmt.Println(err) } // We'll revisit interfaces a little later. Meanwhile, @@ -264,19 +268,19 @@ func learnConcurrency() { // There is no telling in what order the results will arrive! fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. - cs := make(chan string) // another channel, this one handles strings. - cc := make(chan chan string) // a channel of string channels. - go func() { c <- 84 }() // start a new goroutine just to send a value - go func() { cs <- "wordy" }() // again, for cs this time + cs := make(chan string) // Another channel, this one handles strings. + ccs := make(chan chan string) // A channel of string channels. + go func() { c <- 84 }() // Start a new goroutine just to send a value. + go func() { cs <- "wordy" }() // Again, for cs this time. // Select has syntax like a switch statement but each case involves // a channel operation. It selects a case at random out of the cases // that are ready to communicate. select { - case i := <-c: // the value received can be assigned to a variable + case i := <-c: // The value received can be assigned to a variable, fmt.Printf("it's a %T", i) - case <-cs: // or the value received can be discarded + case <-cs: // or the value received can be discarded. fmt.Println("it's a string") - case <-cc: // empty channel, not ready for communication. + case <-ccs: // Empty channel, not ready for communication. fmt.Println("didn't happen.") } // At this point a value was taken from either c or cs. One of the two @@ -287,7 +291,7 @@ func learnConcurrency() { // A single function from package http starts a web server. func learnWebProgramming() { - // ListenAndServe first parameter is TCP address to listen at. + // First parameter of ListenAndServe is TCP address to listen to. // Second parameter is an interface, specifically http.Handler. err := http.ListenAndServe(":8080", pair{}) fmt.Println(err) // don't ignore errors @@ -295,7 +299,7 @@ func learnWebProgramming() { // Make pair an http.Handler by implementing its only method, ServeHTTP. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Serve data with a method of http.ResponseWriter + // Serve data with a method of http.ResponseWriter. w.Write([]byte("You learned Go in Y minutes!")) } ``` -- cgit v1.2.3 From 453341b5271e4136dcebe06dacde8361bfdee676 Mon Sep 17 00:00:00 2001 From: iArnold Date: Fri, 31 Jan 2014 13:55:24 +0100 Subject: Update red.html.markdown Corrections with editors glasses on. --- red.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index c2e81b71..73fe4bb0 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -15,7 +15,7 @@ Red, together with its C-level dialect Red/System, provides a language that cove Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon, Red/System, covers the more basic needs of programming like C can, being closer to the metal. -Red will be the worlds first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level +Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level from the metal to the meta without the aid of other stack tools. Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain from any platform to any other platform. And it will do this all from a binary executable that is supposed to stay under 1 MB. @@ -24,10 +24,10 @@ Ready to learn your first Red? ```Red All text before the header will be treated as comment, as long as you avoid using the word "red" -starting with a capital "R" in this pre-header text. Most of the time you start your script with -the header itself. The header of a redscript is the capitalized word "red" followed by a +starting with a capital "R" in this pre-header text. Most of the time you start your script or program with +the header itself. The header of a red script is the capitalized word "red" followed by a whitespace character followed by a block of square brackets []. -The block of brackets can be filled with useful information about the script or program, the author, +The block of brackets can be filled with useful information about the script or program: the author, the filename, the version, the license, what the program does or needs. The red/System header is just like the red header, only saying "red/System" and not "red". @@ -97,7 +97,7 @@ my-integer: 0 type? my-integer integer! - +; A variable can be initialized using another variable that gets initialized at the same time. i2: 1 + i1: 1 ; Arithmetic is straightforward -- cgit v1.2.3 From 57b0ac6412cec6bcd1dfa50acbfe08805cf9ad95 Mon Sep 17 00:00:00 2001 From: iArnold Date: Fri, 31 Jan 2014 20:44:43 +0100 Subject: Update red.html.markdown Updated document on two things the author of Red pointed out. --- red.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index 73fe4bb0..9206f650 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -24,8 +24,9 @@ Ready to learn your first Red? ```Red All text before the header will be treated as comment, as long as you avoid using the word "red" -starting with a capital "R" in this pre-header text. Most of the time you start your script or program with -the header itself. The header of a red script is the capitalized word "red" followed by a +starting with a capital "R" in this pre-header text. This is a temporary shortcoming of the used lexer but +most of the time you start your script or program with the header itself. +The header of a red script is the capitalized word "red" followed by a whitespace character followed by a block of square brackets []. The block of brackets can be filled with useful information about the script or program: the author, the filename, the version, the license, what the program does or needs. @@ -122,12 +123,12 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0) ; Control Structures ; ; if -; Execute a block of code if a given condition is true. IF does not return any value, +; Evaluate a block of code if a given condition is true. IF does not return any value, ; so cannot be used in an expression. if a < 0 [print "a is negative"] ; either -; Execute a block of code if a given condition is true, else execute an alternative block of code. +; Evaluate a block of code if a given condition is true, else evaluate an alternative block of code. ; If last expressions in both blocks have the same type, EITHER can be used inside an expression. either a < 0 [ either a = 0 [ @@ -165,10 +166,10 @@ until [ ] ; will output: ooooo -; Note that the loop will always be executed at least once, even if the condition is not met from the beginning. +; Note that the loop will always be evaluated at least once, even if the condition is not met from the beginning. ; while -; While a given condition is met, execute a block of code. WHILE does not return any value, +; While a given condition is met, evaluate a block of code. WHILE does not return any value, ; so cannot be used in an expression. c: 5 while [c > 0][ -- cgit v1.2.3 From 01fb4ad36eec1397cf469bc7c0fb935498c72702 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sat, 1 Feb 2014 16:56:37 -0800 Subject: Remove red syntax highlighting (to make it not error out) --- red.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/red.html.markdown b/red.html.markdown index 9206f650..15e36de6 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -22,7 +22,7 @@ from any platform to any other platform. And it will do this all from a binary e Ready to learn your first Red? -```Red +``` All text before the header will be treated as comment, as long as you avoid using the word "red" starting with a capital "R" in this pre-header text. This is a temporary shortcoming of the used lexer but most of the time you start your script or program with the header itself. -- cgit v1.2.3 From 8d82b5594749c52b5b8fa3b988ae65098a47ab1c Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 1 Feb 2014 17:00:04 -0800 Subject: Fix GO yaml to not break in es --- es-es/go-es.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index a7166dc1..e788e810 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -1,14 +1,12 @@ --- -name: Go -category: language language: Go +lang: es-es filename: learngo-es.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] translators: - ["Adrian Espinosa", "http://www.adrianespinosa.com"] - - ["Jesse Johnson, "https://github.com/holocronweaver"] -lang: es-es + - ["Jesse Johnson", "https://github.com/holocronweaver"] --- Go fue creado por la necesidad de hacer el trabajo rápidamente. No es -- cgit v1.2.3 From ded11e254f75edfd83fc816fe609431e182f5155 Mon Sep 17 00:00:00 2001 From: Quint Guvernator Date: Sun, 2 Feb 2014 15:11:15 -0500 Subject: added defer example decided not to use file i/o as an example because external file access is rare in other tutorials. --- go.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/go.html.markdown b/go.html.markdown index d1a0ae34..a66e8c4b 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -7,6 +7,7 @@ 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"] --- Go was created out of the need to get work done. It's not the latest trend @@ -180,9 +181,21 @@ func learnFlowControl() { goto love love: + learnDefer() // A quick detour to an important keyword. learnInterfaces() // Good stuff coming up! } + + +func learnDefer() (ok bool) { + // deferred statements are executed just before the function returns. + defer fmt.Println("deferred statements execute in reverse (LIFO) order.") + defer fmt.Println("\nThis line is being printed first because") + // defer is commonly used to close a file, so the function closing the file + // stays close to the function opening the file + return true +} + // Define Stringer as an interface type with one method, String. type Stringer interface { String() string -- cgit v1.2.3 From e8c8fb0ea551ba26dc6c839a41d4f7fe6fbfe942 Mon Sep 17 00:00:00 2001 From: jgpacker Date: Sun, 2 Feb 2014 23:01:13 -0200 Subject: Added visual basic translation from https://github.com/adambard/learnxinyminutes-docs/issues/448 --- pt-br/visualbasic-pt.html.markdown | 285 +++++++++++++++++++++++++++++++++++++ 1 file changed, 285 insertions(+) create mode 100644 pt-br/visualbasic-pt.html.markdown diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown new file mode 100644 index 00000000..76cca567 --- /dev/null +++ b/pt-br/visualbasic-pt.html.markdown @@ -0,0 +1,285 @@ +--- +language: Visual Basic +contributors: + - ["Brian Martin", "http://brianmartin.biz"] +translators: + - ["AdrianoJP", "https://github.com/AdrianoJP"] +lang: pt-br +filename: learnvisualbasic-pt.vb +--- + +```vb +Module Module1 + +module Module1 + + Sub Main () + ' Uma visão geral de console de aplicativos do Visual Basic antes de + ' mergulharmos mais profundamente na linguagem + ' Aspas simples começam comentários. + ' Para Navegar este tutorial dentro do compilador do Visual Basic, + ' eu criei um sistema de navegação. + ' Este sistema de navegação vai ser explicado conforme avançarmos no + ' tutorial, e você vai entender o que isso significa. + Console.Title = (" Saiba X em Y Minutes" ) + Console.WriteLine ( "NAVEGAÇÃO" ) 'Mostrar + Console.ForegroundColor = ConsoleColor.Green + Console.WriteLine ("1. Saída Olá Mundo" ) + Console.WriteLine ("2. Entrada Olá Mundo" ) + Console.WriteLine ("3. Cálculando números inteiros " ) + Console.WriteLine ("4. Calculando números decimais " ) + Console.WriteLine ("5 . Calculadora de Trabalho " ) + Console.WriteLine ("6. Usando Do While Loops " ) + Console.WriteLine ("7. Usando Para While Loops " ) + Console.WriteLine ("8 . Declarações condicionais " ) + Console.WriteLine ("9. Selecione uma bebida" ) + Console.WriteLine ("50 . About" ) + Console.WriteLine ("Por favor, escolha um número da lista acima " ) + Seleção Dim As String = Console.ReadLine + Select A seleção dos casos + Caso "1" 'Output HelloWorld + Console.clear () ' Limpa a aplicação e abre o sub privado + HelloWorldOutput () ' Nome Private Sub, Abre Private Sub + Caso "2" 'Olá entrada + Console.clear ( ) + HelloWorldInput ( ) + Caso de "3" 'Calculando Números Inteiros + Console.clear ( ) + CalculatingWholeNumbers ( ) + Caso "4" ' Números decimais Calculting + Console.clear ( ) + CalculatingDecimalNumbers ( ) + Caso "5" ' Calcculator Trabalho + Console.clear ( ) + WorkingCalculator ( ) + Caso "6" 'Usando Do While Loops + Console.clear ( ) + UsingDoWhileLoops ( ) + Caso de "7" 'Usando pois enquanto Loops + Console.clear ( ) + UsingForLoops ( ) + Caso "8" ' Instruções condicionais + Console.clear ( ) + ConditionalStatement ( ) + Caso "9" "Declaração If / Else + Console.clear ( ) + IfElseStatement () ' Selecione uma bebida + Caso "50" 'Quem caixa de msg + Console.clear ( ) + Console.Title = (" Saiba X em Y Minutos :: Quem " ) + MsgBox (" Este tutorial é de Brian Martin ( @ BrianMartinn " ) + Console.clear ( ) + Main () + Console.ReadLine () + + End Select + End Sub + + ' Um - Eu estou usando números para ajudar com a navegação acima quando eu voltar + ' depois de construí-lo . + + " Nós usamos subs privadas para separar diferentes seções do programa. + Private Sub HelloWorldOutput () + ' Título de aplicativo do console + Console.Title = " Olá Mundo Ouput | Saiba X em Y Minutes" + 'Use Console.Write ("") ou Console.WriteLine ("") para imprimir saídas. + " Seguido por Console.Read () alternativamente Console.ReadLine () + ' Console.ReadLine () imprime a saída para o console. + Console.WriteLine ( "Olá Mundo" ) + Console.ReadLine () + End Sub + + ' Dois + Private Sub HelloWorldInput () + Console.Title = " Olá Mundo YourName | Saiba X em Y Minutes" + ' Variáveis + 'Os dados inseridos por um usuário precisa ser armazenada . + ' As variáveis ​​também começar com um Dim e terminar com um Como VariableType . + + ' Neste tutorial, nós queremos saber o que o seu nome, e faça o programa + ' Responder ao que é dito. + Nome de usuário Dim As String + " Nós usamos string como string é uma variável de texto baseado . + Console.WriteLine (" Olá, Qual é o seu nome? ") ' Peça ao usuário seu nome. + username = Console.ReadLine () ' armazena o nome usuários. + Console.WriteLine (" Olá " + nome do usuário) " A saída é Olá ' Seu nome ' + Console.ReadLine () ' Outsputs acima. + ' O código acima irá lhe fazer uma pergunta seguiu imprimindo sua resposta. + " Outras variáveis ​​incluem Integer e usamos inteiro para números inteiros. + End Sub + + "Três + Sub CalculatingWholeNumbers particulares () + Console.Title = " Cálculo de Números Inteiros | Saiba X em Y Minutes" + Console.Write ("Primeiro número:") 'Digite um número inteiro, 1, 2, 50, 104 ect + Dim a As Integer = Console.ReadLine () + Console.Write ("Segundo número:") 'Enter segundo número inteiro. + Dim b As Integer = Console.ReadLine () + Dim c As Integer = a + b + Console.WriteLine ( c) + Console.ReadLine () + " O texto acima é uma calculadora simples + End Sub + + 'Quatro + Sub CalculatingDecimalNumbers particulares () + Console.Title = " Calculando com duplo | Saiba X em Y Minutes" + ' Claro que gostaria de ser capaz de somar decimais . + " Por isso, poderia mudar o acima de Integer para Double. + + " Digite um número inteiro , 1,2 , 2,4 , 50,1 , 104,9 ect + Console.Write ("Primeiro número:") + Dim a As Double = Console.ReadLine + Console.Write ("Segundo número:") 'Enter segundo número inteiro. + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Console.WriteLine ( c) + Console.ReadLine () + " Portanto, o programa acima pode adicionar até 1,1-2,2 + End Sub + + ' Cinco + Private Sub WorkingCalculator () + Console.Title = " A Calculadora de Trabalho | Saiba X em Y Minutes" + " No entanto, se você gostaria que a calculadora para subtrair, dividir , múltiplos e + ' somar. + ' Copie e cole o código acima novamente . + Console.Write ("Primeiro número:") + Dim a As Double = Console.ReadLine + Console.Write ("Segundo número:") 'Enter segundo número inteiro. + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + " Ao adicionar as linhas abaixo , somos capazes de calcular a subtração , + ' multply bem como dividir os valores de a e b + Console.Gravar ( a.ToString ( ) + " + " + b.ToString ( ) ) + 'Queremos pad as respostas para a esquerda por três espaços. + Console.WriteLine (" =" + c.ToString.PadLeft (3) ) + Console.Gravar ( a.ToString ( ) + " * " + b.ToString ( ) ) + Console.WriteLine (" =" + d.ToString.PadLeft (3) ) + Console.Gravar ( a.ToString ( ) + " - " + b.ToString ( ) ) + Console.WriteLine (" =" + e.ToString.PadLeft (3) ) + Console.Write ( a.ToString () + "/" + b.ToString ()) + Console.WriteLine (" =" + e.ToString.PadLeft (3) ) + Console.ReadLine () + + End Sub + + ' Seis + Sub UsingDoWhileLoops particulares () + ' Assim como o sub privado anterior + ' Desta vez, perguntar se o usuário deseja continuar ( Sim ou Não ? ) + ' Estamos usando Do While Loop , como não temos certeza se o usuário quer usar o + 'programa mais de uma vez . + Console.Title = " UsingDoWhileLoops | Saiba X em Y Minutes" + Dim resposta As String ' Nós usamos a variável " String" como a resposta é um texto + Do ' Começamos o programa com + Console.Write ("Primeiro número:") + Dim a As Double = Console.ReadLine + Console.Write ("Segundo número:") + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + Console.Gravar ( a.ToString ( ) + " + " + b.ToString ( ) ) + Console.WriteLine (" =" + c.ToString.PadLeft (3) ) + Console.Gravar ( a.ToString ( ) + " * " + b.ToString ( ) ) + Console.WriteLine (" =" + d.ToString.PadLeft (3) ) + Console.Gravar ( a.ToString ( ) + " - " + b.ToString ( ) ) + Console.WriteLine (" =" + e.ToString.PadLeft (3) ) + Console.Write ( a.ToString () + "/" + b.ToString ()) + Console.WriteLine (" =" + e.ToString.PadLeft (3) ) + Console.ReadLine () + ' Faça a pergunta , se o usuário deseja continuar? Infelizmente, + "é sensível a maiúsculas. + Console.Write ( "Deseja continuar? (Sim / não )") + " O programa pega a variável e imprime e começa de novo. + answer = Console.ReadLine + " O comando para a variável para trabalhar seria , neste caso, " sim " + Loop While resposta = "yes" + + End Sub + + ' Sete + Sub UsingForLoops particulares () + ' Às vezes, o programa só precisa ser executado uma vez. + " Neste programa vamos estar em contagem regressiva a partir de 10. + + Console.Title = " Usando Para Loops | Saiba X em Y Minutes" + 'Declare variável e qual o número que deve contar para baixo na etapa 1, + ' Passo -2, -3 Passo ect. + Para i As Integer = 10 para 0 passo -1 + Console.WriteLine ( i.ToString ) ' Imprime o valor do contador + Next i ' Calcular novo valor + Console.WriteLine ( "Start ") ' Vamos começar o bebê programa ! + Console.ReadLine () ' POW ! - Talvez eu fiquei um pouco animado, então :) + End Sub + + ' Oito + Private Sub ConditionalStatement () + Console.Title = " Instruções condicionais | Saiba X em Y Minutes" + UserName Dim As String = Console.ReadLine + Console.WriteLine (" Olá, Qual é o seu nome? ") ' Peça ao usuário seu nome. + username = Console.ReadLine () ' armazena o nome usuários. + Se userName = " Adam " Então + Console.WriteLine (" Olá Adam " ) + Console.WriteLine (" Obrigado por criar este site útil " ) + Console.ReadLine () + outro + Console.WriteLine (" Olá " + nome do usuário) + Console.WriteLine (" Você check-out www.learnxinyminutes.com " ) + Console.ReadLine () ' Fins e imprime a declaração acima . + End If + End Sub + + 'Nove + Private Sub IfElseStatement () + Console.Title = "Se Declaração / Else | Saiba X em Y Minutes" + 'Às vezes é importante ter em conta mais de duas alternativas. + 'Às vezes, há um bom número de outros. + 'Quando este for o caso , mais do que uma if seria necessária . + 'Uma instrução if é ótimo para máquinas de venda automática . Quando o usuário digita um código. + ' A1 , A2, A3 , ect para selecionar um item. + 'Todas as opções podem ser combinadas em uma única if. + + Seleção Dim Valor String = Console.ReadLine ' para a seleção + Console.WriteLine (" A1. Para Soda " ) + Console.WriteLine (" A2. Para Fanta " ) + Console.WriteLine (" A3 . Para Guaraná" ) + Console.WriteLine (" A4. Para Coca Diet" ) + Console.ReadLine () + Se a seleção = "A1" Então + Console.WriteLine (" soda " ) + Console.ReadLine () + Seleção ElseIf = " A2 " Então + Console.WriteLine (" fanta " ) + Console.ReadLine () + Seleção ElseIf = " A3 " Então + Console.WriteLine ( "guaraná" ) + Console.ReadLine () + Seleção ElseIf = " A4 " Então + Console.WriteLine ( "coca diet" ) + Console.ReadLine () + outro + Console.WriteLine (" Por favor seleccione um produto" ) + Console.ReadLine () + End If + + End Sub + +End Module + +``` + +##Referências + +Aprendi Visual Basic no aplicativo de console. Isso me permitiu entender os princípios da programação de computador para continuar a aprender outras linguagens de programação facilmente. + +Eu criei um tutorial mais aprofundado do Visual Basic para aqueles que gostariam de saber mais. + +Toda a sintaxe deste tutorial é válida. Copie e cole o código no compilador do Visual Basic e execute (com o F5) o programa. -- cgit v1.2.3 From 718693ef48641e28c3382467ae2959322923fcda Mon Sep 17 00:00:00 2001 From: Aaron Raimist Date: Mon, 3 Feb 2014 17:09:52 -0600 Subject: [haskell/en] Fixes issue #510 --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 341c013e..e0489710 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -303,7 +303,7 @@ Nothing -- of type `Maybe a` for any `a` -- While IO can't be explained fully without explaining monads, -- it is not hard to explain enough to get going. --- When a Haskell program is executed, the function `main` is +-- When a Haskell program is executed, `main` is -- called. It must return a value of type `IO ()`. For example: main :: IO () -- cgit v1.2.3 From a089ef9b0d9a287e0b90f33f4c40b28b7f992783 Mon Sep 17 00:00:00 2001 From: Xavier Yao Date: Wed, 5 Feb 2014 21:37:17 +0800 Subject: Expend CoffeeScript doc --- coffeescript.html.markdown | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index c61cad67..86c875ba 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -2,9 +2,13 @@ language: coffeescript contributors: - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao"], "http://github.com/xavieryao"] filename: coffeescript.coffee --- +CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime. +As one of the succeeders of JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript codes working well in every JavaScript runtime. + See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript. ``` coffeescript @@ -30,6 +34,17 @@ number = -42 if opposite #=> if(opposite) { number = -42; } # Functions: square = (x) -> x * x #=> var square = function(x) { return x * x; } +fill = (container, liquid = "coffee") -> + "Filling the #{container} with #{liquid}..." +#=>var fill; +# +#fill = function(container, liquid) { +# if (liquid == null) { +# liquid = "coffee"; +# } +# return "Filling the " + container + " with " + liquid + "..."; +#}; + # Ranges: list = [1..5] #=> var list = [1, 2, 3, 4, 5]; @@ -47,11 +62,36 @@ math = # Splats: race = (winner, runners...) -> print winner, runners +#=>race = function() { +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +#}; # Existence: alert "I knew it!" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } # Array comprehensions: -cubes = (math.cube num for num in list) #=> ... +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +foods = ['broccoli', 'spinach', 'chocolate'] +eat food for food in foods when food isnt 'chocolate' +#=>foods = ['broccoli', 'spinach', 'chocolate']; +# +#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) { +# food = foods[_k]; +# if (food !== 'chocolate') { +# eat(food); +# } +#} ``` -- cgit v1.2.3 From b3f363fcf206adb7e63cf46598514fc692ef6a45 Mon Sep 17 00:00:00 2001 From: Xavier Yao Date: Wed, 5 Feb 2014 21:49:10 +0800 Subject: Chinese translation for CoffeeScript --- zh-cn/coffeescript-cn.html.markdown | 101 ++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 zh-cn/coffeescript-cn.html.markdown diff --git a/zh-cn/coffeescript-cn.html.markdown b/zh-cn/coffeescript-cn.html.markdown new file mode 100644 index 00000000..8fb96749 --- /dev/null +++ b/zh-cn/coffeescript-cn.html.markdown @@ -0,0 +1,101 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao"], "http://github.com/xavieryao"] +translators: + - ["Xavier Yao"], "http://github.com/xavieryao"] +filename: coffeescript-cn.coffee +lang: zh-cn +--- + +CoffeeScript是逐句编译为JavaScript的一种小型语言,且没有运行时的解释器。 +作为JavaScript的替代品之一,CoffeeScript旨在编译人类可读、美观优雅且速度不输原生的代码, +且编译后的代码可以在任何JavaScript运行时正确运行。 + +参阅 [CoffeeScript官方网站](http://coffeescript.org/)以获取CoffeeScript的完整教程。 + +``` coffeescript +# CoffeeScript是一种很潮的编程语言, +# 它紧随众多现代编程语言的趋势。 +# 因此正如Ruby和Python,CoffeeScript使用井号标记注释。 + +### +大段落注释以此为例,可以被直接编译为 '/ *' 和 '* /' 包裹的JavaScript代码。 + +在继续之前你需要了解JavaScript的基本概念。 + +示例中 => 后为编译后的JavaScript代码 +### + +# 赋值: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# 条件: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# 函数: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +fill = (container, liquid = "coffee") -> + "Filling the #{container} with #{liquid}..." +#=>var fill; +# +#fill = function(container, liquid) { +# if (liquid == null) { +# liquid = "coffee"; +# } +# return "Filling the " + container + " with " + liquid + "..."; +#}; + +# 区间: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# 对象: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +#} + +# Splats: +race = (winner, runners...) -> + print winner, runners +#=>race = function() { +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +#}; + +# 存在判断: +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# 数组推导: +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +foods = ['broccoli', 'spinach', 'chocolate'] +eat food for food in foods when food isnt 'chocolate' +#=>foods = ['broccoli', 'spinach', 'chocolate']; +# +#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) { +# food = foods[_k]; +# if (food !== 'chocolate') { +# eat(food); +# } +#} +``` -- cgit v1.2.3 From f70b1edcfbe14bd41fb7c1e45113359a3c75b4e3 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Thu, 6 Feb 2014 01:45:16 +0800 Subject: lua: typo `LoudDog.__index` is `Dog`, not `LoudDog`. --- lua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua.html.markdown b/lua.html.markdown index 27ce105b..bdd59999 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -321,7 +321,7 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- Dog.new(LoudDog) as LoudDog has no 'new' key, -- but does have __index = Dog on its metatable. -- Result: seymour's metatable is LoudDog, and --- LoudDog.__index = LoudDog. So seymour.key will +-- LoudDog.__index = Dog. So seymour.key will -- = seymour.key, LoudDog.key, Dog.key, whichever -- table is the first with the given key. -- 4. The 'makeSound' key is found in LoudDog; this -- cgit v1.2.3 From d7ea420ad4980d16bf61d977dfb6bcfb58286238 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Thu, 6 Feb 2014 02:33:05 +0800 Subject: Chinese (simplified) translation of lua --- zh-cn/lua-cn.html.markdown | 413 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 413 insertions(+) create mode 100644 zh-cn/lua-cn.html.markdown diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown new file mode 100644 index 00000000..95a94c76 --- /dev/null +++ b/zh-cn/lua-cn.html.markdown @@ -0,0 +1,413 @@ +--- +language: lua +lang: zh-cn +contributors: + - ["Tyler Neylon", "http://tylerneylon.com/"] + - ["Rob Hoelz", "http://hoelz.ro"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Craig Roddin", "craig.roddin@gmail.com"] + - ["Amr Tamimi", "https://amrtamimi.com"] +translators: + - ["Jakukyo Friel", "http://weakish.github.io"] +--- + +```lua +-- 单行注释以两个连字符开头 + +--[[ + 多行注释 +--]] + +---------------------------------------------------- +-- 1. 变量和流程控制 +---------------------------------------------------- + +num = 42 -- 所有的数字都是双精度浮点型。 +-- 别害怕,64位的双精度浮点型数字中有52位用于 +-- 保存精确的整型值; 对于52位以内的整型值, +-- 不用担心精度问题。 + +s = 'walternate' -- 和Python一样,字符串不可变。 +t = "也可以用双引号" +u = [[ 多行的字符串 + 以两个方括号 + 开始和结尾。]] +t = nil -- 撤销t的定义; Lua 支持垃圾回收。 + +-- 块使用do/end之类的关键字标识: +while num < 50 do + num = num + 1 -- 不支持 ++ 或 += 运算符。 +end + +-- If语句: +if num > 40 then + print('over 40') +elseif s ~= 'walternate' then -- ~= 表示不等于。 + -- 像Python一样,用 == 检查是否相等 ;字符串同样适用。 + io.write('not over 40\n') -- 默认标准输出。 +else + -- 默认全局变量。 + thisIsGlobal = 5 -- 通常使用驼峰。 + + -- 如何定义局部变量: + local line = io.read() -- 读取标准输入的下一行。 + + -- ..操作符用于连接字符串: + print('Winter is coming, ' .. line) +end + +-- 未定义的变量返回nil。 +-- 这不是错误: +foo = anUnknownVariable -- 现在 foo = nil. + +aBoolValue = false + +--只有nil和false为假; 0和 ''都均为真! +if not aBoolValue then print('twas false') end + +-- 'or'和 'and'短路 +-- 类似于C/js里的 a?b:c 操作符: +ans = aBoolValue and 'yes' or 'no' --> 'no' + +karlSum = 0 +for i = 1, 100 do -- 范围包含两端 + karlSum = karlSum + i +end + +-- 使用 "100, 1, -1" 表示递减的范围: +fredSum = 0 +for j = 100, 1, -1 do fredSum = fredSum + j end + +-- 通常,范围表达式为begin, end[, step]. + +-- 循环的另一种结构: +repeat + print('the way of the future') + num = num - 1 +until num == 0 + +---------------------------------------------------- +-- 2. 函数。 +---------------------------------------------------- + +function fib(n) + if n < 2 then return 1 end + return fib(n - 2) + fib(n - 1) +end + +-- 支持闭包及匿名函数: +function adder(x) + -- 调用adder时,会创建返回的函数, + -- 并且会记住x的值: + return function (y) return x + y end +end +a1 = adder(9) +a2 = adder(36) +print(a1(16)) --> 25 +print(a2(64)) --> 100 + +-- 返回值、函数调用和赋值都可以 +-- 使用长度不匹配的list。 +-- 不匹配的接收方会被赋值nil; +-- 不匹配的发送方会被丢弃。 + +x, y, z = 1, 2, 3, 4 +-- x = 1、y = 2、z = 3, 而 4 会被丢弃。 + +function bar(a, b, c) + print(a, b, c) + return 4, 8, 15, 16, 23, 42 +end + +x, y = bar('zaphod') --> 打印 "zaphod nil nil" +-- 现在 x = 4, y = 8, 而值15..42被丢弃。 + +-- 函数是一等公民,可以是局部的,也可以是全局的。 +-- 以下表达式等价: +function f(x) return x * x end +f = function (x) return x * x end + +-- 这些也是等价的: +local function g(x) return math.sin(x) end +local g; g = function (x) return math.sin(x) end +-- 'local g'使得g可以自引用。 + +-- 顺便提下,三角函数以弧度为单位。 + +-- 用一个字符串参数调用函数,可以省略括号: +print 'hello' --可以工作。 + +-- 调用函数时,如果只有一个table参数, +-- 同样可以省略括号(table详情见下): +print {} -- 一样可以工作。 + +---------------------------------------------------- +-- 3. Table。 +---------------------------------------------------- + +-- Table = Lua唯一的组合数据结构; +-- 它们是关联数组。 +-- 类似于PHP的数组或者js的对象, +-- 它们是哈希表或者字典,也可以当初列表使用。 + +-- 按字典/map的方式使用Table: + +-- Dict字面量默认使用字符串类型的key: +t = {key1 = 'value1', key2 = false} + +-- 字符串key可以使用类似js的点标记: +print(t.key1) -- 打印 'value1'. +t.newKey = {} -- 添加新的键值对。 +t.key2 = nil -- 从table删除 key2。 + +-- 使用任何非nil的值作为key: +u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} +print(u[6.28]) -- 打印 "tau" + +-- 数字和字符串的key按值匹配的 +-- table按id匹配。 +a = u['@!#'] -- 现在 a = 'qbert'. +b = u[{}] -- 我们或许期待的是 1729, 但是得到的是nil: +-- b = nil ,因为没有找到。 +-- 之所以没找到,是因为我们用的key与保存数据时用的不是同 +-- 一个对象。 +-- 所以字符串和数字是移植性更好的key。 + +-- 只需要一个table参数的函数调用不需要括号: +function h(x) print(x.key1) end +h{key1 = 'Sonmi~451'} -- 打印'Sonmi~451'. + +for key, val in pairs(u) do -- 遍历Table + print(key, val) +end + +-- _G 是一个特殊的table,用于保存所有的全局变量 +print(_G['_G'] == _G) -- 打印'true'. + +-- 按列表/数组的方式使用: + +-- 列表字面量隐式添加整数键: +v = {'value1', 'value2', 1.21, 'gigawatts'} +for i = 1, #v do -- #v 是列表的大小 + print(v[i]) -- 索引从 1 开始!! 太疯狂了! +end +-- 'list'并非真正的类型,v 其实是一个table, +-- 只不过它用连续的整数作为key,可以像list那样去使用。 + +---------------------------------------------------- +-- 3.1 元表(metatable) 和元方法(metamethod)。 +---------------------------------------------------- + +-- table的元表提供了一种机制,支持类似操作符重载的行为。 +-- 稍后我们会看到元表如何支持类似js prototype的行为。 + +f1 = {a = 1, b = 2} -- 表示一个分数 a/b. +f2 = {a = 2, b = 3} + +-- 这会失败: +-- s = f1 + f2 + +metafraction = {} +function metafraction.__add(f1, f2) + sum = {} + sum.b = f1.b * f2.b + sum.a = f1.a * f2.b + f2.a * f1.b + return sum +end + +setmetatable(f1, metafraction) +setmetatable(f2, metafraction) + +s = f1 + f2 -- 调用在f1的元表上的__add(f1, f2) 方法 + +-- f1, f2 没有关于元表的key,这点和js的prototype不一样。 +-- 因此你必须用getmetatable(f1)获取元表。 +-- 元表是一个普通的table, +-- 元表的key是普通的Lua中的key,例如__add。 + +-- 但是下面一行代码会失败,因为s没有元表: +-- t = s + s +-- 下面提供的与类相似的模式可以解决这个问题: + +-- 元表的__index 可以重载用于查找的点操作符: +defaultFavs = {animal = 'gru', food = 'donuts'} +myFavs = {food = 'pizza'} +setmetatable(myFavs, {__index = defaultFavs}) +eatenBy = myFavs.animal -- 可以工作!感谢元表 + +-- 如果在table中直接查找key失败,会使用 +-- 元表的__index 递归地重试。 + +-- __index的值也可以是function(tbl, key) +-- 这样可以支持自定义查找。 + +-- __index、__add等的值,被称为元方法。 +-- 这里是一个table元方法的清单: + +-- __add(a, b) for a + b +-- __sub(a, b) for a - b +-- __mul(a, b) for a * b +-- __div(a, b) for a / b +-- __mod(a, b) for a % b +-- __pow(a, b) for a ^ b +-- __unm(a) for -a +-- __concat(a, b) for a .. b +-- __len(a) for #a +-- __eq(a, b) for a == b +-- __lt(a, b) for a < b +-- __le(a, b) for a <= b +-- __index(a, b) for a.b +-- __newindex(a, b, c) for a.b = c +-- __call(a, ...) for a(...) + +---------------------------------------------------- +-- 3.2 与类相似的table和继承。 +---------------------------------------------------- + +-- Lua没有内建的类;可以通过不同的方法,利用表和元表 +-- 来实现类。 + +-- 下面是一个例子,解释在后面: + +Dog = {} -- 1. + +function Dog:new() -- 2. + newObj = {sound = 'woof'} -- 3. + self.__index = self -- 4. + return setmetatable(newObj, self) -- 5. +end + +function Dog:makeSound() -- 6. + print('I say ' .. self.sound) +end + +mrDog = Dog:new() -- 7. +mrDog:makeSound() -- 'I say woof' -- 8. + +-- 1. Dog看上去像一个类;其实它是一个table。 +-- 2. 函数tablename:fn(...) 等价于 +-- 函数tablename.fn(self, ...) +-- 冒号(:)只是添加了self作为第一个参数。 +-- 阅读7 & 8条 了解self变量是如何得到其值的。 +-- 3. newObj是类Dog的一个实例。 +-- 4. self = 被继承的类。通常self = Dog,不过继承可以改变它。 +-- 如果把newObj的元表和__index都设置为self, +-- newObj就可以得到self的函数。 +-- 5. 备忘:setmetatable返回其第一个参数。 +-- 6. 冒号(:)的作用和第2条一样,不过这里 +-- self是一个实例,而不是类 +-- 7. 等价于Dog.new(Dog),所以在new()中,self = Dog。 +-- 8. 等价于mrDog.makeSound(mrDog); self = mrDog。 + +---------------------------------------------------- + +-- 继承的例子: + +LoudDog = Dog:new() -- 1. + +function LoudDog:makeSound() + s = self.sound .. ' ' -- 2. + print(s .. s .. s) +end + +seymour = LoudDog:new() -- 3. +seymour:makeSound() -- 'woof woof woof' -- 4. + +-- 1. LoudDog获得Dog的方法和变量列表。 +-- 2. 因为new()的缘故,self拥有了一个'sound' key,参见第3条。 +-- 3. 等价于LoudDog.new(LoudDog),转换一下就是 +-- Dog.new(LoudDog),这是因为LoudDog没有'new' key, +-- 但是它的元表中有 __index = Dog。 +-- 结果: seymour的元表是LoudDog,并且 +-- LoudDog.__index = Dog。所以有seymour.key +-- = seymour.key, LoudDog.key, Dog.key +-- 从其中第一个有指定key的table获取。 +-- 4. 在LoudDog可以找到'makeSound'的key; +-- 等价于LoudDog.makeSound(seymour)。 + +-- 如果有必要,子类也可以有new(),与基类相似: +function LoudDog:new() + newObj = {} + -- 初始化newObj + self.__index = self + return setmetatable(newObj, self) +end + +---------------------------------------------------- +-- 4. 模块 +---------------------------------------------------- + + +--[[ 我把这部分给注释了,这样脚本剩下的部分可以运行 + +-- 假设文件mod.lua的内容类似这样: +local M = {} + +local function sayMyName() + print('Hrunkner') +end + +function M.sayHello() + print('Why hello there') + sayMyName() +end + +return M + +-- 另一个文件可以使用mod.lua的功能: +local mod = require('mod') -- 运行文件mod.lua. + +-- require是包含模块的标准做法。 +-- require等价于: (针对没有被缓存的情况;参见后面的内容) +local mod = (function () + +end)() +-- mod.lua被包在一个函数体中,因此mod.lua的局部变量 +-- 对外不可见。 + +-- 下面的代码可以工作,因为在这里mod = mod.lua 中的 M: +mod.sayHello() -- Says hello to Hrunkner. + +-- 这是错误的;sayMyName只在mod.lua中存在: +mod.sayMyName() -- 错误 + +-- require返回的值会被缓存,所以一个文件只会被运行一次, +-- 即使它被require了多次。 + +-- 假设mod2.lua包含代码"print('Hi!')"。 +local a = require('mod2') -- 打印Hi! +local b = require('mod2') -- 不再打印; a=b. + +-- dofile与require类似,但是不缓存: +dofile('mod2') --> Hi! +dofile('mod2') --> Hi! (再次运行,与require不同) + +-- loadfile加载一个lua文件,但是并不运行它。 +f = loadfile('mod2') -- Calling f() runs mod2.lua. + +-- loadstring是loadfile的字符串版本。 +g = loadstring('print(343)') --返回一个函数。 +g() -- 打印343; 在此之前什么也不打印。 + +--]] +``` + +## 参考 + + + +为什么?我非常兴奋地学习lua, 这样我就可以使用[Löve 2D游戏引擎](http://love2d.org/)来编游戏。 + +怎么做?我从[BlackBulletIV的面向程序员的Lua指南](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/)入门。接着我阅读了官方的[Lua编程](http://www.lua.org/pil/contents.html)一书。 + +lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf)应该值得一看。 + +本文没有涉及标准库的内容: + +* string library +* table library +* math library +* io library +* os library + +使用Lua,欢乐常在! -- cgit v1.2.3 From bcd930047d0613a93b2e98c60cac0d93a1678621 Mon Sep 17 00:00:00 2001 From: iArnold Date: Fri, 7 Feb 2014 20:34:08 +0100 Subject: Update red.html.markdown Some of the code lines were too long to fit the box so I shortened these and made a few changes in the text so it looks better at the points where the extra lines were added. --- red.html.markdown | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/red.html.markdown b/red.html.markdown index 15e36de6..73a13606 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -23,14 +23,17 @@ from any platform to any other platform. And it will do this all from a binary e Ready to learn your first Red? ``` -All text before the header will be treated as comment, as long as you avoid using the word "red" -starting with a capital "R" in this pre-header text. This is a temporary shortcoming of the used lexer but -most of the time you start your script or program with the header itself. +All text before the header will be treated as comment, as long as you avoid using the +word "red" starting with a capital "R" in this pre-header text. This is a temporary +shortcoming of the used lexer but most of the time you start your script or program +with the header itself. The header of a red script is the capitalized word "red" followed by a whitespace character followed by a block of square brackets []. -The block of brackets can be filled with useful information about the script or program: the author, -the filename, the version, the license, what the program does or needs. -The red/System header is just like the red header, only saying "red/System" and not "red". +The block of brackets can be filled with useful information about this script or +program: the author's name, the filename, the version, the license, a summary of +what the program does or any other files it needs. +The red/System header is just like the red header, only saying "red/System" and +not "red". Red [] @@ -98,7 +101,8 @@ my-integer: 0 type? my-integer integer! -; A variable can be initialized using another variable that gets initialized at the same time. +; A variable can be initialized using another variable that gets initialized +; at the same time. i2: 1 + i1: 1 ; Arithmetic is straightforward @@ -128,8 +132,9 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0) if a < 0 [print "a is negative"] ; either -; Evaluate a block of code if a given condition is true, else evaluate an alternative block of code. -; If last expressions in both blocks have the same type, EITHER can be used inside an expression. +; Evaluate a block of code if a given condition is true, else evaluate an alternative +; block of code. If the last expressions in both blocks have the same type, EITHER can +; be used inside an expression. either a < 0 [ either a = 0 [ msg: "zero" @@ -142,7 +147,8 @@ either a < 0 [ print ["a is " msg lf] -; An alternative way to write it (allowed because all code paths return a value of the same type): +; There is an alternative way to write this +; (Which is allowed because all code paths return a value of the same type): msg: either a < 0 [ either a = 0 [ @@ -156,8 +162,8 @@ msg: either a < 0 [ print ["a is " msg lf] ; until -; Loop over a block of code until the condition at end of block, is met. UNTIL does not return any value, -; so cannot be used in an expression. +; Loop over a block of code until the condition at end of block, is met. +; UNTIL does not return any value, so it cannot be used in an expression. c: 5 until [ prin "o" @@ -166,11 +172,12 @@ until [ ] ; will output: ooooo -; Note that the loop will always be evaluated at least once, even if the condition is not met from the beginning. +; Note that the loop will always be evaluated at least once, even if the condition is +; not met from the beginning. ; while -; While a given condition is met, evaluate a block of code. WHILE does not return any value, -; so cannot be used in an expression. +; While a given condition is met, evaluate a block of code. +; WHILE does not return any value, so it cannot be used in an expression. c: 5 while [c > 0][ prin "o" -- cgit v1.2.3 From 0f4760f9eacc787de61e60b333a5ce8b3aa2321a Mon Sep 17 00:00:00 2001 From: brk0_0 Date: Sat, 8 Feb 2014 13:03:50 -0200 Subject: Moved println() from 'Variables and Collections' section --- julia.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 3bc660cf..b8e24b39 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -92,13 +92,13 @@ false # Another way to format strings is the printf macro. @printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 +# Printing is easy +println("I'm Julia. Nice to meet you!") + #################################################### ## 2. Variables and Collections #################################################### -# Printing is easy -println("I'm Julia. Nice to meet you!") - # You don't declare variables before assigning to them. some_var = 5 #=> 5 some_var #=> 5 -- cgit v1.2.3 From 928e53a10885f4bfcb6b603072b0a27cc0caf36d Mon Sep 17 00:00:00 2001 From: "U-Christopher-PC\\Christopher" Date: Mon, 10 Feb 2014 14:28:54 -0700 Subject: Added section on interfaces. Added array info --- java.html.markdown | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 1fbf6a21..3cab973e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -101,14 +101,17 @@ public class LearnJava { // Arrays //The array size must be decided upon instantiation - //The format for declaring an array is follows: + //The following formats work for declaring an arrow // [] = new []; + // [] = new []; int [] intArray = new int[10]; String [] stringArray = new String[1]; - boolean [] booleanArray = new boolean[100]; + boolean boolArray [] = new boolean[100]; // Another way to declare & initialize an array int [] y = {9000, 1000, 1337}; + String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; // Indexing an array - Accessing an element System.out.println("intArray @ 0: " + intArray[0]); @@ -405,6 +408,46 @@ class PennyFarthing extends Bicycle { } +//Interfaces +//Interface declaration syntax +// interface extends { +// //Constants +// //Method declarations +//} + +//Example - Food: +public interface Edible { + public void eat(); //Any class that implements this interface, must implement this method +} + +public interface Digestible { + public void digest(); +} + + +//We can now create a class that implements both of these interfaces +public class Fruit implements Edible, Digestible { + public void eat() { + //... + } + + public void digest() { + //... + } +} + +//In java, you can extend only one class, but you can implement many interfaces. +//For example: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { + public void InterfaceOneMethod() { + + } + + public void InterfaceTwoMethod() { + + } +} + ``` ## Further Reading -- cgit v1.2.3 From 1cf0ff68d05434c863f11cf7935e28834a857490 Mon Sep 17 00:00:00 2001 From: Artyom Date: Wed, 12 Feb 2014 19:20:41 +0300 Subject: Fix typos in russian translation for Go language --- ru-ru/go-ru.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 27b5d894..e9892952 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -17,7 +17,7 @@ Go - это язык общего назначения, целью которо для создания масштабируемых и многопоточных программ. Может похвастаться отличной стандартной библиотекой и большим комьюнити, полным -энтузиазтов. +энтузиастов. ```go // Однострочный комментарий @@ -300,7 +300,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { объемную документацию. Для живого ознакомления рекомендуется почитать исходные коды [стандартной -библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированая, она +библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированная, она является лучшим источником для чтения и понимания Go, его стиля и идиом. Либо можно, кликнув на имени функции в [документации](http://golang.org/pkg/), перейти к ее исходным кодам. -- cgit v1.2.3 From a23e5807ad0c241672eeb7eaffea4798f5954d01 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 12 Feb 2014 12:02:29 -0800 Subject: Update bash.html.markdown use /bin/bash for bash, not /bin/sh --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index a6bd2b7c..e2c5bbaf 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -15,7 +15,7 @@ Nearly all examples below can be a part of a shell script or executed directly i [Read more here.](http://www.gnu.org/software/bash/manual/bashref.html) ```bash -#!/bin/sh +#!/bin/bash # First line of the script is shebang which tells the system how to execute # the script: http://en.wikipedia.org/wiki/Shebang_(Unix) # As you already figured, comments start with #. Shebang is also a comment. -- cgit v1.2.3 From 820a822081ed965be820019fce63b939876b4901 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 12 Feb 2014 12:03:31 -0800 Subject: Update bash-cn.html.markdown --- zh-cn/bash-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index 2e885833..6afa659a 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -17,7 +17,7 @@ Bash 是一个为 GNU 计划编写的 Unix shell,是 Linux 和 Mac OS X 下的 [更多信息](http://www.gnu.org/software/bash/manual/bashref.html) ```bash -#!/bin/sh +#!/bin/bash # 脚本的第一行叫 shebang,用来告知系统如何执行该脚本: # 参见: http://en.wikipedia.org/wiki/Shebang_(Unix) # 如你所见,注释以 # 开头,shebang 也是注释。 -- cgit v1.2.3 From b4e8259cbc22d530121ca507e3394ab8c2219ded Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 12 Feb 2014 12:03:41 -0800 Subject: Update bash-de.html.markdown --- de-de/bash-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index 7b60d79f..ad782e06 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -16,7 +16,7 @@ Beinahe alle der folgenden Beispiele können als Teile eines Shell-Skripts oder [Weitere Informationen \(Englisch\)](http://www.gnu.org/software/bash/manual/bashref.html) ```bash -#!/bin/sh +#!/bin/bash # Die erste Zeile des Scripts nennt sich Shebang in gibt dem System an, wie # wie das Script ausgeführt werden soll: http://de.wikipedia.org/wiki/Shebang # Du hast es bestimmt schon mitgekriegt, Kommentare fangen mit # an. Das Shebang ist auch ein Kommentar -- cgit v1.2.3 From 5746c14db74f65826b297e9ea42e37e8d1ad91f2 Mon Sep 17 00:00:00 2001 From: Ariel Date: Wed, 12 Feb 2014 22:02:58 -0500 Subject: Added additional resources for learning Java --- java.html.markdown | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 3cab973e..50875491 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -454,7 +454,7 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, In The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. -Other Topics To Research: +**Official Oracle Guides**: * [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) @@ -473,6 +473,19 @@ Other Topics To Research: * [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) -Books: +**Online Practice and Tutorials** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Books**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) + -* [Head First Java] (http://www.headfirstlabs.com/books/hfjava/) -- cgit v1.2.3 From 4c25ac36c669ef0c65938d329a7d3baff6a756dd Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Fri, 14 Feb 2014 17:22:38 +0800 Subject: c: reorder paragraphs content about `static` are inserted into the wrong place. --- c.html.markdown | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index e55ff148..d7c682ad 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -454,6 +454,12 @@ void str_reverse(char *str_in) } } +/* +char c[] = "This is a test."; +str_reverse(c); +printf("%s\n", c); // => ".tset a si sihT" +*/ + //if referring to external variables outside function, must use extern keyword. int i = 0; void testFunc() { @@ -467,11 +473,7 @@ void testFunc() { } //**You may also declare functions as static to make them private** -/* -char c[] = "This is a test."; -str_reverse(c); -printf("%s\n", c); // => ".tset a si sihT" -*/ + /////////////////////////////////////// // User-defined types and structs -- cgit v1.2.3 From 2a9fb70f6d62e1cf3a0bc08fa6dc89bb53310624 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Fri, 14 Feb 2014 20:34:23 +0800 Subject: c: typo --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index d7c682ad..0190125b 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -569,7 +569,7 @@ typedef void (*my_fnp_type)(char *); '\b' // backspace character '\0' // null character. Usually put at end of strings in C lang. // hello\n\0. \0 used by convention to mark end of string. -'\\' // backspace +'\\' // backslash '\?' // question mark '\'' // single quote '\"' // double quote -- cgit v1.2.3 From e0b9cd1a8bea27a950d2b8b26ce7329f51ce801a Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Fri, 14 Feb 2014 21:08:09 +0800 Subject: c-cn: improve translations - improve translations - translate the missing part --- zh-cn/c-cn.html.markdown | 394 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 311 insertions(+), 83 deletions(-) diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown index b4bff8fc..ecd2558e 100644 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -5,37 +5,52 @@ contributors: - ["Adam Bard", "http://adambard.com/"] translators: - ["Chenbo Li", "http://binarythink.net/"] + - ["Jakukyo Friel", "http://weakish.github.io"] lang: zh-cn --- C语言在今天仍然是高性能计算的主要选择。 -C大概是大多数程序员用到的最接近底层的语言了,但是C语言本身不仅可以用来提升程序运行的速度 -注意看看C语言的文档,你就会知道C语言在内存管理方面的强大也是其他语言无法比拟的。 +C大概是大多数程序员用到的最接近底层的语言了,C语言原生的速度就很高了,但是别忘了C的手动内存管理,它会让你将性能发挥到极致。 ```c -// 用“//”来实现单行注释 +// 单行注释以//开始。(仅适用于C99或更新的版本。) /* -多行注释是这个样子的 +多行注释是这个样子的。(C89也适用。) */ +// 常数: #define 关键词 +#define DAYS_IN_YEAR 365 + +// 以枚举的方式定义常数 +enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; +// MON自动被定义为2,TUE被定义为3,以此类推。 + // 用#include来导入头文件 #include #include #include -// 函数的标签(signature)应该放在.h文件中,并且引入到程序顶部 -// 也可以直接放到你的.c文件的最上面 -void function_1(); -void function_2(); +// <尖括号>间的文件名是C标准库的头文件。 +// 标准库以外的头文件,使用双引号代替尖括号。 +#include "my_header.h" + +// 函数的签名可以事先在.h文件中定义, +// 也可以直接在.c文件的头部定义。 +void function_1(char c); +void function_2(void); -// c程序的入口是一个返回值为int型的函数,名字叫做main +// 如果函数出现在main()之后,那么必须在main()之前 +// 先声明一个函数原型 +int add_two_ints(int x1, int x2); // 函数原型 + +// 你的程序的入口是一个返回值为整型的main函数 int main() { -// 用printf来实现标准输出,这种输出也可以用格式来控制 -// %d 代表一个整数, \n 代表一个新行 -printf("%d\n", 0); // => 输出 0 +// 用printf打印到标准输出,可以设定格式, +// %d 代表整数, \n 代表换行 +printf("%d\n", 0); // => 打印 0 // 所有的语句都要以分号结束 /////////////////////////////////////// @@ -69,18 +84,29 @@ double x_double = 0.0; // 整数类型也可以有无符号的类型表示。这样这些变量就无法表示负数 // 但是无符号整数所能表示的范围就可以比原来的整数大一些 -unsigned char ux_char; unsigned short ux_short; unsigned int ux_int; unsigned long long ux_long_long; +// 单引号内的字符是机器的字符集中的整数。 +'0' // => 在ASCII字符集中是48 +'A' // => 在ASCII字符集中是65 + // char类型一定会占用1个字节,但是其他的类型却会因具体机器的不同而各异 // sizeof(T) 可以返回T类型在运行的机器上占用多少个字节 // 这样你的代码就可以在各处正确运行了 -// 比如 -printf("%lu\n", sizeof(int)); // => 4 (字长为4的机器上) - -// 数组必须要在开始被初始化为特定的长度 +// sizeof(obj)返回表达式(变量、字面量等)的尺寸 +printf("%zu\n", sizeof(int)); // => 4 (大多数的机器字长为4) + +// 如果`sizeof`的参数是一个表达式,那么这个参数不会被演算(VLA例外,见下) +// 它产生的值是编译期的常数 +int a = 1; +// size_t是一个无符号整型,表示对象的尺寸,至少2个字节 +size_t size = sizeof(a++); // a++ 不会被演算 +printf("sizeof(a++) = %zu where a = %d\n", size, a); +// 打印 "sizeof(a++) = 4 where a = 1" (在32位架构上) + +// 数组必须要被初始化为具体的长度 char my_char_array[20]; // 这个数组占据 1 * 20 = 20 个字节 int my_int_array[20]; // 这个数组占据 4 * 20 = 80 个字节 // (这里我们假设字长为4) @@ -89,48 +115,83 @@ int my_int_array[20]; // 这个数组占据 4 * 20 = 80 个字节 // 可以用下面的方法把数组初始化为0: char my_array[20] = {0}; -// 对数组任意存取就像其他语言的方式 -- 其实是其他的语言像C +// 索引数组和其他语言类似 -- 好吧,其实是其他的语言像C my_array[0]; // => 0 // 数组是可变的,其实就是内存的映射! my_array[1] = 2; printf("%d\n", my_array[1]); // => 2 +// 在C99 (C11中是可选特性),变长数组(VLA)也可以声明长度。 +// 其长度不用是编译期常量。 +printf("Enter the array size: "); // 询问用户数组长度 +char buf[0x100]; +fgets(buf, sizeof buf, stdin); + +// stroul 将字符串解析为无符号整数 +size_t size = strtoul(buf, NULL, 10); +int var_length_array[size]; // 声明VLA +printf("sizeof array = %zu\n", sizeof var_length_array); + +// 上述程序可能的输出为: +// > Enter the array size: 10 +// > sizeof array = 40 + // 字符串就是以 NUL (0x00) 这个字符结尾的字符数组, -// 这个字符可以用'\0'来表示. -// (在字符串字面值中我们不必输入这个字符,编译器会自动添加的) +// NUL可以用'\0'来表示. +// (在字符串字面量中我们不必输入这个字符,编译器会自动添加的) char a_string[20] = "This is a string"; printf("%s\n", a_string); // %s 可以对字符串进行格式化 - /* 也许你会注意到 a_string 实际上只有16个字节长. 第17个字节是一个空字符(NUL) -而第18, 19 和 20 个字符的值是不确定的。 +而第18, 19 和 20 个字符的值是未定义。 */ printf("%d\n", a_string[16]); // => 0 +// byte #17值为0(18,19,20同样为0) + +// 单引号间的字符是字符字面量 +// 它的类型是`int`,而 *不是* `char` +// (由于历史原因) +int cha = 'a'; // 合法 +char chb = 'a'; // 同样合法 (隐式类型转换 + +// 多维数组 +int multi_array[2][5] = { + {1, 2, 3, 4, 5}, + {6, 7, 8, 9, 0} + } +// 获取元素 +int array_int = multi_array[0][2]; // => 3 /////////////////////////////////////// // 操作符 /////////////////////////////////////// -int i1 = 1, i2 = 2; // 多个变量声明的简写 +// 多个变量声明的简写 +int i1 = 1, i2 = 2; float f1 = 1.0, f2 = 2.0; -// 算数运算 +int a, b, c; +a = b = c = 0; + +// 算数运算直截了当 i1 + i2; // => 3 i2 - i1; // => 1 i2 * i1; // => 2 -i1 / i2; // => 0 (0.5 会被化整为 0) +i1 / i2; // => 0 (0.5,但会被化整为 0) f1 / f2; // => 0.5, 也许会有很小的误差 +// 浮点数和浮点数运算都是近似值 // 取余运算 11 % 3; // => 2 -// 比较操作符我们也很熟悉, 但是有一点,C中没有布尔类型 +// 你多半会觉得比较操作符很熟悉, 不过C中没有布尔类型 // 而是用整形替代 -// 0 就是 false, 其他的就是 true. (比较操作符的返回值则仅有0和1) +// (C99中有_Bool或bool。) +// 0为假, 其他均为真. (比较操作符的返回值总是返回0或1) 3 == 2; // => 0 (false) 3 != 2; // => 1 (true) 3 > 2; // => 1 @@ -138,7 +199,14 @@ f1 / f2; // => 0.5, 也许会有很小的误差 2 <= 2; // => 1 2 >= 2; // => 1 -// 逻辑运算符需要作用于整数 +// C不是Python —— 连续比较不合法 +int a = 1; +// 错误 +int between_0_and_2 = 0 < a < 2; +// 正确 +int between_0_and_2 = 0 < a && a < 2; + +// 逻辑运算符适用于整数 !3; // => 0 (非) !0; // => 1 1 && 1; // => 1 (且) @@ -146,6 +214,20 @@ f1 / f2; // => 0.5, 也许会有很小的误差 0 || 1; // => 1 (或) 0 || 0; // => 0 +// 条件表达式 ( ? : ) +int a = 5; +int b = 10; +int z; +z = (a > b) ? a : b; // 10 “若a > b返回a,否则返回b。” + +// 增、减 +char *s = "iLoveC" +int j = 0; +s[j++]; // "i" 返回s的第j项,然后增加j的值。 +j = 0; +s[++j]; // => "L" 增加j的值,然后返回s的第j项。 +// j-- 和 --j 同理 + // 位运算 ~0x0F; // => 0xF0 (取反) 0x0F & 0xF0; // => 0x00 (和) @@ -154,6 +236,13 @@ f1 / f2; // => 0.5, 也许会有很小的误差 0x01 << 1; // => 0x02 (左移1位) 0x02 >> 1; // => 0x01 (右移1位) +// 对有符号整数进行移位操作要小心 —— 以下未定义: +// 有符号整数位移至符号位 int a = 1 << 32 +// 左移位一个负数 int a = -1 << 2 +// 移位超过或等于该类型数值的长度 +// int a = 1 << 32; // 假定int32位 + + /////////////////////////////////////// // 控制结构 /////////////////////////////////////// @@ -168,17 +257,17 @@ if (0) { // While循环 int ii = 0; -while (ii < 10) { +while (ii < 10) { // 任何非0的值均为真 printf("%d, ", ii++); // ii++ 在取值过后自增 -} // => 输出 "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " +} // => 打印 "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); int kk = 0; do { printf("%d, ", kk); -} while (++kk < 10); // ++kk 先自增,在被取值 -// => 输出 "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " +} while (++kk < 10); // ++kk 先自增,再被取值 +// => 打印 "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); @@ -186,29 +275,55 @@ printf("\n"); int jj; for (jj=0; jj < 10; jj++) { printf("%d, ", jj); -} // => 输出 "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " +} // => 打印 "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); +// *****注意*****: +// 循环和函数必须有主体部分,如果不需要主体部分: +int i; + for (i = 0; i <= 5; i++) { + ; // 使用分号表达主体(null语句) +} + +// 多重分支:switch() +switch (some_integral_expression) { +case 0: // 标签必须是整数常量表达式 + do_stuff(); + break; // 如果不使用break,控制结构会继续执行下面的标签 +case 1: + do_something_else(); + break; +default: + // 假设 `some_integral_expression` 不匹配任何标签 + fputs("error!\n", stderr); + exit(-1); + break; + } + /////////////////////////////////////// // 类型转换 /////////////////////////////////////// // 在C中每个变量都有类型,你可以将变量的类型进行转换 +// (有一定限制) -int x_hex = 0x01; // 可以用16进制赋值 +int x_hex = 0x01; // 可以用16进制字面量赋值 // 在类型转换时,数字本身的值会被保留下来 -printf("%d\n", x_hex); // => 输出 1 -printf("%d\n", (short) x_hex); // => 输出 1 -printf("%d\n", (char) x_hex); // => 输出 1 +printf("%d\n", x_hex); // => 打印 1 +printf("%d\n", (short) x_hex); // => 打印 1 +printf("%d\n", (char) x_hex); // => 打印 1 // 类型转换时可能会造成溢出,而且不会抛出警告 -printf("%d\n", (char) 257); // => 1 (char的最大值为255) +printf("%d\n", (char) 257); // => 1 (char的最大值为255,假定char为8位长) + +// 使用提供的CHAR_MAX、SCHAR_MAX和UCHAR_MAX宏可以确定`char`、`signed_char`和`unisigned char`的最大值。 + // 整数型和浮点型可以互相转换 -printf("%f\n", (float)100); // %f 表示单精度浮点 -printf("%lf\n", (double)100); // %lf 表示双精度浮点 +printf("%f\n", (float)100); // %f 格式化单精度浮点 +printf("%lf\n", (double)100); // %lf 格式化双精度浮点 printf("%d\n", (char)100.0); /////////////////////////////////////// @@ -216,67 +331,89 @@ printf("%d\n", (char)100.0); /////////////////////////////////////// // 指针变量是用来储存内存地址的变量 -// 指针变量的定义也会告诉你指向的地址的变量的类型 -// 你也可以得到某个变量的地址,并对它们进行操作 +// 指针变量的声明也会告诉它所指向的数据的类型 +// 你可以得到你的变量的地址,并对它们搞乱。 int x = 0; printf("%p\n", &x); // 用 & 来获取变量的地址 -// (%p 表示一个指针) -// => 输出某个内存地址 +// (%p 格式化一个类型为 void *的指针) +// => 打印某个内存地址 -// 指针类型在定义是需要以*结束 -int* px; // px是一个指向int型的指针 +// 指针类型在声明中以*开头 +int* px, not_a_pointer; // px是一个指向int型的指针 px = &x; // 把x的地址保存到px中 -printf("%p\n", px); // => 输出内存中的某个地址 +printf("%p\n", (void *)px); // => 输出内存中的某个地址 +printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); +// => 在64位系统上打印“8, 4”。 -// 要得到某个指针指向的内容的值,可以在指针前加一个*来取得(去引用) +// 要得到某个指针指向的内容的值,可以在指针前加一个*来取得(取消引用) +// 注意: 是的,这可能让人困惑,'*'在用来声明一个指针的同时取消引用它。 printf("%d\n", *px); // => 输出 0, 即x的值 // 你也可以改变指针所指向的值 -// 此时你需要在*运算符后添加一个括号,因为++比*的优先级更高 -(*px)++; // 把px所指向的值增加2 +// 此时你需要取消引用上添加括号,因为++比*的优先级更高 +(*px)++; // 把px所指向的值增加1 printf("%d\n", *px); // => 输出 1 printf("%d\n", x); // => 输出 1 -int x_array[20]; // 数组是分配一系列连续空间的常用方式 +// 数组是分配一系列连续空间的常用方式 +int x_array[20]; int xx; for (xx=0; xx<20; xx++) { x_array[xx] = 20 - xx; } // 初始化 x_array 为 20, 19, 18,... 2, 1 -// 生命一个变量为指向整型的指针类型,并初始化为指向x_array +// 声明一个整型的指针,并初始化为指向x_array int* x_ptr = x_array; // x_ptr现在指向了数组的第一个元素(即整数20). - -// 事实上数组本身就是指向它的第一个元素的指针 -printf("%d\n", *(x_ptr)); // => 输出 20 -printf("%d\n", x_array[0]); // => 输出 20 +// 这是因为数组通常衰减为指向它们的第一个元素的指针。 +// 例如,当一个数组被传递给一个函数或者绑定到一个指针时, +//它衰减为(隐式转化为)一个指针。 +// 例外: 当数组是`&`操作符的参数: +int arr[10]; +int (*ptr_to_arr)[10] = &arr; // &arr的类型不是`int *`! + // 它的类型是指向数组的指针(数组由10个int组成) +// 或者当数组是字符串字面量(初始化字符数组) +char arr[] = "foobarbazquirk"; +// 或者当它是`sizeof`或`alignof`操作符的参数时: +int arr[10]; +int *ptr = arr; // 等价于 int *ptr = &arr[0]; +printf("%zu, %zu\n", sizeof arr, sizeof ptr); // 应该会输出"40, 4"或"40, 8" // 指针的增减多少是依据它本身的类型而定的 -printf("%d\n", *(x_ptr + 1)); // => 输出 19 -printf("%d\n", x_array[1]); // => 输出 19 +// (这被称为指针算术) +printf("%d\n", *(x_ptr + 1)); // => 打印 19 +printf("%d\n", x_array[1]); // => 打印 19 // 你也可以通过标准库函数malloc来实现动态分配 -// 这个函数接受一个代表容量的参数 -// 系统会从堆区分配指定容量字节大小的空间 -int* my_ptr = (int*) malloc(sizeof(int) * 20); +// 这个函数接受一个代表容量的参数,参数类型为`size_t` +// 系统一般会从堆区分配指定容量字节大小的空间 +// (在一些系统,例如嵌入式系统中这点不一定成立 +// C标准对此未置一词。) +int *my_ptr = malloc(sizeof(*my_ptr) * 20); for (xx=0; xx<20; xx++) { - *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx 也可以 -} // 初始化内存为 20, 19, 18, 17... 2, 1 (as ints) + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx +} // 初始化内存为 20, 19, 18, 17... 2, 1 (类型为int) -// 如果对一些未分配的内存取值则会得到未知的结果 +// 对未分配的内存进行取消引用会产生未定义的结果 printf("%d\n", *(my_ptr + 21)); // => 谁知道会输出什么 -// 当你通过malloc得到一块区域后,你需要释放它 +// malloc分配的区域需要手动释放 // 否则没人能够再次使用这块内存,直到程序结束为止 free(my_ptr); // 字符串通常是字符数组,但是经常用字符指针表示 -// 指针: -char* my_str = "This is my very own string"; - +// (它是指向数组的第一个元素的指针) +// 一个优良的实践是使用`const char *`来引用一个字符串字面量, +// 因为字符串字面量不应当被修改(即"foo"[0] = 'a'犯了大忌) +const char* my_str = "This is my very own string"; printf("%c\n", *my_str); // => 'T' +// 如果字符串是数组,(多半是用字符串字面量初始化的) +// 情况就不一样了,字符串位于可写的内存中 +char foo[] = "foo"; +foo[0] = 'a'; // 这是合法的,foo现在包含"aoo" + function_1(); } // main函数结束 @@ -292,16 +429,21 @@ int add_two_ints(int x1, int x2){ } /* -函数是按值传递的, 但是你可以通过传递参数来传递引用,这样函数就可以更改值 +函数是按值传递的。当调用一个函数的时候,传递给函数的参数 +是原有值的拷贝(数组除外)。你在函数内对参数所进行的操作 +不会改变该参数原有的值。 + +但是你可以通过指针来传递引用,这样函数就可以更改值 例子:字符串本身翻转 */ // 类型为void的函数没有返回值 -void str_reverse(char* str_in){ +void str_reverse(char *str_in){ char tmp; - int ii=0, len = strlen(str_in); // Strlen 是C标准库函数 - for(ii=0; ii ".tset a si sihT" */ +// 如果引用函数之外的变量,必须使用extern关键字 +int i = 0; +void testFunc() { + extern int i; // 使用外部变量 i +} + +// 使用static确保external变量为源文件私有 +static int i = 0; // 其他使用 testFunc()的文件无法访问变量i +void testFunc() { + extern int i; +} +//**你同样可以声明函数为static** + + /////////////////////////////////////// // 用户自定义类型和结构 /////////////////////////////////////// @@ -322,12 +478,16 @@ printf("%s\n", c); // => ".tset a si sihT" typedef int my_type; my_type my_type_var = 0; -// 结构是一系列数据的集合 +// struct是数据的集合,成员依序分配,按照 +// 编写的顺序 struct rectangle { int width; int height; }; +// 一般而言,以下断言不成立: +// sizeof(struct rectangle) == sizeof(int) + sizeof(int) +//这是因为structure成员之间可能存在潜在的间隙(为了对齐)[1] void function_1(){ @@ -338,12 +498,12 @@ void function_1(){ my_rec.height = 20; // 你也可以声明指向结构体的指针 - struct rectangle* my_rec_ptr = &my_rec; + struct rectangle *my_rec_ptr = &my_rec; - // 通过取值来改变结构体的成员... + // 通过取消引用来改变结构体的成员... (*my_rec_ptr).width = 30; - // ... 或者用 -> 操作符作为简写 + // ... 或者用 -> 操作符作为简写提高可读性 my_rec_ptr->height = 10; // Same as (*my_rec_ptr).height = 10; } @@ -354,18 +514,25 @@ int area(rect r){ return r.width * r.height; } +// 如果struct较大,你可以通过指针传递,避免 +// 复制整个struct。 +int area(const rect *r) +{ + return r->width * r->height; +} + /////////////////////////////////////// // 函数指针 /////////////////////////////////////// /* 在运行时,函数本身也被存放到某块内存区域当中 -函数指针就像其他指针一样, 但却可以被用来直接调用函数, -并且可以被四处传递(就像回调函数那样) -但是,定义的语法有可能在一开始会有些误解 +函数指针就像其他指针一样(不过是存储一个内存地址) 但却可以被用来直接调用函数, +并且可以四处传递回调函数 +但是,定义的语法初看令人有些迷惑 例子:通过指针调用str_reverse */ -void str_reverse_through_pointer(char * str_in) { +void str_reverse_through_pointer(char *str_in) { // 定义一个函数指针 f. void (*f)(char *); // 签名一定要与目标函数相同 f = &str_reverse; // 将函数的地址在运行时赋给指针 @@ -374,7 +541,7 @@ void str_reverse_through_pointer(char * str_in) { } /* -只要函数签名是正确的,任何时候都能将正确的函数赋给某个函数指针 +只要函数签名是正确的,任何时候都能将任何函数赋给某个函数指针 为了可读性和简洁性,函数指针经常和typedef搭配使用: */ @@ -384,12 +551,73 @@ typedef void (*my_fnp_type)(char *); // ... // my_fnp_type f; +// 特殊字符 +'\a' // bell +'\n' // 换行 +'\t' // tab +'\v' // vertical tab +'\f' // formfeed +'\r' // 回车 +'\b' // 退格 +'\0' // null,通常置于字符串的最后。 + // hello\n\0. 按照惯例,\0用于标记字符串的末尾。 +'\\' // 反斜杠 +'\?' // 问号 +'\'' // 单引号 +'\"' // 双引号 +'\xhh' // 十六进制数字. 例子: '\xb' = vertical tab +'\ooo' // 十进制数字. 例子: '\013' = vertical tab + +// 打印格式: +"%d" // 整数 +"%3d" // 3位以上整数 (右对齐文本) +"%s" // 字符串 +"%f" // float +"%ld" // long +"%3.2f" // 左3位以上、右2位以上十进制浮 +"%7.4s" // (字符串同样适用) +"%c" // 字母 +"%p" // 指针 +"%x" // 十六进制 +"%o" // 十进制 +"%%" // 打印 % + +/////////////////////////////////////// +// 演算优先级 +/////////////////////////////////////// +//---------------------------------------------------// +// 操作符 | 组合 // +//---------------------------------------------------// +// () [] -> . | 从左到右 // +// ! ~ ++ -- + = *(type)sizeof | 从右到左 // +// * / % | 从左到右 // +// + - | 从左到右 // +// << >> | 从左到右 // +// < <= > >= | 从左到右 // +// == != | 从左到右 // +// & | 从左到右 // +// ^ | 从左到右 // +// | | 从左到右 // +// && | 从左到右 // +// || | 从左到右 // +// ?: | 从右到左 // +// = += -= *= /= %= &= ^= |= <<= >>= | 从右到左 // +// , | 从左到右 // +//---------------------------------------------------// + ``` ## 更多阅读 -最好找一本 [K&R, aka "The C Programming Language", “C程序设计语言”](https://en.wikipedia.org/wiki/The_C_Programming_Language) +最好找一本 [K&R, aka "The C Programming Language", “C程序设计语言”](https://en.wikipedia.org/wiki/The_C_Programming_Language)。它是关于C最重要的一本书,由C的创作者撰写。不过需要留意的是它比较古老了,因此有些不准确的地方。 + -其他一些比较好的资源 [Learn C the hard way](http://c.learncodethehardway.org/book/) +另一个比较好的资源是 [Learn C the hard way](http://c.learncodethehardway.org/book/) +如果你有问题,请阅读[compl.lang.c Frequently Asked Questions](http://c-faq.com/)。 + +使用合适的空格、缩进,保持一致的代码风格非常重要。可读性强的代码比聪明的代码、高速的代码更重要。可以参考下[Linux内核编码风格](https://www.kernel.org/doc/Documentation/CodingStyle) +。 除了这些,多多Google吧 + +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member -- cgit v1.2.3 From 4b8b6240154e1bcb87edfd95d3a1eaf22341f450 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Sat, 15 Feb 2014 21:37:58 +0800 Subject: c-cn: typo --- 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 ecd2558e..223f6e35 100644 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -331,8 +331,8 @@ printf("%d\n", (char)100.0); /////////////////////////////////////// // 指针变量是用来储存内存地址的变量 -// 指针变量的声明也会告诉它所指向的数据的类型 -// 你可以得到你的变量的地址,并对它们搞乱。 +// 指针变量的声明也会告诉它所指向的数据的类型 +// 你可以使用得到你的变量的地址,并把它们搞乱,;-) int x = 0; printf("%p\n", &x); // 用 & 来获取变量的地址 -- cgit v1.2.3 From 1c1dda235b6808f50eb0f8685477299fba785625 Mon Sep 17 00:00:00 2001 From: ryzed Date: Sat, 15 Feb 2014 23:10:35 +0300 Subject: Update haxe.html.markdown fixed typo --- haxe.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index eb39834e..6a868f09 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -231,7 +231,7 @@ class LearnHaxe3{ trace((4 + 3) + " is the value for (4 + 3)"); trace((5 - 1) + " is the value for (5 - 1)"); trace((2 * 4) + " is the value for (2 * 4)"); - trace((8 / 4) + " is the value for (8 / 3) (division always produces Floats)"); + trace((8 / 3) + " is the value for (8 / 3) (division always produces Floats)"); trace((12 % 4) + " is the value for (12 % 4)"); -- cgit v1.2.3 From 00338a1a61040b70ec3e068f69ccfad31aa1934d Mon Sep 17 00:00:00 2001 From: olwaro Date: Sun, 16 Feb 2014 14:24:33 +0100 Subject: Fix some misleading comments --- csharp.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index dad0c26b..3a870b7a 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -105,7 +105,7 @@ namespace Learning Console.WriteLine(fooString); // You can access each character of the string with an indexer: - char charFromString = fooString[1]; // 'y' + char charFromString = fooString[1]; // => 'e' // Strings are immutable: you can't do fooString[1] = 'X'; // Compare strings with current culture, ignoring case @@ -173,7 +173,7 @@ on a new line! ""Wow!"", the masses cried"; int i1 = 1, i2 = 2; // Shorthand for multiple declarations // Arithmetic is straightforward - Console.WriteLine(i1 + i2 - i1 * 3 / 7); // + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 // Modulo Console.WriteLine("11%3 = " + (11 % 3)); // => 2 @@ -241,7 +241,7 @@ on a new line! ""Wow!"", the masses cried"; int fooDoWhile = 0; do { - //Iterated 99 times, fooDoWhile 0->99 + //Iterated 100 times, fooDoWhile 0->99 fooDoWhile++; } while (fooDoWhile < 100); @@ -576,7 +576,7 @@ on a new line! ""Wow!"", the masses cried"; AIST, BMC, Electra = 42, //you can explicitly set a value to a name - Gitane + Gitane // 43 } // 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 -- cgit v1.2.3 From 550b9c9f2ebf8ead67eb723d3b4256064e284b82 Mon Sep 17 00:00:00 2001 From: charalambosp Date: Sun, 16 Feb 2014 18:36:09 +0000 Subject: generators & decorators --- python.html.markdown | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 941ba9f4..fe0ddc8c 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -473,6 +473,54 @@ import math dir(math) +#################################################### +## 6. Advanced +#################################################### + +# Generators help you make lazy code +def double_numbers(iterable): + for i in iterable: + yield i + i + +# generator creates the value 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 +_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(_say): + @wraps(_say) + def wrapper(*args, **kwargs): + msg, say_please = _say(*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? -- cgit v1.2.3 From 3233394cd5079893acb725027f8d0a82e28c16cc Mon Sep 17 00:00:00 2001 From: charalambosp Date: Sun, 16 Feb 2014 18:37:02 +0000 Subject: fix section number --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index fe0ddc8c..15f27d37 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -474,7 +474,7 @@ dir(math) #################################################### -## 6. Advanced +## 7. Advanced #################################################### # Generators help you make lazy code -- cgit v1.2.3 From 8b62c313b1e95428adb363425d35456e726e2d7f Mon Sep 17 00:00:00 2001 From: olwaro Date: Sun, 16 Feb 2014 22:00:33 +0100 Subject: Adds an example of 'using' statement --- csharp.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index dad0c26b..e240bf86 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -30,6 +30,7 @@ using System.Linq; using System.Linq.Expressions; using System.Net; using System.Threading.Tasks; +using System.IO; // defines scope to organize code into "packages" namespace Learning @@ -434,6 +435,17 @@ on a new line! ""Wow!"", the masses cried"; Func square = (x) => x * x; // Last T item is the return value Console.WriteLine(square(3)); // 9 + // DISPOSABLE RESSOURCES MANAGEMENT - let you handle unmanaged resources easily + // Most of objects that access unmanaged resources (file handle, device contexts, etc.) + // implement the IDisposable interface. The using statement takes care of + // cleaning those IDisposable objects for you. + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Nothing suspicious here"); + // At the end of scope, ressources will be released. + // Even if an exception is thrown. + } + // PARALLEL FRAMEWORK // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx var websites = new string[] { -- cgit v1.2.3 From f6032ba1906f51a59ecc17d24864a6f56d100c14 Mon Sep 17 00:00:00 2001 From: olwaro Date: Mon, 17 Feb 2014 10:43:18 +0100 Subject: Fixes typos --- csharp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index e240bf86..12bdf168 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -435,14 +435,14 @@ on a new line! ""Wow!"", the masses cried"; Func square = (x) => x * x; // Last T item is the return value Console.WriteLine(square(3)); // 9 - // DISPOSABLE RESSOURCES MANAGEMENT - let you handle unmanaged resources easily + // DISPOSABLE RESSOURCES MANAGEMENT - let you handle unmanaged resources easily. // Most of objects that access unmanaged resources (file handle, device contexts, etc.) // implement the IDisposable interface. The using statement takes care of // cleaning those IDisposable objects for you. using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("Nothing suspicious here"); - // At the end of scope, ressources will be released. + // At the end of scope, resources will be released. // Even if an exception is thrown. } -- cgit v1.2.3 From da3b7c3520b18bf5b94d99bcf8170d679051810a Mon Sep 17 00:00:00 2001 From: Mark Whiting Date: Mon, 17 Feb 2014 21:07:29 -0500 Subject: Better explanation of list slices Step size and list slice syntax was not quite clear. Upon seeing li[::-1] as it was previously, I was not sure what this really meant so I looked it up and found that this section of the guide may benefit from more explanation. --- python.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 15f27d37..908a0638 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -160,8 +160,12 @@ li[1:3] #=> [2, 4] 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] -- cgit v1.2.3 From c3b6e57e99bfff589399d3c33350ed00ca48c41d Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Thu, 20 Feb 2014 18:12:26 +0800 Subject: clojure-cn: contributor and translator information The translator add his/her name to contributor instead of translator. --- zh-cn/clojure-cn.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zh-cn/clojure-cn.html.markdown b/zh-cn/clojure-cn.html.markdown index d5d8232b..fa241384 100644 --- a/zh-cn/clojure-cn.html.markdown +++ b/zh-cn/clojure-cn.html.markdown @@ -2,6 +2,8 @@ language: clojure filename: learnclojure-cn.clj contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: - ["Bill Zhang", "http://jingege.github.io/"] lang: zh-cn --- -- cgit v1.2.3 From 03e6892a5f84f063b723d433947929750349d625 Mon Sep 17 00:00:00 2001 From: Brian Stearns Date: Thu, 20 Feb 2014 17:12:12 -0500 Subject: Fixed random spelling error. --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index e2c5bbaf..70a3b52a 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -50,7 +50,7 @@ echo ${VARIABLE/Some/A} echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} # This works for null (FOO=), empty string (FOO=""), zero (FOO=0) returns 0 -# Bultin variables: +# Builtin variables: # There are some useful builtin variables, like echo "Last program return value: $?" echo "Script's PID: $$" -- cgit v1.2.3 From 4803b3aa262f2abf0ae69945135c0cefe2e7bc47 Mon Sep 17 00:00:00 2001 From: olwaro Date: Fri, 14 Feb 2014 15:06:56 +0100 Subject: First version of csharp french translation --- fr-fr/csharp-fr.html.markdown | 801 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 801 insertions(+) create mode 100644 fr-fr/csharp-fr.html.markdown diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown new file mode 100644 index 00000000..d85dcfc6 --- /dev/null +++ b/fr-fr/csharp-fr.html.markdown @@ -0,0 +1,801 @@ +--- +language: c# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] + - ["Max Yankov", "https://github.com/golergka"] + - ["Melvyn Laïly", "http://x2a.yt"] + - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] +translators: + - ["Olivier Hoarau", "https://github.com/Olwaro"] +filename: LearnCSharp.cs +lang: fr-fr +--- + +C# est un langage de programmation orienté objet à typage fort qui permet aux développeurs de créer une grande variété d'applications fiables et robustes s'appuyant sur le framework .NET. + +[Plus d'infos](http://msdn.microsoft.com/fr-fr/library/67ef8sbd.aspx) + +```c# +// Les commentaires sur une seule ligne commencent par // +/* +Les +commentaires +multi-lignes +ressemblent +à +ceci +*/ +/// +/// Ceci est un commentaire de documentation XML +/// + +// Utilisez des namespaces avec l'instruction 'using' +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +using System.Net; +using System.Threading.Tasks; + +// Définit la portée du code pour une meilleure organisation +namespace Learning +{ + // Chaque fichier .cs devrait au moins contenir une classe avec le même nom + // que celui du fichier. Ce n'est pas une obligation mais c'est mieux ! + public class LearnCSharp + { + // LES BASES - si vous avez déjà une expérience en Java ou C++ + // passez directement à la partie FONCTIONNALITÉS INTERESSANTES + public static void Syntax() + { + // Utilisez Console.WriteLine pour écrire sur la sortie + Console.WriteLine("Hello World"); + Console.WriteLine( + "Entier: " + 10 + + " Double: " + 3.14 + + " Booleen: " + true); + + // Pour omettre le retour à la ligne : Console.Write + Console.Write("Hello "); + Console.Write("World"); + + /////////////////////////////////////////////////// + // Types et Variables + // Déclarez une variable avec la syntaxe + /////////////////////////////////////////////////// + + // Sbyte - Entier signé sur 8 bits + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Entier non-signé sur 8 bits + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - Entier sur 16 bits + // Signé - (-32,768 <= short <= 32,767) + // Non-signé - (0 <= ushort <= 65,535) + short fooShort = 10000; + ushort fooUshort = 10000; + + // Int - Entier sur 32 bits + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) + + // Long - Entier sur 64 bits + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // Par défaut le type d'un littéral entier est int ou uint + // on ajoute 'L' pour spécifier la création d'un long + + // Double - Réel sur 64 bits en virgule flottante (norme IEEE 754) + double fooDouble = 123.4; // Precision: 15-16 chiffres + + // Float - Réel sur 32 bits en virgule flottante (norme IEEE 754) + float fooFloat = 234.5f; // Precision: 7 chiffres + // Par défaut le type d'un littéral réel est double + // on ajoute 'f' pour spécifier la création d'un float + + // Decimal - Type de donnée numérique sur 128 bits, fournit une plus + // grande précision et une plage de valeurs réduite + // approprié aux calculs financiers et monétaires + decimal fooDecimal = 150.3m; + + // Booléen - vrai / faux + bool fooBoolean = true; // ou false + + // Char - Un unique caractère Unicode sur 16 bits + char fooChar = 'A'; + + // String -- contrairement au types précédents qui sont des types valeurs, + // string est un type référence. Il peut donc avoir la valeur null + string fooString = "\"échappement\" de guillemets et ajout de \n (nouvelle ligne) et de \t (tabulation)"; + Console.WriteLine(fooString); + + // Il est possible d'accéder à chaque caractère d'une string via un indexeur + char charFromString = fooString[1]; // 'é' + // Une string est immuable: impossible de faire fooString[1] = 'X'; + + // Comparaison de strings avec la culture courrante en ignorant la casse + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // Formatage + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + + // Dates et formatage + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // Il est possible d'étaler une string sur plusieurs lignes avec le symbole @. + // Pour échapper " utilisez "" + string bazString = @"Voici quelques trucs +sur une nouvelle ligne! ""Wow!"", quel style"; + + // Utilisez const ou read-only pour rendre une variable immuable + // les valeurs constantes sont calculées au moment de la compilation + const int HEURES_PAR_SEMAINE = 9001; + + /////////////////////////////////////////////////// + // Structures de données + /////////////////////////////////////////////////// + + // Tableaux - indexé à partir de zéro + // La taille d'un tableau doit être décidée à la déclaration + // La syntaxe pour déclarer un tableau est la suivante : + // [] = new [] + int[] intArray = new int[10]; + + // Une autre méthode de déclaration et d'initialisation + int[] y = { 9000, 1000, 1337 }; + + // Indexer un tableau - Accéder à un élément + Console.WriteLine("intArray à 0: " + intArray[0]); + // Les tableaux sont muable. + intArray[1] = 1; + + // Listes + // Elles sont plus souvent utilisées que les tableaux car plus souples + // La syntaxe pour déclarer une liste est la suivante : + // List = new List(); + List intList = new List(); + List stringList = new List(); + List z = new List { 9000, 1000, 1337 }; // intialisation + // Les <> indiquent un type générique + // Pus d'info dans la partie FONCTIONNALITÉS INTERESSANTES + + // Les éléments d'une liste ne sont pas null par défaut + // Il faut ajouter une valeur avant d'y accéder par index + intList.Add(1); + Console.WriteLine("intList à 0: " + intList[0]); + + // Autres structures de données à étudier: + // Stack/Queue (Pile/File) + // Dictionary (une implémentation de hash map) + // HashSet (représente un ensemble) + // Collections en lecture seule + // Tuple (.Net 4+) + + /////////////////////////////////////// + // Opérateurs + /////////////////////////////////////// + Console.WriteLine("\n->Opérateurs"); + + int i1 = 1, i2 = 2; // Raccourci pour des déclarations multiples + + // Arithmétique classique + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Opérateurs de comparaison + Console.WriteLine("3 == 2? " + (3 == 2)); // => False + Console.WriteLine("3 != 2? " + (3 != 2)); // => True + Console.WriteLine("3 > 2? " + (3 > 2)); // => True + Console.WriteLine("3 < 2? " + (3 < 2)); // => False + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => True + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => True + + // Opérateurs bit à bit ! + /* + ~ Compément unaire + << Décalage à gauche + >> Décalage à droite + & ET logique + ^ OU exclusif + | OU inclusif + */ + + // Incrémentations + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrémentation + Console.WriteLine(++i); //i = 2. Pre-Incrémentation + Console.WriteLine(i--); //i = 1. Post-Decrémentation + Console.WriteLine(--i); //i = 0. Pre-Decrémentation + + /////////////////////////////////////// + // Structure de contrôle + /////////////////////////////////////// + Console.WriteLine("\n->Structure de contrôle"); + + // Clause 'if' à la C + int j = 10; + if (j == 10) + { + Console.WriteLine("Je serais affiché"); + } + else if (j > 10) + { + Console.WriteLine("Pas moi"); + } + else + { + Console.WriteLine("Moi non plus"); + } + + // Opérateur ternaire + // Un simple if/else peut s'écrire : + // ? : + string isTrue = (true) ? "True" : "False"; + + // Boucle while + int fooWhile = 0; + while (fooWhile < 100) + { + // 100 passages, de 0 à 99 + fooWhile++; + } + + // Boucle Do While + int fooDoWhile = 0; + do + { + // 100 passages, de 0 à 99 + fooDoWhile++; + } while (fooDoWhile < 100); + + // Boucle for + // Structure : for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + // 10 passages, de 0 à 9 + } + + // La boucle foreach + // Structure : foreach( in ) + // Cette boucle est utilisable sur des objets implémentant IEnumerable ou IEnumerable + // Toutes les collections du framework .NET (Tableaux, Listes, ...) implémentent ces interfaces. + // (Notez que dans l'exemple suivant .ToCharArray() peut être omit car + // string implémente IEnumerable) + foreach (char character in "Hello World".ToCharArray()) + { + //Itération sur chaque caractère + } + + // La structure Switch Case + // Un switch fonctionne avec les types : byte, short, char, et int. + // Les enums sont aussi supportés ainsi que les strings et quelques + // classes spéciales basées sur les types primitifs : Character, Byte, Short, et Integer. + int mois = 3; + string moisString; + switch (mois) + { + case 1: + moisString = "Janvier"; + break; + case 2: + moisString = "Février"; + break; + case 3: + moisString = "Mars"; + break; + + // Vous pouvez assigné plus d'un 'case' à une action + // Mais vous ne pouvez pas ajouter une action sans 'break' avant un 'case' + // (pour ce faire, il faudrait ajouter explicitement un 'goto case x') + case 6: + case 7: + case 8: + moisString = "C'est l'été!"; + break; + default: + moisString = "Un autre mois oO"; + break; + } + + /////////////////////////////////////// + // Convertion de type de donnée et transtypage + /////////////////////////////////////// + + // Convertion de string vers int + // lève une exception en cas d'erreur + int.Parse("123"); //retourne la valeur entière de "123" + + // TryParse affecte la valeur par défaut du type en cas d'erreur + // dans ce cas : 0 + int tryInt; + if (int.TryParse("123", out tryInt)) // La fonction retourne un booléen + Console.WriteLine(tryInt); // => 123 + + // Convertion d'un entier vers une string + // La classe Convert possède plusieur méthodes pour faciliter la convertion + Convert.ToString(123); + // ou + tryInt.ToString(); + } + + /////////////////////////////////////// + // CLASSES - voir les définitions à la fin du fichier + /////////////////////////////////////// + + public static void Classes() + { + // voir les déclarations à la fin du fichier + + // Utilisez 'new' pour instancier une classe + Bicycle trek = new Bicycle(); + + // Appel des méthodes de l'objet + trek.SpeedUp(3); // Il est toujours bon d'utiliser des accesseurs + trek.Cadence = 100; + + // Affichage de la valeur de retour d'une méthode. + Console.WriteLine("trek info: " + trek.Info()); + + // Instanciation d'un nouveau PennyFarthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.Info()); + + Console.Read(); + } + + // POINT D'ENTREE Une application console doit avoir une méthode main comme point d'entrée + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // FONCTIONNALITÉS INTERESSANTES + // + + // SIGNATURE DE METHODE + public // Visibilité + static // Permet un appel direct par la classe (sans instanciation) + int // Type de retour, + MethodSignatures( + int maxCount, // Premier paramètre, de type int + int count = 0, // Valeur par défaut si aucun argument n'est passé + int another = 3, + params string[] otherParams // Capture tous les arguments passés à la méthode + ) + { + return -1; + } + + // Des méthodes peuvent avoir le même nom tant que leur signature est unique + public static void MethodSignature(string maxCount) + { + } + + // TYPE GENERIQUE + + // Les types TKey et TValue sont spécifiés par l'utilisateur lors de l'appel de la fonction + // Cette méthode émule SetDefaut de Python + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // Vous pouvez limiter les types autorisés + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // Nous somme sûr de pouvoir itérer, car T implémente IEnumerable + foreach (var item in toPrint) + // Item sera de type int + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // PARAMÈTERES OPTIONNELS + MethodSignatures(3, 1, 3, "Des", "Paramètres", "En plus"); + MethodSignatures(3, another: 3); // affectation explicite, les autres + // paramètres ont la valeur par défaut + + // MÉTHODE D'EXTENSION + int i = 3; + i.Print(); // Défini plus bas + + // TYPES NULLABLE - idéal pour les interactions avec une base de données ou pour les valeurs de retour + // Tous les types valeurs peuvent être rendu nullable en les suffixant par '?' + // ? = + int? nullable = null; // raccourci pour Nullable + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // retourne vrai si la valeur n'est pas null + + // ?? est un sucre de syntaxe pour spécifier une valeur par défaut + // au cas ou une autre valleur serait nulle + int notNullable = nullable ?? 0; // 0 + + // VARIABLES IMPLICITEMENT TYPÉE - vous pouvez laisser le compilateur deviner le type d'une variable + var magic = "magic est de type string à la compilation, on a toujours un typage fort !"; + // magic = 9; // ne fonctionnera pas car magic est désormais une string + + // TYPES GÉNÉRIQUES + var agenda = new Dictionary() { + {"Sarah", "212 555 5555"} // Ajout d'une entrée à notre agenda + }; + + // Appel de la fonction SetDefault (défini plus haut) + Console.WriteLine(SetDefault(agenda, "Shaun", "Pas de numéro")); // => Pas de numéro + // Notez que vous n'avez pas à spécifier TKey et TValue car le compilateur saura les inférer. + Console.WriteLine(SetDefault(agenda, "Sarah", "No Phone")); // => 212 555 5555 + + // EXPRESSION LAMBDA - permet d'écrire une fonction en tant qu'expression + Func square = (x) => x * x; // Le dernier élément est la valeur de retour + Console.WriteLine(square(3)); // => 9 + + // BIBLIOTHÈQUE DE TÂCHES PARALLÈLE (TPL) + // http://msdn.microsoft.com/fr-fr/library/dd460717.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary(); + + // L'exemple suivant executera chaque requête dans un thread séparé, + // et attendera la fin de chacun d'entre eux avant de continuer + Parallel.ForEach(websites, + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // maximum de 3 threads + website => + { + // Faire quelque chose de long sur le fichier + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // Ceci ne s'exécutera pas tant que les threads n'auront pas fini leur travail + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // TYPE DYNAMIQUE - idéal pour travailler avec d'autres langages + dynamic student = new ExpandoObject(); + student.FirstName = "Mon prénom"; // Pas besoin de définir l'objet + + // Vous pouvez même ajouter des méthodes (dans ce cas: qui prend une string et retourne une string) + student.Introduce = new Func( + (introduceTo) => string.Format("Hey {0}, c'est {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE - quasiment toutes les collections implémentent cette interface + // ce qui permet d'utiliser des méthodes de style Filter / Map / Reduce + var bikes = new List(); + bikes.Sort(); // Trie le tableau sur place + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Trie en se basant sur la propriété Wheels + var result = bikes + .Where(b => b.Wheels > 3) // 'Filter' - enchaînable (retourne un IQueryable du type précédent) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // 'Map' - on retourne le .ToString() de chaque élément filtré, + // le résultat est un IQueryable + + var sum = bikes.Sum(b => b.Wheels); // 'Reduce' - fait la somme de tous les Wheels de la liste + + // Creation d'une liste d'objet anonymes basés sur des paramètres de la classe Bike + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Le compilateur peut inférer le type de ces objets annonymes, permettant à certain IDE d'effectuer + // des autos-complétion. + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + + // ASPARALLEL + // C'est ici que les choses se compliquent - un mélange de LINQ et de TPL + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // La ligne précédente s'exécute en parallèle ! Des threads seront gérés automatiquement + // et les données y seront réparties. Idéal sur de grosses données (et si votre + // machine dispose de plusieurs coeurs) + + + // LINQ - lie une source de donnée à des objets IQueryable + // ex: LindToSql => liaison avec une base de donnée, LinqToXml => liaison avec un document xml + var db = new BikeRespository(); + + // l'execution est décalée, ce qui est préférable quand on travail sur une base données + var fitler = db.Bikes.Where(b => b.HasTassles); // pas de requête exécutée + if (42 > 6) // Vous pouvez continuez à affiner la recherche + fitler = fitler.Where(b => b.IsBroken); // pas de requête exécutée + + var query = fitler + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // toujours pas de requête exécutée + + // Maintenant la requête est exécutée, mais retourne des données uniquement au fil de l'itération + foreach (string bike in query) + Console.WriteLine(result); + + } + + } // Fin de la classe LearnCSharp + + // Il est possible d'inclure plusieur classes dans un fichier .cs + + public static class Extensions + { + // EXTENSION DE FONCTIONS + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } + + // Syntaxe de déclaration de classe : + // class { + // // champs, constructeurs, fonctions + // // tout est déclaré et implémenté à l'intérieur + // } + + public class Bicycle + { + // Propriétés et variable de la classe + public int Cadence // Public: peut être accédé de partout + { + get // get - définit une méthode pour lire la propriété + { + return _cadence; + } + set // set - définit une méthode pour affecté une valeur à la propriété + { + _cadence = value; // 'value' est la valeur passée en argument au setteur + } + } + private int _cadence; + + protected virtual int Gear // Protected: accessible depuis la classe et ses classes filles + { + get; // crée une propriété automatique, pas besoin de créer une variable de stockage + set; + } + + internal int Wheels // Internal: accessible depuis l'assembly + { + get; + private set; // Il est possible de choisir la portée d'un accesseur + } + + int _speed; // Par défaut tout est privé au sein d'une classe : accessible uniquement depuis la classe + // on peut ajouter explicitement le mot clé 'private' + + public string Name { get; set; } + + + // Enum est un type valeur formé par un ensemble de constantes nommées + // C'est simplement une manière de mettre un nom sur une valeur (int par défaut). + // Les types compatibles pour un enum sont : byte, sbyte, short, ushort, int, uint, long, et ulong. + // Un enum ne peut pas contenir deux fois la même valeur + public enum BikeBrand + { + AIST, + BMC, + Electra = 42, // il est possible de donner explicitement une valeur + Gitane // 43 + } + // Nous avons défini cet enum à l'intérieur de la classe Bicycle, c'est donc un type imbriqué + // Pour le référencer à l'extérieur, il faudra utiliser Bicycle.BikeBrand + + public BikeBrand Brand; // Après avoir déclaré notre type enum, on peut créer un champ de ce type + + // Les membres statiques appartiennent à une classe plutôt qu'à une instance particulière + // Il est possible d'y accéder sans passer par un objet: + // ex: Console.WriteLine("Bicycles créés: " + Bicycle.bicyclesCreated); + static public int BicyclesCreated = 0; + + // Les valeurs en lecture seule sont affectées lors de l'exécution + // Elles ne peuvent être assignées que lors de leur déclaration ou dans un constructeur + readonly bool _hasCardsInSpokes = false; // variable en lecture et privée + + // Les contructeurs sont un moyen de créer des objets + // Voici un constructeur par défaut (pas d'arguments) + public Bicycle() + { + this.Gear = 1; // accès aux membres de la classe via le mot clé this + Cadence = 50; // qui est souvent implicite + _speed = 5; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; + } + + // Voici un constructeur spécifique (qui prends des arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // possibilité d'appeler le constructeur de la classe mère (ici Object) + { + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; + } + + // Les constructeur peuvent s'enchaîner + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) + { + } + + // Syntaxe de méthode: + // () + + // Les classes peuvent implémenter des accesseurs pour leur champs + // ou implémenter des propriétés (c'est la méthode dominante en C#) + + // Les paramètres de méthodes peuvent avoir des valeur par défaut + // Dans ce cas, la méthode peut être appelée sans arguments + public void SpeedUp(int increment = 1) + { + _speed += increment; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // Les propriétés se chargent de lire/modifier des valeurs + // elles peuvent être en lecture(get), en écriture(set) ou les deux + private bool _hasTassles; // variable privée + public bool HasTassles // propriété publique + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + // Il est possible de définir une propriété automatique sur une ligne + // cette syntaxe créera une variable de stockage automatiquement. + // Il est possible de modifier l'accèsibilité des getter/setter pour limiter leur utilisation + public bool IsBroken { get; private set; } + + // La même chose sur plusieurs lignes + public int FrameSize + { + get; + // Notez que seule la classe Bicycle peut changer la valeur de FrameSize + private set; + } + + // Méthode qui affiche les valeurs des champs de cet objet + public virtual string Info() + { + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + + // Les méthodes peuvent aussi être statiques. Utile pour les méthode d'aide. + public static bool DidWeCreateEnoughBycles() + { + // A l'intérieur d'une méthode statique on ne peut que référencer des membres statiques ! + return BicyclesCreated > 9000; + } // Si votre classe n'a que des membres statiques, marquez la comme statique + + } // fin de la classe Bicycle + + // PennyFarthing est une classe dérivée de Bicycle + class PennyFarthing : Bicycle + { + // Appel au constructeur de la classe mère + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) + { + } + + protected override int Gear + { + get + { + return 0; + } + set + { + // Lève une exception + throw new ArgumentException("Impossible de modifier Gear sur un PennyFarthing"); + } + } + + public override string Info() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Appel à la version de base de cette méthode + return result; + } + } + + // Les interfaces contiennent uniquement la signature de leurs membres, sans implémentation. + interface IJumpable + { + void Jump(int meters); // Tout les membres d'interface sont publique par défaut + } + + interface IBreakable + { + bool Broken { get; } // Les interfaces peuvent contenir des propriétés, + // des méthodes et des évènements + } + + // Une classe ne peut hériter que d'une seule autre classe, mais peut implémenter plusieur interfaces + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public bool Broken + { + get + { + return damage > 100; + } + } + } + + /// + /// Utilisé pour illustrer la connexion à une base donnée dans l'exemple LinqToSql + /// L'approche code first d'EntityFramework est très pratique (un peu comme ActiveRecord de Ruby) + /// http://msdn.microsoft.com/fr-fr/data/jj193542.aspx + /// + public class BikeRespository : DbSet + { + public BikeRespository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // Fin du namespace +``` + +## Sujets non-abordés + + * Flags + * Attribus + * Propriétés statiques + * Exceptions, Abstraction + * ASP.NET (Web Forms/MVC/WebMatrix) + * Winforms + * Windows Presentation Foundation (WPF) + +## Lectures Complémentaires + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + +[Convention de codage C#](http://msdn.microsoft.com/library/vstudio/ff926074) -- cgit v1.2.3 From 5c19094fb080653f0bf733997ad5241ee9f69d84 Mon Sep 17 00:00:00 2001 From: olwaro Date: Fri, 14 Feb 2014 21:33:43 +0100 Subject: A bunch of typo fix --- fr-fr/csharp-fr.html.markdown | 62 +++++++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown index d85dcfc6..032d94a6 100644 --- a/fr-fr/csharp-fr.html.markdown +++ b/fr-fr/csharp-fr.html.markdown @@ -109,7 +109,7 @@ namespace Learning // Char - Un unique caractère Unicode sur 16 bits char fooChar = 'A'; - // String -- contrairement au types précédents qui sont des types valeurs, + // String -- contrairement aux types précédents qui sont des types valeurs, // string est un type référence. Il peut donc avoir la valeur null string fooString = "\"échappement\" de guillemets et ajout de \n (nouvelle ligne) et de \t (tabulation)"; Console.WriteLine(fooString); @@ -152,7 +152,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Indexer un tableau - Accéder à un élément Console.WriteLine("intArray à 0: " + intArray[0]); - // Les tableaux sont muable. + // Les tableaux sont muables. intArray[1] = 1; // Listes @@ -268,7 +268,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Structure : foreach( in ) // Cette boucle est utilisable sur des objets implémentant IEnumerable ou IEnumerable // Toutes les collections du framework .NET (Tableaux, Listes, ...) implémentent ces interfaces. - // (Notez que dans l'exemple suivant .ToCharArray() peut être omit car + // (Notez que dans l'exemple suivant .ToCharArray() peut être omit car, // string implémente IEnumerable) foreach (char character in "Hello World".ToCharArray()) { @@ -276,9 +276,9 @@ sur une nouvelle ligne! ""Wow!"", quel style"; } // La structure Switch Case - // Un switch fonctionne avec les types : byte, short, char, et int. + // Un switch fonctionne avec les types : byte, short, char et int. // Les enums sont aussi supportés ainsi que les strings et quelques - // classes spéciales basées sur les types primitifs : Character, Byte, Short, et Integer. + // classes spéciales basées sur les types primitifs : Character, Byte, Short et Integer. int mois = 3; string moisString; switch (mois) @@ -293,7 +293,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; moisString = "Mars"; break; - // Vous pouvez assigné plus d'un 'case' à une action + // Vous pouvez assigner plus d'un 'case' à une action // Mais vous ne pouvez pas ajouter une action sans 'break' avant un 'case' // (pour ce faire, il faudrait ajouter explicitement un 'goto case x') case 6: @@ -307,10 +307,10 @@ sur une nouvelle ligne! ""Wow!"", quel style"; } /////////////////////////////////////// - // Convertion de type de donnée et transtypage + // conversion de type de donnée et transtypage /////////////////////////////////////// - // Convertion de string vers int + // conversion de string vers int // lève une exception en cas d'erreur int.Parse("123"); //retourne la valeur entière de "123" @@ -320,8 +320,8 @@ sur une nouvelle ligne! ""Wow!"", quel style"; if (int.TryParse("123", out tryInt)) // La fonction retourne un booléen Console.WriteLine(tryInt); // => 123 - // Convertion d'un entier vers une string - // La classe Convert possède plusieur méthodes pour faciliter la convertion + // conversion d'un entier vers une string + // La classe Convert possède plusieurs méthodes pour faciliter la conversion Convert.ToString(123); // ou tryInt.ToString(); @@ -399,7 +399,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Vous pouvez limiter les types autorisés public static void IterateAndPrint(T toPrint) where T: IEnumerable { - // Nous somme sûr de pouvoir itérer, car T implémente IEnumerable + // Nous sommes sûrs de pouvoir itérer, car T implémente IEnumerable foreach (var item in toPrint) // Item sera de type int Console.WriteLine(item.ToString()); @@ -417,14 +417,14 @@ sur une nouvelle ligne! ""Wow!"", quel style"; i.Print(); // Défini plus bas // TYPES NULLABLE - idéal pour les interactions avec une base de données ou pour les valeurs de retour - // Tous les types valeurs peuvent être rendu nullable en les suffixant par '?' + // Tous les types valeurs peuvent être rendus nullable en les suffixant par '?' // ? = int? nullable = null; // raccourci pour Nullable Console.WriteLine("Nullable variable: " + nullable); bool hasValue = nullable.HasValue; // retourne vrai si la valeur n'est pas null // ?? est un sucre de syntaxe pour spécifier une valeur par défaut - // au cas ou une autre valleur serait nulle + // au cas ou une autre valeur serait nulle int notNullable = nullable ?? 0; // 0 // VARIABLES IMPLICITEMENT TYPÉE - vous pouvez laisser le compilateur deviner le type d'une variable @@ -445,7 +445,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; Func square = (x) => x * x; // Le dernier élément est la valeur de retour Console.WriteLine(square(3)); // => 9 - // BIBLIOTHÈQUE DE TÂCHES PARALLÈLE (TPL) + // BIBLIOTHÈQUE DE TÂCHES PARALLÈLES (TPL) // http://msdn.microsoft.com/fr-fr/library/dd460717.aspx var websites = new string[] { "http://www.google.com", "http://www.reddit.com", @@ -453,8 +453,8 @@ sur une nouvelle ligne! ""Wow!"", quel style"; }; var responses = new Dictionary(); - // L'exemple suivant executera chaque requête dans un thread séparé, - // et attendera la fin de chacun d'entre eux avant de continuer + // L'exemple suivant exécutera chaque requête dans un thread séparé, + // et attendra la fin de chacun d'entre eux avant de continuer Parallel.ForEach(websites, new ParallelOptions() {MaxDegreeOfParallelism = 3}, // maximum de 3 threads website => @@ -494,7 +494,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Creation d'une liste d'objet anonymes basés sur des paramètres de la classe Bike var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); - // Le compilateur peut inférer le type de ces objets annonymes, permettant à certain IDE d'effectuer + // Le compilateur peut inférer le type de ces objets anonymes, permettant à certain IDE d'effectuer // des autos-complétion. foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) Console.WriteLine(bikeSummary.Name); @@ -509,12 +509,12 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // LINQ - lie une source de donnée à des objets IQueryable - // ex: LindToSql => liaison avec une base de donnée, LinqToXml => liaison avec un document xml + // ex: LindToSql => liaison avec une base de données, LinqToXml => liaison avec un document xml var db = new BikeRespository(); - // l'execution est décalée, ce qui est préférable quand on travail sur une base données + // l'exécution est décalée, ce qui est préférable quand on travaille sur une base données var fitler = db.Bikes.Where(b => b.HasTassles); // pas de requête exécutée - if (42 > 6) // Vous pouvez continuez à affiner la recherche + if (42 > 6) // Vous pouvez continuer à affiner la recherche fitler = fitler.Where(b => b.IsBroken); // pas de requête exécutée var query = fitler @@ -530,7 +530,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; } // Fin de la classe LearnCSharp - // Il est possible d'inclure plusieur classes dans un fichier .cs + // Il est possible d'inclure plusieurs classes dans un fichier .cs public static class Extensions { @@ -556,7 +556,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; { return _cadence; } - set // set - définit une méthode pour affecté une valeur à la propriété + set // set - définit une méthode pour affecter une valeur à la propriété { _cadence = value; // 'value' est la valeur passée en argument au setteur } @@ -583,7 +583,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Enum est un type valeur formé par un ensemble de constantes nommées // C'est simplement une manière de mettre un nom sur une valeur (int par défaut). - // Les types compatibles pour un enum sont : byte, sbyte, short, ushort, int, uint, long, et ulong. + // Les types compatibles pour un enum sont : byte, sbyte, short, ushort, int, uint, long et ulong. // Un enum ne peut pas contenir deux fois la même valeur public enum BikeBrand { @@ -606,7 +606,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Elles ne peuvent être assignées que lors de leur déclaration ou dans un constructeur readonly bool _hasCardsInSpokes = false; // variable en lecture et privée - // Les contructeurs sont un moyen de créer des objets + // Les constructeurs sont un moyen de créer des objets // Voici un constructeur par défaut (pas d'arguments) public Bicycle() { @@ -618,7 +618,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; BicyclesCreated++; } - // Voici un constructeur spécifique (qui prends des arguments) + // Voici un constructeur spécifique (qui prend des arguments) public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes, BikeBrand brand) : base() // possibilité d'appeler le constructeur de la classe mère (ici Object) @@ -631,7 +631,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; Brand = brand; } - // Les constructeur peuvent s'enchaîner + // Les constructeurs peuvent s'enchaîner public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : this(startCadence, startSpeed, 0, "big wheels", true, brand) { @@ -640,10 +640,10 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Syntaxe de méthode: // () - // Les classes peuvent implémenter des accesseurs pour leur champs + // Les classes peuvent implémenter des accesseurs pour leurs champs // ou implémenter des propriétés (c'est la méthode dominante en C#) - // Les paramètres de méthodes peuvent avoir des valeur par défaut + // Les paramètres de méthodes peuvent avoir des valeurs par défaut // Dans ce cas, la méthode peut être appelée sans arguments public void SpeedUp(int increment = 1) { @@ -689,7 +689,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; ; } - // Les méthodes peuvent aussi être statiques. Utile pour les méthode d'aide. + // Les méthodes peuvent aussi être statiques. Utile pour les méthodes d'aide. public static bool DidWeCreateEnoughBycles() { // A l'intérieur d'une méthode statique on ne peut que référencer des membres statiques ! @@ -731,7 +731,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Les interfaces contiennent uniquement la signature de leurs membres, sans implémentation. interface IJumpable { - void Jump(int meters); // Tout les membres d'interface sont publique par défaut + void Jump(int meters); // Tous les membres d'interface sont publics par défaut } interface IBreakable @@ -740,7 +740,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // des méthodes et des évènements } - // Une classe ne peut hériter que d'une seule autre classe, mais peut implémenter plusieur interfaces + // Une classe ne peut hériter que d'une seule autre classe, mais peut implémenter plusieurs interfaces class MountainBike : Bicycle, IJumpable, IBreakable { int damage = 0; -- cgit v1.2.3 From 7350deb1035369453c0651ecd81c4e00cae04142 Mon Sep 17 00:00:00 2001 From: olwaro Date: Mon, 24 Feb 2014 19:54:54 +0100 Subject: Adds loan pattern example to french translation. --- csharp.html.markdown | 2 +- fr-fr/csharp-fr.html.markdown | 47 ++++++++++++++++++++++++++----------------- 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 81b50e08..a5b2e1c2 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -435,7 +435,7 @@ on a new line! ""Wow!"", the masses cried"; Func square = (x) => x * x; // Last T item is the return value Console.WriteLine(square(3)); // 9 - // DISPOSABLE RESSOURCES MANAGEMENT - let you handle unmanaged resources easily. + // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. // Most of objects that access unmanaged resources (file handle, device contexts, etc.) // implement the IDisposable interface. The using statement takes care of // cleaning those IDisposable objects for you. diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown index 032d94a6..cf95a881 100644 --- a/fr-fr/csharp-fr.html.markdown +++ b/fr-fr/csharp-fr.html.markdown @@ -99,8 +99,8 @@ namespace Learning // on ajoute 'f' pour spécifier la création d'un float // Decimal - Type de donnée numérique sur 128 bits, fournit une plus - // grande précision et une plage de valeurs réduite - // approprié aux calculs financiers et monétaires + // grande précision et une plage de valeurs réduite. + // Approprié aux calculs financiers et monétaires decimal fooDecimal = 150.3m; // Booléen - vrai / faux @@ -114,11 +114,11 @@ namespace Learning string fooString = "\"échappement\" de guillemets et ajout de \n (nouvelle ligne) et de \t (tabulation)"; Console.WriteLine(fooString); - // Il est possible d'accéder à chaque caractère d'une string via un indexeur + // Il est possible d'accéder à chaque caractère d'une chaîne de caractères via un indexeur char charFromString = fooString[1]; // 'é' - // Une string est immuable: impossible de faire fooString[1] = 'X'; + // une chaîne de caractères est immuable: impossible de faire fooString[1] = 'X'; - // Comparaison de strings avec la culture courrante en ignorant la casse + // Comparaison de chaînes de caractères avec la culture courrante en ignorant la casse string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); // Formatage @@ -128,14 +128,14 @@ namespace Learning DateTime fooDate = DateTime.Now; Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - // Il est possible d'étaler une string sur plusieurs lignes avec le symbole @. + // Il est possible d'étaler une chaîne de caractères sur plusieurs lignes avec le symbole @. // Pour échapper " utilisez "" string bazString = @"Voici quelques trucs sur une nouvelle ligne! ""Wow!"", quel style"; - // Utilisez const ou read-only pour rendre une variable immuable - // les valeurs constantes sont calculées au moment de la compilation - const int HEURES_PAR_SEMAINE = 9001; + // Utilisez const ou read-only pour rendre une variable immuable. + // Les valeurs constantes sont calculées au moment de la compilation + const int HOURS_I_WORK_PER_WEEK = 9001; /////////////////////////////////////////////////// // Structures de données @@ -225,7 +225,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; int j = 10; if (j == 10) { - Console.WriteLine("Je serais affiché"); + Console.WriteLine("Je serai affiché"); } else if (j > 10) { @@ -277,7 +277,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // La structure Switch Case // Un switch fonctionne avec les types : byte, short, char et int. - // Les enums sont aussi supportés ainsi que les strings et quelques + // Les enums sont aussi supportés ainsi que les chaînes de caractères et quelques // classes spéciales basées sur les types primitifs : Character, Byte, Short et Integer. int mois = 3; string moisString; @@ -320,7 +320,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; if (int.TryParse("123", out tryInt)) // La fonction retourne un booléen Console.WriteLine(tryInt); // => 123 - // conversion d'un entier vers une string + // conversion d'un entier vers une chaîne de caractères // La classe Convert possède plusieurs méthodes pour faciliter la conversion Convert.ToString(123); // ou @@ -423,13 +423,13 @@ sur une nouvelle ligne! ""Wow!"", quel style"; Console.WriteLine("Nullable variable: " + nullable); bool hasValue = nullable.HasValue; // retourne vrai si la valeur n'est pas null - // ?? est un sucre de syntaxe pour spécifier une valeur par défaut + // ?? est un sucre syntaxique pour spécifier une valeur par défaut // au cas ou une autre valeur serait nulle int notNullable = nullable ?? 0; // 0 // VARIABLES IMPLICITEMENT TYPÉE - vous pouvez laisser le compilateur deviner le type d'une variable - var magic = "magic est de type string à la compilation, on a toujours un typage fort !"; - // magic = 9; // ne fonctionnera pas car magic est désormais une string + var magic = "magic est de type string à la compilation. On a toujours un typage fort !"; + // magic = 9; // ne fonctionnera pas car magic est désormais une chaîne de caractères // TYPES GÉNÉRIQUES var agenda = new Dictionary() { @@ -445,6 +445,17 @@ sur une nouvelle ligne! ""Wow!"", quel style"; Func square = (x) => x * x; // Le dernier élément est la valeur de retour Console.WriteLine(square(3)); // => 9 + // GESTION AUTOMATIQUE DES RESSOURCES - vous permet de manipuler facilement des resources non-managées + // La plus part des objets qui accèdent à des ressources non-managées (handle de fichier, périphérique, etc.) + // implémentent l'interface IDisposable. L'instruction using prends soin + // de libérer ses objets IDisposable proprement à votre place. + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Rien à signaler"); + // À la fin de cette portée, les ressources seront libérées. + // Même si une exception est levée. + } + // BIBLIOTHÈQUE DE TÂCHES PARALLÈLES (TPL) // http://msdn.microsoft.com/fr-fr/library/dd460717.aspx var websites = new string[] { @@ -459,7 +470,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; new ParallelOptions() {MaxDegreeOfParallelism = 3}, // maximum de 3 threads website => { - // Faire quelque chose de long sur le fichier + // Fait quelque chose de long using (var r = WebRequest.Create(new Uri(website)).GetResponse()) { responses[website] = r.ContentType; @@ -474,13 +485,13 @@ sur une nouvelle ligne! ""Wow!"", quel style"; dynamic student = new ExpandoObject(); student.FirstName = "Mon prénom"; // Pas besoin de définir l'objet - // Vous pouvez même ajouter des méthodes (dans ce cas: qui prend une string et retourne une string) + // Vous pouvez même ajouter des méthodes (dans cet exemple: la méthode prend une chaîne de caractères et retourne une chaîne de caractères) student.Introduce = new Func( (introduceTo) => string.Format("Hey {0}, c'est {1}", student.FirstName, introduceTo)); Console.WriteLine(student.Introduce("Beth")); // IQUERYABLE - quasiment toutes les collections implémentent cette interface - // ce qui permet d'utiliser des méthodes de style Filter / Map / Reduce + // ce qui permet d'utiliser des méthodes de style 'Filter' / 'Map' / 'Reduce' var bikes = new List(); bikes.Sort(); // Trie le tableau sur place bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Trie en se basant sur la propriété Wheels -- cgit v1.2.3 From 9d7566d82edf776b5f52ec397cd06f8e24e54b86 Mon Sep 17 00:00:00 2001 From: olwaro Date: Mon, 24 Feb 2014 21:39:05 +0100 Subject: Fix what Nami-Doc spotted. --- csharp.html.markdown | 6 ++-- fr-fr/csharp-fr.html.markdown | 76 +++++++++++++++++++++---------------------- 2 files changed, 41 insertions(+), 41 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index a5b2e1c2..a689fe97 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -511,11 +511,11 @@ on a new line! ""Wow!"", the masses cried"; var db = new BikeRespository(); // execution is delayed, which is great when querying a database - var fitler = db.Bikes.Where(b => b.HasTassles); // no query run + var filter = db.Bikes.Where(b => b.HasTassles); // no query run if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality - fitler = fitler.Where(b => b.IsBroken); // no query run + filter = filter.Where(b => b.IsBroken); // no query run - var query = fitler + var query = filter .OrderBy(b => b.Wheels) .ThenBy(b => b.Name) .Select(b => b.Name); // still no query run diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown index cf95a881..c1641716 100644 --- a/fr-fr/csharp-fr.html.markdown +++ b/fr-fr/csharp-fr.html.markdown @@ -29,7 +29,7 @@ ceci /// Ceci est un commentaire de documentation XML /// -// Utilisez des namespaces avec l'instruction 'using' +// Importez des namespaces avec l'instruction 'using' using System; using System.Collections.Generic; using System.Data.Entity; @@ -46,8 +46,8 @@ namespace Learning // que celui du fichier. Ce n'est pas une obligation mais c'est mieux ! public class LearnCSharp { - // LES BASES - si vous avez déjà une expérience en Java ou C++ - // passez directement à la partie FONCTIONNALITÉS INTERESSANTES + // LES BASES - si vous avez déjà de l'expérience en Java ou C++ + // passez directement à la partie FONCTIONNALITÉS INTERÉSSANTES public static void Syntax() { // Utilisez Console.WriteLine pour écrire sur la sortie @@ -91,10 +91,10 @@ namespace Learning // on ajoute 'L' pour spécifier la création d'un long // Double - Réel sur 64 bits en virgule flottante (norme IEEE 754) - double fooDouble = 123.4; // Precision: 15-16 chiffres + double fooDouble = 123.4; // Precision : 15-16 chiffres // Float - Réel sur 32 bits en virgule flottante (norme IEEE 754) - float fooFloat = 234.5f; // Precision: 7 chiffres + float fooFloat = 234.5f; // Precision : 7 chiffres // Par défaut le type d'un littéral réel est double // on ajoute 'f' pour spécifier la création d'un float @@ -114,9 +114,9 @@ namespace Learning string fooString = "\"échappement\" de guillemets et ajout de \n (nouvelle ligne) et de \t (tabulation)"; Console.WriteLine(fooString); - // Il est possible d'accéder à chaque caractère d'une chaîne de caractères via un indexeur + // Il est possible d'accéder à chaque caractère d'une chaîne de caractères via son index char charFromString = fooString[1]; // 'é' - // une chaîne de caractères est immuable: impossible de faire fooString[1] = 'X'; + // une chaîne de caractères est immuable : impossible de faire fooString[1] = 'X'; // Comparaison de chaînes de caractères avec la culture courrante en ignorant la casse string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); @@ -163,14 +163,14 @@ sur une nouvelle ligne! ""Wow!"", quel style"; List stringList = new List(); List z = new List { 9000, 1000, 1337 }; // intialisation // Les <> indiquent un type générique - // Pus d'info dans la partie FONCTIONNALITÉS INTERESSANTES + // Pus d'info dans la partie FONCTIONNALITÉS INTERÉSSANTES // Les éléments d'une liste ne sont pas null par défaut // Il faut ajouter une valeur avant d'y accéder par index intList.Add(1); Console.WriteLine("intList à 0: " + intList[0]); - // Autres structures de données à étudier: + // Autres structures de données à étudier : // Stack/Queue (Pile/File) // Dictionary (une implémentation de hash map) // HashSet (représente un ensemble) @@ -217,11 +217,11 @@ sur une nouvelle ligne! ""Wow!"", quel style"; Console.WriteLine(--i); //i = 0. Pre-Decrémentation /////////////////////////////////////// - // Structure de contrôle + // Structures de contrôle /////////////////////////////////////// - Console.WriteLine("\n->Structure de contrôle"); + Console.WriteLine("\n->Structures de contrôle"); - // Clause 'if' à la C + // Structure conditionnelle int j = 10; if (j == 10) { @@ -268,7 +268,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Structure : foreach( in ) // Cette boucle est utilisable sur des objets implémentant IEnumerable ou IEnumerable // Toutes les collections du framework .NET (Tableaux, Listes, ...) implémentent ces interfaces. - // (Notez que dans l'exemple suivant .ToCharArray() peut être omit car, + // (Notez que dans l'exemple suivant .ToCharArray() peut être omit car // string implémente IEnumerable) foreach (char character in "Hello World".ToCharArray()) { @@ -352,14 +352,14 @@ sur une nouvelle ligne! ""Wow!"", quel style"; Console.Read(); } - // POINT D'ENTREE Une application console doit avoir une méthode main comme point d'entrée + // POINT D'ENTRÉE - Une application console doit avoir une méthode main comme point d'entrée public static void Main(string[] args) { OtherInterestingFeatures(); } // - // FONCTIONNALITÉS INTERESSANTES + // FONCTIONNALITÉS INTÉRÉSSANTES // // SIGNATURE DE METHODE @@ -381,7 +381,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; { } - // TYPE GENERIQUE + // TYPE GÉNÉRIQUE // Les types TKey et TValue sont spécifiés par l'utilisateur lors de l'appel de la fonction // Cette méthode émule SetDefaut de Python @@ -414,7 +414,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // MÉTHODE D'EXTENSION int i = 3; - i.Print(); // Défini plus bas + i.Print(); // Définit plus bas // TYPES NULLABLE - idéal pour les interactions avec une base de données ou pour les valeurs de retour // Tous les types valeurs peuvent être rendus nullable en les suffixant par '?' @@ -427,7 +427,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // au cas ou une autre valeur serait nulle int notNullable = nullable ?? 0; // 0 - // VARIABLES IMPLICITEMENT TYPÉE - vous pouvez laisser le compilateur deviner le type d'une variable + // VARIABLES IMPLICITEMENT TYPÉES - vous pouvez laisser le compilateur deviner le type d'une variable var magic = "magic est de type string à la compilation. On a toujours un typage fort !"; // magic = 9; // ne fonctionnera pas car magic est désormais une chaîne de caractères @@ -436,23 +436,23 @@ sur une nouvelle ligne! ""Wow!"", quel style"; {"Sarah", "212 555 5555"} // Ajout d'une entrée à notre agenda }; - // Appel de la fonction SetDefault (défini plus haut) + // Appel de la fonction SetDefault (définie plus haut) Console.WriteLine(SetDefault(agenda, "Shaun", "Pas de numéro")); // => Pas de numéro // Notez que vous n'avez pas à spécifier TKey et TValue car le compilateur saura les inférer. Console.WriteLine(SetDefault(agenda, "Sarah", "No Phone")); // => 212 555 5555 // EXPRESSION LAMBDA - permet d'écrire une fonction en tant qu'expression - Func square = (x) => x * x; // Le dernier élément est la valeur de retour + Func square = (x) => x * x; // La dernière expression est la valeur de retour Console.WriteLine(square(3)); // => 9 // GESTION AUTOMATIQUE DES RESSOURCES - vous permet de manipuler facilement des resources non-managées // La plus part des objets qui accèdent à des ressources non-managées (handle de fichier, périphérique, etc.) - // implémentent l'interface IDisposable. L'instruction using prends soin - // de libérer ses objets IDisposable proprement à votre place. + // implémentent l'interface IDisposable. L'instruction using prend soin + // de libérer les objets IDisposable proprement à votre place. using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("Rien à signaler"); - // À la fin de cette portée, les ressources seront libérées. + // À la fin de cette portée les ressources seront libérées. // Même si une exception est levée. } @@ -485,7 +485,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; dynamic student = new ExpandoObject(); student.FirstName = "Mon prénom"; // Pas besoin de définir l'objet - // Vous pouvez même ajouter des méthodes (dans cet exemple: la méthode prend une chaîne de caractères et retourne une chaîne de caractères) + // Vous pouvez même ajouter des méthodes (dans cet exemple : la méthode prend une chaîne de caractères et retourne une chaîne de caractères) student.Introduce = new Func( (introduceTo) => string.Format("Hey {0}, c'est {1}", student.FirstName, introduceTo)); Console.WriteLine(student.Introduce("Beth")); @@ -505,7 +505,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Creation d'une liste d'objet anonymes basés sur des paramètres de la classe Bike var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); - // Le compilateur peut inférer le type de ces objets anonymes, permettant à certain IDE d'effectuer + // Le compilateur peut inférer le type de ces objets anonymes, permettant à certains IDE d'effectuer // des autos-complétion. foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) Console.WriteLine(bikeSummary.Name); @@ -519,16 +519,16 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // machine dispose de plusieurs coeurs) - // LINQ - lie une source de donnée à des objets IQueryable - // ex: LindToSql => liaison avec une base de données, LinqToXml => liaison avec un document xml + // LINQ - lie une source de données à des objets IQueryable + // ex : LindToSql => liaison avec une base de données, LinqToXml => liaison avec un document xml var db = new BikeRespository(); // l'exécution est décalée, ce qui est préférable quand on travaille sur une base données - var fitler = db.Bikes.Where(b => b.HasTassles); // pas de requête exécutée + var filter = db.Bikes.Where(b => b.HasTassles); // pas de requête exécutée if (42 > 6) // Vous pouvez continuer à affiner la recherche - fitler = fitler.Where(b => b.IsBroken); // pas de requête exécutée + filter = filter.Where(b => b.IsBroken); // pas de requête exécutée - var query = fitler + var query = filter .OrderBy(b => b.Wheels) .ThenBy(b => b.Name) .Select(b => b.Name); // toujours pas de requête exécutée @@ -561,7 +561,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; public class Bicycle { // Propriétés et variable de la classe - public int Cadence // Public: peut être accédé de partout + public int Cadence // Public : peut être accédé de partout { get // get - définit une méthode pour lire la propriété { @@ -574,13 +574,13 @@ sur une nouvelle ligne! ""Wow!"", quel style"; } private int _cadence; - protected virtual int Gear // Protected: accessible depuis la classe et ses classes filles + protected virtual int Gear // Protected : accessible depuis la classe et ses classes filles { get; // crée une propriété automatique, pas besoin de créer une variable de stockage set; } - internal int Wheels // Internal: accessible depuis l'assembly + internal int Wheels // Internal : accessible depuis l'assembly { get; private set; // Il est possible de choisir la portée d'un accesseur @@ -609,8 +609,8 @@ sur une nouvelle ligne! ""Wow!"", quel style"; public BikeBrand Brand; // Après avoir déclaré notre type enum, on peut créer un champ de ce type // Les membres statiques appartiennent à une classe plutôt qu'à une instance particulière - // Il est possible d'y accéder sans passer par un objet: - // ex: Console.WriteLine("Bicycles créés: " + Bicycle.bicyclesCreated); + // Il est possible d'y accéder sans passer par un objet : + // ex : Console.WriteLine("Bicycles créés : " + Bicycle.bicyclesCreated); static public int BicyclesCreated = 0; // Les valeurs en lecture seule sont affectées lors de l'exécution @@ -648,7 +648,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; { } - // Syntaxe de méthode: + // Syntaxe de méthode : // () // Les classes peuvent implémenter des accesseurs pour leurs champs @@ -688,7 +688,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; private set; } - // Méthode qui affiche les valeurs des champs de cet objet + // Méthode qui affiche la valeur des champs de cet objet public virtual string Info() { return "Gear: " + Gear + @@ -703,7 +703,7 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Les méthodes peuvent aussi être statiques. Utile pour les méthodes d'aide. public static bool DidWeCreateEnoughBycles() { - // A l'intérieur d'une méthode statique on ne peut que référencer des membres statiques ! + // À l'intérieur d'une méthode statique on ne peut que référencer des membres statiques ! return BicyclesCreated > 9000; } // Si votre classe n'a que des membres statiques, marquez la comme statique -- cgit v1.2.3 From 4c579c9a6c5cebe0ee4fe8bfa96da6fce02d2d49 Mon Sep 17 00:00:00 2001 From: dev-sala Date: Tue, 25 Feb 2014 17:30:02 +0100 Subject: Java - Added Italian [it-it] translation -> First relase --- it-it/java.html.markdown | 500 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 500 insertions(+) create mode 100644 it-it/java.html.markdown diff --git a/it-it/java.html.markdown b/it-it/java.html.markdown new file mode 100644 index 00000000..76e0f027 --- /dev/null +++ b/it-it/java.html.markdown @@ -0,0 +1,500 @@ +--- + +language: java +filename: LearnJava.java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Madison Dickson", "http://github.com/mix3d"] +translators: + - ["Ivan Sala","http://github.com/dev-sala"] +lang: it-it + +--- +Java è un linguaggio di programmazione orientato ad oggetti, +concorrente, basato su classi e adatto a svariati scopi. +[Per saperne di più](http://docs.oracle.com/javase/tutorial/java/index.html) + +```java +// I commenti su singola linea incominciano con // +/* +I commenti su più linee invece sono così +*/ +/** +I commenti per la documentazione JavaDoc si fanno così. +Vengono usati per descrivere una classe o alcuni suoi attributi. +*/ + +// Per importare la classe ArrayList conenuta nel package java.util +import java.util.ArrayList; +// Per importare tutte le classi contenute nel package java.security +import java.security.*; + +// Ogni filce .java contiene una classe pubblica, con lo stesso nome del file +public class LearnJava { + + // Un programma deve avere un metodo main come punto di partenza + public static void main (String[] args) { + + // Per stampare a schermo si usa System.out.println + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Se non si vuole andare a capo, si può usare System.out.print + System.out.print("Hello "); + System.out.print("World"); + + + /////////////////////////////////////// + // Tipi e Variabili + /////////////////////////////////////// + // Si dichiara una variabile usando + // Byte - 8-bit signed two's complement integer + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 16-bit signed two's complement integer + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 32-bit signed two's complement integer + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 64-bit signed two's complement integer + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L is used to denote that this variable value is of type Long; + // anything without is treated as integer by default. + + // Nota: Java non dispone di variabili senza segno + + // Float - Single-precision 32-bit IEEE 754 Floating Point + float fooFloat = 234.5f; + // f is used to denote that this variable value is of type float; + // otherwise it is treated as double. + + // Double - Double-precision 64-bit IEEE 754 Floating Point + double fooDouble = 123.4; + + // Boolean - true & false + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // final - Costanti, non possono essere riassegnate ad un altro oggetto + final int HOURS_I_WORK_PER_WEEK = 9001; + + // Stringhe + String fooString = "My String Is Here!"; + + // \n è un carattere speciale che permette di andare a capo. + String barString = "Printing on a new line?\nNo Problem!"; + // \t è un carattere speciale che permette di aggiungere un 'Tab' + String bazString = "Do you want to add a tab?\tNo Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Vettori + //La lunghezza del vettore deve essere decisa quando viene istanziato + //Si può dichiarare come segue: + // [] = new []; + // [] = new []; + int [] intArray = new int[10]; + String [] stringArray = new String[1]; + boolean boolArray [] = new boolean[100]; + + // Un altro modo per dichiarare & inizializzare un vettore + int [] y = {9000, 1000, 1337}; + String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Accesso diretto ad un elemento + System.out.println("intArray @ 0: " + intArray[0]); + + // I vettori vengono indicizzati a parire dallo 0, ma sono mutabili + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Altro da aggiungere: + // Liste di array - come i vettori ma vi sono più funzioni + // e la grandezza può variare in corso di esecuzione + // Liste concatenate + // Maps + // HashMaps + + /////////////////////////////////////// + // Operatori + /////////////////////////////////////// + System.out.println("\n->Operatori"); + + int i1 = 1, i2 = 2; // Dichiarazone multipla in contemporanea + + // L'aritmetica è lineare. + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 + // (con 0.5 arrotonda per difetto) + + // Modulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Operatori di confronto + System.out.println("3 == 2? " + (3 == 2)); // => falso + System.out.println("3 != 2? " + (3 != 2)); // => vero + System.out.println("3 > 2? " + (3 > 2)); // => vero + System.out.println("3 < 2? " + (3 < 2)); // => falso + System.out.println("2 <= 2? " + (2 <= 2)); // => vero + System.out.println("2 >= 2? " + (2 >= 2)); // => vero + + // Bitwise operators! + // Operatori binari + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + >>> Unsigned right shift + & AND Binario Bitwise AND + ^ OR Esclusivo + | OR Incusivo + */ + + // Incrementare + int i = 0; + System.out.println("\n->Incrementare/Decrementare"); + // Gli operatori ++ e -- incrementano e decrementano ripettivamente di 1. + // Se posizionati prima della variabile, incrementano, quindi riportano. + // Se si trovano dopo la variabile, riporano, e quindi incrementano. + System.out.println(i++); //i = 1, Stampa 0 (post-incremento) + System.out.println(++i); //i = 2, Stampa 2 (pre-incremento) + System.out.println(i--); //i = 1, Stampa 2 (post-decremento) + System.out.println(--i); //i = 0, Stampa 0 (pre-decremento) + + /////////////////////////////////////// + // Strutture di controllo + /////////////////////////////////////// + System.out.println("\n->Strutture di controllo"); + + // La dichiarazione dell'If è C-like. + int j = 10; + if (j == 10){ + System.out.println("Io vengo stampato"); + } else if (j > 10) { + System.out.println("Io no"); + } else { + System.out.println("E io neppure"); + } + + // Struttura While + int fooWhile = 0; + while(fooWhile < 100) + { + //System.out.println(fooWhile); + //Incrementa il contatore + //Si ripete per 100 volte, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("Valore di fooWhile: " + fooWhile); + + // Struttura Do While + int fooDoWhile = 0; + do + { + //System.out.println(fooDoWhile); + //Incrementa il contaore + //Si repete per 99 volte, fooDoWhile 0->99 + fooDoWhile++; + }while(fooDoWhile < 100); + System.out.println("Valore di fooWhile: " + fooDoWhile); + + // Struttura For + int fooFor; + //Struttura For => for(; ; ) + for(fooFor=0; fooFor<10; fooFor++){ + //System.out.println(fooFor); + //Itera 10 volte, fooFor 0->9 + } + System.out.println("Valore di fooFor: " + fooFor); + + // Struttura For Each + // Una iterazione automatica attraverso un array o una lista di oggetti + int[] fooList = {1,2,3,4,5,6,7,8,9}; + //struttura for each => for( : ) + //si legge: per ogni oggetto dell'array fai... + //Nota: il tipo dell'oggetto deve essere uguale a quello dell'array + + for( int bar : fooList ){ + //System.out.println(bar); + //Itera 9 volte e stampa 1-9 andando a capo. + } + + // Struttura Switch Case + // La struttura switch lavora con byte, short, char e int. + // Se funziona con i char funzionerà ovviamente anche con le stringhe. + int mese = 3; + String stringaMese; + switch (mese){ + case 1: + stringaMese = "Genneio"; + break; + case 2: + strigaMese = "Febbraio"; + break; + case 3: + stringaMese = "Marzo"; + break; + default: + stringaMese = "Altri mesi"; + break; + } + System.out.println("Risultato del costrutto switch:: " + stringaMese); + + // Condizioni brevi + // Si può usare l'operatore '?' per un rapido assegnamento + // o per operazioni logiche. + // Si legge: + // Se (condizione) è vera, usa , altrimenti usa + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Stampa A, perchè la condizione è vera. + + + ///////////////////////////////////////// + // Convertire i tipi di tati e Typcasting + ///////////////////////////////////////// + + // Convertire tipi di dati + + // Stringhe ad interi + Integer.parseInt("123");//Riporta una versione intera di "123" + + // Interi a Stringhe + Integer.toString(123);//Riporta la stringa "123" + // Per altre conversioni guarda le seguenti classi + // Double + // Long + // String + + // Typecasting + // Vi sono molti dettagli che non si possono spiegare qui, + // java dispone di una ottima documentazione + // Sentiti libero di leggerla + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Classi e funzioni + /////////////////////////////////////// + + System.out.println("\n->Classi & Funzioni"); + + // (Di seguito la definizione della classe Bicicletta) + + // Instanziare una nuova classe + Bicycle trek = new Bicycle(); + + // Chiamare metodi + trek.speedUp(3); // Si usano sempre metodi set... get... + trek.setCadence(100); + + // toString riporta la rappresenzazione dell'oggetto + // come se fosse una stringa + System.out.println("trek info: " + trek.toString()); + + } // Fine metodo main +} // Fine classe ImparareJavas + + +// Si possono inculdere altre anche delle classi non pubbliche (private) +// oltre a quella pubblica principale, in un file .java + +// Sintassi per dichiarare una classe: +// class { +// //dati, variabili, costruttori, funzioni, tutto qua. +// //le funzioni sono chiamate come i metodi. +// } + +class Bicicletta { + + // Variabili della bicicletta + public int cadence; + // Public: Può essere richiamato da qualsiasi classe + private int speed; + // Private: è accessibile solo dalla classe dove è stato inizializzato + protected int gear; + // Protected: è visto sia dalla classe che dalle sottoclassi + String name; + // default: è accessibile sono all'interno dello stesso package + + // I costruttori vengono usati per creare variabili + // Questo è un costruttore + public Bicicletta() { + ingranaggi = 1; + ritmo = 50; + velocità = 5; + nome = "Bontrager"; + } + + // Questo è un costruttore che richiede parametri + public Bicycle(int startCadence, int startSpeed, int startGear, String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // Sintassi delle funzioni: + // () + + // Le classi in java spesso implementano delle funzioni o metodo + // 'get...' o 'set...' + + // Dichiarazione di un metodo + // () + public int getCadence() { + return cadence; + } + + // i medodi (void) non necessitano di riportare un valore + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Medoto per visualizzare gli attributi dell'oggetto + @Override + public String toString() { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + speed + + " name: " + name; + } +} // Fine classe bicicletta + +// PennyFarthing è una sottoclasse della bicicletta +class PennyFarthing extends Bicycle { + // (Sono quelle biciclette con un unica ruota enorme + // Non hanno ingranaggi.) + + public PennyFarthing(int startCadence, int startSpeed){ + // Richiamo il costruttore del padre con super + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // You should mark a method you're overriding with an @annotation + // Bisogna contrassegnre un medodo che si sta riscrivendo + // con una @annotazione + // Per saperne di più sulle annotazioni + // Vedi la guida: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + gear = 0; + } + +} + +//Interfaccie +//Sintassi per dichiarare una interfaccia +// interface extends { +// //Constants +// //Method declarations +//} + +//Example - Food: +public interface Edible { + public void eat(); //Any class that implements this interface, must implement this method +} + +public interface Digestible { + public void digest(); +} + +//Possiamo quindi creare una classe che implementa entrambe le interfaccie +public class Fruit implements Edible, Digestible { + public void eat() { + //... + } + + public void digest() { + //... + } +} + +//In Java si può estendere solo una classe, ma si possono implementare +//più interfaccie, per esempio: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { + public void InterfaceOneMethod() { + + } + + public void InterfaceTwoMethod() { + + } +} + +``` + +## Letture future + +I link di seguito sono solo per capire l'argomento, cerca pure su Google degli esempi specifici + +**Guida ufficiale di Oracle**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + +**Tutorial Online** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Libri**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) + + -- cgit v1.2.3 From 0d63865f21f143eb85b65c1cbcaba4769c2cb8cd Mon Sep 17 00:00:00 2001 From: Abner Date: Tue, 25 Feb 2014 17:33:02 -0500 Subject: Create visualbasic-cn.html.markdown First Version of Translate. --- zh-cn/visualbasic-cn.html.markdown | 272 +++++++++++++++++++++++++++++++++++++ 1 file changed, 272 insertions(+) create mode 100644 zh-cn/visualbasic-cn.html.markdown diff --git a/zh-cn/visualbasic-cn.html.markdown b/zh-cn/visualbasic-cn.html.markdown new file mode 100644 index 00000000..fa5db923 --- /dev/null +++ b/zh-cn/visualbasic-cn.html.markdown @@ -0,0 +1,272 @@ +--- +language: Visual Basic +contributors: + - ["Brian Martin", "http://brianmartin.biz"] + translators: + - ["Abner Chou", "http://github.com/NoahDragon"] +lang: zh-cn +filename: learnvisualbasic.vb-cn +--- + +```vb +Module Module1 + + Sub Main() + ' 让我们先从简单的终端程序学起。 + ' 单引号用来生成注释(注意是半角单引号,非全角单引好’) + ' 为了方便运行此示例代码,我写了个目录索引。 + ' 可能你还不了解以下代码的意义,但随着教程的深入,你会 + ' 渐渐理解其用法。 + Console.Title = ("Learn X in Y Minutes") + Console.WriteLine("NAVIGATION") ' 显示目录 + Console.WriteLine("") + Console.ForegroundColor = ConsoleColor.Green + Console.WriteLine("1. Hello World Output") ' Hello world 输出示例 + Console.WriteLine("2. Hello World Input") ' Hello world 输入示例 + Console.WriteLine("3. Calculating Whole Numbers") ' 求整数之和 + Console.WriteLine("4. Calculating Decimal Numbers") ' 求小数之和 + Console.WriteLine("5. Working Calculator") ' 计算器 + Console.WriteLine("6. Using Do While Loops") ' 使用 do while 循环 + Console.WriteLine("7. Using For While Loops") ' 使用 for while 循环 + Console.WriteLine("8. Conditional Statements") ' 条件语句 + Console.WriteLine("9. Select A Drink") ' 买饮料 + Console.WriteLine("50. About") ' 关于 + Console.WriteLine("Please Choose A Number From The Above List") + Dim selection As String = Console.ReadLine + Select Case selection + Case "1" ' Hello world 输出示例 + Console.Clear() ' 清空屏幕 + HelloWorldOutput() ' 调用程序块 + Case "2" ' Hello world 输入示例 + Console.Clear() + HelloWorldInput() + Case "3" ' 求整数之和 + Console.Clear() + CalculatingWholeNumbers() + Case "4" ' 求小数之和 + Console.Clear() + CalculatingDecimalNumbers() + Case "5" ' 计算器 + Console.Clear() + WorkingCalculator() + Case "6" ' 使用 do while 循环 + Console.Clear() + UsingDoWhileLoops() + Case "7" ' 使用 for while 循环 + Console.Clear() + UsingForLoops() + Case "8" ' 条件语句 + Console.Clear() + ConditionalStatement() + Case "9" ' If/Else 条件语句 + Console.Clear() + IfElseStatement() ' 选饮料 + Case "50" ' 关于 + Console.Clear() + Console.Title = ("Learn X in Y Minutes :: About") + MsgBox("This tutorial is by Brian Martin (@BrianMartinn") + Console.Clear() + Main() + Console.ReadLine() + + End Select + End Sub + + ' 一、对应程序目录1,下同 + + ' 使用 private subs 来区分程序块. + Private Sub HelloWorldOutput() + ' 程序名 + Console.Title = "Hello World Ouput | Learn X in Y Minutes" + ' 使用 Console.Write("") 或者 Console.WriteLine("") 来输出文本到屏幕上 + ' 对应的 Console.Read() 或 Console.Readline() 用来读取键盘输入 + Console.WriteLine("Hello World") + Console.ReadLine() + End Sub + + ' 二 + Private Sub HelloWorldInput() + Console.Title = "Hello World YourName | Learn X in Y Minutes" + ' 变量 + ' 用来存储用户输入的数据 + ' 变量声明以 Dim 开始,结尾为 As VariableType (变量类型). + + ' 此教程中,我们希望知道你的姓名,并让程序记录并输出。 + Dim username As String + ' 我们使用字符串类型(String)来记录文本信息。 + Console.WriteLine("Hello, What is your name? ") ' 询问用户输入姓名 + username = Console.ReadLine() 'Stores the users name. + Console.WriteLine("Hello " + username) ' 输出将是 Hello '姓名' + Console.ReadLine() 'Outsputs the above. + ' 以上程序将询问你的姓名,并和你打招呼。 + ' 其它变量如整型(Integer)我们用整型来处理整数。 + End Sub + + ' 三 + Private Sub CalculatingWholeNumbers() + Console.Title = "Calculating Whole Numbers | Learn X in Y Minutes" + Console.Write("First number: ") ' 输入一个整数:1,2,50,104,等等 + Dim a As Integer = Console.ReadLine() + Console.Write("Second number: ") ' 输入第二个整数 + Dim b As Integer = Console.ReadLine() + Dim c As Integer = a + b + Console.WriteLine(c) + Console.ReadLine() + ' 以上程序将两个整数相加 + End Sub + + ' 四 + Private Sub CalculatingDecimalNumbers() + Console.Title = "Calculating with Double | Learn X in Y Minutes" + ' 当然,我们还需要能够处理小数。 + ' 只需要要将整型(Integer)改为小数(Double)类型即可。 + + ' 输入一个小数: 1.2, 2.4, 50.1, 104.9,等等 + Console.Write("First number: ") + Dim a As Double = Console.ReadLine + Console.Write("Second number: ") ' 输入第二个数 + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Console.WriteLine(c) + Console.ReadLine() + ' 以上代码能实现两个小数相加 + End Sub + + ' 五 + Private Sub WorkingCalculator() + Console.Title = "The Working Calculator| Learn X in Y Minutes" + ' 但是如果你希望有个能够处理加减乘除的计算器呢? + ' 只需将上面代码复制粘帖即可。 + Console.Write("First number: ") ' 输入第一个数 + Dim a As Double = Console.ReadLine + Console.Write("Second number: ") ' 输入第二个数 + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + ' 通过以下代码我们可以将以上所算的加减乘除结果输出到屏幕上。 + Console.Write(a.ToString() + " + " + b.ToString()) + ' 我们希望答案开头能有3个空格,可以使用String.PadLeft(3)方法。 + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.ReadLine() + + End Sub + + ' 六 + Private Sub UsingDoWhileLoops() + ' 如同以上的代码一样 + ' 这次我们将询问用户是否继续 (Yes or No?) + ' 我们将使用Do While循环,因为我们不知到用户是否需要使用一次以上。 + Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes" + Dim answer As String 'We use the variable "String" as the answer is text + Do ' 循环开始 + Console.Write("First number: ") + Dim a As Double = Console.ReadLine + Console.Write("Second number: ") + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + Console.Write(a.ToString() + " + " + b.ToString()) + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.ReadLine() + ' 询问用户是否继续,注意大小写。 + Console.Write("Would you like to continue? (yes / no)") + ' 程序读入用户输入 + answer = Console.ReadLine() ' added a bracket here + ' 当用户输入"yes"时,程序将跳转到Do,并再次执行 + Loop While answer = "yes" + + End Sub + + ' 七 + Private Sub UsingForLoops() + ' 有一些程序只需要运行一次。 + ' 这个程序我们将实现从10倒数计数. + + Console.Title = "Using For Loops | Learn X in Y Minutes" + ' 声明变量和步长(即递减的速度,如-1,-2,-3等)。 + For i As Integer = 10 To 0 Step -1 + Console.WriteLine(i.ToString) ' 将计数结果输出的屏幕 + Next i ' 计算新的i值 + Console.WriteLine("Start") + Console.ReadLine() + End Sub + + ' 八 + Private Sub ConditionalStatement() + Console.Title = "Conditional Statements | Learn X in Y Minutes" + Dim userName As String = Console.ReadLine + Console.WriteLine("Hello, What is your name? ") ' 询问用户姓名 + userName = Console.ReadLine() ' 存储用户姓名 + If userName = "Adam" Then + Console.WriteLine("Hello Adam") + Console.WriteLine("Thanks for creating this useful site") + Console.ReadLine() + Else + Console.WriteLine("Hello " + userName) + Console.WriteLine("Have you checked out www.learnxinyminutes.com") + Console.ReadLine() ' 程序停止,并输出以上文本 + End If + End Sub + + ' 九 + Private Sub IfElseStatement() + Console.Title = "If / Else Statement | Learn X in Y Minutes" + ' 有时候我们需要考虑多于两种情况。 + ' 这时我们就需要使用If条件语句。 + ' If语句就好似个自动售货机,当用户输入A1,A2,A3,等去选择物品时, + ' 所有的选择可以合并到一个If语句中 + + Dim selection As String = Console.ReadLine 'Value for selection + Console.WriteLine("A1. for 7Up") ' A1 七喜 + Console.WriteLine("A2. for Fanta") ' A2 芬达 + Console.WriteLine("A3. for Dr. Pepper") ' A3 胡椒医生 + Console.WriteLine("A4. for Diet Coke") ' A4 无糖可乐 + Console.ReadLine() + If selection = "A1" Then + Console.WriteLine("7up") + Console.ReadLine() + ElseIf selection = "A2" Then + Console.WriteLine("fanta") + Console.ReadLine() + ElseIf selection = "A3" Then + Console.WriteLine("dr. pepper") + Console.ReadLine() + ElseIf selection = "A4" Then + Console.WriteLine("diet coke") + Console.ReadLine() + Else + Console.WriteLine("Please select a product") ' 请选择你需要的产品 + Console.ReadLine() + End If + + End Sub + +End Module + +``` + +## 参考 + +我(译注:原作者)在命令行下学习的VB。命令行编程使我能够更好的了解程序编译运行机制,并使学习其它语言变得容易。 + +如果希望进一步学习VB,这里还有更深层次的 VB教学(英文)。 + +所有代码均通过测试。只需复制粘帖到Visual Basic中,并按F5运行即可。 -- cgit v1.2.3 From b1ad921af57d17631f73316dfca3aa39425bbd72 Mon Sep 17 00:00:00 2001 From: Abner Date: Tue, 25 Feb 2014 17:35:27 -0500 Subject: Slight change the format. --- zh-cn/visualbasic-cn.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zh-cn/visualbasic-cn.html.markdown b/zh-cn/visualbasic-cn.html.markdown index fa5db923..4459a2cd 100644 --- a/zh-cn/visualbasic-cn.html.markdown +++ b/zh-cn/visualbasic-cn.html.markdown @@ -2,7 +2,7 @@ language: Visual Basic contributors: - ["Brian Martin", "http://brianmartin.biz"] - translators: +translators: - ["Abner Chou", "http://github.com/NoahDragon"] lang: zh-cn filename: learnvisualbasic.vb-cn @@ -74,7 +74,7 @@ Module Module1 ' 一、对应程序目录1,下同 - ' 使用 private subs 来区分程序块. + ' 使用 private subs 声明函数。 Private Sub HelloWorldOutput() ' 程序名 Console.Title = "Hello World Ouput | Learn X in Y Minutes" -- cgit v1.2.3 From e31bfb31f7762aaded54f51d87ee883fb49f5d82 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Wed, 26 Feb 2014 15:51:07 +0800 Subject: clojure-macro: chinese translation --- zh-cn/clojure-macro-cn.html.markdown | 151 +++++++++++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 zh-cn/clojure-macro-cn.html.markdown diff --git a/zh-cn/clojure-macro-cn.html.markdown b/zh-cn/clojure-macro-cn.html.markdown new file mode 100644 index 00000000..e1b68a83 --- /dev/null +++ b/zh-cn/clojure-macro-cn.html.markdown @@ -0,0 +1,151 @@ +--- +language: "clojure macros" +filename: learnclojuremacros.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Jakukyo Friel", "http://weakish.github.io"] +--- + +和所有Lisp一样,Clojure内在的[同构性](https://en.wikipedia.org/wiki/Homoiconic)使得你可以穷尽语言的特性,编写生成代码的子过程——“宏”。宏是一种按需调制语言的强大方式。 + +小心!可以用函数完成的事用宏去实现可不是什么好事。你应该仅在需要控制参数是否或者何时eval的时候使用宏。 + +你应该熟悉Clojure.确保你了解[Y分钟学Clojure](http://learnxinyminutes.com/docs/zh-cn/clojure-cn/)中的所有内容。 + +```clojure +;; 使用defmacro定义宏。宏应该输出一个可以作为clojure代码演算的列表。 +;; +;; 以下宏的效果和直接写(reverse "Hello World")一致。 + +(defmacro my-first-macro [] + (list reverse "Hello World")) + +;; 使用macroexpand或macroexpand-1查看宏的结果。 +;; +;; 注意,调用需要引用。 +(macroexpand '(my-first-macro)) +;; -> (# "Hello World") + +;; 你可以直接eval macroexpand的结果 +(eval (macroexpand '(my-first-macro))) +; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; 不过一般使用以下形式,更简短,更像函数: +(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; 创建宏的时候可以使用更简短的引用形式来创建列表 +(defmacro my-first-quoted-macro [] + '(reverse "Hello World")) + +(macroexpand '(my-first-quoted-macro)) +;; -> (reverse "Hello World") +;; 注意reverse不再是一个函数对象,而是一个符号。 + +;; 宏可以传入参数。 +(defmacro inc2 [arg] + (list + 2 arg)) + +(inc2 2) ; -> 4 + +;; 不过,如果你尝试配合使用引用列表,会导致错误, +;; 因为参数也会被引用。 +;; 为了避免这个问题,clojure提供了引用宏的另一种方式:` +;; 在`之内,你可以使用~获得外圈作用域的变量。 +(defmacro inc2-quoted [arg] + `(+ 2 ~arg)) + +(inc2-quoted 2) + +;; 你可以使用通常的析构参数。用~@展开列表中的变量。 +(defmacro unless [arg & body] + `(if (not ~arg) + (do ~@body))) ; 别忘了 do! + +(macroexpand '(unless true (reverse "Hello World"))) + +;; -> +;; (if (clojure.core/not true) (do (reverse "Hello World"))) + +;; 当第一个参数为假时,(unless)会演算、返回主体。 +;; 否则返回nil。 + +(unless true "Hello") ; -> nil +(unless false "Hello") ; -> "Hello" + +;; 需要小心,宏会搞乱你的变量 +(defmacro define-x [] + '(do + (def x 2) + (list x))) + +(def x 4) +(define-x) ; -> (2) +(list x) ; -> (2) + +;; 使用gensym来获得独有的标识符 +(gensym 'x) ; -> x1281 (or some such thing) + +(defmacro define-x-safely [] + (let [sym (gensym 'x)] + `(do + (def ~sym 2) + (list ~sym)))) + +(def x 4) +(define-x-safely) ; -> (2) +(list x) ; -> (4) + +;; 你可以在 ` 中使用 # 为每个符号自动生成gensym +(defmacro define-x-hygenically [] + `(do + (def x# 2) + (list x#))) + +(def x 4) +(define-x-hygenically) ; -> (2) +(list x) ; -> (4) + +;; 通常会配合宏使用帮助函数。 +;; 让我们创建一些帮助函数来支持(无聊的)算术语法: + +(declare inline-2-helper) +(defn clean-arg [arg] + (if (seq? arg) + (inline-2-helper arg) + arg)) + +(defn apply-arg + "Given args [x (+ y)], return (+ x y)" + [val [op arg]] + (list op val (clean-arg arg))) + +(defn inline-2-helper + [[arg1 & ops-and-args]] + (let [ops (partition 2 ops-and-args)] + (reduce apply-arg (clean-arg arg1) ops))) + +;; 在创建宏前,我们可以先测试 +(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5)) + +; 然而,如果我们希望它在编译期执行,就需要创建宏 +(defmacro inline-2 [form] + (inline-2-helper form))) + +(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) +; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) + +(inline-2 (1 + (3 / 2) - (1 / 2) + 1)) +; -> 3 (事实上,结果是3N, 因为数字被转化为带/的有理分数) +``` + +## 扩展阅读 + +[Clojure for the Brave and True](http://www.braveclojure.com/)系列的编写宏 +http://www.braveclojure.com/writing-macros/ + +官方文档 +http://clojure.org/macros + +何时使用宏? +http://dunsmor.com/lisp/onlisp/onlisp_12.html -- cgit v1.2.3 From ccf61c677944ee2f925e4b6a8ee3e25856287281 Mon Sep 17 00:00:00 2001 From: Ivan Sala Date: Wed, 26 Feb 2014 15:27:10 +0100 Subject: Updated links and other -> Middle relase [java/it-it] - Java translation * Completed general translation. * Updated all link with italian's one. * Fixed some errors. --- it-it/java.html.markdown | 93 +++++++++++++++++++++++++----------------------- 1 file changed, 49 insertions(+), 44 deletions(-) diff --git a/it-it/java.html.markdown b/it-it/java.html.markdown index 76e0f027..afd41af5 100644 --- a/it-it/java.html.markdown +++ b/it-it/java.html.markdown @@ -10,6 +10,7 @@ translators: lang: it-it --- + Java è un linguaggio di programmazione orientato ad oggetti, concorrente, basato su classi e adatto a svariati scopi. [Per saperne di più](http://docs.oracle.com/javase/tutorial/java/index.html) @@ -29,7 +30,7 @@ import java.util.ArrayList; // Per importare tutte le classi contenute nel package java.security import java.security.*; -// Ogni filce .java contiene una classe pubblica, con lo stesso nome del file +// Ogni file .java contiene una classe pubblica, con lo stesso nome del file public class LearnJava { // Un programma deve avere un metodo main come punto di partenza @@ -38,59 +39,62 @@ public class LearnJava { // Per stampare a schermo si usa System.out.println System.out.println("Hello World!"); System.out.println( - "Integer: " + 10 + - " Double: " + 3.14 + - " Boolean: " + true); + "Intero [integer]: " + 10 + + " Reale [double]: " + 3.14 + + " Booleano [boolean]: " + true); // Se non si vuole andare a capo, si può usare System.out.print - System.out.print("Hello "); - System.out.print("World"); + System.out.print("Ciao "); + System.out.print("Mondo"); /////////////////////////////////////// // Tipi e Variabili /////////////////////////////////////// // Si dichiara una variabile usando - // Byte - 8-bit signed two's complement integer + // Byte - variabile intera da 8 bit con segno // (-128 <= byte <= 127) byte fooByte = 100; - // Short - 16-bit signed two's complement integer + // Short - variabile intera da 18 bit con segno // (-32,768 <= short <= 32,767) short fooShort = 10000; - // Integer - 32-bit signed two's complement integer + // Integer - variabile intera da 32 bit con segno // (-2,147,483,648 <= int <= 2,147,483,647) int fooInt = 1; - // Long - 64-bit signed two's complement integer + // Long - variabile da 64 bit intera con segno // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) long fooLong = 100000L; - // L is used to denote that this variable value is of type Long; - // anything without is treated as integer by default. + // L viene usato per specificare che il valore dalla variabile + // è di tipo "Long", qualsiasi variabile che non viene contrassegnata + // è trattata di base come un intero. // Nota: Java non dispone di variabili senza segno - // Float - Single-precision 32-bit IEEE 754 Floating Point + // Float - variabile più precisa, con virgola [numeri reali] + // di grandezza 32 bit float fooFloat = 234.5f; - // f is used to denote that this variable value is of type float; - // otherwise it is treated as double. + // f è usato per specificare che la variabile è di tipo "float" + // altrimenti da default viene trattata come "dobule" - // Double - Double-precision 64-bit IEEE 754 Floating Point + // Double - ancora più precisione la si può ottenere con una variabile + // Double, con granzezza di 64 bit. double fooDouble = 123.4; - // Boolean - true & false + // Boolean - vero & falso boolean fooBoolean = true; boolean barBoolean = false; - // Char - A single 16-bit Unicode character + // Char - un singolo carattere con grandezza 16 bit char fooChar = 'A'; // final - Costanti, non possono essere riassegnate ad un altro oggetto final int HOURS_I_WORK_PER_WEEK = 9001; - // Stringhe - String fooString = "My String Is Here!"; + // Stringhe [String] + String fooString = "Ecco una stringa!"; // \n è un carattere speciale che permette di andare a capo. String barString = "Printing on a new line?\nNo Problem!"; @@ -100,7 +104,7 @@ public class LearnJava { System.out.println(barString); System.out.println(bazString); - // Vettori + // Vettori [array] //La lunghezza del vettore deve essere decisa quando viene istanziato //Si può dichiarare come segue: // [] = new []; @@ -111,22 +115,21 @@ public class LearnJava { // Un altro modo per dichiarare & inizializzare un vettore int [] y = {9000, 1000, 1337}; - String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; + String nomi [] = {"Andrea", "Bob", "Pippo", "Susan"}; boolean bools[] = new boolean[] {true, false, false}; // Accesso diretto ad un elemento System.out.println("intArray @ 0: " + intArray[0]); - // I vettori vengono indicizzati a parire dallo 0, ma sono mutabili + // I vettori vengono indicizzati a parire dallo 0 + // Ma questo indice può essere cambiato. intArray[1] = 1; System.out.println("intArray @ 1: " + intArray[1]); // => 1 - // Altro da aggiungere: - // Liste di array - come i vettori ma vi sono più funzioni - // e la grandezza può variare in corso di esecuzione - // Liste concatenate - // Maps - // HashMaps + // Altro da vedere: + // Liste di array - come i vettori ma più funzionali + // e la loro grandezza può variare in corso di esecuzione + // Liste concatenate di memoria /////////////////////////////////////// // Operatori @@ -153,22 +156,22 @@ public class LearnJava { System.out.println("2 <= 2? " + (2 <= 2)); // => vero System.out.println("2 >= 2? " + (2 >= 2)); // => vero - // Bitwise operators! - // Operatori binari + // Operatori binari orientati ai bit + // effettuano le operazioni logiche confrontando, i bit degli operandi: /* - ~ Unary bitwise complement - << Signed left shift - >> Signed right shift - >>> Unsigned right shift + ~ complemento + << shift sinistro con segno + >> shift destro con segno + >>> shift destro senza segno & AND Binario Bitwise AND ^ OR Esclusivo | OR Incusivo */ - // Incrementare + // Incrementare e Decrementare int i = 0; System.out.println("\n->Incrementare/Decrementare"); - // Gli operatori ++ e -- incrementano e decrementano ripettivamente di 1. + // Gli operatori ++ e -- incrementano e decrementano rispettivamente di 1. // Se posizionati prima della variabile, incrementano, quindi riportano. // Se si trovano dopo la variabile, riporano, e quindi incrementano. System.out.println(i++); //i = 1, Stampa 0 (post-incremento) @@ -308,7 +311,7 @@ public class LearnJava { System.out.println("trek info: " + trek.toString()); } // Fine metodo main -} // Fine classe ImparareJavas +} // Fine classe LearnJava // Si possono inculdere altre anche delle classi non pubbliche (private) @@ -463,7 +466,8 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, In I link di seguito sono solo per capire l'argomento, cerca pure su Google degli esempi specifici -**Guida ufficiale di Oracle**: + +**Guida ufficiale di Oracle [solo in inglese]**: * [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) @@ -482,19 +486,20 @@ I link di seguito sono solo per capire l'argomento, cerca pure su Google degli e * [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) -**Tutorial Online** + +**Tutorial Online [in inglese]** * [Learneroo.com - Learn Java](http://www.learneroo.com) * [Codingbat.com](http://codingbat.com/java) -**Libri**: +**Libri [in italiano] **: -* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) +* [Java la guida completa](http://www.amazon.it/Java-guida-completa-Herbert-Schildt/dp/8838667667/ref=sr_1_1?ie=UTF8&qid=1393422296&sr=8-1&keywords=java) -* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) +* [Thinking in java](http://www.amazon.it/Thinking-Java-1-Bruce-Eckel/dp/8871923030/ref=sr_1_8?ie=UTF8&qid=1393422296&sr=8-8&keywords=java) -* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) +* [Manuale di Java 7](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From c9a51abc13ba6ae2ffe012f8ef443b4e13b54692 Mon Sep 17 00:00:00 2001 From: Abner Date: Wed, 26 Feb 2014 09:39:03 -0500 Subject: Update visualbasic-cn.html.markdown fix some typoes and untranslated comments. change some expression to make user more easily understand. --- zh-cn/visualbasic-cn.html.markdown | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/zh-cn/visualbasic-cn.html.markdown b/zh-cn/visualbasic-cn.html.markdown index 4459a2cd..95f01ed6 100644 --- a/zh-cn/visualbasic-cn.html.markdown +++ b/zh-cn/visualbasic-cn.html.markdown @@ -13,10 +13,10 @@ Module Module1 Sub Main() ' 让我们先从简单的终端程序学起。 - ' 单引号用来生成注释(注意是半角单引号,非全角单引好’) + ' 单引号用来生成注释(注意是半角单引号,非全角单引号’) ' 为了方便运行此示例代码,我写了个目录索引。 - ' 可能你还不了解以下代码的意义,但随着教程的深入,你会 - ' 渐渐理解其用法。 + ' 可能你还不了解以下代码的意义,但随着教程的深入, + ' 你会渐渐理解其用法。 Console.Title = ("Learn X in Y Minutes") Console.WriteLine("NAVIGATION") ' 显示目录 Console.WriteLine("") @@ -26,10 +26,10 @@ Module Module1 Console.WriteLine("3. Calculating Whole Numbers") ' 求整数之和 Console.WriteLine("4. Calculating Decimal Numbers") ' 求小数之和 Console.WriteLine("5. Working Calculator") ' 计算器 - Console.WriteLine("6. Using Do While Loops") ' 使用 do while 循环 - Console.WriteLine("7. Using For While Loops") ' 使用 for while 循环 + Console.WriteLine("6. Using Do While Loops") ' 使用 Do While 循环 + Console.WriteLine("7. Using For While Loops") ' 使用 For While 循环 Console.WriteLine("8. Conditional Statements") ' 条件语句 - Console.WriteLine("9. Select A Drink") ' 买饮料 + Console.WriteLine("9. Select A Drink") ' 选饮料 Console.WriteLine("50. About") ' 关于 Console.WriteLine("Please Choose A Number From The Above List") Dim selection As String = Console.ReadLine @@ -61,7 +61,7 @@ Module Module1 Case "9" ' If/Else 条件语句 Console.Clear() IfElseStatement() ' 选饮料 - Case "50" ' 关于 + Case "50" ' 关于本程序和作者 Console.Clear() Console.Title = ("Learn X in Y Minutes :: About") MsgBox("This tutorial is by Brian Martin (@BrianMartinn") @@ -81,7 +81,9 @@ Module Module1 ' 使用 Console.Write("") 或者 Console.WriteLine("") 来输出文本到屏幕上 ' 对应的 Console.Read() 或 Console.Readline() 用来读取键盘输入 Console.WriteLine("Hello World") - Console.ReadLine() + Console.ReadLine() + ' Console.WriteLine()后加Console.ReadLine()是为了防止屏幕输出信息一闪而过 + ' 类似平时常见的“单击任意键继续”的意思。 End Sub ' 二 @@ -93,11 +95,11 @@ Module Module1 ' 此教程中,我们希望知道你的姓名,并让程序记录并输出。 Dim username As String - ' 我们使用字符串类型(String)来记录文本信息。 + ' 我们定义username使用字符串类型(String)来记录用户姓名。 Console.WriteLine("Hello, What is your name? ") ' 询问用户输入姓名 - username = Console.ReadLine() 'Stores the users name. - Console.WriteLine("Hello " + username) ' 输出将是 Hello '姓名' - Console.ReadLine() 'Outsputs the above. + username = Console.ReadLine() ' 存储用户名到变量 username + Console.WriteLine("Hello " + username) ' 输出将是 Hello + username + Console.ReadLine() ' 暂停屏幕并显示以上输出 ' 以上程序将询问你的姓名,并和你打招呼。 ' 其它变量如整型(Integer)我们用整型来处理整数。 End Sub @@ -166,7 +168,7 @@ Module Module1 ' 这次我们将询问用户是否继续 (Yes or No?) ' 我们将使用Do While循环,因为我们不知到用户是否需要使用一次以上。 Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes" - Dim answer As String 'We use the variable "String" as the answer is text + Dim answer As String ' 我们使用字符串变量来存储answer(答案) Do ' 循环开始 Console.Write("First number: ") Dim a As Double = Console.ReadLine @@ -201,7 +203,7 @@ Module Module1 ' 这个程序我们将实现从10倒数计数. Console.Title = "Using For Loops | Learn X in Y Minutes" - ' 声明变量和步长(即递减的速度,如-1,-2,-3等)。 + ' 声明变量和Step (步长,即递减的速度,如-1,-2,-3等)。 For i As Integer = 10 To 0 Step -1 Console.WriteLine(i.ToString) ' 将计数结果输出的屏幕 Next i ' 计算新的i值 @@ -230,11 +232,11 @@ Module Module1 Private Sub IfElseStatement() Console.Title = "If / Else Statement | Learn X in Y Minutes" ' 有时候我们需要考虑多于两种情况。 - ' 这时我们就需要使用If条件语句。 + ' 这时我们就需要使用If/ElesIf条件语句。 ' If语句就好似个自动售货机,当用户输入A1,A2,A3,等去选择物品时, ' 所有的选择可以合并到一个If语句中 - Dim selection As String = Console.ReadLine 'Value for selection + Dim selection As String = Console.ReadLine() ' 读入用户选择 Console.WriteLine("A1. for 7Up") ' A1 七喜 Console.WriteLine("A2. for Fanta") ' A2 芬达 Console.WriteLine("A3. for Dr. Pepper") ' A3 胡椒医生 -- cgit v1.2.3 From 06328316d1eee3c578ab66d7d36742c7d3c14887 Mon Sep 17 00:00:00 2001 From: dev-sala Date: Wed, 26 Feb 2014 18:17:19 +0100 Subject: Updated classes name and other -> Middle relase [java/it-it] - Java translation * Completed translation of classes names, variables names ... fixed some errors --- it-it/java.html.markdown | 115 ++++++++++++++++++++++++----------------------- 1 file changed, 58 insertions(+), 57 deletions(-) diff --git a/it-it/java.html.markdown b/it-it/java.html.markdown index afd41af5..702977d3 100644 --- a/it-it/java.html.markdown +++ b/it-it/java.html.markdown @@ -93,7 +93,7 @@ public class LearnJava { // final - Costanti, non possono essere riassegnate ad un altro oggetto final int HOURS_I_WORK_PER_WEEK = 9001; - // Stringhe [String] + // String - Stringhe, array di caratteri (char) String fooString = "Ecco una stringa!"; // \n è un carattere speciale che permette di andare a capo. @@ -300,15 +300,15 @@ public class LearnJava { // (Di seguito la definizione della classe Bicicletta) // Instanziare una nuova classe - Bicycle trek = new Bicycle(); + Bicicletta perocorso = new Bicicletta(); // Chiamare metodi - trek.speedUp(3); // Si usano sempre metodi set... get... - trek.setCadence(100); + perorso.velocità(3); // Si usano sempre metodi set... get... + percorso.setCadenza(100); // toString riporta la rappresenzazione dell'oggetto // come se fosse una stringa - System.out.println("trek info: " + trek.toString()); + System.out.println("percorso info: " + percorso.toString()); } // Fine metodo main } // Fine classe LearnJava @@ -326,136 +326,137 @@ public class LearnJava { class Bicicletta { // Variabili della bicicletta - public int cadence; + public int cadenza; // Public: Può essere richiamato da qualsiasi classe - private int speed; + private int velocità; // Private: è accessibile solo dalla classe dove è stato inizializzato - protected int gear; + protected int ingranaggi; // Protected: è visto sia dalla classe che dalle sottoclassi - String name; + String nome; // default: è accessibile sono all'interno dello stesso package // I costruttori vengono usati per creare variabili // Questo è un costruttore public Bicicletta() { ingranaggi = 1; - ritmo = 50; + cadenza = 50; velocità = 5; nome = "Bontrager"; } // Questo è un costruttore che richiede parametri - public Bicycle(int startCadence, int startSpeed, int startGear, String name) { - this.gear = startGear; - this.cadence = startCadence; - this.speed = startSpeed; - this.name = name; + public Bicicletta(int cadenzaIniziale, int velocitàIniziale, int ingranaggiIniziali, String nome) { + this.ingranaggi = ingranaggiIniziali; + this.cadenza = CadenzaIniziale; + this.velocità = VelocitàIniziale; + this.nome = nome; } // Sintassi delle funzioni: - // () + // () // Le classi in java spesso implementano delle funzioni o metodo // 'get...' o 'set...' // Dichiarazione di un metodo - // () - public int getCadence() { - return cadence; + // () + public int getCandenza() { + return cadenza; } // i medodi (void) non necessitano di riportare un valore - public void setCadence(int newValue) { - cadence = newValue; + public void setCadenza(int nuovoValore) { + cadenza = nuovoValore; } - public void setGear(int newValue) { - gear = newValue; + public void setIngranaggi(int nuovoValore) { + ingranaggi = nuovoValore; } - public void speedUp(int increment) { - speed += increment; + public void accellera(int incrementa) { + velocità += incrementa; } - public void slowDown(int decrement) { - speed -= decrement; + public void decellera(int decrementa) { + velocità -= decrementa; } - public void setName(String newName) { - name = newName; + public void setNome(String nuovoNome) { + nome = nuovoNome; } - public String getName() { - return name; + public String getNome() { + return nome; } //Medoto per visualizzare gli attributi dell'oggetto @Override public String toString() { - return "gear: " + gear + - " cadence: " + cadence + - " speed: " + speed + - " name: " + name; + return "Ingranaggi: " + ingranaggi + + " Cadenza: " + cadenza + + " Velocità: " + velocità + + " Nome: " + nome; } } // Fine classe bicicletta // PennyFarthing è una sottoclasse della bicicletta -class PennyFarthing extends Bicycle { +class PennyFarthing extends Bicicletta { // (Sono quelle biciclette con un unica ruota enorme // Non hanno ingranaggi.) - public PennyFarthing(int startCadence, int startSpeed){ + public PennyFarthing(int cadenzaIniziale, int velocitàIniziale){ // Richiamo il costruttore del padre con super - super(startCadence, startSpeed, 0, "PennyFarthing"); + super(cadenzaIniziale, velocitàIniziale, 0, "PennyFarthing"); } - // You should mark a method you're overriding with an @annotation // Bisogna contrassegnre un medodo che si sta riscrivendo // con una @annotazione // Per saperne di più sulle annotazioni // Vedi la guida: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override - public void setGear(int gear) { - gear = 0; + public void setIngranaggi(int ingranaggi) { + ingranaggi = 0; } } -//Interfaccie +//Interfacce //Sintassi per dichiarare una interfaccia -// interface extends { -// //Constants -// //Method declarations +// interface extends { +// //Costanti +// //Dichiarazioni dei metodi //} -//Example - Food: -public interface Edible { - public void eat(); //Any class that implements this interface, must implement this method -} +//Esempi- Cibo: +public interface Commestribile { + public void mangia(); + //Ogni classe che implementa questa interfaccia + //deve implementare questo metodo. + } -public interface Digestible { - public void digest(); +public interface Digestibile { + public void digerisci(); } //Possiamo quindi creare una classe che implementa entrambe le interfaccie -public class Fruit implements Edible, Digestible { - public void eat() { +public class Frutta implements Edible, Digestible { + public void mangia() { //... } - public void digest() { + public void digerisci() { //... } } //In Java si può estendere solo una classe, ma si possono implementare //più interfaccie, per esempio: -public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { - public void InterfaceOneMethod() { +public class ClasseEsempio extends AltraClasse implements PrimaInterfaccia, SecondaInterfaccia { + public void MetodoPrimaInterfaccia() { } - public void InterfaceTwoMethod() { + public void MetodoSecondaInterfaccia() { } } -- cgit v1.2.3 From bceeba2040cb292d3746262ce0e7d43392eb5dfd Mon Sep 17 00:00:00 2001 From: Marco Scannadinari Date: Wed, 26 Feb 2014 21:22:39 +0000 Subject: Add missing semicolons --- css.html.markdown | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index 26eaae53..76319340 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -2,6 +2,7 @@ language: css contributors: - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] filename: learncss.css --- @@ -129,11 +130,11 @@ selector { width: 5in; /* in inches */ /* Colors */ - background-color: #F6E /* in short hex */ - background-color: #F262E2 /* in long hex format */ - background-color: tomato /* can be a named color */ - background-color: rgb(255, 255, 255) /* in rgb */ - background-color: rgb(10%, 20%, 50%) /* in rgb percent */ + background-color: #F6E; /* in short hex */ + background-color: #F262E2; /* in long hex format */ + background-color: tomato; /* can be a named color */ + background-color: rgb(255, 255, 255); /* in rgb */ + background-color: rgb(10%, 20%, 50%); /* in rgb percent */ background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb */ /* Images */ -- cgit v1.2.3 From 54c3e392379b57786129ef80f816d71416415b35 Mon Sep 17 00:00:00 2001 From: Ivan Sala Date: Thu, 27 Feb 2014 17:05:26 +0100 Subject: Fixed all -> Final relase fixed names, italians sentencens, compile&exec things and so on. now imho this can be merged. --- it-it/java.html.markdown | 124 +++++++++++++++++++++++------------------------ 1 file changed, 61 insertions(+), 63 deletions(-) diff --git a/it-it/java.html.markdown b/it-it/java.html.markdown index 702977d3..b41c7457 100644 --- a/it-it/java.html.markdown +++ b/it-it/java.html.markdown @@ -15,13 +15,13 @@ Java è un linguaggio di programmazione orientato ad oggetti, concorrente, basato su classi e adatto a svariati scopi. [Per saperne di più](http://docs.oracle.com/javase/tutorial/java/index.html) -```java +```Java // I commenti su singola linea incominciano con // /* -I commenti su più linee invece sono così +I commenti su piu' linee invece sono cosi' */ /** -I commenti per la documentazione JavaDoc si fanno così. +I commenti per la documentazione JavaDoc si fanno cosi'. Vengono usati per descrivere una classe o alcuni suoi attributi. */ @@ -34,6 +34,8 @@ import java.security.*; public class LearnJava { // Un programma deve avere un metodo main come punto di partenza + // Ma si possono creare anche file senza main, che però per essere usati + // devono essere richiamati da altri file. public static void main (String[] args) { // Per stampare a schermo si usa System.out.println @@ -43,9 +45,9 @@ public class LearnJava { " Reale [double]: " + 3.14 + " Booleano [boolean]: " + true); - // Se non si vuole andare a capo, si può usare System.out.print + // Se non si vuole andare a capo, si puo' usare System.out.print System.out.print("Ciao "); - System.out.print("Mondo"); + System.out.print("Mondo "); /////////////////////////////////////// @@ -68,18 +70,18 @@ public class LearnJava { // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) long fooLong = 100000L; // L viene usato per specificare che il valore dalla variabile - // è di tipo "Long", qualsiasi variabile che non viene contrassegnata - // è trattata di base come un intero. + // e' di tipo "Long", qualsiasi variabile che non viene contrassegnata + // e' trattata di base come un intero. // Nota: Java non dispone di variabili senza segno - // Float - variabile più precisa, con virgola [numeri reali] + // Float - variabile piu' precisa, con virgola [numeri reali] // di grandezza 32 bit float fooFloat = 234.5f; - // f è usato per specificare che la variabile è di tipo "float" - // altrimenti da default viene trattata come "dobule" + // f e' usato per specificare che la variabile e'' di tipo "float" + // altrimenti di default viene trattata come un "dobule" - // Double - ancora più precisione la si può ottenere con una variabile + // Double - ancora piu' precisione la si puo' ottenere con una variabile // Double, con granzezza di 64 bit. double fooDouble = 123.4; @@ -93,12 +95,12 @@ public class LearnJava { // final - Costanti, non possono essere riassegnate ad un altro oggetto final int HOURS_I_WORK_PER_WEEK = 9001; - // String - Stringhe, array di caratteri (char) + // String - Stringhe, array di caratteri String fooString = "Ecco una stringa!"; - // \n è un carattere speciale che permette di andare a capo. + // \n e' un carattere speciale che permette di andare a capo. String barString = "Printing on a new line?\nNo Problem!"; - // \t è un carattere speciale che permette di aggiungere un 'Tab' + // \t e' un carattere speciale che permette di aggiungere un 'Tab' String bazString = "Do you want to add a tab?\tNo Problem!"; System.out.println(fooString); System.out.println(barString); @@ -106,7 +108,7 @@ public class LearnJava { // Vettori [array] //La lunghezza del vettore deve essere decisa quando viene istanziato - //Si può dichiarare come segue: + //Si puo' dichiarare come segue: // [] = new []; // [] = new []; int [] intArray = new int[10]; @@ -117,18 +119,17 @@ public class LearnJava { int [] y = {9000, 1000, 1337}; String nomi [] = {"Andrea", "Bob", "Pippo", "Susan"}; boolean bools[] = new boolean[] {true, false, false}; - - // Accesso diretto ad un elemento + + // I vettori vengono indicizzati a parire dallo 0 System.out.println("intArray @ 0: " + intArray[0]); - // I vettori vengono indicizzati a parire dallo 0 - // Ma questo indice può essere cambiato. + // e' possibile un accesso diretto ad un elemento intArray[1] = 1; System.out.println("intArray @ 1: " + intArray[1]); // => 1 // Altro da vedere: - // Liste di array - come i vettori ma più funzionali - // e la loro grandezza può variare in corso di esecuzione + // Liste di array - come i vettori ma piu' funzionali + // e la loro grandezza puo' variare in corso di esecuzione // Liste concatenate di memoria /////////////////////////////////////// @@ -138,7 +139,7 @@ public class LearnJava { int i1 = 1, i2 = 2; // Dichiarazone multipla in contemporanea - // L'aritmetica è lineare. + // L'aritmetica e' lineare. System.out.println("1+2 = " + (i1 + i2)); // => 3 System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 @@ -184,7 +185,7 @@ public class LearnJava { /////////////////////////////////////// System.out.println("\n->Strutture di controllo"); - // La dichiarazione dell'If è C-like. + // La dichiarazione dell'If e'' C-like. int j = 10; if (j == 10){ System.out.println("Io vengo stampato"); @@ -239,7 +240,7 @@ public class LearnJava { // Struttura Switch Case // La struttura switch lavora con byte, short, char e int. - // Se funziona con i char funzionerà ovviamente anche con le stringhe. + // Se funziona con i char funzionera ovviamente anche con le stringhe. int mese = 3; String stringaMese; switch (mese){ @@ -247,7 +248,7 @@ public class LearnJava { stringaMese = "Genneio"; break; case 2: - strigaMese = "Febbraio"; + stringaMese = "Febbraio"; break; case 3: stringaMese = "Marzo"; @@ -256,16 +257,17 @@ public class LearnJava { stringaMese = "Altri mesi"; break; } - System.out.println("Risultato del costrutto switch:: " + stringaMese); + System.out.println("Risultato del costrutto switch: " + stringaMese); // Condizioni brevi - // Si può usare l'operatore '?' per un rapido assegnamento + // Si puo' usare l'operatore '?' per un rapido assegnamento // o per operazioni logiche. // Si legge: - // Se (condizione) è vera, usa , altrimenti usa + // Se (condizione) e' vera, usa , altrimenti usa int foo = 5; String bar = (foo < 10) ? "A" : "B"; - System.out.println(bar); // Stampa A, perchè la condizione è vera. + System.out.println("Se la condizione e' vera stampa A: "+bar); + // Stampa A, perche' la condizione e' vera. ///////////////////////////////////////// @@ -300,10 +302,10 @@ public class LearnJava { // (Di seguito la definizione della classe Bicicletta) // Instanziare una nuova classe - Bicicletta perocorso = new Bicicletta(); + Bicicletta percorso = new Bicicletta(); // Chiamare metodi - perorso.velocità(3); // Si usano sempre metodi set... get... + percorso.accellera(3); // Si usano sempre metodi set... get... percorso.setCadenza(100); // toString riporta la rappresenzazione dell'oggetto @@ -327,28 +329,28 @@ class Bicicletta { // Variabili della bicicletta public int cadenza; - // Public: Può essere richiamato da qualsiasi classe - private int velocità; - // Private: è accessibile solo dalla classe dove è stato inizializzato + // Public: Puo' essere richiamato da qualsiasi classe + private int velocita; + // Private: e'' accessibile solo dalla classe dove e'' stato inizializzato protected int ingranaggi; - // Protected: è visto sia dalla classe che dalle sottoclassi + // Protected: e'' visto sia dalla classe che dalle sottoclassi String nome; - // default: è accessibile sono all'interno dello stesso package + // default: e'' accessibile sono all'interno dello stesso package // I costruttori vengono usati per creare variabili - // Questo è un costruttore + // Questo e'' un costruttore public Bicicletta() { ingranaggi = 1; cadenza = 50; - velocità = 5; + velocita = 5; nome = "Bontrager"; } - // Questo è un costruttore che richiede parametri - public Bicicletta(int cadenzaIniziale, int velocitàIniziale, int ingranaggiIniziali, String nome) { - this.ingranaggi = ingranaggiIniziali; - this.cadenza = CadenzaIniziale; - this.velocità = VelocitàIniziale; + // Questo e'' un costruttore che richiede parametri + public Bicicletta(int cadenza, int velocita, int ingranaggi, String nome) { + this.ingranaggi = ingranaggi; + this.cadenza = cadenza; + this.velocita = velocita; this.nome = nome; } @@ -374,11 +376,11 @@ class Bicicletta { } public void accellera(int incrementa) { - velocità += incrementa; + velocita += incrementa; } public void decellera(int decrementa) { - velocità -= decrementa; + velocita -= decrementa; } public void setNome(String nuovoNome) { @@ -394,24 +396,24 @@ class Bicicletta { public String toString() { return "Ingranaggi: " + ingranaggi + " Cadenza: " + cadenza + - " Velocità: " + velocità + + " Velocita: " + velocita + " Nome: " + nome; } } // Fine classe bicicletta -// PennyFarthing è una sottoclasse della bicicletta +// PennyFarthing e'' una sottoclasse della bicicletta class PennyFarthing extends Bicicletta { // (Sono quelle biciclette con un unica ruota enorme // Non hanno ingranaggi.) - public PennyFarthing(int cadenzaIniziale, int velocitàIniziale){ + public PennyFarthing(int cadenzaIniziale, int velocitaIniziale){ // Richiamo il costruttore del padre con super - super(cadenzaIniziale, velocitàIniziale, 0, "PennyFarthing"); + super(cadenzaIniziale, velocitaIniziale, 0, "PennyFarthing"); } // Bisogna contrassegnre un medodo che si sta riscrivendo // con una @annotazione - // Per saperne di più sulle annotazioni + // Per saperne di piu' sulle annotazioni // Vedi la guida: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setIngranaggi(int ingranaggi) { @@ -419,27 +421,26 @@ class PennyFarthing extends Bicicletta { } } - +/* //Interfacce //Sintassi per dichiarare una interfaccia // interface extends { -// //Costanti +// //Costanti // //Dichiarazioni dei metodi //} //Esempi- Cibo: -public interface Commestribile { +interface Commestibile { public void mangia(); //Ogni classe che implementa questa interfaccia //deve implementare questo metodo. } - -public interface Digestibile { +interface Digeribile { public void digerisci(); } //Possiamo quindi creare una classe che implementa entrambe le interfaccie -public class Frutta implements Edible, Digestible { +class Frutta implements Commestibile, Digestibile { public void mangia() { //... } @@ -449,9 +450,9 @@ public class Frutta implements Edible, Digestible { } } -//In Java si può estendere solo una classe, ma si possono implementare -//più interfaccie, per esempio: -public class ClasseEsempio extends AltraClasse implements PrimaInterfaccia, SecondaInterfaccia { +//In Java si puo' estendere solo una classe, ma si possono implementare +//piu' interfaccie, per esempio: +class ClasseEsempio extends AltraClasse implements PrimaInterfaccia, SecondaInterfaccia { public void MetodoPrimaInterfaccia() { } @@ -460,9 +461,8 @@ public class ClasseEsempio extends AltraClasse implements PrimaInterfaccia, Seco } } - +*/ ``` - ## Letture future I link di seguito sono solo per capire l'argomento, cerca pure su Google degli esempi specifici @@ -502,5 +502,3 @@ I link di seguito sono solo per capire l'argomento, cerca pure su Google degli e * [Thinking in java](http://www.amazon.it/Thinking-Java-1-Bruce-Eckel/dp/8871923030/ref=sr_1_8?ie=UTF8&qid=1393422296&sr=8-8&keywords=java) * [Manuale di Java 7](http://www.amazon.com/gp/product/0071606300) - - -- cgit v1.2.3 From 9c081a7a65a1855253e706e916f4a6a83a7c6d9b Mon Sep 17 00:00:00 2001 From: Ivan Sala Date: Thu, 27 Feb 2014 17:09:27 +0100 Subject: Update java.html.markdown --- it-it/java.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/it-it/java.html.markdown b/it-it/java.html.markdown index b41c7457..4854fc73 100644 --- a/it-it/java.html.markdown +++ b/it-it/java.html.markdown @@ -39,7 +39,7 @@ public class LearnJava { public static void main (String[] args) { // Per stampare a schermo si usa System.out.println - System.out.println("Hello World!"); + System.out.println("Ciao Mondo!"); System.out.println( "Intero [integer]: " + 10 + " Reale [double]: " + 3.14 + @@ -93,15 +93,15 @@ public class LearnJava { char fooChar = 'A'; // final - Costanti, non possono essere riassegnate ad un altro oggetto - final int HOURS_I_WORK_PER_WEEK = 9001; + final int ORE_LAVORATIVE_DI_UNA_SETTIMANA = 9001; // String - Stringhe, array di caratteri String fooString = "Ecco una stringa!"; // \n e' un carattere speciale che permette di andare a capo. - String barString = "Printing on a new line?\nNo Problem!"; + String barString = "Andare a capo?\nNessun problema!"; // \t e' un carattere speciale che permette di aggiungere un 'Tab' - String bazString = "Do you want to add a tab?\tNo Problem!"; + String bazString = "Vuoi inserire tab?\tNessun problema"; System.out.println(fooString); System.out.println(barString); System.out.println(bazString); @@ -495,7 +495,7 @@ I link di seguito sono solo per capire l'argomento, cerca pure su Google degli e * [Codingbat.com](http://codingbat.com/java) -**Libri [in italiano] **: +**Libri [in italiano]** : * [Java la guida completa](http://www.amazon.it/Java-guida-completa-Herbert-Schildt/dp/8838667667/ref=sr_1_1?ie=UTF8&qid=1393422296&sr=8-1&keywords=java) -- cgit v1.2.3 From 12c8e5ca321a5423e93c3ae58dbda12b9a8d3397 Mon Sep 17 00:00:00 2001 From: Ivan Sala Date: Thu, 27 Feb 2014 21:16:30 +0100 Subject: Rename java.html.markdown to java-it.html.markdown --- it-it/java-it.html.markdown | 504 ++++++++++++++++++++++++++++++++++++++++++++ it-it/java.html.markdown | 504 -------------------------------------------- 2 files changed, 504 insertions(+), 504 deletions(-) create mode 100644 it-it/java-it.html.markdown delete mode 100644 it-it/java.html.markdown diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown new file mode 100644 index 00000000..4854fc73 --- /dev/null +++ b/it-it/java-it.html.markdown @@ -0,0 +1,504 @@ +--- + +language: java +filename: LearnJava.java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Madison Dickson", "http://github.com/mix3d"] +translators: + - ["Ivan Sala","http://github.com/dev-sala"] +lang: it-it + +--- + +Java è un linguaggio di programmazione orientato ad oggetti, +concorrente, basato su classi e adatto a svariati scopi. +[Per saperne di più](http://docs.oracle.com/javase/tutorial/java/index.html) + +```Java +// I commenti su singola linea incominciano con // +/* +I commenti su piu' linee invece sono cosi' +*/ +/** +I commenti per la documentazione JavaDoc si fanno cosi'. +Vengono usati per descrivere una classe o alcuni suoi attributi. +*/ + +// Per importare la classe ArrayList conenuta nel package java.util +import java.util.ArrayList; +// Per importare tutte le classi contenute nel package java.security +import java.security.*; + +// Ogni file .java contiene una classe pubblica, con lo stesso nome del file +public class LearnJava { + + // Un programma deve avere un metodo main come punto di partenza + // Ma si possono creare anche file senza main, che però per essere usati + // devono essere richiamati da altri file. + public static void main (String[] args) { + + // Per stampare a schermo si usa System.out.println + System.out.println("Ciao Mondo!"); + System.out.println( + "Intero [integer]: " + 10 + + " Reale [double]: " + 3.14 + + " Booleano [boolean]: " + true); + + // Se non si vuole andare a capo, si puo' usare System.out.print + System.out.print("Ciao "); + System.out.print("Mondo "); + + + /////////////////////////////////////// + // Tipi e Variabili + /////////////////////////////////////// + // Si dichiara una variabile usando + // Byte - variabile intera da 8 bit con segno + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - variabile intera da 18 bit con segno + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - variabile intera da 32 bit con segno + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - variabile da 64 bit intera con segno + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L viene usato per specificare che il valore dalla variabile + // e' di tipo "Long", qualsiasi variabile che non viene contrassegnata + // e' trattata di base come un intero. + + // Nota: Java non dispone di variabili senza segno + + // Float - variabile piu' precisa, con virgola [numeri reali] + // di grandezza 32 bit + float fooFloat = 234.5f; + // f e' usato per specificare che la variabile e'' di tipo "float" + // altrimenti di default viene trattata come un "dobule" + + // Double - ancora piu' precisione la si puo' ottenere con una variabile + // Double, con granzezza di 64 bit. + double fooDouble = 123.4; + + // Boolean - vero & falso + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - un singolo carattere con grandezza 16 bit + char fooChar = 'A'; + + // final - Costanti, non possono essere riassegnate ad un altro oggetto + final int ORE_LAVORATIVE_DI_UNA_SETTIMANA = 9001; + + // String - Stringhe, array di caratteri + String fooString = "Ecco una stringa!"; + + // \n e' un carattere speciale che permette di andare a capo. + String barString = "Andare a capo?\nNessun problema!"; + // \t e' un carattere speciale che permette di aggiungere un 'Tab' + String bazString = "Vuoi inserire tab?\tNessun problema"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Vettori [array] + //La lunghezza del vettore deve essere decisa quando viene istanziato + //Si puo' dichiarare come segue: + // [] = new []; + // [] = new []; + int [] intArray = new int[10]; + String [] stringArray = new String[1]; + boolean boolArray [] = new boolean[100]; + + // Un altro modo per dichiarare & inizializzare un vettore + int [] y = {9000, 1000, 1337}; + String nomi [] = {"Andrea", "Bob", "Pippo", "Susan"}; + boolean bools[] = new boolean[] {true, false, false}; + + // I vettori vengono indicizzati a parire dallo 0 + System.out.println("intArray @ 0: " + intArray[0]); + + // e' possibile un accesso diretto ad un elemento + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Altro da vedere: + // Liste di array - come i vettori ma piu' funzionali + // e la loro grandezza puo' variare in corso di esecuzione + // Liste concatenate di memoria + + /////////////////////////////////////// + // Operatori + /////////////////////////////////////// + System.out.println("\n->Operatori"); + + int i1 = 1, i2 = 2; // Dichiarazone multipla in contemporanea + + // L'aritmetica e' lineare. + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 + // (con 0.5 arrotonda per difetto) + + // Modulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Operatori di confronto + System.out.println("3 == 2? " + (3 == 2)); // => falso + System.out.println("3 != 2? " + (3 != 2)); // => vero + System.out.println("3 > 2? " + (3 > 2)); // => vero + System.out.println("3 < 2? " + (3 < 2)); // => falso + System.out.println("2 <= 2? " + (2 <= 2)); // => vero + System.out.println("2 >= 2? " + (2 >= 2)); // => vero + + // Operatori binari orientati ai bit + // effettuano le operazioni logiche confrontando, i bit degli operandi: + /* + ~ complemento + << shift sinistro con segno + >> shift destro con segno + >>> shift destro senza segno + & AND Binario Bitwise AND + ^ OR Esclusivo + | OR Incusivo + */ + + // Incrementare e Decrementare + int i = 0; + System.out.println("\n->Incrementare/Decrementare"); + // Gli operatori ++ e -- incrementano e decrementano rispettivamente di 1. + // Se posizionati prima della variabile, incrementano, quindi riportano. + // Se si trovano dopo la variabile, riporano, e quindi incrementano. + System.out.println(i++); //i = 1, Stampa 0 (post-incremento) + System.out.println(++i); //i = 2, Stampa 2 (pre-incremento) + System.out.println(i--); //i = 1, Stampa 2 (post-decremento) + System.out.println(--i); //i = 0, Stampa 0 (pre-decremento) + + /////////////////////////////////////// + // Strutture di controllo + /////////////////////////////////////// + System.out.println("\n->Strutture di controllo"); + + // La dichiarazione dell'If e'' C-like. + int j = 10; + if (j == 10){ + System.out.println("Io vengo stampato"); + } else if (j > 10) { + System.out.println("Io no"); + } else { + System.out.println("E io neppure"); + } + + // Struttura While + int fooWhile = 0; + while(fooWhile < 100) + { + //System.out.println(fooWhile); + //Incrementa il contatore + //Si ripete per 100 volte, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("Valore di fooWhile: " + fooWhile); + + // Struttura Do While + int fooDoWhile = 0; + do + { + //System.out.println(fooDoWhile); + //Incrementa il contaore + //Si repete per 99 volte, fooDoWhile 0->99 + fooDoWhile++; + }while(fooDoWhile < 100); + System.out.println("Valore di fooWhile: " + fooDoWhile); + + // Struttura For + int fooFor; + //Struttura For => for(; ; ) + for(fooFor=0; fooFor<10; fooFor++){ + //System.out.println(fooFor); + //Itera 10 volte, fooFor 0->9 + } + System.out.println("Valore di fooFor: " + fooFor); + + // Struttura For Each + // Una iterazione automatica attraverso un array o una lista di oggetti + int[] fooList = {1,2,3,4,5,6,7,8,9}; + //struttura for each => for( : ) + //si legge: per ogni oggetto dell'array fai... + //Nota: il tipo dell'oggetto deve essere uguale a quello dell'array + + for( int bar : fooList ){ + //System.out.println(bar); + //Itera 9 volte e stampa 1-9 andando a capo. + } + + // Struttura Switch Case + // La struttura switch lavora con byte, short, char e int. + // Se funziona con i char funzionera ovviamente anche con le stringhe. + int mese = 3; + String stringaMese; + switch (mese){ + case 1: + stringaMese = "Genneio"; + break; + case 2: + stringaMese = "Febbraio"; + break; + case 3: + stringaMese = "Marzo"; + break; + default: + stringaMese = "Altri mesi"; + break; + } + System.out.println("Risultato del costrutto switch: " + stringaMese); + + // Condizioni brevi + // Si puo' usare l'operatore '?' per un rapido assegnamento + // o per operazioni logiche. + // Si legge: + // Se (condizione) e' vera, usa , altrimenti usa + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println("Se la condizione e' vera stampa A: "+bar); + // Stampa A, perche' la condizione e' vera. + + + ///////////////////////////////////////// + // Convertire i tipi di tati e Typcasting + ///////////////////////////////////////// + + // Convertire tipi di dati + + // Stringhe ad interi + Integer.parseInt("123");//Riporta una versione intera di "123" + + // Interi a Stringhe + Integer.toString(123);//Riporta la stringa "123" + // Per altre conversioni guarda le seguenti classi + // Double + // Long + // String + + // Typecasting + // Vi sono molti dettagli che non si possono spiegare qui, + // java dispone di una ottima documentazione + // Sentiti libero di leggerla + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Classi e funzioni + /////////////////////////////////////// + + System.out.println("\n->Classi & Funzioni"); + + // (Di seguito la definizione della classe Bicicletta) + + // Instanziare una nuova classe + Bicicletta percorso = new Bicicletta(); + + // Chiamare metodi + percorso.accellera(3); // Si usano sempre metodi set... get... + percorso.setCadenza(100); + + // toString riporta la rappresenzazione dell'oggetto + // come se fosse una stringa + System.out.println("percorso info: " + percorso.toString()); + + } // Fine metodo main +} // Fine classe LearnJava + + +// Si possono inculdere altre anche delle classi non pubbliche (private) +// oltre a quella pubblica principale, in un file .java + +// Sintassi per dichiarare una classe: +// class { +// //dati, variabili, costruttori, funzioni, tutto qua. +// //le funzioni sono chiamate come i metodi. +// } + +class Bicicletta { + + // Variabili della bicicletta + public int cadenza; + // Public: Puo' essere richiamato da qualsiasi classe + private int velocita; + // Private: e'' accessibile solo dalla classe dove e'' stato inizializzato + protected int ingranaggi; + // Protected: e'' visto sia dalla classe che dalle sottoclassi + String nome; + // default: e'' accessibile sono all'interno dello stesso package + + // I costruttori vengono usati per creare variabili + // Questo e'' un costruttore + public Bicicletta() { + ingranaggi = 1; + cadenza = 50; + velocita = 5; + nome = "Bontrager"; + } + + // Questo e'' un costruttore che richiede parametri + public Bicicletta(int cadenza, int velocita, int ingranaggi, String nome) { + this.ingranaggi = ingranaggi; + this.cadenza = cadenza; + this.velocita = velocita; + this.nome = nome; + } + + // Sintassi delle funzioni: + // () + + // Le classi in java spesso implementano delle funzioni o metodo + // 'get...' o 'set...' + + // Dichiarazione di un metodo + // () + public int getCandenza() { + return cadenza; + } + + // i medodi (void) non necessitano di riportare un valore + public void setCadenza(int nuovoValore) { + cadenza = nuovoValore; + } + + public void setIngranaggi(int nuovoValore) { + ingranaggi = nuovoValore; + } + + public void accellera(int incrementa) { + velocita += incrementa; + } + + public void decellera(int decrementa) { + velocita -= decrementa; + } + + public void setNome(String nuovoNome) { + nome = nuovoNome; + } + + public String getNome() { + return nome; + } + + //Medoto per visualizzare gli attributi dell'oggetto + @Override + public String toString() { + return "Ingranaggi: " + ingranaggi + + " Cadenza: " + cadenza + + " Velocita: " + velocita + + " Nome: " + nome; + } +} // Fine classe bicicletta + +// PennyFarthing e'' una sottoclasse della bicicletta +class PennyFarthing extends Bicicletta { + // (Sono quelle biciclette con un unica ruota enorme + // Non hanno ingranaggi.) + + public PennyFarthing(int cadenzaIniziale, int velocitaIniziale){ + // Richiamo il costruttore del padre con super + super(cadenzaIniziale, velocitaIniziale, 0, "PennyFarthing"); + } + + // Bisogna contrassegnre un medodo che si sta riscrivendo + // con una @annotazione + // Per saperne di piu' sulle annotazioni + // Vedi la guida: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setIngranaggi(int ingranaggi) { + ingranaggi = 0; + } + +} +/* +//Interfacce +//Sintassi per dichiarare una interfaccia +// interface extends { +// //Costanti +// //Dichiarazioni dei metodi +//} + +//Esempi- Cibo: +interface Commestibile { + public void mangia(); + //Ogni classe che implementa questa interfaccia + //deve implementare questo metodo. + } +interface Digeribile { + public void digerisci(); +} + +//Possiamo quindi creare una classe che implementa entrambe le interfaccie +class Frutta implements Commestibile, Digestibile { + public void mangia() { + //... + } + + public void digerisci() { + //... + } +} + +//In Java si puo' estendere solo una classe, ma si possono implementare +//piu' interfaccie, per esempio: +class ClasseEsempio extends AltraClasse implements PrimaInterfaccia, SecondaInterfaccia { + public void MetodoPrimaInterfaccia() { + + } + + public void MetodoSecondaInterfaccia() { + + } +} +*/ +``` +## Letture future + +I link di seguito sono solo per capire l'argomento, cerca pure su Google degli esempi specifici + + +**Guida ufficiale di Oracle [solo in inglese]**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + + +**Tutorial Online [in inglese]** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Libri [in italiano]** : + +* [Java la guida completa](http://www.amazon.it/Java-guida-completa-Herbert-Schildt/dp/8838667667/ref=sr_1_1?ie=UTF8&qid=1393422296&sr=8-1&keywords=java) + +* [Thinking in java](http://www.amazon.it/Thinking-Java-1-Bruce-Eckel/dp/8871923030/ref=sr_1_8?ie=UTF8&qid=1393422296&sr=8-8&keywords=java) + +* [Manuale di Java 7](http://www.amazon.com/gp/product/0071606300) diff --git a/it-it/java.html.markdown b/it-it/java.html.markdown deleted file mode 100644 index 4854fc73..00000000 --- a/it-it/java.html.markdown +++ /dev/null @@ -1,504 +0,0 @@ ---- - -language: java -filename: LearnJava.java -contributors: - - ["Jake Prather", "http://github.com/JakeHP"] - - ["Madison Dickson", "http://github.com/mix3d"] -translators: - - ["Ivan Sala","http://github.com/dev-sala"] -lang: it-it - ---- - -Java è un linguaggio di programmazione orientato ad oggetti, -concorrente, basato su classi e adatto a svariati scopi. -[Per saperne di più](http://docs.oracle.com/javase/tutorial/java/index.html) - -```Java -// I commenti su singola linea incominciano con // -/* -I commenti su piu' linee invece sono cosi' -*/ -/** -I commenti per la documentazione JavaDoc si fanno cosi'. -Vengono usati per descrivere una classe o alcuni suoi attributi. -*/ - -// Per importare la classe ArrayList conenuta nel package java.util -import java.util.ArrayList; -// Per importare tutte le classi contenute nel package java.security -import java.security.*; - -// Ogni file .java contiene una classe pubblica, con lo stesso nome del file -public class LearnJava { - - // Un programma deve avere un metodo main come punto di partenza - // Ma si possono creare anche file senza main, che però per essere usati - // devono essere richiamati da altri file. - public static void main (String[] args) { - - // Per stampare a schermo si usa System.out.println - System.out.println("Ciao Mondo!"); - System.out.println( - "Intero [integer]: " + 10 + - " Reale [double]: " + 3.14 + - " Booleano [boolean]: " + true); - - // Se non si vuole andare a capo, si puo' usare System.out.print - System.out.print("Ciao "); - System.out.print("Mondo "); - - - /////////////////////////////////////// - // Tipi e Variabili - /////////////////////////////////////// - // Si dichiara una variabile usando - // Byte - variabile intera da 8 bit con segno - // (-128 <= byte <= 127) - byte fooByte = 100; - - // Short - variabile intera da 18 bit con segno - // (-32,768 <= short <= 32,767) - short fooShort = 10000; - - // Integer - variabile intera da 32 bit con segno - // (-2,147,483,648 <= int <= 2,147,483,647) - int fooInt = 1; - - // Long - variabile da 64 bit intera con segno - // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - long fooLong = 100000L; - // L viene usato per specificare che il valore dalla variabile - // e' di tipo "Long", qualsiasi variabile che non viene contrassegnata - // e' trattata di base come un intero. - - // Nota: Java non dispone di variabili senza segno - - // Float - variabile piu' precisa, con virgola [numeri reali] - // di grandezza 32 bit - float fooFloat = 234.5f; - // f e' usato per specificare che la variabile e'' di tipo "float" - // altrimenti di default viene trattata come un "dobule" - - // Double - ancora piu' precisione la si puo' ottenere con una variabile - // Double, con granzezza di 64 bit. - double fooDouble = 123.4; - - // Boolean - vero & falso - boolean fooBoolean = true; - boolean barBoolean = false; - - // Char - un singolo carattere con grandezza 16 bit - char fooChar = 'A'; - - // final - Costanti, non possono essere riassegnate ad un altro oggetto - final int ORE_LAVORATIVE_DI_UNA_SETTIMANA = 9001; - - // String - Stringhe, array di caratteri - String fooString = "Ecco una stringa!"; - - // \n e' un carattere speciale che permette di andare a capo. - String barString = "Andare a capo?\nNessun problema!"; - // \t e' un carattere speciale che permette di aggiungere un 'Tab' - String bazString = "Vuoi inserire tab?\tNessun problema"; - System.out.println(fooString); - System.out.println(barString); - System.out.println(bazString); - - // Vettori [array] - //La lunghezza del vettore deve essere decisa quando viene istanziato - //Si puo' dichiarare come segue: - // [] = new []; - // [] = new []; - int [] intArray = new int[10]; - String [] stringArray = new String[1]; - boolean boolArray [] = new boolean[100]; - - // Un altro modo per dichiarare & inizializzare un vettore - int [] y = {9000, 1000, 1337}; - String nomi [] = {"Andrea", "Bob", "Pippo", "Susan"}; - boolean bools[] = new boolean[] {true, false, false}; - - // I vettori vengono indicizzati a parire dallo 0 - System.out.println("intArray @ 0: " + intArray[0]); - - // e' possibile un accesso diretto ad un elemento - intArray[1] = 1; - System.out.println("intArray @ 1: " + intArray[1]); // => 1 - - // Altro da vedere: - // Liste di array - come i vettori ma piu' funzionali - // e la loro grandezza puo' variare in corso di esecuzione - // Liste concatenate di memoria - - /////////////////////////////////////// - // Operatori - /////////////////////////////////////// - System.out.println("\n->Operatori"); - - int i1 = 1, i2 = 2; // Dichiarazone multipla in contemporanea - - // L'aritmetica e' lineare. - System.out.println("1+2 = " + (i1 + i2)); // => 3 - System.out.println("2-1 = " + (i2 - i1)); // => 1 - System.out.println("2*1 = " + (i2 * i1)); // => 2 - System.out.println("1/2 = " + (i1 / i2)); // => 0 - // (con 0.5 arrotonda per difetto) - - // Modulo - System.out.println("11%3 = "+(11 % 3)); // => 2 - - // Operatori di confronto - System.out.println("3 == 2? " + (3 == 2)); // => falso - System.out.println("3 != 2? " + (3 != 2)); // => vero - System.out.println("3 > 2? " + (3 > 2)); // => vero - System.out.println("3 < 2? " + (3 < 2)); // => falso - System.out.println("2 <= 2? " + (2 <= 2)); // => vero - System.out.println("2 >= 2? " + (2 >= 2)); // => vero - - // Operatori binari orientati ai bit - // effettuano le operazioni logiche confrontando, i bit degli operandi: - /* - ~ complemento - << shift sinistro con segno - >> shift destro con segno - >>> shift destro senza segno - & AND Binario Bitwise AND - ^ OR Esclusivo - | OR Incusivo - */ - - // Incrementare e Decrementare - int i = 0; - System.out.println("\n->Incrementare/Decrementare"); - // Gli operatori ++ e -- incrementano e decrementano rispettivamente di 1. - // Se posizionati prima della variabile, incrementano, quindi riportano. - // Se si trovano dopo la variabile, riporano, e quindi incrementano. - System.out.println(i++); //i = 1, Stampa 0 (post-incremento) - System.out.println(++i); //i = 2, Stampa 2 (pre-incremento) - System.out.println(i--); //i = 1, Stampa 2 (post-decremento) - System.out.println(--i); //i = 0, Stampa 0 (pre-decremento) - - /////////////////////////////////////// - // Strutture di controllo - /////////////////////////////////////// - System.out.println("\n->Strutture di controllo"); - - // La dichiarazione dell'If e'' C-like. - int j = 10; - if (j == 10){ - System.out.println("Io vengo stampato"); - } else if (j > 10) { - System.out.println("Io no"); - } else { - System.out.println("E io neppure"); - } - - // Struttura While - int fooWhile = 0; - while(fooWhile < 100) - { - //System.out.println(fooWhile); - //Incrementa il contatore - //Si ripete per 100 volte, fooWhile 0,1,2...99 - fooWhile++; - } - System.out.println("Valore di fooWhile: " + fooWhile); - - // Struttura Do While - int fooDoWhile = 0; - do - { - //System.out.println(fooDoWhile); - //Incrementa il contaore - //Si repete per 99 volte, fooDoWhile 0->99 - fooDoWhile++; - }while(fooDoWhile < 100); - System.out.println("Valore di fooWhile: " + fooDoWhile); - - // Struttura For - int fooFor; - //Struttura For => for(; ; ) - for(fooFor=0; fooFor<10; fooFor++){ - //System.out.println(fooFor); - //Itera 10 volte, fooFor 0->9 - } - System.out.println("Valore di fooFor: " + fooFor); - - // Struttura For Each - // Una iterazione automatica attraverso un array o una lista di oggetti - int[] fooList = {1,2,3,4,5,6,7,8,9}; - //struttura for each => for( : ) - //si legge: per ogni oggetto dell'array fai... - //Nota: il tipo dell'oggetto deve essere uguale a quello dell'array - - for( int bar : fooList ){ - //System.out.println(bar); - //Itera 9 volte e stampa 1-9 andando a capo. - } - - // Struttura Switch Case - // La struttura switch lavora con byte, short, char e int. - // Se funziona con i char funzionera ovviamente anche con le stringhe. - int mese = 3; - String stringaMese; - switch (mese){ - case 1: - stringaMese = "Genneio"; - break; - case 2: - stringaMese = "Febbraio"; - break; - case 3: - stringaMese = "Marzo"; - break; - default: - stringaMese = "Altri mesi"; - break; - } - System.out.println("Risultato del costrutto switch: " + stringaMese); - - // Condizioni brevi - // Si puo' usare l'operatore '?' per un rapido assegnamento - // o per operazioni logiche. - // Si legge: - // Se (condizione) e' vera, usa , altrimenti usa - int foo = 5; - String bar = (foo < 10) ? "A" : "B"; - System.out.println("Se la condizione e' vera stampa A: "+bar); - // Stampa A, perche' la condizione e' vera. - - - ///////////////////////////////////////// - // Convertire i tipi di tati e Typcasting - ///////////////////////////////////////// - - // Convertire tipi di dati - - // Stringhe ad interi - Integer.parseInt("123");//Riporta una versione intera di "123" - - // Interi a Stringhe - Integer.toString(123);//Riporta la stringa "123" - // Per altre conversioni guarda le seguenti classi - // Double - // Long - // String - - // Typecasting - // Vi sono molti dettagli che non si possono spiegare qui, - // java dispone di una ottima documentazione - // Sentiti libero di leggerla - // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html - - - /////////////////////////////////////// - // Classi e funzioni - /////////////////////////////////////// - - System.out.println("\n->Classi & Funzioni"); - - // (Di seguito la definizione della classe Bicicletta) - - // Instanziare una nuova classe - Bicicletta percorso = new Bicicletta(); - - // Chiamare metodi - percorso.accellera(3); // Si usano sempre metodi set... get... - percorso.setCadenza(100); - - // toString riporta la rappresenzazione dell'oggetto - // come se fosse una stringa - System.out.println("percorso info: " + percorso.toString()); - - } // Fine metodo main -} // Fine classe LearnJava - - -// Si possono inculdere altre anche delle classi non pubbliche (private) -// oltre a quella pubblica principale, in un file .java - -// Sintassi per dichiarare una classe: -// class { -// //dati, variabili, costruttori, funzioni, tutto qua. -// //le funzioni sono chiamate come i metodi. -// } - -class Bicicletta { - - // Variabili della bicicletta - public int cadenza; - // Public: Puo' essere richiamato da qualsiasi classe - private int velocita; - // Private: e'' accessibile solo dalla classe dove e'' stato inizializzato - protected int ingranaggi; - // Protected: e'' visto sia dalla classe che dalle sottoclassi - String nome; - // default: e'' accessibile sono all'interno dello stesso package - - // I costruttori vengono usati per creare variabili - // Questo e'' un costruttore - public Bicicletta() { - ingranaggi = 1; - cadenza = 50; - velocita = 5; - nome = "Bontrager"; - } - - // Questo e'' un costruttore che richiede parametri - public Bicicletta(int cadenza, int velocita, int ingranaggi, String nome) { - this.ingranaggi = ingranaggi; - this.cadenza = cadenza; - this.velocita = velocita; - this.nome = nome; - } - - // Sintassi delle funzioni: - // () - - // Le classi in java spesso implementano delle funzioni o metodo - // 'get...' o 'set...' - - // Dichiarazione di un metodo - // () - public int getCandenza() { - return cadenza; - } - - // i medodi (void) non necessitano di riportare un valore - public void setCadenza(int nuovoValore) { - cadenza = nuovoValore; - } - - public void setIngranaggi(int nuovoValore) { - ingranaggi = nuovoValore; - } - - public void accellera(int incrementa) { - velocita += incrementa; - } - - public void decellera(int decrementa) { - velocita -= decrementa; - } - - public void setNome(String nuovoNome) { - nome = nuovoNome; - } - - public String getNome() { - return nome; - } - - //Medoto per visualizzare gli attributi dell'oggetto - @Override - public String toString() { - return "Ingranaggi: " + ingranaggi + - " Cadenza: " + cadenza + - " Velocita: " + velocita + - " Nome: " + nome; - } -} // Fine classe bicicletta - -// PennyFarthing e'' una sottoclasse della bicicletta -class PennyFarthing extends Bicicletta { - // (Sono quelle biciclette con un unica ruota enorme - // Non hanno ingranaggi.) - - public PennyFarthing(int cadenzaIniziale, int velocitaIniziale){ - // Richiamo il costruttore del padre con super - super(cadenzaIniziale, velocitaIniziale, 0, "PennyFarthing"); - } - - // Bisogna contrassegnre un medodo che si sta riscrivendo - // con una @annotazione - // Per saperne di piu' sulle annotazioni - // Vedi la guida: http://docs.oracle.com/javase/tutorial/java/annotations/ - @Override - public void setIngranaggi(int ingranaggi) { - ingranaggi = 0; - } - -} -/* -//Interfacce -//Sintassi per dichiarare una interfaccia -// interface extends { -// //Costanti -// //Dichiarazioni dei metodi -//} - -//Esempi- Cibo: -interface Commestibile { - public void mangia(); - //Ogni classe che implementa questa interfaccia - //deve implementare questo metodo. - } -interface Digeribile { - public void digerisci(); -} - -//Possiamo quindi creare una classe che implementa entrambe le interfaccie -class Frutta implements Commestibile, Digestibile { - public void mangia() { - //... - } - - public void digerisci() { - //... - } -} - -//In Java si puo' estendere solo una classe, ma si possono implementare -//piu' interfaccie, per esempio: -class ClasseEsempio extends AltraClasse implements PrimaInterfaccia, SecondaInterfaccia { - public void MetodoPrimaInterfaccia() { - - } - - public void MetodoSecondaInterfaccia() { - - } -} -*/ -``` -## Letture future - -I link di seguito sono solo per capire l'argomento, cerca pure su Google degli esempi specifici - - -**Guida ufficiale di Oracle [solo in inglese]**: - -* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) - -* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) - -* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): - * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) - * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) - * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) - -* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) - -* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) - -* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) - -* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) - - -**Tutorial Online [in inglese]** - -* [Learneroo.com - Learn Java](http://www.learneroo.com) - -* [Codingbat.com](http://codingbat.com/java) - - -**Libri [in italiano]** : - -* [Java la guida completa](http://www.amazon.it/Java-guida-completa-Herbert-Schildt/dp/8838667667/ref=sr_1_1?ie=UTF8&qid=1393422296&sr=8-1&keywords=java) - -* [Thinking in java](http://www.amazon.it/Thinking-Java-1-Bruce-Eckel/dp/8871923030/ref=sr_1_8?ie=UTF8&qid=1393422296&sr=8-8&keywords=java) - -* [Manuale di Java 7](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From 25d54beab143de977627bbcf0821782551788bf1 Mon Sep 17 00:00:00 2001 From: Ivan Sala Date: Thu, 27 Feb 2014 21:18:58 +0100 Subject: Update java-it.html.markdown --- it-it/java-it.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 4854fc73..127569c3 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -1,7 +1,7 @@ --- language: java -filename: LearnJava.java +filename: LearnJava-it.java contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Madison Dickson", "http://github.com/mix3d"] -- cgit v1.2.3 From 41edfb0c104e9a870e1bef5c59c97d8452b74535 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 27 Feb 2014 14:18:35 -0800 Subject: Update clojure-macro-cn.html.markdown --- zh-cn/clojure-macro-cn.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zh-cn/clojure-macro-cn.html.markdown b/zh-cn/clojure-macro-cn.html.markdown index e1b68a83..9324841e 100644 --- a/zh-cn/clojure-macro-cn.html.markdown +++ b/zh-cn/clojure-macro-cn.html.markdown @@ -1,10 +1,11 @@ --- language: "clojure macros" -filename: learnclojuremacros.clj +filename: learnclojuremacros-zh.clj contributors: - ["Adam Bard", "http://adambard.com/"] translators: - ["Jakukyo Friel", "http://weakish.github.io"] +lang: zh-cn --- 和所有Lisp一样,Clojure内在的[同构性](https://en.wikipedia.org/wiki/Homoiconic)使得你可以穷尽语言的特性,编写生成代码的子过程——“宏”。宏是一种按需调制语言的强大方式。 -- cgit v1.2.3 From d8fd766c8803b5c19eaea832e41ef2c333268a71 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 27 Feb 2014 14:19:42 -0800 Subject: Update java-it.html.markdown --- it-it/java-it.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 127569c3..91eb0162 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -1,5 +1,4 @@ --- - language: java filename: LearnJava-it.java contributors: @@ -8,7 +7,6 @@ contributors: translators: - ["Ivan Sala","http://github.com/dev-sala"] lang: it-it - --- Java è un linguaggio di programmazione orientato ad oggetti, -- cgit v1.2.3 From 31b542777449d6a2a8bbd66a0e1cf570ea82e335 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 27 Feb 2014 22:26:49 +0000 Subject: Oops, syntax highlighter didn't like that. --- it-it/java-it.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 91eb0162..fb91aa19 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -13,7 +13,7 @@ Java è un linguaggio di programmazione orientato ad oggetti, concorrente, basato su classi e adatto a svariati scopi. [Per saperne di più](http://docs.oracle.com/javase/tutorial/java/index.html) -```Java +```java // I commenti su singola linea incominciano con // /* I commenti su piu' linee invece sono cosi' -- cgit v1.2.3 From bd6d3be775fd6be55f92d1d368b303f40618c0e1 Mon Sep 17 00:00:00 2001 From: rostdotio Date: Fri, 28 Feb 2014 10:31:10 +0100 Subject: Added explanation for colon character Use of the colon character for value assignment is now explained by example of function add10. --- scala.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5dfaefe0..2666746e 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -104,10 +104,13 @@ val sq = (x:Int) => x * x sq(10) // Gives you this: res33: Int = 100. +// The colon explicitly defines the type of a value, in this case a function +// taking an Int and returning an Int. +val add10: Int => Int = _ + 10 + // 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: -- cgit v1.2.3 From 1b67b8f2304c1787d14bb26c817774b4b7aa2eac Mon Sep 17 00:00:00 2001 From: Justin Campbell Date: Fri, 28 Feb 2014 11:24:45 -0500 Subject: Variable substr --- bash.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 70a3b52a..d5d08e9d 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -46,6 +46,10 @@ echo '$VARIABLE' echo ${VARIABLE/Some/A} # This will substitute the first occurance of "Some" with "A" +# Substring from a variable +echo ${VARIABLE:0:7} +# This will return only the first 7 characters of the value + # Default value for variable echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} # This works for null (FOO=), empty string (FOO=""), zero (FOO=0) returns 0 -- cgit v1.2.3 From 0f0ab04b27b2164611f0e9f870192094160ec941 Mon Sep 17 00:00:00 2001 From: Eka Y Saputra Date: Sat, 1 Mar 2014 20:05:19 +0700 Subject: Create css-id --- id-id/css-id.html.markdown | 235 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 235 insertions(+) create mode 100644 id-id/css-id.html.markdown diff --git a/id-id/css-id.html.markdown b/id-id/css-id.html.markdown new file mode 100644 index 00000000..7b0d8a6d --- /dev/null +++ b/id-id/css-id.html.markdown @@ -0,0 +1,235 @@ +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] +translators: + - ["Eka Y Saputra", "http://github.com/ekajogja"] +lang: id-id +filename: learncss-id.css +--- + +Pada mulanya, web tidak memiliki elemen visual, murni teks saja. Tapi seiring +perkembangan peramban, laman web dengan elemen visual menjadi umum. +CSS adalah bahasa standar yang ada untuk menjaga keterpisahan antara +konten (HTML) serta tampilan-dan-kesan laman web. + +Singkatnya, fungsi CSS ialah menyajikan sintaks yang memampukan kita untuk +menyasar elemen tertentu dalam sebuah laman HTML dan menerapkan +berbagai properti visual bagi elemen tersebut. + +Seperti bahasa lainnya, CSS memiliki banyak versi. Di artikel ini, kita fokus +pada CSS2.0 yang meskipun bukan versi termutakhir namun paling kompatibel +dan didukung secara luas. + +**CATATAN:** Lantaran keluaran dari CSS berwujud efek-efek visual, maka untuk +mempelajarinya, kita perlu mencoba berbagai hal dalam dunia olah CSS semisal +[dabblet](http://dabblet.com/). Fokus utama artikel ini ialah pada sintaks dan sejumlah tips umum. + + +```css +/* comments appear inside slash-asterisk, just like this line! */ + +/* #################### + ## SELECTORS + ####################*/ + +/* Generally, the primary statement in CSS is very simple */ +selector { property: value; /* more properties...*/ } + +/* the selector is used to target an element on page. + +You can target all elments on the page! */ +* { color:red; } + +/* +Given an element like this on the page: + +
+*/ + +/* you can target it by it's class name */ +.some-class { } + +/*or by both classes! */ +.some-class.class2 { } + +/* or by it's tag name */ +div { } + +/* or it's id */ +#someId { } + +/* or by the fact that it has an attribute! */ +[attr] { font-size:smaller; } + +/* or that the attribute has a specific value */ +[attr='value'] { font-size:smaller; } + +/* start with a value*/ +[attr^='val'] { font-size:smaller; } + +/* or ends with */ +[attr$='ue'] { font-size:smaller; } + +/* or even contains a value */ +[attr~='lu'] { font-size:smaller; } + + +/* and more importantly you can combine these together -- there shouldn't be +any spaaace between different parts because that makes it to have another +meaning.*/ +div.some-class[attr$='ue'] { } + +/* you can also select an element based on how it's parent is.*/ + +/*an element which is direct child of an element (selected the same way) */ +div.some-parent > .class-name {} + +/* or any of it's parents in the tree */ +/* the following basically means any element that has class "class-name" +and is child of a div with class name "some-parent" IN ANY DEPTH */ +div.some-parent .class-name {} + +/* warning: the same selector wihout spaaace has another meaning. +can you say what? */ +div.some-parent.class-name {} + +/* you also might choose to select an element based on it's direct +previous sibling */ +.i-am-before + .this-element { } + +/*or any sibling before this */ +.i-am-any-before ~ .this-element {} + +/* There are some pseudo classes that allows you to select an element +based on it's page behaviour (rather than page structure) */ + +/* for example for when an element is hovered */ +:hover {} + +/* or a visited link*/ +:visited {} + +/* or not visited link*/ +:link {} + +/* or an input element which is focused */ +:focus {} + + +/* #################### + ## PROPERTIES + ####################*/ + +selector { + + /* Units */ + width: 50%; /* in percent */ + font-size: 2em; /* times current font-size */ + width: 200px; /* in pixels */ + font-size: 20pt; /* in points */ + width: 5cm; /* in centimeters */ + width: 50mm; /* in millimeters */ + width: 5in; /* in inches */ + + /* Colors */ + background-color: #F6E; /* in short hex */ + background-color: #F262E2; /* in long hex format */ + background-color: tomato; /* can be a named color */ + background-color: rgb(255, 255, 255); /* in rgb */ + background-color: rgb(10%, 20%, 50%); /* in rgb percent */ + background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb */ + + /* Images */ + background-image: url(/path-to-image/image.jpg); + + /* Fonts */ + font-family: Arial; + font-family: "Courier New"; /* if name has spaaace it appears in double-quote */ + font-family: "Courier New", Trebuchet, Arial; /* if first one was not found + browser uses the second font, and so forth */ +} + +``` + +## Usage + +Save any CSS you want in a file with extension `.css`. + +```xml + + + + + + + +
+
+ +``` + +## Precedence + +As you noticed an element may be targetted by more than one selector. +and may have a property set on it in more than one. +In these cases, one of the rules takes precedence over others. + +Given the following CSS: + +```css +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +and the following markup: + +```xml +

+

+``` + +The precedence of style is as followed: +Remember, the precedence is for each **property**, not for the entire block. + +* `E` has the highest precedence because of the keyword `!important`. + It is recommended to avoid this unless it is strictly necessary to use. +* `F` is next, because it is inline style. +* `A` is next, because it is more "specific" than anything else. + more specific = more specifiers. here 3 specifiers: 1 tagname `p` + + class name `class1` + 1 attribute `attr='value'` +* `C` is next. although it has the same specificness as `B` + but it appears last. +* Then is `B` +* and lastly is `D`. + +## Compatibility + +Most of the features in CSS2 (and gradually in CSS3) are compatible across +all browsers and devices. But it's always vital to have in mind the compatiblity +of what you use in CSS with your target browsers. + +[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. + +## Further Reading + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) + -- cgit v1.2.3 From e5bec988bb56307975913232841d5e604534f4e1 Mon Sep 17 00:00:00 2001 From: iirelu Date: Sat, 1 Mar 2014 19:43:03 +0000 Subject: added json.html.markdown Very short and slightly silly, but I think it works. --- json.html.markdown | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 json.html.markdown diff --git a/json.html.markdown b/json.html.markdown new file mode 100644 index 00000000..7df47a4a --- /dev/null +++ b/json.html.markdown @@ -0,0 +1,49 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] +--- + + 0 +As JSON is an extremely simple data-interchange format, this is most likely going +to be the simplest Learn X in Y Minutes ever. + +JSON in its purest form has no actual comments, but most parsers will accept +C-style (//, /\* \*/) comments. For the purposes of this, everything is going to +be 100% valid JSON. Luckily, it kind of speaks for itself. + +```json +{ + "numbers": 0, + "strings": "Hellø, wørld. All unicode is allowed.", + "has bools?": true, + "nothingness": null, + + "big number": 1.2e+100, + + "objects": { + "comment": "Most of your structure will come from objects.", + + "array": [0, 1, 2, 3, "banana", 5], + + "another object": { + "comment": "These things can be nested, very useful." + } + }, + + "silliness": [ + { + "sources of potassium": ["bananas"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "that was short": "And, you're done. You know know everything JSON has to offer." +} +``` -- cgit v1.2.3 From 9894e0ce15a618910f9335e2e46b18ff805d9438 Mon Sep 17 00:00:00 2001 From: iirelu Date: Sat, 1 Mar 2014 19:46:36 +0000 Subject: slightly expanded on json.html.markdown Removed useless stuff, added new stuff. --- json.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/json.html.markdown b/json.html.markdown index 7df47a4a..f86f0ae9 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -5,18 +5,17 @@ contributors: - ["Anna Harren", "https://github.com/iirelu"] --- - 0 As JSON is an extremely simple data-interchange format, this is most likely going to be the simplest Learn X in Y Minutes ever. JSON in its purest form has no actual comments, but most parsers will accept -C-style (//, /\* \*/) comments. For the purposes of this, everything is going to -be 100% valid JSON. Luckily, it kind of speaks for itself. +C-style (//, /\* \*/) comments. For the purposes of this, however, everything is +going to be 100% valid JSON. Luckily, it kind of speaks for itself. ```json { "numbers": 0, - "strings": "Hellø, wørld. All unicode is allowed.", + "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", "has bools?": true, "nothingness": null, @@ -25,7 +24,7 @@ be 100% valid JSON. Luckily, it kind of speaks for itself. "objects": { "comment": "Most of your structure will come from objects.", - "array": [0, 1, 2, 3, "banana", 5], + "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], "another object": { "comment": "These things can be nested, very useful." -- cgit v1.2.3 From c899fe9eb8e727d9b7a39a1a30dfb48a939b095c Mon Sep 17 00:00:00 2001 From: iirelu Date: Sat, 1 Mar 2014 19:49:07 +0000 Subject: added learnjson.json Forgot this thing, oops. --- learnjson.json | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 learnjson.json diff --git a/learnjson.json b/learnjson.json new file mode 100644 index 00000000..b3f8c30c --- /dev/null +++ b/learnjson.json @@ -0,0 +1,32 @@ +{ + "numbers": 0, + "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", + "has bools?": true, + "nothingness": null, + + "big number": 1.2e+100, + + "objects": { + "comment": "Most of your structure will come from objects.", + + "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], + + "another object": { + "comment": "These things can be nested, very useful." + } + }, + + "silliness": [ + { + "sources of potassium": ["bananas"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "that was short": "And, you're done. You know know everything JSON has to offer." +} -- cgit v1.2.3 From 5260bbac08a2110145e0695abe1560ab909099ec Mon Sep 17 00:00:00 2001 From: iirelu Date: Sat, 1 Mar 2014 19:52:39 +0000 Subject: removed learnjson.json. i am so confused. I think it automatically generates it? I can't tell. --- learnjson.json | 32 -------------------------------- 1 file changed, 32 deletions(-) delete mode 100644 learnjson.json diff --git a/learnjson.json b/learnjson.json deleted file mode 100644 index b3f8c30c..00000000 --- a/learnjson.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "numbers": 0, - "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", - "has bools?": true, - "nothingness": null, - - "big number": 1.2e+100, - - "objects": { - "comment": "Most of your structure will come from objects.", - - "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], - - "another object": { - "comment": "These things can be nested, very useful." - } - }, - - "silliness": [ - { - "sources of potassium": ["bananas"] - }, - [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, "neo"], - [0, 0, 0, 1] - ] - ], - - "that was short": "And, you're done. You know know everything JSON has to offer." -} -- cgit v1.2.3 From ff5e64f4043fa06461ef422885444e837bfab6c9 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sun, 2 Mar 2014 12:01:54 +1030 Subject: Add YAML guide --- yaml.html.markdown | 139 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 yaml.html.markdown diff --git a/yaml.html.markdown b/yaml.html.markdown new file mode 100644 index 00000000..c5d15895 --- /dev/null +++ b/yaml.html.markdown @@ -0,0 +1,139 @@ +--- +language: yaml +filename: learnyaml.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +--- + +YAML is a data serialisation language designed to be directly writable and +readable by humans. + +It's a strict superset of JSON, with the addition of syntactically +significant newlines and indentation, like Python. Unlike Python, however, +YAML doesn't allow literal tab characters at all. + +```yaml +# Comments in YAML look like this. + +################ +# SCALAR TYPES # +################ + +# Our root object (which continues for the entire document) will be a map, +# which is equivalent to a dictionary, hash or object in other languages. +key: value +another_key: Another value goes here. +a_number_value: 100 +scientific_notation: 1e+12 +boolean: true +null_value: null +key with spaces: value +# Notice that strings don't need to be quoted. However, they can be. +however: "A string, enclosed in quotes." +"Keys can be quoted too.": "Useful if you want to put a ':' in your key." + +# Multiple-line strings can be written either as a 'literal block' (using |), +# or a 'folded block' (using '>') +literal_block: | + This entire block of text will be the value of the 'literal_block' key, + with line breaks being preserved. + + The literal continues until de-dented, and the leading indentation is + stripped. + + Any lines that are 'more-indented' keep the rest of their indentation - + these lines will be indented by 4 spaces. +folded_style: > + This entire block of text will be the value of 'folded_style', but this + time, all newlines will be replaced with a single space. + + Blank lines, like above, are converted to a newline character. + + 'More-indented' lines keep their newlines, too - + this text will appear over two lines. + +#################### +# COLLECTION TYPES # +#################### + +# Nesting is achieved by indentation. +a_nested_map: + key: value + another_key: Another Value + another_nested_map: + hello: hello + +# Maps don't have to have string keys. +0.25: a float key + +# Keys can also be multi-line objects, using ? to indicate the start of a key +? | + This is a key + that has multiple lines +: and this is its value + +# YAML also allows collection types in keys, but many programming languages +# will complain. + +# Sequences (equivalent to lists or arrays) look like this: +a_sequence: + - Item 1 + - Item 2 + - 0.5 # sequences can contain disparate types + - Item 4 + - key: value + another_key: another_value + - + - This is a sequence + - inside another sequence + +# Since YAML is a superset of JSON, you can also write JSON-style maps and +# sequences: +json_map: {"key": "value"} +json_seq: [3, 2, 1, "takeoff"] + +####################### +# EXTRA YAML FEATURES # +####################### + +# YAML also has a handy feature called 'anchors', which let you easily duplicate +# content across your document. Both of these keys will have the same value: +anchored_content: &anchor_name This string will appear as the value of two keys. +other_anchor: *anchor_name + +# YAML also has tags, which you can use to explicitly declare types. +explicit_string: !!str 0.5 +# Some parsers implement language specific tags, like this one for Python's +# complex number type. +python_complex_number: !!python/complex 1+2j + +#################### +# EXTRA YAML TYPES # +#################### + +# Strings and numbers aren't the only scalars that YAML can understand. +# ISO-formatted date and datetime literals are also parsed. +datetime: 2001-12-15T02:59:43.1Z +datetime_with_spaces: 2001-12-14 21:59:43.10 -5 +date: 2002-12-14 + +# The !!binary tag indicates that a string is actually a base64-encoded +# representation of a binary blob. +gif_file: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML also has a set type, which looks like this: +set: + ? item1 + ? item2 + ? item3 + +# Like Python, sets are just maps with null values; the above is equivalent to: +set2: + item1: null + item2: null + item3: null +``` -- cgit v1.2.3 From 2f86f48005cf4d2168529235c5747448ef3f0932 Mon Sep 17 00:00:00 2001 From: Eka Y Saputra Date: Mon, 3 Mar 2014 07:00:33 +0700 Subject: Create css-id --- id-id/css-id.html.markdown | 252 +++++++++++++++++++++++---------------------- 1 file changed, 131 insertions(+), 121 deletions(-) diff --git a/id-id/css-id.html.markdown b/id-id/css-id.html.markdown index 7b0d8a6d..1013a623 100644 --- a/id-id/css-id.html.markdown +++ b/id-id/css-id.html.markdown @@ -7,182 +7,191 @@ lang: id-id filename: learncss-id.css --- -Pada mulanya, web tidak memiliki elemen visual, murni teks saja. Tapi seiring -perkembangan peramban, laman web dengan elemen visual menjadi umum. -CSS adalah bahasa standar yang ada untuk menjaga keterpisahan antara +Pada mulanya, web tidak memiliki elemen visual, murni teks saja. +Tapi seiring perkembangan peramban, laman web dengan elemen visual menjadi umum. +CSS adalah bahasa standar yang ada untuk menjaga keterpisahan antara konten (HTML) serta tampilan-dan-kesan laman web. -Singkatnya, fungsi CSS ialah menyajikan sintaks yang memampukan kita untuk -menyasar elemen tertentu dalam sebuah laman HTML dan menerapkan -berbagai properti visual bagi elemen tersebut. +Singkatnya, fungsi CSS ialah menyajikan sintaks yang memampukan kita +untuk memilih elemen tertentu dalam sebuah laman HTML +dan menerapkan berbagai properti visual bagi elemen tersebut. -Seperti bahasa lainnya, CSS memiliki banyak versi. Di artikel ini, kita fokus -pada CSS2.0 yang meskipun bukan versi termutakhir namun paling kompatibel -dan didukung secara luas. +Seperti bahasa lainnya, CSS memiliki banyak versi. +Di artikel ini, kita fokus pada CSS2.0 - yang meskipun bukan versi termutakhir +namun paling kompatibel dan didukung secara luas. -**CATATAN:** Lantaran keluaran dari CSS berwujud efek-efek visual, maka untuk -mempelajarinya, kita perlu mencoba berbagai hal dalam dunia olah CSS semisal -[dabblet](http://dabblet.com/). Fokus utama artikel ini ialah pada sintaks dan sejumlah tips umum. +**CATATAN:** Lantaran keluaran dari CSS berwujud efek-efek visual, +maka untuk mempelajarinya, kita perlu mencoba berbagai hal dalam dunia olah CSS +semisal [dabblet](http://dabblet.com/). +Fokus utama artikel ini ialah pada sintaks dan sejumlah tips umum. ```css -/* comments appear inside slash-asterisk, just like this line! */ +/* komentar terletak diantara sepasang tanda garis miring dan bintang, +persis seperti larik ini! */ /* #################### - ## SELECTORS + ## SELEKTOR ####################*/ -/* Generally, the primary statement in CSS is very simple */ -selector { property: value; /* more properties...*/ } +/* Secara garis besar, statemen utama dalam CSS sangat sederhana */ +selektor { properti: nilai; /* properti lainnya */ } -/* the selector is used to target an element on page. +/* selektor berfungsi untuk memilih suatu elemen dalam sebuah laman. -You can target all elments on the page! */ +Kita juga bisa memilih semua elemen di sebuah halaman! */ * { color:red; } /* -Given an element like this on the page: +Dengan menentukan sebuah elemen seperti ini pada sebuah laman: -
+
*/ -/* you can target it by it's class name */ -.some-class { } +/* kita bisa memilih elemen berdasarkan nama class-nya */ +.suatu-class { } -/*or by both classes! */ -.some-class.class2 { } +/*atau dengan dua class sekaligus! */ +.suatu-class.class2 { } -/* or by it's tag name */ +/* atau dengan nama tag-nya */ div { } -/* or it's id */ -#someId { } +/* atau id-nya */ +#suatuId { } -/* or by the fact that it has an attribute! */ +/* atau - jika ada - dengan attribute-nya! */ [attr] { font-size:smaller; } -/* or that the attribute has a specific value */ -[attr='value'] { font-size:smaller; } +/* atau jika attribute tersebut memiliki nilai spesifik */ +[attr='nilai'] { font-size:smaller; } -/* start with a value*/ -[attr^='val'] { font-size:smaller; } +/* dibuka dengan sebuah nilai*/ +[attr^='nil'] { font-size:smaller; } -/* or ends with */ -[attr$='ue'] { font-size:smaller; } +/* atau ditutup dengan nilai */ +[attr$='ai'] { font-size:smaller; } -/* or even contains a value */ -[attr~='lu'] { font-size:smaller; } +/* atau bahkan disisipi nilai */ +[attr~='la'] { font-size:smaller; } -/* and more importantly you can combine these together -- there shouldn't be -any spaaace between different parts because that makes it to have another -meaning.*/ -div.some-class[attr$='ue'] { } +/* dan yang lebih penting lagi, kita bisa mengombinasikannya sekaligus +dengan syarat tidak ada spasi diantara selektor-selektor. sebab adanya spasi +akan membuat selektor itu memiliki makna yang berbeda.*/ +div.suatu-class[attr$='ai'] { } -/* you can also select an element based on how it's parent is.*/ +/* kita juga bisa memilih sebuah elemen berdasarkan posisi elemen induknya.*/ -/*an element which is direct child of an element (selected the same way) */ -div.some-parent > .class-name {} +/*sebuah elemen yang merupakan anak langsung dari elemen induk (diseleksi dng +cara yang sama) */ +div.suatu-induk > .-suatu-class {} -/* or any of it's parents in the tree */ -/* the following basically means any element that has class "class-name" -and is child of a div with class name "some-parent" IN ANY DEPTH */ -div.some-parent .class-name {} +/* atau salah satu induk elemennya dalam hirarki elemen */ +/* berikut ini dimaksudkan pada elemen manapun dengan class "class-entah" dan +merupakan anak elemen dari suatu div dengan class "induk-entah" PADA LEVEL +HIRARKI MANAPUN */ +div.suatu-induk .suatu-class {} -/* warning: the same selector wihout spaaace has another meaning. -can you say what? */ -div.some-parent.class-name {} +/* peringatan: selektor yang sama jika tanpa ada spasi akan bermakna lain. +misalnya? */ +div.suatu-induk.suatu-class {} -/* you also might choose to select an element based on it's direct -previous sibling */ -.i-am-before + .this-element { } +/* kita juga bisa memilih sebuah elemen berdasarkan saudara elemen yang muncul +tepat sebelumnya */ +.aku-muncul-tepat-sebelum + .elemen-ini { } -/*or any sibling before this */ -.i-am-any-before ~ .this-element {} +/*atau saudara elemen manapun yang pernah muncul selang beberapa elemen +sebelumnya */ +.aku-pernah-muncul-sebelum ~ .elemen-ini {} -/* There are some pseudo classes that allows you to select an element -based on it's page behaviour (rather than page structure) */ +/* Ada beberapa pseudo-class yang memampukan kita memilih suatu elemen +berdasarkan perilaku lamannya (bukan struktur lamannya) */ -/* for example for when an element is hovered */ +/* semisal ketika sebuah elemen ditimpa hover (pointer mouse) */ :hover {} -/* or a visited link*/ +/* atau link yang sudah pernah diklik*/ :visited {} -/* or not visited link*/ +/* atau link yang belum pernah diklik*/ :link {} -/* or an input element which is focused */ +/* atau elemen input yang menjadi fokus */ :focus {} /* #################### - ## PROPERTIES + ## PROPERTI ####################*/ -selector { +selektor { - /* Units */ - width: 50%; /* in percent */ - font-size: 2em; /* times current font-size */ - width: 200px; /* in pixels */ - font-size: 20pt; /* in points */ - width: 5cm; /* in centimeters */ - width: 50mm; /* in millimeters */ - width: 5in; /* in inches */ + /* Unit */ + width: 50%; /* dalam persen */ + font-size: 2em; /* angka kali jumlah font-size saat ini */ + width: 200px; /* dalam pixel */ + font-size: 20pt; /* dalam point */ + width: 5cm; /* dalam centimeter */ + width: 50mm; /* dalam milimeter */ + width: 5in; /* dalam inci */ - /* Colors */ - background-color: #F6E; /* in short hex */ - background-color: #F262E2; /* in long hex format */ - background-color: tomato; /* can be a named color */ - background-color: rgb(255, 255, 255); /* in rgb */ - background-color: rgb(10%, 20%, 50%); /* in rgb percent */ - background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb */ + /* Warna */ + background-color: #F6E; /* dalam short hex */ + background-color: #F262E2; /* dalam format long hex */ + background-color: tomato; /* warna yang sudah punya konvensi nama */ + background-color: rgb(255, 255, 255); /* dalam rgb */ + background-color: rgb(10%, 20%, 50%); /* dalam persen rgb */ + background-color: rgba(255, 0, 0, 0.3); /* dalam rgb semi-transparan*/ - /* Images */ - background-image: url(/path-to-image/image.jpg); + /* Gambar */ + background-image: url(/folder-gambar/image.jpg); - /* Fonts */ + /* Font */ font-family: Arial; - font-family: "Courier New"; /* if name has spaaace it appears in double-quote */ - font-family: "Courier New", Trebuchet, Arial; /* if first one was not found - browser uses the second font, and so forth */ + font-family: "Courier New"; /* jika nama font memiliki spasi, + ia diketik dalam tanda petik ganda */ + font-family: "Courier New", Trebuchet, Arial; /* jika font pertama tidak + ditemukan, peramban menggunakan font berikutnya, + demikian secara berturut-turut */ } ``` -## Usage +## Penggunaan -Save any CSS you want in a file with extension `.css`. +Simpan semua CSS yang hendak kita pakai dengan ekstensi `.css`. ```xml - - + + - + - -
+ +
``` -## Precedence +## Prioritas -As you noticed an element may be targetted by more than one selector. -and may have a property set on it in more than one. -In these cases, one of the rules takes precedence over others. +Kita tahu bahwa sebuah elemen bisa dipilih dengan lebih dari satu selektor, +serta bisa diberi lebih dari satu properti. +Dalam kasus seperti ini, hanya salah satu properti saja yang akan diterapkan +pada elemen dengan prioritas tertentu. -Given the following CSS: +Dengan susunan CSS: ```css + /*A*/ -p.class1[attr='value'] +p.class1[attr='nilai'] /*B*/ p.class1 {} @@ -194,40 +203,41 @@ p.class2 {} p {} /*E*/ -p { property: value !important; } +p { properti: nilai !important; } ``` -and the following markup: +dan susunan markup: ```xml -

+

``` -The precedence of style is as followed: -Remember, the precedence is for each **property**, not for the entire block. +Maka prioritas penerapan style-nya ialah sbb.: +Ingat, penerapan ini untuk masing-masing properti **property**, +bukan keseluruhan larik. -* `E` has the highest precedence because of the keyword `!important`. - It is recommended to avoid this unless it is strictly necessary to use. -* `F` is next, because it is inline style. -* `A` is next, because it is more "specific" than anything else. - more specific = more specifiers. here 3 specifiers: 1 tagname `p` + - class name `class1` + 1 attribute `attr='value'` -* `C` is next. although it has the same specificness as `B` - but it appears last. -* Then is `B` -* and lastly is `D`. +* `E` prioritas pertama sebab ada kata `!important`. + Dianjurkan untuk menghindari kata ini jika tidak benar-benar perlu. +* `F` prioritas kedua sebab ia diketik secara inline. +* `A` prioritas ketiga sebab selektor ini lebih spesifik dibanding yang lain. + lebih spesifik = lebih banyak unsur selektor. contoh ini punya 3 unsur: + 1 tagname `p` + 1 nama class `class1` + 1 attribute `attr='nilai'` +* `C` prioritas berikutnya sebab meski sama spesifik dengan `B` namun + ia muncul lebih akhir. +* Lalu `B` +* dan terakhir baru `D`. -## Compatibility +## Kompatibilitas -Most of the features in CSS2 (and gradually in CSS3) are compatible across -all browsers and devices. But it's always vital to have in mind the compatiblity -of what you use in CSS with your target browsers. +Sebagian besar fitur dalam CSS2 (dan lambat laun juga CSS3) kompatibel dengan +semua peramban dan perangkat. Namun selalu vital untuk memastikan kompatibilitas +unsur dan nilai yang kita ketikkan dalam CSS dengan peramban yang ditargetkan. -[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. +[QuirksMode CSS](http://www.quirksmode.org/css/) ialah salah satu sumber terbaik untuk memeriksa kompatibilitas CSS dan peramban. -## Further Reading +## Referensi Lanjut * [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) * [QuirksMode CSS](http://www.quirksmode.org/css/) -- cgit v1.2.3 From 88274f8a3af0c270b1580b561e6f1c0a8dfbd3ec Mon Sep 17 00:00:00 2001 From: iirelu Date: Mon, 3 Mar 2014 15:49:12 +0000 Subject: normalised lua doc to 80 chars per line When this was originally written, it was written for a line-width of 50 characters, however Learn X in Y Minutes' site is designed for 80-character widths. This made it look very out of place. --- lua.html.markdown | 151 +++++++++++++++++++++++++----------------------------- 1 file changed, 69 insertions(+), 82 deletions(-) diff --git a/lua.html.markdown b/lua.html.markdown index bdd59999..be9f3141 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -12,15 +12,13 @@ filename: learnlua.lua Adding two ['s and ]'s makes it a multi-line comment. --]] - ----------------------------------------------------- +-------------------------------------------------------------------------------- -- 1. Variables and flow control. ----------------------------------------------------- +-------------------------------------------------------------------------------- num = 42 -- All numbers are doubles. --- Don't freak out, 64-bit doubles have 52 bits for --- storing exact int values; machine precision is --- not a problem for ints that need < 52 bits. +-- Don't freak out, 64-bit doubles have 52 bits for storing exact int +-- values; machine precision is not a problem for ints that need < 52 bits. s = 'walternate' -- Immutable strings like Python. t = "double-quotes are also fine" @@ -60,8 +58,8 @@ aBoolValue = false -- Only nil and false are falsy; 0 and '' are true! if not aBoolValue then print('twas false') end --- 'or' and 'and' are short-circuited. --- This is similar to the a?b:c operator in C/js: +-- 'or' and 'and' are short-circuited. This is similar to the a?b:c operator +-- in C/js: ans = aBoolValue and 'yes' or 'no' --> 'no' karlSum = 0 @@ -81,10 +79,9 @@ repeat num = num - 1 until num == 0 - ----------------------------------------------------- +-------------------------------------------------------------------------------- -- 2. Functions. ----------------------------------------------------- +-------------------------------------------------------------------------------- function fib(n) if n < 2 then return n end @@ -93,8 +90,8 @@ end -- Closures and anonymous functions are ok: function adder(x) - -- The returned function is created when adder is - -- called, and remembers the value of x: + -- The returned function is created when adder is called, and remembers the + -- value of x: return function (y) return x + y end end a1 = adder(9) @@ -102,10 +99,9 @@ a2 = adder(36) print(a1(16)) --> 25 print(a2(64)) --> 100 --- Returns, func calls, and assignments all work --- with lists that may be mismatched in length. --- Unmatched receivers are nil; --- unmatched senders are discarded. +-- Returns, func calls, and assignments all work with lists that may be +-- mismatched in length. Unmatched receivers are nil; unmatched senders are +-- discarded. x, y, z = 1, 2, 3, 4 -- Now x = 1, y = 2, z = 3, and 4 is thrown away. @@ -118,16 +114,15 @@ end x, y = bar('zaphod') --> prints "zaphod nil nil" -- Now x = 4, y = 8, values 15..42 are discarded. --- Functions are first-class, may be local/global. --- These are the same: +-- Functions are first-class, may be local/global. These are the same: function f(x) return x * x end f = function (x) return x * x end -- And so are these: local function g(x) return math.sin(x) end local g = function(x) return math.sin(x) end --- Equivalent to local function g(x)..., except referring --- to g in the function body won't work as expected. +-- Equivalent to local function g(x)..., except referring to g in the function +-- body won't work as expected. local g; g = function (x) return math.sin(x) end -- the 'local g' decl makes g-self-references ok. @@ -136,19 +131,16 @@ local g; g = function (x) return math.sin(x) end -- Calls with one string param don't need parens: print 'hello' -- Works fine. --- Calls with one table param don't need parens --- either (more on tables below): +-- Calls with one table param don't need parens either (more on tables below): print {} -- Works fine too. - ----------------------------------------------------- +-------------------------------------------------------------------------------- -- 3. Tables. ----------------------------------------------------- +-------------------------------------------------------------------------------- --- Tables = Lua's only compound data structure; --- they are associative arrays. --- Similar to php arrays or js objects, they are --- hash-lookup dicts that can also be used as lists. +-- Tables = Lua's only compound data structure; they are associative arrays. +-- Similar to php arrays or js objects, they are hash-lookup dicts that can +-- also be used as lists. -- Using tables as dictionaries / maps: @@ -164,14 +156,13 @@ t.key2 = nil -- Removes key2 from the table. u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} print(u[6.28]) -- prints "tau" --- Key matching is basically by value for numbers --- and strings, but by identity for tables. +-- Key matching is basically by value for numbers and strings, but by identity +-- for tables. a = u['@!#'] -- Now a = 'qbert'. b = u[{}] -- We might expect 1729, but it's nil: --- b = nil since the lookup fails. It fails --- because the key we used is not the same object --- as the one used to store the original value. So --- strings & numbers are more portable keys. +-- b = nil since the lookup fails. It fails because the key we used is not the +-- same object as the one used to store the original value. So strings & +-- numbers are more portable keys. -- A one-table-param function call needs no parens: function h(x) print(x.key1) end @@ -191,16 +182,15 @@ v = {'value1', 'value2', 1.21, 'gigawatts'} for i = 1, #v do -- #v is the size of v for lists. print(v[i]) -- Indices start at 1 !! SO CRAZY! end --- A 'list' is not a real type. v is just a table --- with consecutive integer keys, treated as a list. +-- A 'list' is not a real type. v is just a table with consecutive integer +-- keys, treated as a list. ----------------------------------------------------- +-------------------------------------------------------------------------------- -- 3.1 Metatables and metamethods. ----------------------------------------------------- +-------------------------------------------------------------------------------- --- A table can have a metatable that gives the table --- operator-overloadish behavior. Later we'll see --- how metatables support js-prototypey behavior. +-- A table can have a metatable that gives the table operator-overloadish +-- behavior. Later we'll see how metatables support js-prototypey behavior. f1 = {a = 1, b = 2} -- Represents the fraction a/b. f2 = {a = 2, b = 3} @@ -221,10 +211,9 @@ setmetatable(f2, metafraction) s = f1 + f2 -- call __add(f1, f2) on f1's metatable --- f1, f2 have no key for their metatable, unlike --- prototypes in js, so you must retrieve it as in --- getmetatable(f1). The metatable is a normal table --- with keys that Lua knows about, like __add. +-- f1, f2 have no key for their metatable, unlike prototypes in js, so you must +-- retrieve it as in getmetatable(f1). The metatable is a normal table with +-- keys that Lua knows about, like __add. -- But the next line fails since s has no metatable: -- t = s + s @@ -236,11 +225,12 @@ myFavs = {food = 'pizza'} setmetatable(myFavs, {__index = defaultFavs}) eatenBy = myFavs.animal -- works! thanks, metatable --- Direct table lookups that fail will retry using --- the metatable's __index value, and this recurses. +-------------------------------------------------------------------------------- +-- Direct table lookups that fail will retry using the metatable's __index +-- value, and this recurses. --- An __index value can also be a function(tbl, key) --- for more customized lookups. +-- An __index value can also be a function(tbl, key) for more customized +-- lookups. -- Values of __index,add, .. are called metamethods. -- Full list. Here a is a table with the metamethod. @@ -261,12 +251,12 @@ eatenBy = myFavs.animal -- works! thanks, metatable -- __newindex(a, b, c) for a.b = c -- __call(a, ...) for a(...) ----------------------------------------------------- +-------------------------------------------------------------------------------- -- 3.2 Class-like tables and inheritance. ----------------------------------------------------- +-------------------------------------------------------------------------------- --- Classes aren't built in; there are different ways --- to make them using tables and metatables. +-- Classes aren't built in; there are different ways to make them using +-- tables and metatables. -- Explanation for this example is below it. @@ -286,22 +276,20 @@ mrDog = Dog:new() -- 7. mrDog:makeSound() -- 'I say woof' -- 8. -- 1. Dog acts like a class; it's really a table. --- 2. function tablename:fn(...) is the same as --- function tablename.fn(self, ...) --- The : just adds a first arg called self. --- Read 7 & 8 below for how self gets its value. +-- 2. "function tablename:fn(...)" is the same as +-- "function tablename.fn(self, ...)", The : just adds a first arg called +-- self. Read 7 & 8 below for how self gets its value. -- 3. newObj will be an instance of class Dog. --- 4. self = the class being instantiated. Often --- self = Dog, but inheritance can change it. --- newObj gets self's functions when we set both --- newObj's metatable and self's __index to self. +-- 4. "self" is the class being instantiated. Often self = Dog, but inheritance +-- can change it. newObj gets self's functions when we set both newObj's +-- metatable and self's __index to self. -- 5. Reminder: setmetatable returns its first arg. --- 6. The : works as in 2, but this time we expect --- self to be an instance instead of a class. +-- 6. The : works as in 2, but this time we expect self to be an instance +-- instead of a class. -- 7. Same as Dog.new(Dog), so self = Dog in new(). -- 8. Same as mrDog.makeSound(mrDog); self = mrDog. ----------------------------------------------------- +-------------------------------------------------------------------------------- -- Inheritance example: @@ -315,17 +303,16 @@ end seymour = LoudDog:new() -- 3. seymour:makeSound() -- 'woof woof woof' -- 4. +-------------------------------------------------------------------------------- -- 1. LoudDog gets Dog's methods and variables. -- 2. self has a 'sound' key from new(), see 3. --- 3. Same as LoudDog.new(LoudDog), and converted to --- Dog.new(LoudDog) as LoudDog has no 'new' key, --- but does have __index = Dog on its metatable. --- Result: seymour's metatable is LoudDog, and --- LoudDog.__index = Dog. So seymour.key will --- = seymour.key, LoudDog.key, Dog.key, whichever +-- 3. Same as "LoudDog.new(LoudDog)", and converted to "Dog.new(LoudDog)" as +-- LoudDog has no 'new' key, but does have "__index = Dog" on its metatable. +-- Result: seymour's metatable is LoudDog, and "LoudDog.__index = Dog". So +-- seymour.key will equal seymour.key, LoudDog.key, Dog.key, whichever -- table is the first with the given key. --- 4. The 'makeSound' key is found in LoudDog; this --- is the same as LoudDog.makeSound(seymour). +-- 4. The 'makeSound' key is found in LoudDog; this is the same as +-- "LoudDog.makeSound(seymour)". -- If needed, a subclass's new() is like the base's: function LoudDog:new() @@ -335,13 +322,13 @@ function LoudDog:new() return setmetatable(newObj, self) end ----------------------------------------------------- +-------------------------------------------------------------------------------- -- 4. Modules. ----------------------------------------------------- +-------------------------------------------------------------------------------- ---[[ I'm commenting out this section so the rest of --- this script remains runnable. +--[[ I'm commenting out this section so the rest of this script remains +-- runnable. ``` ```lua @@ -367,8 +354,8 @@ local mod = require('mod') -- Run the file mod.lua. local mod = (function () end)() --- It's like mod.lua is a function body, so that --- locals inside mod.lua are invisible outside it. +-- It's like mod.lua is a function body, so that locals inside mod.lua are +-- invisible outside it. -- This works because mod here = M in mod.lua: mod.sayHello() -- Says hello to Hrunkner. @@ -376,8 +363,8 @@ mod.sayHello() -- Says hello to Hrunkner. -- This is wrong; sayMyName only exists in mod.lua: mod.sayMyName() -- error --- require's return values are cached so a file is --- run at most once, even when require'd many times. +-- require's return values are cached so a file is run at most once, even when +-- require'd many times. -- Suppose mod2.lua contains "print('Hi!')". local a = require('mod2') -- Prints Hi! -- cgit v1.2.3 From 301069610be9d3c0a5ccae3f75ae69a34c2ad619 Mon Sep 17 00:00:00 2001 From: Eka Y Saputra Date: Wed, 5 Mar 2014 16:39:26 +0700 Subject: Changed "property" to "properti" --- id-id/css-id.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id-id/css-id.html.markdown b/id-id/css-id.html.markdown index 1013a623..d0798ec7 100644 --- a/id-id/css-id.html.markdown +++ b/id-id/css-id.html.markdown @@ -215,7 +215,7 @@ dan susunan markup: ``` Maka prioritas penerapan style-nya ialah sbb.: -Ingat, penerapan ini untuk masing-masing properti **property**, +Ingat, penerapan ini untuk masing-masing **properti**, bukan keseluruhan larik. * `E` prioritas pertama sebab ada kata `!important`. -- cgit v1.2.3 From d756acce79a8fbac549251dae329650f99ba5533 Mon Sep 17 00:00:00 2001 From: dev-sala Date: Wed, 5 Mar 2014 16:06:23 +0100 Subject: [Brainfuck/it-it] started the translation\n\nStarted the english-italian translation of Brainfuck document. --- it-it/.java-it.html.markdown.swp | Bin 0 -> 16384 bytes it-it/brainfuck-it.html.markdown | 92 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 it-it/.java-it.html.markdown.swp create mode 100644 it-it/brainfuck-it.html.markdown diff --git a/it-it/.java-it.html.markdown.swp b/it-it/.java-it.html.markdown.swp new file mode 100644 index 00000000..6a112d73 Binary files /dev/null and b/it-it/.java-it.html.markdown.swp differ diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown new file mode 100644 index 00000000..9b882b2f --- /dev/null +++ b/it-it/brainfuck-it.html.markdown @@ -0,0 +1,92 @@ +--- + +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Ivan Sala", "http://slavni.github.io/"] +lang: it-it + +--- + +Brainfuck è un linguaggio di programmazione estremamente minimale, +ma è ingrado di rappresentare completamente una macchina di turnig, +e sfrutta solo 8 caratteri. +[Per saperne di più](http://it.wikipedia.org/wiki/Brainfuck) + +``` + +Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici) viene ignorato. +Branfuck è caratterizzato da un array (vettore) di 30,000 celle inizializzare a zero, e un puntatore che punta alla cella corrente. + +Vi sono solo otto comando: ++ : Incrementa il valore della cella attuale di uno. +- : Decrementa il valore della cella attuale di uno. +> : Sposta il puntatore sulla cella seguente (prossima a destra). +< : Sposta il puntatore sulla cella precendete (precedente a sinistra). +. : Stampa il valore in ASCII della cella corrente. (es: 65 = 'A') +, : Legge un singolo carattere come input per la cella corrente. +[ : Se il valore della cella corrente è zero, conclude il ciclo + andando alla sua corrispondente ]. + Altrimenti, passa alla prossima istruzione. +] : Se il valore della cella corrente è zero, passa alla prossima istruzione. + Altrimenti torna indetro fino alla [ corrispondente. + +[ e ] creano un loop (while). Ovviamente dovranno essere bilanciati. +Per ogni [ dovrà corrispondere una ] + +Alcuni semplici esempi di programmi scritti in Brainfuck: + +++++++ [ > ++++++++++ < - ] > +++++ . + +Questo programma stampa in output la lettera 'A'. Priam incrementa +la cella #1 fino a 6, Quindi la cella #1 viene usata per crare un ciclo. +Poi, entra in un loop ([) e si sposta alla cella #2. +Incrementa la cella #2 10 volte, e torna alla cella #1, e la decrementa. +Questo avviene 6 volte (servono che la cella #1 venga decrementata 6 volte +per raggiungere lo 0. Quindi passa alla corrispondente ] e prosegue). + +A questo punto, siamo sulla cella #1, che ha valore 0, +la cella #2 ha valore 60 (6*10). Ci spostiamo sulla cella #2, incrementiamo +per 5 volte, e otteniamo il valore 65, quindi stampaimo il valore della cella +#2 (.). +65 è 'A' in ASCII, quindi alla fine viene stampata 'A'. + + +, [ > + < - ] > . + +This program reads a character from the user input and copies the character into +cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, +move back to cell #1, and decrement the value at cell #1. This continues on +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 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. 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. +``` + +E questo è brainfuck...Non è difficele, vero? +Per divertimento adesso puoi scrivere i tuoi programmi in brainfuck, +oppure puoi scrivere un interprete brainfuck in un altro linguaggio. +L'interprete è abbastanza semplice da implementare, ma se sei veramente +masochista prova ad implementare un interprete brainfuck in... +brainfuck. + -- cgit v1.2.3 From 07e8f770d9a875afc01fa9c31fb406f4c5e1f3fd Mon Sep 17 00:00:00 2001 From: dev-sala Date: Wed, 5 Mar 2014 16:06:34 +0100 Subject: [Brainfuck/it-it] started the translation\n\nStarted the english-italian translation of Brainfuck document. --- it-it/.java-it.html.markdown.swp | Bin 16384 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 it-it/.java-it.html.markdown.swp diff --git a/it-it/.java-it.html.markdown.swp b/it-it/.java-it.html.markdown.swp deleted file mode 100644 index 6a112d73..00000000 Binary files a/it-it/.java-it.html.markdown.swp and /dev/null differ -- cgit v1.2.3 From 0bea9954748c01f5e039ec940630ff3447148655 Mon Sep 17 00:00:00 2001 From: dev-sala Date: Wed, 5 Mar 2014 16:12:13 +0100 Subject: [Brainfuck/it-it] some fixes\n\nWrong translator name. Italian corrections --- it-it/brainfuck-it.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown index 9b882b2f..2705fb4c 100644 --- a/it-it/brainfuck-it.html.markdown +++ b/it-it/brainfuck-it.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - - ["Ivan Sala", "http://slavni.github.io/"] + - ["Ivan Sala", "http://slavni96.github.io/"] lang: it-it --- -- cgit v1.2.3 From 3a2ee0480fd24b9f7d7681e9f848f921356db585 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81rp=C3=A1d=20Goretity=20=EF=A3=BF?= Date: Fri, 7 Mar 2014 07:38:07 +0100 Subject: fixed orthographic and grammar mistakes --- hu-hu/go.html.markdown | 42 ++++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/hu-hu/go.html.markdown b/hu-hu/go.html.markdown index 621ebdbf..638c9489 100644 --- a/hu-hu/go.html.markdown +++ b/hu-hu/go.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Sonia Keys", "https://github.com/soniakeys"] translators: - ["Szabó Krisztián", "https://github.com/thenonameguy/"] + - ["Árpád Goretity", "https://github.com/H2CO3"] --- A Go programozási nyelv az életszerű feladatok könnyebb elvégzése miatt született. @@ -38,14 +39,14 @@ import ( "strconv" // Stringek átalakítására szolgáló csomag ) -// Funkció deklarálás, a main nevű funkció a program kezdőpontja. +// Függvénydeklarálás, a main nevű függvény a program kezdőpontja. func main() { // Println kiírja a beadott paramétereket a standard kimenetre. - // Ha más csomagot funkcióját akarjuk használni, akkor azt jelezni kell a + // Ha más csomagot függvényeit akarjuk használni, akkor azt jelezni kell a // csomag nevével fmt.Println("Hello world!") - // Meghívunk egy másik funkciót ebből a csomagból + // Meghívunk egy másik függvényt ebből a csomagból beyondHello() } @@ -92,7 +93,7 @@ func learnTypes() { // lebegőpontos szám c := 3 + 4i // complex128, belsőleg két float64-gyel tárolva - // Var szintaxis változó típus definiálással + // Var szintaxis változótípus-definiálással var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az // int-nél var pi float32 = 22. / 7 @@ -105,8 +106,8 @@ func learnTypes() { a3 := [...]int{3, 1, 5} // egy tömb 3 int-tel, láthatóan inicalizálva egyedi // értékekre - // Szeleteknek dinamikus a méretük. A szeleteknek és a tömböknek is meg - // vannak az előnyeik de a szeleteket sokkal gyakrabban használjuk. + // A "szeleteknek" (slices) dinamikus a méretük. A szeleteknek és a tömböknek is + // megvannak az előnyeik de a szeleteket sokkal gyakrabban használjuk. s3 := []int{4, 5, 9} // vesd össze a3-mal, nincsenek pontok. s4 := make([]int, 4) // allokál 4 int-et, mind 0-ra inicializálva var d2 [][]float64 // ez csak deklaráció, semmi sincs még allokálva @@ -129,8 +130,8 @@ func learnTypes() { learnFlowControl() } -// A Go nyelv teljesen szemétgyűjtött (garbage-collected). Megtalálhatók benne -// mutatók, de nincs mutató aritmetika. Ez azt jelenti, hogy üres mutatóval még +// A Go nyelvben szemétgyűjtés (garbage collection) működik. Megtalálhatók benne +// mutatók, de nincs pointeraritmetika. Ez azt jelenti, hogy üres (null) mutatóval még // mindig hibázhatsz, de hozzáadni/műveleteket végezni már nem lehet. func learnMemory() (p, q *int) { // Elnevezett visszatérési változóknak int-re mutató a típusa @@ -213,7 +214,7 @@ type pair struct { } // Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer interfészt. -func (p pair) String() string { // p lesz a "vevő" +func (p pair) String() string { // p lesz a "fogadó" (receiver) // Sprintf az fmt csomag egy publikus függvénye, műkődése megegyezik a C-s // megfelelőjével. A pontokkal érjük el a mindenkori p struktúra elemeit return fmt.Sprintf("(%d, %d)", p.x, p.y) @@ -230,7 +231,7 @@ func learnInterfaces() { // Meghívjuk i String metódusát, az eredmény ugyanaz, mint az előbb. fmt.Println(i.String()) - // Az fmt csomag funckciói automatikusan meghívják a String funkciót + // Az fmt csomag függvényei automatikusan meghívják a String függvényt // hogy megtudják egy objektum szöveges reprezentációját. fmt.Println(p) // ugyan az az eredmény mint az előbb, a Println meghívja // a String metódust. @@ -267,8 +268,8 @@ func inc(i int, c chan int) { // Az inc-et fogjuk arra használni, hogy konkurensen megnöveljünk számokat func learnConcurrency() { - // Ugyan az a make funkció amivel korábban szeleteket hoztunk létre. - // Make allokál mapokat, szeleteket és csatornákat. + // Ugyanaz a make függvény, amivel korábban szeleteket hoztunk létre. + // A make allokál map-eket, szeleteket és csatornákat. c := make(chan int) // Indítsunk három konkurens goroutine-t. A számok konkurensen lesznek // megnövelve, ha a számítógép képes rá és jól be van állítva, akkor pedig @@ -299,14 +300,14 @@ func learnConcurrency() { case <-cc: // üres csatorna, soha nem fog rajta semmi se érkezni fmt.Println("sose futok le :'( ") } - // Ezen a ponton vagy c vagy a cs goroutineja lefutott. + // Ezen a ponton vagy c vagy a cs goroutine-ja lefutott. // Amelyik hamarabb végzett, annak a megfelelő case-e lefutott, a másik // blokkolva vár. - learnWebProgramming() // Go képes rá. Te is képes akarsz rá lenni. + learnWebProgramming() // a Go képes rá. Te is képes akarsz rá lenni. } -// Egy funkció a http csomagból elindít egy webszervert. +// Egy függvény a http csomagból elindít egy webszervert. func learnWebProgramming() { // A ListenAndServe első paramétre egy TCP port, amin kiszolgálunk majd. // Második paramétere egy interfész, pontosabban a http.Handler interfész. @@ -315,7 +316,7 @@ func learnWebProgramming() { } // Csináljunk a pair-ból egy http.Handler-t úgy, hogy implementáljuk az -// egyetlen metódusát a ServeHTTP-t. +// egyetlen metódusát, a ServeHTTP-t. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Minden kapcsolatra elküldjük ezt a http.ResponseWriter-rel w.Write([]byte("Megtanultad a Go-t Y perc alatt!")) @@ -325,11 +326,12 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ## További olvasmányok Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](http://golang.org/). -Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten és sok érdekességet olvashatsz. +Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten, és sok érdekességet olvashatsz. A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és sokat tanul belőle az ember. -Ha pedig jobban bele akarod vetni magad a Go-ba, akkor a standard könyvtárban a legjobb praktikákat kilesheted. -TIPP: a dokumentációban kattints egy funkció nevére és rögtön megmutatja a hozzá tartozó kódot! +Ha pedig jobban bele akarod vetni magad a Go-ba, akkor a legjobb praktikákat kilesheted a standard könyvtárból. +TIPP: a dokumentációban kattints egy függvény nevére és rögtön megmutatja a hozzá tartozó kódot! -Ha pedig a nyelvnek egy bizonyos részéről szeretnél hasonló leírást találni, akkor a [gobyexample.com](https://gobyexample.com/)-on megtalálod, amit keresel. +Ha pedig a nyelvnek egy bizonyos részéről szeretnél hasonló leírást találni, akkor a +[gobyexample.com](https://gobyexample.com/)-on megtalálod, amit keresel. -- cgit v1.2.3 From 35acb53ee3b99f52d1b4f588200c724ce338be3a Mon Sep 17 00:00:00 2001 From: Adrian Bordinc Date: Fri, 7 Mar 2014 19:09:56 +0100 Subject: Added ruby/ro-ro translation --- ro-ro/ruby-ro.html.markdown | 479 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 479 insertions(+) create mode 100644 ro-ro/ruby-ro.html.markdown diff --git a/ro-ro/ruby-ro.html.markdown b/ro-ro/ruby-ro.html.markdown new file mode 100644 index 00000000..27c6c462 --- /dev/null +++ b/ro-ro/ruby-ro.html.markdown @@ -0,0 +1,479 @@ +--- +language: ruby +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] +translators: + - ["Adrian Bordinc", "https://github.com/ellimist"] +filename: learnruby-ro.rb +lang: ro-ro +--- + +```ruby +# Acesta este un comentariu + +=begin +Acesta este un comentariu pe mai multe linii +Nimeni nu le foloseste +Si nici tu nu ar trebui sa o faci +=end + +# In primul rand: totul este un obiect + +# Numerele sunt obiecte + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Aritmetica de baza +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Aritmetica este doar "zahar sintactic" +# pentru a putea chema metode pe un obiect +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Valorile speciale sunt obiecte +nil # Nimic +true # true +false # false + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Egalitate +1 == 1 #=> true +2 == 1 #=> false + +# Inegalitate +1 != 1 #=> false +2 != 1 #=> true +!true #=> false +!false #=> true + +# Excluzand "false", "nil" este singura valoare "falsa" + +!nil #=> true +!false #=> true +!0 #=> false + +# Mai multe comparatii +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Sirurule de caractere sunt obiecte + +'Sunt un sir de caractere'.class #=> String +"Si eu sunt un sir de caractere".class #=> String + +fi_inlocuit = "inlocui o valoare in string" +"Pot #{fi_inlocuit} atunci cand folosesc dublu apostrof" +#=> "Pot inlocui o valoare intr-un sir de caractere atunci cand folosesc dublu apostrof" + + +# Printeaza +puts "Afisez rezultate!" + +# Variabile +x = 25 #=> 25 +x #=> 25 + +# Retineti faptul ca atribuire unei valori, o si returneaza pe aceasta +# Asta inseamna ca poti sa faci atribuire multipla: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Prin conventie se foloseste "snake_case" in denumirea variabilelor +snake_case = true + +# Folositi nume descriptive pentru variablie +adresa_radacina_proiect = '/nume/bun/' +adresa = '/nume/nu atat de bun/' + +# Simbolurile (sunt obiecte) +# Simbolurile sunt constante imutabile, reutilizabile, reprezentate intern +# de o valoare numerica. Sunt deseori folosite in locul sirurilor de caractere pentru a da un nume reprezentativ unei valori + +:exemplu_simbol.class #=> Symbol + +status = :exemplu_simbol + +status == :exemplu_simbol #=> adevarat + +status == 'exemplu_simbol' #=> fals + +status == :aprobat #=> fals + +# Vectori + +# Acesta este un vector +vector = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Vectorii pot contine diferite tipuri de date + +[1, "salut", false] #=> [1, "salut", false] + +# Vectorii pot fi indexati +# de la inceput +vector[0] #=> 1 +vector[12] #=> nil + +# Ca si aritmetica, accessul [valoare] +# este doar "zahar sintactic" +# pentru a chema metoda [] a unui obiect +vector.[] 0 #=> 1 +vector.[] 12 #=> nil + +# De la sfarsit +vector[-1] #=> 5 + +# Cu un index de inceput si o lungime +vector[2, 3] #=> [3, 4, 5] + +# Sau cu un interval +vector[1..3] #=> [2, 3, 4] + +# Adauga elemente intr-un vector in felul urmator: +vector << 6 #=> [1, 2, 3, 4, 5, 6] + +# Hash-urile sunt dictionarele din Ruby cu perechi cheie/valoare. +# Hash-urile sunt notate cu acolade +hash = {'culoare' => 'verde', 'numar' => 5} + +hash.keys #=> ['culoare', 'numar'] + +# Poti lua valoare unui element dintr-un hash foarte rapid folosind cheia +hash['culoare'] #=> 'verde' +hash['numar'] #=> 5 + +# Incercand sa accesezi un element dintr-un hash printr-o cheie care nu exista va returna "nil". +hash['nimic_aici'] #=> nil + +# Incepand cu Ruby 1.9, este o sintaxa speciala pentru atunci cand se folosesc simboluri drept chei: + +hash_nou = { defcon: 3, actiune: true} + +hash_now.keys #=> [:defcon, :actiune] + +# Pont: Atat vectorii (Array) si hash-urile (Hash) sunt enumerabile (Enumerable) +# Ele impart o multime de metode utile precum each, map, count si altele + + +# Structuri de control + +if true + "instructiune if" +elsif false + "else if, optional" +else + "else, de asemenea optional" +end + +for numar in 1..5 + puts "iteratia #{numar}" +end +#=> iteratia 1 +#=> iteratia 2 +#=> iteratia 3 +#=> iteratia 4 +#=> iteratia 5 + +# TOTUSI, Nici una nu foloseste instructiunea for +# In locul acesteia ar trebui sa folosesti metoda "each" si sa ii trimiti un block +# Un bloc este o bucata de cod pe care o poti trimite unei metode precum "each". +# Este analog pentru "lambda", functii anonime, sau closures in alte limbaje de programare. +# +# The "each" method of a range runs the block once for each element of the range. +# Metoda "each" a unui interval, ruleaza block-ul o data pentru fiecare element din interval. +# Block-ul primeste ca si parametru un index +# Invocand metoda "each" cu un block, arata in urmatorul fel: + +(1..5).each do |index| + puts "iteratia #{index}" +end +#=> iteratia 1 +#=> iteratia 2 +#=> iteratia 3 +#=> iteratia 4 +#=> iteratia 5 + +# Poti de asemenea sa pui block-ul intre acolade +(1..5).each {|index| puts "iteratia #{index}"} + +# Continutul unei structuri de date poate fi parcurs folosind "each". +array.each do |element| + puts "#{element} parte din vector" +end +hash.each do |cheie, valoare| + puts "#{cheie} este #{valoare}" +end + +index = 1 +while index <= 5 do + puts "iteratia #{index}" + index += 1 +end +#=> iteratia 1 +#=> iteratia 2 +#=> iteratia 3 +#=> iteratia 4 +#=> iteratia 5 + +nota = 'B' + +case nota +when 'A' + puts "Bravo pustiule!" +when 'B' + puts "Mai mult noroc data viitoare" +when 'C' + puts "Poti mai mult" +when 'D' + puts "Incet, incet..." +when 'F' + puts "Ai esuat!" +else + puts "Sistem de notare alternativ?!" +end + +# Functii + +def dublu(x) + x * 2 +end + +# Functille (si toate block-urile) returneaza implicit valoarea ultimei instructiuni +dublu(2) #=> 4 + +# Parantezele sunt optionale cand rezultatul nu este ambiguu +dublu 3 #=> 6 + +dublu dublu 3 #=> 12 + +def suma(x,y) + x + y +end + +# Argumentele metodei sunt separate printr-o virgula +suma 3, 4 #=> 7 + +suma suma(3,4), 5 #=> 12 + +# yield +# Toate metodele au un parametru block, implicit si optional +# care poate fi invocat folosit cuvantul cheie 'yield' + +def incercuieste + puts "{" + yield + puts "}" +end + +incercuieste { puts 'Salut Mihai!' } + +# { +# Salut Mihai! +# } + + +# Poti trimite un block unei functii. +# "&" marcheaza o referinta trimisa unui block +def vizitatori(&block) + block.call "un_parametru" +end + +# Poti trimite o lista de argumente, care va fi convertita intr-un vector (array). +# Pentru asta se foloseste ("*") +def vizitatori(*vector) + vector.each { |vizitator| puts "#{vizitator}" } +end + +# Defineste o clasa folosind cuvantul cheie "class" +class Om + + # O variabila apartinand clasei. Este folosita in toate instantele clasei + @@specie = "H. sapiens" + + # Constructor + def initialize(nume, varsta=0) + # Atribuie argumentul, variabilei "nume", care apartine doar unei instante + @nume = nume + # Daca varsta nu este data, o sa ii atribuim valoarea implicita din lista de argumente (0, in cazul nostru) + @varsta = varsta + end + + # Metoda pentru a seta valoarea unei variabile + def nume=(nume) + @nume = nume + end + + # Metoda pentru a lua valoarea unei variabile + def nume + @nume + end + + # Functionalitatea de mai sus poate fi obtinuta folosing metoda "attr_accessor" dupa cum urmeaza: + attr_accessor :nume + + # Metodele pentru a lua si a seta valoarea unei variabile pot fi de asemenea obtinute individial: + attr_reader :nume + attr_writer :nume + + # O metoda apartinand unei clase foloseste "self" pentru a se diferentia de metodele unei instante ale clasei respective + # Poate fi invocata doar pe clasa, si nu pe o instanta a acesteia + def self.spune(msg) + puts "#{msg}" + end + + def specie + @@specie + end + +end + + +# Creaza o instanta a unei clase +ion = Om.new("Ionut Popescu") + +eugen = Om.new("Eugen Ionescu") + +# Sa invocam niste metode +ion.specie #=> "H. sapiens" +ion.nume #=> "Ionut Popescu" +ion.nume = "Ionut Popescu JR." #=> "Ionut Popescu JR." +ion.nume #=> "Ionut Popescu JR." +eugen.specie #=> "H. sapiens" +eugen.nume #=> "Eugen Ionescu" + +# Invoca o metoda a unei clase +Om.spune("Salut") #=> "Salut" + + +# Scopul unei variabile este definit de modul in care le numim +# Variabilele care incep cu $ au scop global +$var = "Sunt o variabila globala" +defined? $var #=> "global-variable" + +# Variabilele care incep cu @ apartin unei instante +@var = "Sunt o variabila a unei instante" +defined? @var #=> "instance-variable" + +# Variabilele care incep cu @@ apartin unei clase +@@var = "Sunt variabila unei clase" +defined? @@var #=> "class variable" + +# Variabilele care incep cu litera mare sunt constante +Var = "Sunt o constanta" +defined? Var #=> "constant" + +# Clasele sunt de asemenea obiecte in ruby. Astfel incat clasele pot avea variabile care apartin unei instante +# O variabila care apartine unei clase poate fi accesata de toate instantele acesteia si de clasele care o extind + +# clasa parinte +class Om + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(valoare) + @@foo = valoare + end +end + +# clasa copil +class Muncitor < Om +end + +Om.foo # 0 +Muncitor.foo # 0 + +Om.foo = 2 # 2 +Muncitor.foo # 2 + +# Variabilele care apartin unei instante ale unei clase, nu sunt impartite de (copii acesteia) clasele care o extind +class Om + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(valoare) + @bar = valoare + end +end + +class Doctor < Om +end + +Om.bar # 0 +Doctor.bar # nil + +module ExempluModul + def foo + 'foo' + end +end + +# Incluzand modulul instantei unui obiect +# Extinzand modulul unei instante ale unei clase + +class Persoana + include ExempluModul +end + +class Carte + extend ExempluModul +end + +Persoana.foo # => NoMethodError: undefined method `foo' for Persoana:Class +Persoana.new.foo # => 'foo' +Carte.foo # => 'foo' +Carte.new.foo # => NoMethodError: undefined method `foo' + +# Callbacks atunci cand includerea si extinderea unui modul sunt executate + +module ModulExempluCallBack + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class CevaRelevant + include ModulExempluCallBack +end + +CevaRelevant.bar # => 'bar' +CevaRelevant.qux # => NoMethodError: undefined method `qux' +CevaRelevant.new.bar # => NoMethodError: undefined method `bar' +CevaRelevant.new.qux # => 'qux' +``` -- cgit v1.2.3 From 0e0ae337d43d7c418f2fc59f62abede8de0323a4 Mon Sep 17 00:00:00 2001 From: Adrian Bordinc Date: Fri, 7 Mar 2014 20:01:32 +0100 Subject: Added bash/ro-ro translation --- .DS_Store | Bin 0 -> 15364 bytes ro-ro/bash-ro.html.markdown | 171 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 171 insertions(+) create mode 100644 .DS_Store create mode 100644 ro-ro/bash-ro.html.markdown diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..5ea5f7b2 Binary files /dev/null and b/.DS_Store differ diff --git a/ro-ro/bash-ro.html.markdown b/ro-ro/bash-ro.html.markdown new file mode 100644 index 00000000..fa91cca4 --- /dev/null +++ b/ro-ro/bash-ro.html.markdown @@ -0,0 +1,171 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] +translators: + - ["Adrian Bordinc", "https://github.com/ellimist"] +lang: ro-ro +filename: LearnBash-ro.sh +--- + +Bash este numele shell-ului unix, care a fost de asemenea distribuit drept shell pentru pentru sistemul de operare GNU si ca shell implicit pentru Linux si Mac OS X. +Aproape toate exemplele de mai jos pot fi parte dintr-un script sau pot fi executate direct in linia de comanda. + +[Citeste mai multe:](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Prima linie din script se numeste "shebang" care spune systemului cum sa execute scriptul +# http://en.wikipedia.org/wiki/Shebang_(Unix) +# Dupa cum te-ai prins deja, comentariile incep cu #. Shebang este de asemenea un comentariu. + +# Exemplu simplu de hello world: +echo Hello world! + +# Fiecare comanda incepe pe o linie noua, sau dupa punct si virgula ; +echo 'Prima linie'; echo 'A doua linie' + +# Declararea unei variabile se face astfel: +VARIABLE="Niste text" + +# DAR nu asa: +VARIABLE = "Niste text" +# Bash va crede ca VARIABLE este o comanda care trebuie executata si va +# returna o eroare pentru ca nu va putea fi gasita. + +# Folosind variabila: +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' +# Atunci cand folosesti variabila, o atribui, o exporti sau altfel, numele ei se scrie fara $. +# Daca vrei sa folosesti valoarea variabilei, atunci trebuie sa folosesti $. +# Atentie la faptul ca ' (apostrof) nu va inlocui variabla cu valoarea ei. + +# Inlocuirea de caractere in variabile +echo ${VARIABLE/Some/A} +# Asta va inlocui prima aparitie a "Some" cu "A" in variabila de mai sus. + +# Substring dintr-o variabila +echo ${VARIABLE:0:7} +# Asta va returna numai primele 7 caractere din variabila. + +# Valoarea implicita a unei variabile: +echo ${FOO:-"ValoareaImplicitaDacaFOOLipsesteSauEGoala"} +# Asta functioneaza pentru null (FOO=), sir de caractere gol (FOO=""), zero (FOO=0) returneaza 0 + +# Variabile pre-existente +echo "Ulima valoare returnata de ultimul program rulat: $?" +echo "ID-ul procesului (PID) care ruleaza scriptul: $$" +echo "Numarul de argumente: $#" +echo "Argumentele scriptului: $@" +echo "Argumentele scriptului separate in variabile: $1 $2..." + +# Citind o valoare din consola +echo "Care e numele tau?" +read NAME # Observa faptul ca nu a trebuit sa declaram o variabila noua +echo Salut, $NAME! + +# Avem obisnuita instructiune "if" +# Foloseste "man test" pentru mai multe informatii despre instructinea conditionala +if [ $NAME -ne $USER ] +then + echo "Numele tau este username-ul tau" +else + echo "Numele tau nu este username-ul tau" +fi + +# Este de asemenea si executarea conditionala de comenzi +echo "Intotdeauna executat" || echo "Executat numai daca prima instructiune esueaza" +echo "Intotdeauna executat" && echo "Executat numai daca prima instructiune NU esueaza" + +# Expresiile apar in urmatorul format +echo $(( 10 + 5 )) + +# Spre deosebire de alte limbaje de programare bash este un shell - asa ca +# functioneaza in contextul directorului curent. Poti vedea fisiere si directoare +# din directorul curent folosind comanda "ls": +ls + +# Aceste comenzi au optiuni care la controleaza executia +ls -l # Listeaza fiecare fisier si director pe o linie separata + +# Rezultatele comenzii precedente poate fi trimis urmatoarei comenzi drept argument +# Comanda grep filtreaza argumentele trimise cu sabloane. Astfel putem vedea fiserele +# .txt din directorul curent. +ls -l | grep "\.txt" + +# De asemenea poti redirectiona o comanda, input si error output +python2 hello.py < "input.in" +python2 hello.py > "output.out" +python2 hello.py 2> "error.err" +# Output-ul va suprascrie fisierul daca acesta exista. +# Daca vrei sa fie concatenate poti folosi ">>" + +# Comenzile pot fi inlocuite in interiorul altor comenzi folosind $( ): +# Urmatoarea comanda afiseaza numarul de fisiere si directoare din directorul curent +echo "Sunt $(ls | wc -l) fisiere aici." + +# The same can be done using backticks `` but they can't be nested - the preferred way +# is to use $( ). +# Acelasi lucru se poate obtine folosind apostrf-ul inversat ``, dar nu pot fi folosite +# unele in interiorul celorlalte asa ca modalitatea preferata este de a folosi $( ) +echo "Sunt `ls | wc -l` fisiere aici." + +# Bash foloseste o instructiune 'case' care functioneaza in mod similar cu instructiunea +# switch din Java si C++ +case "$VARIABLE" in + 0) echo "Este un zero.";; + 1) echo "Este un unu.";; + *) echo "Nu este null";; +esac + +# Instructiunea for parcurge toate elementele trimise: +# Continutul variabilei $VARIABLE este printat de 3 ori +for VARIABLE in {1..3} +do + echo "$VARIABLE" +done + +# while loop: +while [true] +do + echo "in interiorul iteratiei aici..." + break +done + +# De asemenea poti defini functii +# Definitie: +function foo () +{ + echo "Argumentele functioneaza ca si argumentele scriptului: $@" + echo "Si: $1 $2..." + echo "Asta este o functie" + return 0 +} + +# sau mai simplu +bar () +{ + echo "Alta metoda de a declara o functie" + return 0 +} + +# Invocarea unei functii +foo "Numele meu este: " $NAME + +# Sunt o multime de comenzi utile pe care ar trebui sa le inveti: +tail -n 10 file.txt +# printeaza ultimele 10 linii din fisierul file.txt +head -n 10 file.txt +# printeaza primele 10 linii din fisierul file.txt +sort file.txt +# sorteaza liniile din file.txt +uniq -d file.txt +# raporteaza sau omite liniile care se repeta, cu -d le raporteaza +cut -d ',' -f 1 file.txt +# printeaza doar prima coloana inainte de caracterul "," +``` -- cgit v1.2.3 From 54cde3d98d6d4365ee3f683b2a04882ac21ee0ed Mon Sep 17 00:00:00 2001 From: Adrian Bordinc Date: Fri, 7 Mar 2014 20:19:48 +0100 Subject: removed .DS_store --- .DS_Store | Bin 15364 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 5ea5f7b2..00000000 Binary files a/.DS_Store and /dev/null differ -- cgit v1.2.3 From 08f2ae632429f032f524a94226485cd6d69aa91d Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Mon, 10 Mar 2014 16:53:27 +0800 Subject: common-lisp-cn: refine Chinese translation Typos & refinements. --- zh-cn/common-lisp-cn.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/zh-cn/common-lisp-cn.html.markdown b/zh-cn/common-lisp-cn.html.markdown index f005dd58..c4dc3274 100644 --- a/zh-cn/common-lisp-cn.html.markdown +++ b/zh-cn/common-lisp-cn.html.markdown @@ -56,11 +56,11 @@ t ;还是一个原子,代表逻辑真值。 ;; 有很多不同的Common Lisp的实现;并且大部分的实现是一致(可移植)的。 ;; 对于入门学习来说,CLISP是个不错的选择。 -;; 可以通过QuickLisp.org's Quicklisp系统可以管理你的库。 +;; 可以通过QuickLisp.org的Quicklisp系统管理你的库。 -;; 通常,使用一个文本编辑器和一个的“REPL”来开发Common Lisp; +;; 通常,使用文本编辑器和“REPL”来开发Common Lisp; ;; (译者注:“REPL”指读取-求值-打印循环)。 -;; “REPL”允许对程序进行交互式的运行、调试,就好像在系统中这是一场“现场直播”。 +;; “REPL”允许对程序进行交互式的运行、调试,就好像在系统“现场”操作。 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -329,7 +329,7 @@ nil ; 逻辑假,或者空列表 ;; 或者使用`apply` (apply (lambda () "Hello World") nil) ; => "Hello World" -;; 显示地定义一个函数(译者注:即非匿名的) +;; 显式地定义一个函数(译者注:即非匿名的) (defun hello-world () "Hello World") (hello-world) ; => "Hello World" @@ -537,7 +537,7 @@ nil ; 逻辑假,或者空列表 ;; 注意到这些有用的返回信息——Common Lisp一直是一个交互式的系统。 ;; 若要定义一个方法; -;; 先让我们注意到我们计算自行车轮子周长时使用了这样一个公式:C = d * pi +;; 注意,我们计算自行车轮子周长时使用了这样一个公式:C = d * pi (defmethod circumference ((object bicycle)) (* pi (wheel-size object))) @@ -593,7 +593,7 @@ nil ; 逻辑假,或者空列表 ;; 然而,在一个比较现代化的编译环境下,这样的WHILE是没有必要的; ;; LOOP形式的循环和这个WHILE同样的好,并且更易于阅读。 -;; 注意到反引号'`',逗号','以及'@'符号,这三个符号; +;; 注意反引号'`',逗号','以及'@'这三个符号; ;; 反引号'`'是一种所谓“quasiquote”的引用类型的运算符,有了它,之后的逗号“,”才有意义。 ;; 逗号“,”意味着解除引用(unquote,即开始求值); ;; “@”符号则表示将当前的参数插入到当前整个列表中。 -- cgit v1.2.3 From d25c10969d2f21c2dde1c89b491f4a7ef15476c4 Mon Sep 17 00:00:00 2001 From: Ariel Date: Mon, 10 Mar 2014 17:05:49 -0400 Subject: Added some example code and resources. --- ruby.html.markdown | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index a4c74a4f..0a28a000 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -8,6 +8,8 @@ contributors: - ["Tristan Hume", "http://thume.ca/"] - ["Nick LaMuro", "https://github.com/NickLaMuro"] - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + --- ```ruby @@ -33,6 +35,7 @@ You shouldn't either 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 +2 ** 5 #=> 32 # Arithmetic is just syntactic sugar # for calling a method on an object @@ -79,6 +82,10 @@ placeholder = "use string interpolation" "I can #{placeholder} when using double quoted strings" #=> "I can use string interpolation when using double quoted strings" +#Combine strings but not with numbers +"hello " + "world" #=> "hello world" +"hello " + 3 #=> TypeError: can't convert Fixnum into String +"hello " +3.to_s #=> "hello 3" # print to the output puts "I'm printing!" @@ -247,6 +254,22 @@ else puts "Alternative grading system, eh?" end +#=> "Better luck next time" + +# cases can also use ranges +grade = 82 +case grade + when 90..100 + puts "Hooray!" + when 80...90 + puts "OK job" + else + puts "You failed!" +end + +#=> "OK job" + + # Functions def double(x) @@ -474,3 +497,12 @@ Something.qux # => NoMethodError: undefined method `qux' Something.new.bar # => NoMethodError: undefined method `bar' Something.new.qux # => 'qux' ``` + +## Additional resources + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. + + -- cgit v1.2.3 From 0590851a648b7afbc1fd8df332307688b9784a84 Mon Sep 17 00:00:00 2001 From: Ariel Date: Mon, 10 Mar 2014 17:23:49 -0400 Subject: Added a bit of example code and resources. --- javascript.html.markdown | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 85c5d817..03a12372 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -2,6 +2,7 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] filename: javascript.js --- @@ -103,7 +104,13 @@ false; "5" === 5; // = false // You can access characters in a string with charAt -"This is a string".charAt(0); +"This is a string".charAt(0); // = 'T' + +//...or use substring to get larger pieces +"Hello world".substring(0, 5); // = "Hello" + +// length is a property, so don't use () +"Hello".length; // = 5 // There's also null and undefined null; // used to indicate a deliberate non-value @@ -148,6 +155,9 @@ myArray[1]; // = 45 myArray.push("World"); myArray.length; // = 4 +// Add/Modify at specific index +myArray[3] = "Hello"; + // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; @@ -171,6 +181,8 @@ myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Logic and Control Structures +// The syntax for this section is almost identical to Java's. + // The if structure works as you'd expect. var count = 1; if (count == 3){ @@ -209,6 +221,27 @@ if (colour == "red" || colour == "blue"){ // && and || "short circuit", which is useful for setting default values. var name = otherName || "default"; + +// switch statement checks for equality with === +// use 'break' after each case +// or the cases after the correct one will be executed too. +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + /////////////////////////////////// // 4. Functions, Scope and Closures @@ -477,9 +510,13 @@ more about how to use JavaScript in web pages, start by learning about the [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. + [JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth guide of all the counter-intuitive parts of the language. +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. + In addition to direct contributors to this article, some content is adapted from Louie Dinh's Python tutorial on this site, and the [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -- cgit v1.2.3 From 933cf6f10d3e894edef4efe1c0d2a4e7aafd3192 Mon Sep 17 00:00:00 2001 From: Ariel Date: Mon, 10 Mar 2014 18:06:44 -0400 Subject: fixed space --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 0a28a000..962853a2 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -82,10 +82,10 @@ placeholder = "use string interpolation" "I can #{placeholder} when using double quoted strings" #=> "I can use string interpolation when using double quoted strings" -#Combine strings but not with numbers +# Combine strings, but not with numbers "hello " + "world" #=> "hello world" "hello " + 3 #=> TypeError: can't convert Fixnum into String -"hello " +3.to_s #=> "hello 3" +"hello " + 3.to_s #=> "hello 3" # print to the output puts "I'm printing!" -- cgit v1.2.3 From 6348a3adde95e72334bf8bfd1ca95079862c1c0b Mon Sep 17 00:00:00 2001 From: Ariel Date: Mon, 10 Mar 2014 18:08:50 -0400 Subject: space --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 03a12372..76017c17 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -106,7 +106,7 @@ false; // You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' -//...or use substring to get larger pieces +// ...or use substring to get larger pieces "Hello world".substring(0, 5); // = "Hello" // length is a property, so don't use () -- cgit v1.2.3 From 64e6da392320d0706520f4edf9008f8a775c8a78 Mon Sep 17 00:00:00 2001 From: dev-sala Date: Tue, 11 Mar 2014 15:37:10 +0100 Subject: Complited translation finishied translating brainfuck form english to italian --- it-it/brainfuck-it.html.markdown | 50 ++++++++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown index 2705fb4c..9316c35e 100644 --- a/it-it/brainfuck-it.html.markdown +++ b/it-it/brainfuck-it.html.markdown @@ -17,8 +17,10 @@ e sfrutta solo 8 caratteri. ``` -Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici) viene ignorato. -Branfuck è caratterizzato da un array (vettore) di 30,000 celle inizializzare a zero, e un puntatore che punta alla cella corrente. +Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici) +viene ignorato. +Branfuck è caratterizzato da un array (vettore) di 30,000 celle +inizializzare a zero, e un puntatore che punta alla cella corrente. Vi sono solo otto comando: + : Incrementa il valore della cella attuale di uno. @@ -56,31 +58,39 @@ per 5 volte, e otteniamo il valore 65, quindi stampaimo il valore della cella , [ > + < - ] > . -This program reads a character from the user input and copies the character into -cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, -move back to cell #1, and decrement the value at cell #1. This continues on -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. +Questo programma legge un carattere come input dall'utente, +quindi salva il carattere dentro la cella #1. +In seguito, incominca a ciclare. +Si sposta alla cella #², e increementa il valore della cella (#2). +Quindi torna alla cella #1, e decrementa il valore della cella (#1). +Questo continua fino a quando la cella #²1 diventa 0, e quindi la cella #2 +avrà il valore iniziale della cella #1. +Infine, visto che ci troviamo sulla cella #1 alla fine del ciclo, si sposta +sulla cella #2 e stampa il valore in ASCII. -Also keep in mind that the spaces are purely for readability purposes. You -could just as easily write it as: +Gli spazi nel codice sovrastante, sono presenti solo a scopo di ottenere +una maggiore leggibilità, si poteva anche scrivere senza: ,[>+<-]>. -Try and figure out what this program does: +Proviamo, adesso, a capire cosa fa invece questo programma: ,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> -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. 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. +Prende due numeri in input e quindi li moltiplica. + +Prima prende in input i due numeri (,>,<), quindi inizia un cilclo +basandosi sulla cella #1. +Quindi si sposta sulla cella #2, e inizia un altro ciclo condizionato +dal valore della cella #2, incrementando la cella #3. +Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno +la cella #2 ha valore 0. In questo caso, quando il ciclo esterno rifarà +partire il ciclo interno, non funzionerà più perchè la cella #2 ha valore 0. +Per ovviare a questo problema, oltre alla cella 3, incrementiamo anche la cella +#4, e alla fine di ogni ciclo interno copiala il valore della cella #4 +nella cella #2, in modo che il ciclo interno +possa essere eseguito una altra volta. +Alla fine la cella #3 contiene il risultato. ``` E questo è brainfuck...Non è difficele, vero? -- cgit v1.2.3 From 92aa655d76f05ead8b4c9130f575740c1233e8ab Mon Sep 17 00:00:00 2001 From: dev-sala Date: Tue, 11 Mar 2014 15:40:05 +0100 Subject: Revert "Complited translation" This reverts commit 64e6da392320d0706520f4edf9008f8a775c8a78. --- it-it/brainfuck-it.html.markdown | 50 ++++++++++++++++------------------------ 1 file changed, 20 insertions(+), 30 deletions(-) diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown index 9316c35e..2705fb4c 100644 --- a/it-it/brainfuck-it.html.markdown +++ b/it-it/brainfuck-it.html.markdown @@ -17,10 +17,8 @@ e sfrutta solo 8 caratteri. ``` -Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici) -viene ignorato. -Branfuck è caratterizzato da un array (vettore) di 30,000 celle -inizializzare a zero, e un puntatore che punta alla cella corrente. +Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici) viene ignorato. +Branfuck è caratterizzato da un array (vettore) di 30,000 celle inizializzare a zero, e un puntatore che punta alla cella corrente. Vi sono solo otto comando: + : Incrementa il valore della cella attuale di uno. @@ -58,39 +56,31 @@ per 5 volte, e otteniamo il valore 65, quindi stampaimo il valore della cella , [ > + < - ] > . -Questo programma legge un carattere come input dall'utente, -quindi salva il carattere dentro la cella #1. -In seguito, incominca a ciclare. -Si sposta alla cella #², e increementa il valore della cella (#2). -Quindi torna alla cella #1, e decrementa il valore della cella (#1). -Questo continua fino a quando la cella #²1 diventa 0, e quindi la cella #2 -avrà il valore iniziale della cella #1. -Infine, visto che ci troviamo sulla cella #1 alla fine del ciclo, si sposta -sulla cella #2 e stampa il valore in ASCII. +This program reads a character from the user input and copies the character into +cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, +move back to cell #1, and decrement the value at cell #1. This continues on +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. -Gli spazi nel codice sovrastante, sono presenti solo a scopo di ottenere -una maggiore leggibilità, si poteva anche scrivere senza: +Also keep in mind that the spaces are purely for readability purposes. You +could just as easily write it as: ,[>+<-]>. -Proviamo, adesso, a capire cosa fa invece questo programma: +Try and figure out what this program does: ,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> -Prende due numeri in input e quindi li moltiplica. - -Prima prende in input i due numeri (,>,<), quindi inizia un cilclo -basandosi sulla cella #1. -Quindi si sposta sulla cella #2, e inizia un altro ciclo condizionato -dal valore della cella #2, incrementando la cella #3. -Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno -la cella #2 ha valore 0. In questo caso, quando il ciclo esterno rifarà -partire il ciclo interno, non funzionerà più perchè la cella #2 ha valore 0. -Per ovviare a questo problema, oltre alla cella 3, incrementiamo anche la cella -#4, e alla fine di ogni ciclo interno copiala il valore della cella #4 -nella cella #2, in modo che il ciclo interno -possa essere eseguito una altra volta. -Alla fine la cella #3 contiene il risultato. +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. 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. ``` E questo è brainfuck...Non è difficele, vero? -- cgit v1.2.3 From a679cc8281627bfce9337774fb076bcd402007e5 Mon Sep 17 00:00:00 2001 From: dev-sala Date: Tue, 11 Mar 2014 15:44:47 +0100 Subject: Complited translation finished translating brainfuck from english to italian --- it-it/brainfuck-it.html.markdown | 51 +++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown index 2705fb4c..4999d7e6 100644 --- a/it-it/brainfuck-it.html.markdown +++ b/it-it/brainfuck-it.html.markdown @@ -17,8 +17,10 @@ e sfrutta solo 8 caratteri. ``` -Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici) viene ignorato. -Branfuck è caratterizzato da un array (vettore) di 30,000 celle inizializzare a zero, e un puntatore che punta alla cella corrente. +Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici) +viene ignorato. +Branfuck è caratterizzato da un array (vettore) di 30,000 celle +inizializzare a zero, e un puntatore che punta alla cella corrente. Vi sono solo otto comando: + : Incrementa il valore della cella attuale di uno. @@ -56,31 +58,39 @@ per 5 volte, e otteniamo il valore 65, quindi stampaimo il valore della cella , [ > + < - ] > . -This program reads a character from the user input and copies the character into -cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, -move back to cell #1, and decrement the value at cell #1. This continues on -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. +Questo programma legge un carattere come input dall'utente, +quindi salva il carattere dentro la cella #1. +In seguito, incominca a ciclare. +Si sposta alla cella #², e increementa il valore della cella (#2). +Quindi torna alla cella #1, e decrementa il valore della cella (#1). +Questo continua fino a quando la cella #²1 diventa 0, e quindi la cella #2 +avrà il valore iniziale della cella #1. +Infine, visto che ci troviamo sulla cella #1 alla fine del ciclo, si sposta +sulla cella #2 e stampa il valore in ASCII. -Also keep in mind that the spaces are purely for readability purposes. You -could just as easily write it as: +Gli spazi nel codice sovrastante, sono presenti solo a scopo di ottenere +una maggiore leggibilità, si poteva anche scrivere senza: ,[>+<-]>. -Try and figure out what this program does: +Proviamo, adesso, a capire cosa fa invece questo programma: ,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> -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. 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. +Prende due numeri in input e quindi li moltiplica. + +Prima prende in input i due numeri (,>,<), quindi inizia un cilclo +basandosi sulla cella #1. +Quindi si sposta sulla cella #2, e inizia un altro ciclo condizionato +dal valore della cella #2, incrementando la cella #3. +Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno +la cella #2 ha valore 0. In questo caso, quando il ciclo esterno rifarà +partire il ciclo interno, non funzionerà più perchè la cella #2 ha valore 0. +Per ovviare a questo problema, oltre alla cella 3, incrementiamo anche la cella +#4, e alla fine di ogni ciclo interno copiala il valore della cella #4 +nella cella #2, in modo che il ciclo interno +possa essere eseguito una altra volta. +Alla fine la cella #3 contiene il risultato. ``` E questo è brainfuck...Non è difficele, vero? @@ -89,4 +99,3 @@ oppure puoi scrivere un interprete brainfuck in un altro linguaggio. L'interprete è abbastanza semplice da implementare, ma se sei veramente masochista prova ad implementare un interprete brainfuck in... brainfuck. - -- cgit v1.2.3 From 194d910e1bfc897592e2431cc06bd78865afc933 Mon Sep 17 00:00:00 2001 From: dev-sala Date: Tue, 11 Mar 2014 15:50:12 +0100 Subject: [Java/it-it] fixed link --- it-it/java-it.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 127569c3..e729f223 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -6,7 +6,7 @@ contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Madison Dickson", "http://github.com/mix3d"] translators: - - ["Ivan Sala","http://github.com/dev-sala"] + - ["Ivan Sala","http://github.com/slavni96"] lang: it-it --- -- cgit v1.2.3 From 6c3fb00239fc0a6bb518a5b086827140403bbb1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Guilherme=20Farias=20Duda?= Date: Fri, 14 Mar 2014 14:37:48 -0200 Subject: Create xml.html.markdown --- xml.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 xml.html.markdown diff --git a/xml.html.markdown b/xml.html.markdown new file mode 100644 index 00000000..4063afdc --- /dev/null +++ b/xml.html.markdown @@ -0,0 +1,7 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +--- + -- cgit v1.2.3 From 91bab3c90cd8b8b16521b7359977edcd90bc6bdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Guilherme=20Farias=20Duda?= Date: Fri, 14 Mar 2014 15:53:38 -0200 Subject: XML - Syntax and Document Definition using DTD The only problem was highlighting the DTD code without breaking the XML code block. --- xml.html.markdown | 124 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) diff --git a/xml.html.markdown b/xml.html.markdown index 4063afdc..349d4763 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -5,3 +5,127 @@ contributors: - ["João Farias", "https://github.com/JoaoGFarias"] --- +XML is a markup language designed to store and transport data. + +Unlike HTML, XML does not specifies how to display or to format data, just carry it. + +* XML Syntax + +```XML + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + + + +computer.gif + + +``` + +* Well-Formated Document x Validation + +A XML document is well-formated if it is syntactically correct. +However, is possible to inject more constraints in the document, +using document definitions, such as DTD and XML Schema. + +A XML document which follows a document definition is called valid, +regarding that document. + +With this tool, you can check the XML data outside the application logic. + +```XML + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + + + +``` + + + -- cgit v1.2.3 From ef16c2025e11b26f0589cd3719e55237abbb8a35 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 14 Mar 2014 18:18:23 +0000 Subject: Fix syntax errors in coffeescript headers --- coffeescript.html.markdown | 2 +- zh-cn/coffeescript-cn.html.markdown | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index 86c875ba..82c6024c 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -2,7 +2,7 @@ language: coffeescript contributors: - ["Tenor Biel", "http://github.com/L8D"] - - ["Xavier Yao"], "http://github.com/xavieryao"] + - ["Xavier Yao", "http://github.com/xavieryao"] filename: coffeescript.coffee --- diff --git a/zh-cn/coffeescript-cn.html.markdown b/zh-cn/coffeescript-cn.html.markdown index 8fb96749..44561541 100644 --- a/zh-cn/coffeescript-cn.html.markdown +++ b/zh-cn/coffeescript-cn.html.markdown @@ -2,9 +2,9 @@ language: coffeescript contributors: - ["Tenor Biel", "http://github.com/L8D"] - - ["Xavier Yao"], "http://github.com/xavieryao"] + - ["Xavier Yao", "http://github.com/xavieryao"] translators: - - ["Xavier Yao"], "http://github.com/xavieryao"] + - ["Xavier Yao", "http://github.com/xavieryao"] filename: coffeescript-cn.coffee lang: zh-cn --- -- cgit v1.2.3 From 04e1239c1230b3f6438ab36cb5c3d60242f28711 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 14 Mar 2014 18:19:06 +0000 Subject: fix syntax error --- id-id/css-id.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/id-id/css-id.html.markdown b/id-id/css-id.html.markdown index d0798ec7..456dfafe 100644 --- a/id-id/css-id.html.markdown +++ b/id-id/css-id.html.markdown @@ -1,3 +1,4 @@ +--- language: css contributors: - ["Mohammad Valipour", "https://github.com/mvalipour"] -- cgit v1.2.3 From 9395900afd940e265b21a050f05290214ef37d44 Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Tue, 18 Mar 2014 13:57:02 -0500 Subject: Remove multiline comments Julia introduced "#=" and "=#" as the delimiters for multiline comments. --- julia.html.markdown | 318 ++++++++++++++++++++++++++-------------------------- 1 file changed, 159 insertions(+), 159 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index b8e24b39..8245e616 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -21,58 +21,58 @@ This is based on the current development version of Julia, as of October 18th, 2 # Everything in Julia is a expression. # There are several basic types of numbers. -3 #=> 3 (Int64) -3.2 #=> 3.2 (Float64) -2 + 1im #=> 2 + 1im (Complex{Int64}) -2//3 #=> 2//3 (Rational{Int64}) +3 # => 3 (Int64) +3.2 # => 3.2 (Float64) +2 + 1im # => 2 + 1im (Complex{Int64}) +2//3 # => 2//3 (Rational{Int64}) # All of the normal infix operators are available. -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7.0 -5 / 2 #=> 2.5 # dividing an Int by an Int always results in a Float -div(5, 2) #=> 2 # for a truncated result, use div -5 \ 35 #=> 7.0 -2 ^ 2 #=> 4 # power, not bitwise xor -12 % 10 #=> 2 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 +5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float +div(5, 2) # => 2 # for a truncated result, use div +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # power, not bitwise xor +12 % 10 # => 2 # Enforce precedence with parentheses -(1 + 3) * 2 #=> 8 +(1 + 3) * 2 # => 8 # Bitwise Operators -~2 #=> -3 # bitwise not -3 & 5 #=> 1 # bitwise and -2 | 4 #=> 6 # bitwise or -2 $ 4 #=> 6 # bitwise xor -2 >>> 1 #=> 1 # logical shift right -2 >> 1 #=> 1 # arithmetic shift right -2 << 1 #=> 4 # logical/arithmetic shift left +~2 # => -3 # bitwise not +3 & 5 # => 1 # bitwise and +2 | 4 # => 6 # bitwise or +2 $ 4 # => 6 # bitwise xor +2 >>> 1 # => 1 # logical shift right +2 >> 1 # => 1 # arithmetic shift right +2 << 1 # => 4 # logical/arithmetic shift left # You can use the bits function to see the binary representation of a number. bits(12345) -#=> "0000000000000000000000000000000000000000000000000011000000111001" +# => "0000000000000000000000000000000000000000000000000011000000111001" bits(12345.0) -#=> "0100000011001000000111001000000000000000000000000000000000000000" +# => "0100000011001000000111001000000000000000000000000000000000000000" # Boolean values are primitives true false # Boolean operators -!true #=> false -!false #=> true -1 == 1 #=> true -2 == 1 #=> false -1 != 1 #=> false -2 != 1 #=> true -1 < 10 #=> true -1 > 10 #=> false -2 <= 2 #=> true -2 >= 2 #=> true +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +1 < 10 # => true +1 > 10 # => false +2 <= 2 # => true +2 >= 2 # => true # Comparisons can be chained -1 < 2 < 3 #=> true -2 < 3 < 2 #=> false +1 < 2 < 3 # => true +2 < 3 < 2 # => false # Strings are created with " "This is a string." @@ -81,12 +81,12 @@ false 'a' # A string can be indexed like an array of characters -"This is a string"[1] #=> 'T' # Julia indexes from 1 +"This is a string"[1] # => 'T' # Julia indexes from 1 # However, this is will not work well for UTF8 strings, # so iterating over strings is recommended (map, for loops, etc). # $ can be used for string interpolation: -"2 + 2 = $(2 + 2)" #=> "2 + 2 = 4" +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" # You can put any Julia expression inside the parenthesis. # Another way to format strings is the printf macro. @@ -100,24 +100,24 @@ println("I'm Julia. Nice to meet you!") #################################################### # You don't declare variables before assigning to them. -some_var = 5 #=> 5 -some_var #=> 5 +some_var = 5 # => 5 +some_var # => 5 # Accessing a previously unassigned variable is an error try - some_other_var #=> ERROR: some_other_var not defined + some_other_var # => ERROR: some_other_var not defined catch e println(e) end # Variable names start with a letter. # After that, you can use letters, digits, underscores, and exclamation points. -SomeOtherVar123! = 6 #=> 6 +SomeOtherVar123! = 6 # => 6 # You can also use unicode characters -☃ = 8 #=> 8 +☃ = 8 # => 8 # These are especially handy for mathematical notation -2 * π #=> 6.283185307179586 +2 * π # => 6.283185307179586 # A note on naming conventions in Julia: # @@ -133,49 +133,49 @@ SomeOtherVar123! = 6 #=> 6 # functions are sometimes called mutating functions or in-place functions. # Arrays store a sequence of values indexed by integers 1 through n: -a = Int64[] #=> 0-element Int64 Array +a = Int64[] # => 0-element Int64 Array # 1-dimensional array literals can be written with comma-separated values. -b = [4, 5, 6] #=> 3-element Int64 Array: [4, 5, 6] -b[1] #=> 4 -b[end] #=> 6 +b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] +b[1] # => 4 +b[end] # => 6 # 2-dimentional arrays use space-separated values and semicolon-separated rows. -matrix = [1 2; 3 4] #=> 2x2 Int64 Array: [1 2; 3 4] +matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] # Add stuff to the end of a list with push! and append! -push!(a,1) #=> [1] -push!(a,2) #=> [1,2] -push!(a,4) #=> [1,2,4] -push!(a,3) #=> [1,2,4,3] -append!(a,b) #=> [1,2,4,3,4,5,6] +push!(a,1) # => [1] +push!(a,2) # => [1,2] +push!(a,4) # => [1,2,4] +push!(a,3) # => [1,2,4,3] +append!(a,b) # => [1,2,4,3,4,5,6] # Remove from the end with pop -pop!(b) #=> 6 and b is now [4,5] +pop!(b) # => 6 and b is now [4,5] # Let's put it back push!(b,6) # b is now [4,5,6] again. -a[1] #=> 1 # remember that Julia indexes from 1, not 0! +a[1] # => 1 # remember that Julia indexes from 1, not 0! # end is a shorthand for the last index. It can be used in any # indexing expression -a[end] #=> 6 +a[end] # => 6 # we also have shift and unshift -shift!(a) #=> 1 and a is now [2,4,3,4,5,6] -unshift!(a,7) #=> [7,2,4,3,4,5,6] +shift!(a) # => 1 and a is now [2,4,3,4,5,6] +unshift!(a,7) # => [7,2,4,3,4,5,6] # Function names that end in exclamations points indicate that they modify # their argument. -arr = [5,4,6] #=> 3-element Int64 Array: [5,4,6] -sort(arr) #=> [4,5,6]; arr is still [5,4,6] -sort!(arr) #=> [4,5,6]; arr is now [4,5,6] +arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] +sort(arr) # => [4,5,6]; arr is still [5,4,6] +sort!(arr) # => [4,5,6]; arr is now [4,5,6] # Looking out of bounds is a BoundsError try - a[0] #=> ERROR: BoundsError() in getindex at array.jl:270 - a[end+1] #=> ERROR: BoundsError() in getindex at array.jl:270 + a[0] # => ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 catch e println(e) end @@ -185,110 +185,110 @@ end # inside the julia folder to find these files. # You can initialize arrays from ranges -a = [1:5] #=> 5-element Int64 Array: [1,2,3,4,5] +a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] # You can look at ranges with slice syntax. -a[1:3] #=> [1, 2, 3] -a[2:] #=> [2, 3, 4, 5] -a[2:end] #=> [2, 3, 4, 5] +a[1:3] # => [1, 2, 3] +a[2:] # => [2, 3, 4, 5] +a[2:end] # => [2, 3, 4, 5] # Remove elements from an array by index with splice! arr = [3,4,5] -splice!(arr,2) #=> 4 ; arr is now [3,5] +splice!(arr,2) # => 4 ; arr is now [3,5] # Concatenate lists with append! b = [1,2,3] append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] # Check for existence in a list with in -in(1, a) #=> true +in(1, a) # => true # Examine the length with length -length(a) #=> 8 +length(a) # => 8 # Tuples are immutable. -tup = (1, 2, 3) #=> (1,2,3) # an (Int64,Int64,Int64) tuple. -tup[1] #=> 1 +tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. +tup[1] # => 1 try: - tup[1] = 3 #=> ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) + tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) catch e println(e) end # Many list functions also work on tuples -length(tup) #=> 3 -tup[1:2] #=> (1,2) -in(2, tup) #=> true +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true # You can unpack tuples into variables -a, b, c = (1, 2, 3) #=> (1,2,3) # a is now 1, b is now 2 and c is now 3 +a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 # Tuples are created even if you leave out the parentheses -d, e, f = 4, 5, 6 #=> (4,5,6) +d, e, f = 4, 5, 6 # => (4,5,6) # A 1-element tuple is distinct from the value it contains -(1,) == 1 #=> false -(1) == 1 #=> true +(1,) == 1 # => false +(1) == 1 # => true # Look how easy it is to swap two values -e, d = d, e #=> (5,4) # d is now 5 and e is now 4 +e, d = d, e # => (5,4) # d is now 5 and e is now 4 # Dictionaries store mappings -empty_dict = Dict() #=> Dict{Any,Any}() +empty_dict = Dict() # => Dict{Any,Any}() # You can create a dictionary using a literal filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] # => Dict{ASCIIString,Int64} # Look up values with [] -filled_dict["one"] #=> 1 +filled_dict["one"] # => 1 # Get all keys keys(filled_dict) -#=> KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Note - dictionary keys are not sorted or in the order you inserted them. # Get all values values(filled_dict) -#=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Note - Same as above regarding key ordering. # Check for existence of keys in a dictionary with in, haskey -in(("one", 1), filled_dict) #=> true -in(("two", 3), filled_dict) #=> false -haskey(filled_dict, "one") #=> true -haskey(filled_dict, 1) #=> false +in(("one", 1), filled_dict) # => true +in(("two", 3), filled_dict) # => false +haskey(filled_dict, "one") # => true +haskey(filled_dict, 1) # => false # Trying to look up a non-existant key will raise an error try - filled_dict["four"] #=> ERROR: key not found: four in getindex at dict.jl:489 + filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 catch e println(e) end # Use the get method to avoid that error by providing a default value # get(dictionary,key,default_value) -get(filled_dict,"one",4) #=> 1 -get(filled_dict,"four",4) #=> 4 +get(filled_dict,"one",4) # => 1 +get(filled_dict,"four",4) # => 4 # Use Sets to represent collections of unordered, unique values -empty_set = Set() #=> Set{Any}() +empty_set = Set() # => Set{Any}() # Initialize a set with values -filled_set = Set(1,2,2,3,4) #=> Set{Int64}(1,2,3,4) +filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) # Add more values to a set -push!(filled_set,5) #=> Set{Int64}(5,4,2,3,1) +push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) # Check if the values are in the set -in(2, filled_set) #=> true -in(10, filled_set) #=> false +in(2, filled_set) # => true +in(10, filled_set) # => false # There are functions for set intersection, union, and difference. -other_set = Set(3, 4, 5, 6) #=> Set{Int64}(6,4,5,3) -intersect(filled_set, other_set) #=> Set{Int64}(3,4,5) -union(filled_set, other_set) #=> Set{Int64}(1,2,3,4,5,6) -setdiff(Set(1,2,3,4),Set(2,3,5)) #=> Set{Int64}(1,4) +other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) +intersect(filled_set, other_set) # => Set{Int64}(3,4,5) +union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) +setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) #################################################### @@ -306,7 +306,7 @@ elseif some_var < 10 # This elseif clause is optional. else # The else clause is optional too. println("some_var is indeed 10.") end -#=> prints "some var is smaller than 10" +# => prints "some var is smaller than 10" # For loops iterate over iterables. @@ -363,7 +363,7 @@ try catch e println("caught it $e") end -#=> caught it ErrorException("help") +# => caught it ErrorException("help") #################################################### @@ -381,7 +381,7 @@ function add(x, y) x + y end -add(5, 6) #=> 11 after printing out "x is 5 and y is 6" +add(5, 6) # => 11 after printing out "x is 5 and y is 6" # You can define functions that take a variable number of # positional arguments @@ -389,20 +389,20 @@ function varargs(args...) return args # use the keyword return to return anywhere in the function end -#=> varargs (generic function with 1 method) +# => varargs (generic function with 1 method) -varargs(1,2,3) #=> (1,2,3) +varargs(1,2,3) # => (1,2,3) # The ... is called a splat. # We just used it in a function definition. # It can also be used in a fuction call, # where it will splat an Array or Tuple's contents into the argument list. -Set([1,2,3]) #=> Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays -Set([1,2,3]...) #=> Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) +Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays +Set([1,2,3]...) # => Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) -x = (1,2,3) #=> (1,2,3) -Set(x) #=> Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples -Set(x...) #=> Set{Int64}(2,3,1) +x = (1,2,3) # => (1,2,3) +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples +Set(x...) # => Set{Int64}(2,3,1) # You can define functions with optional positional arguments @@ -410,12 +410,12 @@ function defaults(a,b,x=5,y=6) return "$a $b and $x $y" end -defaults('h','g') #=> "h g and 5 6" -defaults('h','g','j') #=> "h g and j 6" -defaults('h','g','j','k') #=> "h g and j k" +defaults('h','g') # => "h g and 5 6" +defaults('h','g','j') # => "h g and j 6" +defaults('h','g','j','k') # => "h g and j k" try - defaults('h') #=> ERROR: no method defaults(Char,) - defaults() #=> ERROR: no methods defaults() + defaults('h') # => ERROR: no method defaults(Char,) + defaults() # => ERROR: no methods defaults() catch e println(e) end @@ -425,9 +425,9 @@ function keyword_args(;k1=4,name2="hello") # note the ; return ["k1"=>k1,"name2"=>name2] end -keyword_args(name2="ness") #=> ["name2"=>"ness","k1"=>4] -keyword_args(k1="mine") #=> ["k1"=>"mine","name2"=>"hello"] -keyword_args() #=> ["name2"=>"hello","k1"=>4] +keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] +keyword_args() # => ["name2"=>"hello","k1"=>4] # You can combine all kinds of arguments in the same function function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") @@ -451,7 +451,7 @@ function create_adder(x) end # This is "stabby lambda syntax" for creating anonymous functions -(x -> x > 2)(3) #=> true +(x -> x > 2)(3) # => true # This function is identical to create_adder implementation above. function create_adder(x) @@ -467,16 +467,16 @@ function create_adder(x) end add_10 = create_adder(10) -add_10(3) #=> 13 +add_10(3) # => 13 # There are built-in higher order functions -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] +map(add_10, [1,2,3]) # => [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # We can use list comprehensions for nicer maps -[add_10(i) for i=[1, 2, 3]] #=> [11, 12, 13] -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] #################################################### ## 5. Types @@ -485,11 +485,11 @@ filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] # Julia has a type system. # Every value has a type; variables do not have types themselves. # You can use the `typeof` function to get the type of a value. -typeof(5) #=> Int64 +typeof(5) # => Int64 # Types are first-class values -typeof(Int64) #=> DataType -typeof(DataType) #=> DataType +typeof(Int64) # => DataType +typeof(DataType) # => DataType # DataType is the type that represents types, including itself. # Types are used for documentation, optimizations, and dispatch. @@ -510,10 +510,10 @@ end # The default constructor's arguments are the properties # of the type, in the order they are listed in the definition -tigger = Tiger(3.5,"orange") #=> Tiger(3.5,"orange") +tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") # The type doubles as the constructor function for values of that type -sherekhan = typeof(tigger)(5.6,"fire") #=> Tiger(5.6,"fire") +sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") # These struct-style types are called concrete types # They can be instantiated, but cannot have subtypes. @@ -524,23 +524,23 @@ abstract Cat # just a name and point in the type hierarchy # Abstract types cannot be instantiated, but can have subtypes. # For example, Number is an abstract type -subtypes(Number) #=> 6-element Array{Any,1}: +subtypes(Number) # => 6-element Array{Any,1}: # Complex{Float16} # Complex{Float32} # Complex{Float64} # Complex{T<:Real} # ImaginaryUnit # Real -subtypes(Cat) #=> 0-element Array{Any,1} +subtypes(Cat) # => 0-element Array{Any,1} # Every type has a super type; use the `super` function to get it. -typeof(5) #=> Int64 -super(Int64) #=> Signed -super(Signed) #=> Real -super(Real) #=> Number -super(Number) #=> Any -super(super(Signed)) #=> Number -super(Any) #=> Any +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Number +super(Any) # => Any # All of these type, except for Int64, are abstract. # <: is the subtyping operator @@ -588,23 +588,23 @@ function meow(animal::Tiger) end # Testing the meow function -meow(tigger) #=> "rawwr" -meow(Lion("brown","ROAAR")) #=> "ROAAR" -meow(Panther()) #=> "grrr" +meow(tigger) # => "rawwr" +meow(Lion("brown","ROAAR")) # => "ROAAR" +meow(Panther()) # => "grrr" # Review the local type hierarchy -issubtype(Tiger,Cat) #=> false -issubtype(Lion,Cat) #=> true -issubtype(Panther,Cat) #=> true +issubtype(Tiger,Cat) # => false +issubtype(Lion,Cat) # => true +issubtype(Panther,Cat) # => true # Defining a function that takes Cats function pet_cat(cat::Cat) println("The cat says $(meow(cat))") end -pet_cat(Lion("42")) #=> prints "The cat says 42" +pet_cat(Lion("42")) # => prints "The cat says 42" try - pet_cat(tigger) #=> ERROR: no method pet_cat(Tiger,) + pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) catch e println(e) end @@ -617,31 +617,31 @@ end function fight(t::Tiger,c::Cat) println("The $(t.coatcolor) tiger wins!") end -#=> fight (generic function with 1 method) +# => fight (generic function with 1 method) -fight(tigger,Panther()) #=> prints The orange tiger wins! -fight(tigger,Lion("ROAR")) #=> prints The orange tiger wins! +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! # Let's change the behavior when the Cat is specifically a Lion fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") -#=> fight (generic function with 2 methods) +# => fight (generic function with 2 methods) -fight(tigger,Panther()) #=> prints The orange tiger wins! -fight(tigger,Lion("ROAR")) #=> prints The green-maned lion wins! +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! # We don't need a Tiger in order to fight fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") -#=> fight (generic function with 3 methods) +# => fight (generic function with 3 methods) -fight(Lion("balooga!"),Panther()) #=> prints The victorious cat says grrr +fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr try - fight(Panther(),Lion("RAWR")) #=> ERROR: no method fight(Panther,Lion) + fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) catch end # Also let the cat go first fight(c::Cat,l::Lion) = println("The cat beats the Lion") -#=> Warning: New definition +# => Warning: New definition # fight(Cat,Lion) at none:1 # is ambiguous with # fight(Lion,Cat) at none:2. @@ -651,11 +651,11 @@ fight(c::Cat,l::Lion) = println("The cat beats the Lion") #fight (generic function with 4 methods) # This warning is because it's unclear which fight will be called in: -fight(Lion("RAR"),Lion("brown","rarrr")) #=> prints The victorious cat says rarrr +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr # The result may be different in other versions of Julia fight(l::Lion,l2::Lion) = println("The lions come to a tie") -fight(Lion("RAR"),Lion("brown","rarrr")) #=> prints The lions come to a tie +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie # Under the hood -- cgit v1.2.3 From a375065b1993d281a54a868675273de0a322ed04 Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Tue, 18 Mar 2014 14:05:24 -0500 Subject: Fix julia comments in russian version --- ru-ru/julia-ru.html.markdown | 318 +++++++++++++++++++++---------------------- 1 file changed, 159 insertions(+), 159 deletions(-) diff --git a/ru-ru/julia-ru.html.markdown b/ru-ru/julia-ru.html.markdown index c9213a42..cd55e116 100644 --- a/ru-ru/julia-ru.html.markdown +++ b/ru-ru/julia-ru.html.markdown @@ -24,58 +24,58 @@ Julia — гомоиконный функциональный язык прог # Всё в Julia — выражение. # Простые численные типы -3 #=> 3 (Int64) -3.2 #=> 3.2 (Float64) -2 + 1im #=> 2 + 1im (Complex{Int64}) -2//3 #=> 2//3 (Rational{Int64}) +3 # => 3 (Int64) +3.2 # => 3.2 (Float64) +2 + 1im # => 2 + 1im (Complex{Int64}) +2//3 # => 2//3 (Rational{Int64}) # Доступны все привычные инфиксные операторы -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7.0 -5 / 2 #=> 2.5 # деление Int на Int всегда возвращает Float -div(5, 2) #=> 2 # для округления к нулю используется div -5 \ 35 #=> 7.0 -2 ^ 2 #=> 4 # возведение в степень -12 % 10 #=> 2 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 +5 / 2 # => 2.5 # деление Int на Int всегда возвращает Float +div(5, 2) # => 2 # для округления к нулю используется div +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # возведение в степень +12 % 10 # => 2 # С помощью скобок можно изменить приоритет операций -(1 + 3) * 2 #=> 8 +(1 + 3) * 2 # => 8 # Побитовые операторы -~2 #=> -3 # НЕ (NOT) -3 & 5 #=> 1 # И (AND) -2 | 4 #=> 6 # ИЛИ (OR) -2 $ 4 #=> 6 # сложение по модулю 2 (XOR) -2 >>> 1 #=> 1 # логический сдвиг вправо -2 >> 1 #=> 1 # арифметический сдвиг вправо -2 << 1 #=> 4 # логический/арифметический сдвиг влево +~2 # => -3 # НЕ (NOT) +3 & 5 # => 1 # И (AND) +2 | 4 # => 6 # ИЛИ (OR) +2 $ 4 # => 6 # сложение по модулю 2 (XOR) +2 >>> 1 # => 1 # логический сдвиг вправо +2 >> 1 # => 1 # арифметический сдвиг вправо +2 << 1 # => 4 # логический/арифметический сдвиг влево # Функция bits возвращает бинарное представление числа bits(12345) -#=> "0000000000000000000000000000000000000000000000000011000000111001" +# => "0000000000000000000000000000000000000000000000000011000000111001" bits(12345.0) -#=> "0100000011001000000111001000000000000000000000000000000000000000" +# => "0100000011001000000111001000000000000000000000000000000000000000" # Логические значения являются примитивами true false # Булевы операторы -!true #=> false -!false #=> true -1 == 1 #=> true -2 == 1 #=> false -1 != 1 #=> false -2 != 1 #=> true -1 < 10 #=> true -1 > 10 #=> false -2 <= 2 #=> true -2 >= 2 #=> true +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +1 < 10 # => true +1 > 10 # => false +2 <= 2 # => true +2 >= 2 # => true # Сравнения можно объединять цепочкой -1 < 2 < 3 #=> true -2 < 3 < 2 #=> false +1 < 2 < 3 # => true +2 < 3 < 2 # => false # Строки объявляются с помощью двойных кавычек — " "This is a string." @@ -84,12 +84,12 @@ false 'a' # Строки индексируются как массивы символов -"This is a string"[1] #=> 'T' # Индексы начинаются с единицы +"This is a string"[1] # => 'T' # Индексы начинаются с единицы # Индексирование не всегда правильно работает для UTF8-строк, # поэтому рекомендуется использовать итерирование (map, for-циклы и т.п.). # Для строковой интерполяции используется знак доллара ($): -"2 + 2 = $(2 + 2)" #=> "2 + 2 = 4" +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" # В скобках можно использовать любое выражение языка. # Другой способ форматирования строк — макрос printf @@ -103,12 +103,12 @@ false println("I'm Julia. Nice to meet you!") # Переменные инициализируются без предварительного объявления -some_var = 5 #=> 5 -some_var #=> 5 +some_var = 5 # => 5 +some_var # => 5 # Попытка доступа к переменной до инициализации вызывает ошибку try - some_other_var #=> ERROR: some_other_var not defined + some_other_var # => ERROR: some_other_var not defined catch e println(e) end @@ -116,12 +116,12 @@ end # Имена переменных начинаются с букв. # После первого символа можно использовать буквы, цифры, # символы подчёркивания и восклицательные знаки. -SomeOtherVar123! = 6 #=> 6 +SomeOtherVar123! = 6 # => 6 # Допустимо использование unicode-символов -☃ = 8 #=> 8 +☃ = 8 # => 8 # Это особенно удобно для математических обозначений -2 * π #=> 6.283185307179586 +2 * π # => 6.283185307179586 # Рекомендации по именованию: # * имена переменных в нижнем регистре, слова разделяются символом @@ -136,49 +136,49 @@ SomeOtherVar123! = 6 #=> 6 # оканчивается восклицательным знаком. # Массив хранит последовательность значений, индексируемых с единицы до n: -a = Int64[] #=> пустой массив Int64-элементов +a = Int64[] # => пустой массив Int64-элементов # Одномерный массив объявляется разделёнными запятой значениями. -b = [4, 5, 6] #=> массив из трёх Int64-элементов: [4, 5, 6] -b[1] #=> 4 -b[end] #=> 6 +b = [4, 5, 6] # => массив из трёх Int64-элементов: [4, 5, 6] +b[1] # => 4 +b[end] # => 6 # Строки двумерного массива разделяются точкой с запятой. # Элементы строк разделяются пробелами. -matrix = [1 2; 3 4] #=> 2x2 Int64 Array: [1 2; 3 4] +matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] # push! и append! добавляют в список новые элементы -push!(a,1) #=> [1] -push!(a,2) #=> [1,2] -push!(a,4) #=> [1,2,4] -push!(a,3) #=> [1,2,4,3] -append!(a,b) #=> [1,2,4,3,4,5,6] +push!(a,1) # => [1] +push!(a,2) # => [1,2] +push!(a,4) # => [1,2,4] +push!(a,3) # => [1,2,4,3] +append!(a,b) # => [1,2,4,3,4,5,6] # pop! удаляет из списка последний элемент -pop!(b) #=> возвращает 6; массив b снова равен [4,5] +pop!(b) # => возвращает 6; массив b снова равен [4,5] # Вернём 6 обратно push!(b,6) # b снова [4,5,6]. -a[1] #=> 1 # индексы начинаются с единицы! +a[1] # => 1 # индексы начинаются с единицы! # Последний элемент можно получить с помощью end -a[end] #=> 6 +a[end] # => 6 # Операции сдвига -shift!(a) #=> 1 and a is now [2,4,3,4,5,6] -unshift!(a,7) #=> [7,2,4,3,4,5,6] +shift!(a) # => 1 and a is now [2,4,3,4,5,6] +unshift!(a,7) # => [7,2,4,3,4,5,6] # Восклицательный знак на конце названия функции означает, # что функция изменяет переданные ей аргументы. -arr = [5,4,6] #=> массив из 3 Int64-элементов: [5,4,6] -sort(arr) #=> [4,5,6]; но arr равен [5,4,6] -sort!(arr) #=> [4,5,6]; а теперь arr — [4,5,6] +arr = [5,4,6] # => массив из 3 Int64-элементов: [5,4,6] +sort(arr) # => [4,5,6]; но arr равен [5,4,6] +sort!(arr) # => [4,5,6]; а теперь arr — [4,5,6] # Попытка доступа за пределами массива выбрасывает BoundsError try - a[0] #=> ERROR: BoundsError() in getindex at array.jl:270 - a[end+1] #=> ERROR: BoundsError() in getindex at array.jl:270 + a[0] # => ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 catch e println(e) end @@ -189,111 +189,111 @@ end # то найти эти файлы можно в директории base. # Создавать массивы можно из последовательности -a = [1:5] #=> массив из 5 Int64-элементов: [1,2,3,4,5] +a = [1:5] # => массив из 5 Int64-элементов: [1,2,3,4,5] # Срезы -a[1:3] #=> [1, 2, 3] -a[2:] #=> [2, 3, 4, 5] -a[2:end] #=> [2, 3, 4, 5] +a[1:3] # => [1, 2, 3] +a[2:] # => [2, 3, 4, 5] +a[2:end] # => [2, 3, 4, 5] # splice! удаляет элемент из массива # Remove elements from an array by index with splice! arr = [3,4,5] -splice!(arr,2) #=> 4 ; arr теперь равен [3,5] +splice!(arr,2) # => 4 ; arr теперь равен [3,5] # append! объединяет списки b = [1,2,3] append!(a,b) # теперь a равен [1, 2, 3, 4, 5, 1, 2, 3] # Проверка на вхождение -in(1, a) #=> true +in(1, a) # => true # Длина списка -length(a) #=> 8 +length(a) # => 8 # Кортеж — неизменяемая структура. -tup = (1, 2, 3) #=> (1,2,3) # кортеж (Int64,Int64,Int64). -tup[1] #=> 1 +tup = (1, 2, 3) # => (1,2,3) # кортеж (Int64,Int64,Int64). +tup[1] # => 1 try: - tup[1] = 3 #=> ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) + tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) catch e println(e) end # Многие функции над списками работают и для кортежей -length(tup) #=> 3 -tup[1:2] #=> (1,2) -in(2, tup) #=> true +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true # Кортежи можно распаковывать в переменные -a, b, c = (1, 2, 3) #=> (1,2,3) # a = 1, b = 2 и c = 3 +a, b, c = (1, 2, 3) # => (1,2,3) # a = 1, b = 2 и c = 3 # Скобки из предыдущего примера можно опустить -d, e, f = 4, 5, 6 #=> (4,5,6) +d, e, f = 4, 5, 6 # => (4,5,6) # Кортеж из одного элемента не равен значению этого элемента -(1,) == 1 #=> false -(1) == 1 #=> true +(1,) == 1 # => false +(1) == 1 # => true # Обмен значений -e, d = d, e #=> (5,4) # d = 5, e = 4 +e, d = d, e # => (5,4) # d = 5, e = 4 # Словари содержат ассоциативные массивы -empty_dict = Dict() #=> Dict{Any,Any}() +empty_dict = Dict() # => Dict{Any,Any}() # Для создания словаря можно использовать литерал filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] # => Dict{ASCIIString,Int64} # Значения ищутся по ключу с помощью оператора [] -filled_dict["one"] #=> 1 +filled_dict["one"] # => 1 # Получить все ключи keys(filled_dict) -#=> KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Заметьте, словарь не запоминает порядок, в котором добавляются ключи. # Получить все значения. values(filled_dict) -#=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # То же касается и порядка значений. # Проверка вхождения ключа в словарь -in(("one", 1), filled_dict) #=> true -in(("two", 3), filled_dict) #=> false -haskey(filled_dict, "one") #=> true -haskey(filled_dict, 1) #=> false +in(("one", 1), filled_dict) # => true +in(("two", 3), filled_dict) # => false +haskey(filled_dict, "one") # => true +haskey(filled_dict, 1) # => false # Попытка обратиться к несуществующему ключу выбросит ошибку try - filled_dict["four"] #=> ERROR: key not found: four in getindex at dict.jl:489 + filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 catch e println(e) end # Используйте метод get со значением по умолчанию, чтобы избежать этой ошибки # get(dictionary,key,default_value) -get(filled_dict,"one",4) #=> 1 -get(filled_dict,"four",4) #=> 4 +get(filled_dict,"one",4) # => 1 +get(filled_dict,"four",4) # => 4 # Для коллекций неотсортированных уникальных элементов используйте Set -empty_set = Set() #=> Set{Any}() +empty_set = Set() # => Set{Any}() # Инициализация множества -filled_set = Set(1,2,2,3,4) #=> Set{Int64}(1,2,3,4) +filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) # Добавление элементов -push!(filled_set,5) #=> Set{Int64}(5,4,2,3,1) +push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) # Проверка вхождения элементов во множество -in(2, filled_set) #=> true -in(10, filled_set) #=> false +in(2, filled_set) # => true +in(10, filled_set) # => false # Функции для получения пересечения, объединения и разницы. -other_set = Set(3, 4, 5, 6) #=> Set{Int64}(6,4,5,3) -intersect(filled_set, other_set) #=> Set{Int64}(3,4,5) -union(filled_set, other_set) #=> Set{Int64}(1,2,3,4,5,6) -setdiff(Set(1,2,3,4),Set(2,3,5)) #=> Set{Int64}(1,4) +other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) +intersect(filled_set, other_set) # => Set{Int64}(3,4,5) +union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) +setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) #################################################### @@ -311,7 +311,7 @@ elseif some_var < 10 # Необязательная ветка elseif. else # else-ветка также опциональна. println("some_var is indeed 10.") end -#=> prints "some var is smaller than 10" +# => prints "some var is smaller than 10" # Цикл for проходит по итерируемым объектам @@ -368,7 +368,7 @@ try catch e println("caught it $e") end -#=> caught it ErrorException("help") +# => caught it ErrorException("help") #################################################### @@ -386,27 +386,27 @@ function add(x, y) x + y end -add(5, 6) #=> Вернёт 11, напечатав "x is 5 and y is 6" +add(5, 6) # => Вернёт 11, напечатав "x is 5 and y is 6" # Функция может принимать переменное количество позиционных аргументов. function varargs(args...) return args # для возвращения из функции в любом месте используется 'return' end -#=> varargs (generic function with 1 method) +# => varargs (generic function with 1 method) -varargs(1,2,3) #=> (1,2,3) +varargs(1,2,3) # => (1,2,3) # Многоточие (...) — это splat. # Мы только что воспользовались им в определении функции. # Также его можно использовать при вызове функции, # где он преобразует содержимое массива или кортежа в список аргументов. -Set([1,2,3]) #=> Set{Array{Int64,1}}([1,2,3]) # формирует множество массивов -Set([1,2,3]...) #=> Set{Int64}(1,2,3) # эквивалентно Set(1,2,3) +Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # формирует множество массивов +Set([1,2,3]...) # => Set{Int64}(1,2,3) # эквивалентно Set(1,2,3) -x = (1,2,3) #=> (1,2,3) -Set(x) #=> Set{(Int64,Int64,Int64)}((1,2,3)) # множество кортежей -Set(x...) #=> Set{Int64}(2,3,1) +x = (1,2,3) # => (1,2,3) +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # множество кортежей +Set(x...) # => Set{Int64}(2,3,1) # Опциональные позиционные аргументы @@ -414,12 +414,12 @@ function defaults(a,b,x=5,y=6) return "$a $b and $x $y" end -defaults('h','g') #=> "h g and 5 6" -defaults('h','g','j') #=> "h g and j 6" -defaults('h','g','j','k') #=> "h g and j k" +defaults('h','g') # => "h g and 5 6" +defaults('h','g','j') # => "h g and j 6" +defaults('h','g','j','k') # => "h g and j k" try - defaults('h') #=> ERROR: no method defaults(Char,) - defaults() #=> ERROR: no methods defaults() + defaults('h') # => ERROR: no method defaults(Char,) + defaults() # => ERROR: no methods defaults() catch e println(e) end @@ -429,9 +429,9 @@ function keyword_args(;k1=4,name2="hello") # обратите внимание return ["k1"=>k1,"name2"=>name2] end -keyword_args(name2="ness") #=> ["name2"=>"ness","k1"=>4] -keyword_args(k1="mine") #=> ["k1"=>"mine","name2"=>"hello"] -keyword_args() #=> ["name2"=>"hello","k2"=>4] +keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] +keyword_args() # => ["name2"=>"hello","k2"=>4] # В одной функции можно совмещать все виды аргументов function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") @@ -455,7 +455,7 @@ function create_adder(x) end # Анонимная функция -(x -> x > 2)(3) #=> true +(x -> x > 2)(3) # => true # Эта функция идентичная предыдущей версии create_adder function create_adder(x) @@ -471,16 +471,16 @@ function create_adder(x) end add_10 = create_adder(10) -add_10(3) #=> 13 +add_10(3) # => 13 # Встроенные функции высшего порядка -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] +map(add_10, [1,2,3]) # => [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # Списковые сборки -[add_10(i) for i=[1, 2, 3]] #=> [11, 12, 13] -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] #################################################### ## 5. Типы @@ -489,12 +489,12 @@ filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] # Julia has a type system. # Каждое значение имеет тип, но переменные не определяют тип значения. # Функция `typeof` возвращает тип значения. -typeof(5) #=> Int64 +typeof(5) # => Int64 # Types are first-class values # Типы являются значениями первого класса -typeof(Int64) #=> DataType -typeof(DataType) #=> DataType +typeof(Int64) # => DataType +typeof(DataType) # => DataType # Тип DataType представляет типы, включая себя самого. # Типы используются в качестве документации, для оптимизации и организации. @@ -515,10 +515,10 @@ end # Аргументы конструктора по умолчанию — свойства типа # в порядке их определения. -tigger = Tiger(3.5,"orange") #=> Tiger(3.5,"orange") +tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") # Тип объекта по сути является конструктором значений такого типа -sherekhan = typeof(tigger)(5.6,"fire") #=> Tiger(5.6,"fire") +sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") # Эти типы, похожие на структуры, называются конкретными. # Можно создавать объекты таких типов, но не их подтипы. @@ -530,23 +530,23 @@ abstract Cat # просто имя и точка в иерархии типов # Объекты абстрактных типов создавать нельзя, # но зато от них можно наследовать подтипы. # Например, Number — это абстрактный тип. -subtypes(Number) #=> 6 элементов в массиве Array{Any,1}: +subtypes(Number) # => 6 элементов в массиве Array{Any,1}: # Complex{Float16} # Complex{Float32} # Complex{Float64} # Complex{T<:Real} # ImaginaryUnit # Real -subtypes(Cat) #=> пустой массив Array{Any,1} +subtypes(Cat) # => пустой массив Array{Any,1} # У всех типов есть супертип. Для его определения есть функция `super`. -typeof(5) #=> Int64 -super(Int64) #=> Signed -super(Signed) #=> Real -super(Real) #=> Number -super(Number) #=> Any -super(super(Signed)) #=> Number -super(Any) #=> Any +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Number +super(Any) # => Any # Все эти типы, за исключением Int64, абстрактные. # Для создания подтипа используется оператор <: @@ -595,23 +595,23 @@ function meow(animal::Tiger) end # Проверка -meow(tigger) #=> "rawwr" -meow(Lion("brown","ROAAR")) #=> "ROAAR" -meow(Panther()) #=> "grrr" +meow(tigger) # => "rawwr" +meow(Lion("brown","ROAAR")) # => "ROAAR" +meow(Panther()) # => "grrr" # Вспомним иерархию типов -issubtype(Tiger,Cat) #=> false -issubtype(Lion,Cat) #=> true -issubtype(Panther,Cat) #=> true +issubtype(Tiger,Cat) # => false +issubtype(Lion,Cat) # => true +issubtype(Panther,Cat) # => true # Определим функцию, принимающую на вход объекты типа Cat function pet_cat(cat::Cat) println("The cat says $(meow(cat))") end -pet_cat(Lion("42")) #=> выведет "The cat says 42" +pet_cat(Lion("42")) # => выведет "The cat says 42" try - pet_cat(tigger) #=> ERROR: no method pet_cat(Tiger,) + pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) catch e println(e) end @@ -624,31 +624,31 @@ end function fight(t::Tiger,c::Cat) println("The $(t.coatcolor) tiger wins!") end -#=> fight (generic function with 1 method) +# => fight (generic function with 1 method) -fight(tigger,Panther()) #=> выведет The orange tiger wins! -fight(tigger,Lion("ROAR")) #=> выведет The orange tiger wins! +fight(tigger,Panther()) # => выведет The orange tiger wins! +fight(tigger,Lion("ROAR")) # => выведет The orange tiger wins! # Переопределим поведение функции, если Cat-объект является Lion-объектом fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") -#=> fight (generic function with 2 methods) +# => fight (generic function with 2 methods) -fight(tigger,Panther()) #=> выведет The orange tiger wins! -fight(tigger,Lion("ROAR")) #=> выведет The green-maned lion wins! +fight(tigger,Panther()) # => выведет The orange tiger wins! +fight(tigger,Lion("ROAR")) # => выведет The green-maned lion wins! # Драться можно не только с тиграми! fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") -#=> fight (generic function with 3 methods) +# => fight (generic function with 3 methods) -fight(Lion("balooga!"),Panther()) #=> выведет The victorious cat says grrr +fight(Lion("balooga!"),Panther()) # => выведет The victorious cat says grrr try - fight(Panther(),Lion("RAWR")) #=> ERROR: no method fight(Panther,Lion) + fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) catch end # Вообще, пускай кошачьи могут первыми проявлять агрессию fight(c::Cat,l::Lion) = println("The cat beats the Lion") -#=> Warning: New definition +# => Warning: New definition # fight(Cat,Lion) at none:1 # is ambiguous with # fight(Lion,Cat) at none:2. @@ -658,11 +658,11 @@ fight(c::Cat,l::Lion) = println("The cat beats the Lion") #fight (generic function with 4 methods) # Предупреждение говорит, что неясно, какой из методов вызывать: -fight(Lion("RAR"),Lion("brown","rarrr")) #=> выведет The victorious cat says rarrr +fight(Lion("RAR"),Lion("brown","rarrr")) # => выведет The victorious cat says rarrr # Результат может оказаться разным в разных версиях Julia fight(l::Lion,l2::Lion) = println("The lions come to a tie") -fight(Lion("RAR"),Lion("brown","rarrr")) #=> выведет The lions come to a tie +fight(Lion("RAR"),Lion("brown","rarrr")) # => выведет The lions come to a tie # Под капотом -- cgit v1.2.3 From 0ac421577bd903d214b236c8fc0cd099ad83d736 Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Tue, 18 Mar 2014 14:20:14 -0500 Subject: Add paragraph about multiline commments in julia --- julia.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/julia.html.markdown b/julia.html.markdown index 8245e616..8bd0d1df 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -13,6 +13,10 @@ This is based on the current development version of Julia, as of October 18th, 2 ```ruby # Single line comments start with a hash. +#= Multiline comments can be written + by putting '#=' before the text and '=#' + after the text +=# #################################################### ## 1. Primitive Datatypes and Operators -- cgit v1.2.3 From 23a5fc837d9080e15ba152ccf7bca473916eb12a Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Tue, 18 Mar 2014 14:27:49 -0500 Subject: Add comment about nesting julia multiline comments --- julia.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 8bd0d1df..36c57b2a 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -15,7 +15,7 @@ This is based on the current development version of Julia, as of October 18th, 2 # Single line comments start with a hash. #= Multiline comments can be written by putting '#=' before the text and '=#' - after the text + after the text. They can also be nested. =# #################################################### -- cgit v1.2.3 From 64f4d444cca52197db8dd728d073144663e1f00a Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Tue, 18 Mar 2014 23:51:32 -0500 Subject: Add file for spanish translation of julia --- es-es/julia-es.html.markdown | 747 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 747 insertions(+) create mode 100644 es-es/julia-es.html.markdown diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown new file mode 100644 index 00000000..36c57b2a --- /dev/null +++ b/es-es/julia-es.html.markdown @@ -0,0 +1,747 @@ +--- +language: julia +contributors: + - ["Leah Hanson", "http://leahhanson.us"] +filename: learnjulia.jl +--- + +Julia is a new homoiconic functional language focused on technical computing. +While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. + +This is based on the current development version of Julia, as of October 18th, 2013. + +```ruby + +# Single line comments start with a hash. +#= Multiline comments can be written + by putting '#=' before the text and '=#' + after the text. They can also be nested. +=# + +#################################################### +## 1. Primitive Datatypes and Operators +#################################################### + +# Everything in Julia is a expression. + +# There are several basic types of numbers. +3 # => 3 (Int64) +3.2 # => 3.2 (Float64) +2 + 1im # => 2 + 1im (Complex{Int64}) +2//3 # => 2//3 (Rational{Int64}) + +# All of the normal infix operators are available. +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 +5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float +div(5, 2) # => 2 # for a truncated result, use div +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # power, not bitwise xor +12 % 10 # => 2 + +# Enforce precedence with parentheses +(1 + 3) * 2 # => 8 + +# Bitwise Operators +~2 # => -3 # bitwise not +3 & 5 # => 1 # bitwise and +2 | 4 # => 6 # bitwise or +2 $ 4 # => 6 # bitwise xor +2 >>> 1 # => 1 # logical shift right +2 >> 1 # => 1 # arithmetic shift right +2 << 1 # => 4 # logical/arithmetic shift left + +# You can use the bits function to see the binary representation of a number. +bits(12345) +# => "0000000000000000000000000000000000000000000000000011000000111001" +bits(12345.0) +# => "0100000011001000000111001000000000000000000000000000000000000000" + +# Boolean values are primitives +true +false + +# Boolean operators +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +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 " +"This is a string." + +# Character literals are written with ' +'a' + +# A string can be indexed like an array of characters +"This is a string"[1] # => 'T' # Julia indexes from 1 +# However, this is will not work well for UTF8 strings, +# so iterating over strings is recommended (map, for loops, etc). + +# $ can be used for string interpolation: +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" +# You can put any Julia expression inside the parenthesis. + +# Another way to format strings is the printf macro. +@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 + +# Printing is easy +println("I'm Julia. Nice to meet you!") + +#################################################### +## 2. Variables and Collections +#################################################### + +# You don't declare variables before assigning to them. +some_var = 5 # => 5 +some_var # => 5 + +# Accessing a previously unassigned variable is an error +try + some_other_var # => ERROR: some_other_var not defined +catch e + println(e) +end + +# Variable names start with a letter. +# After that, you can use letters, digits, underscores, and exclamation points. +SomeOtherVar123! = 6 # => 6 + +# You can also use unicode characters +☃ = 8 # => 8 +# These are especially handy for mathematical notation +2 * π # => 6.283185307179586 + +# A note on naming conventions in Julia: +# +# * Names of variables are in lower case, with word separation indicated by +# underscores ('\_'). +# +# * Names of Types begin with a capital letter and word separation is shown +# with CamelCase instead of underscores. +# +# * Names of functions and macros are in lower case, without underscores. +# +# * Functions that modify their inputs have names that end in !. These +# functions are sometimes called mutating functions or in-place functions. + +# Arrays store a sequence of values indexed by integers 1 through n: +a = Int64[] # => 0-element Int64 Array + +# 1-dimensional array literals can be written with comma-separated values. +b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] +b[1] # => 4 +b[end] # => 6 + +# 2-dimentional arrays use space-separated values and semicolon-separated rows. +matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] + +# Add stuff to the end of a list with push! and append! +push!(a,1) # => [1] +push!(a,2) # => [1,2] +push!(a,4) # => [1,2,4] +push!(a,3) # => [1,2,4,3] +append!(a,b) # => [1,2,4,3,4,5,6] + +# Remove from the end with pop +pop!(b) # => 6 and b is now [4,5] + +# Let's put it back +push!(b,6) # b is now [4,5,6] again. + +a[1] # => 1 # remember that Julia indexes from 1, not 0! + +# end is a shorthand for the last index. It can be used in any +# indexing expression +a[end] # => 6 + +# we also have shift and unshift +shift!(a) # => 1 and a is now [2,4,3,4,5,6] +unshift!(a,7) # => [7,2,4,3,4,5,6] + +# Function names that end in exclamations points indicate that they modify +# their argument. +arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] +sort(arr) # => [4,5,6]; arr is still [5,4,6] +sort!(arr) # => [4,5,6]; arr is now [4,5,6] + +# Looking out of bounds is a BoundsError +try + a[0] # => ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 +catch e + println(e) +end + +# Errors list the line and file they came from, even if it's in the standard +# library. If you built Julia from source, you can look in the folder base +# inside the julia folder to find these files. + +# You can initialize arrays from ranges +a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] + +# You can look at ranges with slice syntax. +a[1:3] # => [1, 2, 3] +a[2:] # => [2, 3, 4, 5] +a[2:end] # => [2, 3, 4, 5] + +# Remove elements from an array by index with splice! +arr = [3,4,5] +splice!(arr,2) # => 4 ; arr is now [3,5] + +# Concatenate lists with append! +b = [1,2,3] +append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] + +# Check for existence in a list with in +in(1, a) # => true + +# Examine the length with length +length(a) # => 8 + +# Tuples are immutable. +tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. +tup[1] # => 1 +try: + tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +catch e + println(e) +end + +# Many list functions also work on tuples +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true + +# You can unpack tuples into variables +a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 + +# Tuples are created even if you leave out the parentheses +d, e, f = 4, 5, 6 # => (4,5,6) + +# A 1-element tuple is distinct from the value it contains +(1,) == 1 # => false +(1) == 1 # => true + +# Look how easy it is to swap two values +e, d = d, e # => (5,4) # d is now 5 and e is now 4 + + +# Dictionaries store mappings +empty_dict = Dict() # => Dict{Any,Any}() + +# You can create a dictionary using a literal +filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +# => Dict{ASCIIString,Int64} + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys +keys(filled_dict) +# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# Note - dictionary keys are not sorted or in the order you inserted them. + +# Get all values +values(filled_dict) +# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# Note - Same as above regarding key ordering. + +# Check for existence of keys in a dictionary with in, haskey +in(("one", 1), filled_dict) # => true +in(("two", 3), filled_dict) # => false +haskey(filled_dict, "one") # => true +haskey(filled_dict, 1) # => false + +# Trying to look up a non-existant key will raise an error +try + filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 +catch e + println(e) +end + +# Use the get method to avoid that error by providing a default value +# get(dictionary,key,default_value) +get(filled_dict,"one",4) # => 1 +get(filled_dict,"four",4) # => 4 + +# Use Sets to represent collections of unordered, unique values +empty_set = Set() # => Set{Any}() +# Initialize a set with values +filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) + +# Add more values to a set +push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) + +# Check if the values are in the set +in(2, filled_set) # => true +in(10, filled_set) # => false + +# There are functions for set intersection, union, and difference. +other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) +intersect(filled_set, other_set) # => Set{Int64}(3,4,5) +union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) +setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) + + +#################################################### +## 3. Control Flow +#################################################### + +# Let's make a variable +some_var = 5 + +# Here is an if statement. Indentation is not meaningful in Julia. +if some_var > 10 + println("some_var is totally bigger than 10.") +elseif some_var < 10 # This elseif clause is optional. + println("some_var is smaller than 10.") +else # The else clause is optional too. + println("some_var is indeed 10.") +end +# => prints "some var is smaller than 10" + + +# For loops iterate over iterables. +# Iterable types include Range, Array, Set, Dict, and String. +for animal=["dog", "cat", "mouse"] + println("$animal is a mammal") + # You can use $ to interpolate variables or expression into strings +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# You can use 'in' instead of '='. +for animal in ["dog", "cat", "mouse"] + println("$animal is a mammal") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$(a[1]) is a $(a[2])") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$k is a $v") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# While loops loop while a condition is true +x = 0 +while x < 4 + println(x) + x += 1 # Shorthand for x = x + 1 +end +# prints: +# 0 +# 1 +# 2 +# 3 + +# Handle exceptions with a try/catch block +try + error("help") +catch e + println("caught it $e") +end +# => caught it ErrorException("help") + + +#################################################### +## 4. Functions +#################################################### + +# The keyword 'function' creates new functions +#function name(arglist) +# body... +#end +function add(x, y) + println("x is $x and y is $y") + + # Functions return the value of their last statement + x + y +end + +add(5, 6) # => 11 after printing out "x is 5 and y is 6" + +# You can define functions that take a variable number of +# positional arguments +function varargs(args...) + return args + # use the keyword return to return anywhere in the function +end +# => varargs (generic function with 1 method) + +varargs(1,2,3) # => (1,2,3) + +# The ... is called a splat. +# We just used it in a function definition. +# It can also be used in a fuction call, +# where it will splat an Array or Tuple's contents into the argument list. +Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays +Set([1,2,3]...) # => Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) + +x = (1,2,3) # => (1,2,3) +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples +Set(x...) # => Set{Int64}(2,3,1) + + +# You can define functions with optional positional arguments +function defaults(a,b,x=5,y=6) + return "$a $b and $x $y" +end + +defaults('h','g') # => "h g and 5 6" +defaults('h','g','j') # => "h g and j 6" +defaults('h','g','j','k') # => "h g and j k" +try + defaults('h') # => ERROR: no method defaults(Char,) + defaults() # => ERROR: no methods defaults() +catch e + println(e) +end + +# You can define functions that take keyword arguments +function keyword_args(;k1=4,name2="hello") # note the ; + return ["k1"=>k1,"name2"=>name2] +end + +keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] +keyword_args() # => ["name2"=>"hello","k1"=>4] + +# You can combine all kinds of arguments in the same function +function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") + println("normal arg: $normal_arg") + println("optional arg: $optional_positional_arg") + println("keyword arg: $keyword_arg") +end + +all_the_args(1, 3, keyword_arg=4) +# prints: +# normal arg: 1 +# optional arg: 3 +# keyword arg: 4 + +# Julia has first class functions +function create_adder(x) + adder = function (y) + return x + y + end + return adder +end + +# This is "stabby lambda syntax" for creating anonymous functions +(x -> x > 2)(3) # => true + +# This function is identical to create_adder implementation above. +function create_adder(x) + y -> x + y +end + +# You can also name the internal function, if you want +function create_adder(x) + function adder(y) + x + y + end + adder +end + +add_10 = create_adder(10) +add_10(3) # => 13 + + +# There are built-in higher order functions +map(add_10, [1,2,3]) # => [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# We can use list comprehensions for nicer maps +[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] + +#################################################### +## 5. Types +#################################################### + +# Julia has a type system. +# Every value has a type; variables do not have types themselves. +# You can use the `typeof` function to get the type of a value. +typeof(5) # => Int64 + +# Types are first-class values +typeof(Int64) # => DataType +typeof(DataType) # => DataType +# DataType is the type that represents types, including itself. + +# Types are used for documentation, optimizations, and dispatch. +# They are not statically checked. + +# Users can define types +# They are like records or structs in other languages. +# New types are defined used the `type` keyword. + +# type Name +# field::OptionalType +# ... +# end +type Tiger + taillength::Float64 + coatcolor # not including a type annotation is the same as `::Any` +end + +# The default constructor's arguments are the properties +# of the type, in the order they are listed in the definition +tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") + +# The type doubles as the constructor function for values of that type +sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") + +# These struct-style types are called concrete types +# They can be instantiated, but cannot have subtypes. +# The other kind of types is abstract types. + +# abstract Name +abstract Cat # just a name and point in the type hierarchy + +# Abstract types cannot be instantiated, but can have subtypes. +# For example, Number is an abstract type +subtypes(Number) # => 6-element Array{Any,1}: + # Complex{Float16} + # Complex{Float32} + # Complex{Float64} + # Complex{T<:Real} + # ImaginaryUnit + # Real +subtypes(Cat) # => 0-element Array{Any,1} + +# Every type has a super type; use the `super` function to get it. +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Number +super(Any) # => Any +# All of these type, except for Int64, are abstract. + +# <: is the subtyping operator +type Lion <: Cat # Lion is a subtype of Cat + mane_color + roar::String +end + +# You can define more constructors for your type +# Just define a function of the same name as the type +# and call an existing constructor to get a value of the correct type +Lion(roar::String) = Lion("green",roar) +# This is an outer constructor because it's outside the type definition + +type Panther <: Cat # Panther is also a subtype of Cat + eye_color + Panther() = new("green") + # Panthers will only have this constructor, and no default constructor. +end +# Using inner constructors, like Panther does, gives you control +# over how values of the type can be created. +# When possible, you should use outer constructors rather than inner ones. + +#################################################### +## 6. Multiple-Dispatch +#################################################### + +# In Julia, all named functions are generic functions +# This means that they are built up from many small methods +# Each constructor for Lion is a method of the generic function Lion. + +# For a non-constructor example, let's make a function meow: + +# Definitions for Lion, Panther, Tiger +function meow(animal::Lion) + animal.roar # access type properties using dot notation +end + +function meow(animal::Panther) + "grrr" +end + +function meow(animal::Tiger) + "rawwwr" +end + +# Testing the meow function +meow(tigger) # => "rawwr" +meow(Lion("brown","ROAAR")) # => "ROAAR" +meow(Panther()) # => "grrr" + +# Review the local type hierarchy +issubtype(Tiger,Cat) # => false +issubtype(Lion,Cat) # => true +issubtype(Panther,Cat) # => true + +# Defining a function that takes Cats +function pet_cat(cat::Cat) + println("The cat says $(meow(cat))") +end + +pet_cat(Lion("42")) # => prints "The cat says 42" +try + pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) +catch e + println(e) +end + +# In OO languages, single dispatch is common; +# this means that the method is picked based on the type of the first argument. +# In Julia, all of the argument types contribute to selecting the best method. + +# Let's define a function with more arguments, so we can see the difference +function fight(t::Tiger,c::Cat) + println("The $(t.coatcolor) tiger wins!") +end +# => fight (generic function with 1 method) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! + +# Let's change the behavior when the Cat is specifically a Lion +fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") +# => fight (generic function with 2 methods) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! + +# We don't need a Tiger in order to fight +fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +# => fight (generic function with 3 methods) + +fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr +try + fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) +catch +end + +# Also let the cat go first +fight(c::Cat,l::Lion) = println("The cat beats the Lion") +# => Warning: New definition +# fight(Cat,Lion) at none:1 +# is ambiguous with +# fight(Lion,Cat) at none:2. +# Make sure +# fight(Lion,Lion) +# is defined first. +#fight (generic function with 4 methods) + +# This warning is because it's unclear which fight will be called in: +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr +# The result may be different in other versions of Julia + +fight(l::Lion,l2::Lion) = println("The lions come to a tie") +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie + + +# Under the hood +# You can take a look at the llvm and the assembly code generated. + +square_area(l) = l * l # square_area (generic function with 1 method) + +square_area(5) #25 + +# What happens when we feed square_area an integer? +code_native(square_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 # Prologue + # push RBP + # mov RBP, RSP + # Source line: 1 + # movsxd RAX, EDI # Fetch l from memory? + # imul RAX, RAX # Square l and store the result in RAX + # pop RBP # Restore old base pointer + # ret # Result will still be in RAX + +code_native(square_area, (Float32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) + # pop RBP + # ret + +code_native(square_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) + # pop RBP + # ret + # +# Note that julia will use floating point instructions if any of the +# arguements are floats. +# Let's calculate the area of a circle +circle_area(r) = pi * r * r # circle_area (generic function with 1 method) +circle_area(5) # 78.53981633974483 + +code_native(circle_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory + # movabs RAX, 4593140240 # Load pi + # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r + # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r + # pop RBP + # ret + # + +code_native(circle_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # movabs RAX, 4593140496 + # Source line: 1 + # vmulsd XMM1, XMM0, QWORD PTR [RAX] + # vmulsd XMM0, XMM1, XMM0 + # pop RBP + # ret + # +``` + +## Further Reading + +You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) + +The best place to get help with Julia is the (very friendly) [mailing list](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From 38f55957ac1773098ce17bf59dba2b1f704e9245 Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Wed, 19 Mar 2014 00:08:07 -0500 Subject: Translate Julia to Spanish This is based partly on the Python translation. --- es-es/julia-es.html.markdown | 700 ++++++++++++++++++++++--------------------- 1 file changed, 351 insertions(+), 349 deletions(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 36c57b2a..6c5a6428 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -12,39 +12,39 @@ This is based on the current development version of Julia, as of October 18th, 2 ```ruby -# Single line comments start with a hash. -#= Multiline comments can be written - by putting '#=' before the text and '=#' - after the text. They can also be nested. +# Comentarios de una línea comienzan con una almohadilla (o signo gato) +#= Commentarios multilinea pueden escribirse + usando '#=' antes de que el texto and '=#' + después del texto. También se pueden anidar. =# #################################################### -## 1. Primitive Datatypes and Operators +## 1. Tipos de datos primitivos y operadores. #################################################### -# Everything in Julia is a expression. +# Todo en Julia es una expresión. -# There are several basic types of numbers. +# Hay varios tipos básicos de números. 3 # => 3 (Int64) 3.2 # => 3.2 (Float64) 2 + 1im # => 2 + 1im (Complex{Int64}) 2//3 # => 2//3 (Rational{Int64}) -# All of the normal infix operators are available. +# Todos los operadores infijos normales están disponibles. 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7.0 -5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float -div(5, 2) # => 2 # for a truncated result, use div +5/2 # => 2.5 # dividir un Int por un Int siempre resulta en un Fload +div (5, 2) # => 2 # para un resultado truncado, usa div 5 \ 35 # => 7.0 -2 ^ 2 # => 4 # power, not bitwise xor +2 ^ 2 # => 4 # exponente, no exclusivo bit a bit 12 % 10 # => 2 -# Enforce precedence with parentheses +# Refuerza la precedencia con paréntesis (1 + 3) * 2 # => 8 -# Bitwise Operators +# Operadores a nivel de bit ~2 # => -3 # bitwise not 3 & 5 # => 1 # bitwise and 2 | 4 # => 6 # bitwise or @@ -53,17 +53,17 @@ div(5, 2) # => 2 # for a truncated result, use div 2 >> 1 # => 1 # arithmetic shift right 2 << 1 # => 4 # logical/arithmetic shift left -# You can use the bits function to see the binary representation of a number. +# Se puede utilizar la función bits para ver la representación binaria de un número. bits(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" bits(12345.0) # => "0100000011001000000111001000000000000000000000000000000000000000" -# Boolean values are primitives +# Valores 'boolean' (booleanos) son primitivos true false -# Boolean operators +# Operadores Boolean (booleanos) !true # => false !false # => true 1 == 1 # => true @@ -74,109 +74,112 @@ false 1 > 10 # => false 2 <= 2 # => true 2 >= 2 # => true -# Comparisons can be chained +# ¡Las comparaciones pueden ser concatenadas! 1 < 2 < 3 # => true 2 < 3 < 2 # => false -# Strings are created with " -"This is a string." +# Strings se crean con " +"Esto es un string." -# Character literals are written with ' +# Literales de caracteres se escriben con ' 'a' -# A string can be indexed like an array of characters -"This is a string"[1] # => 'T' # Julia indexes from 1 +# Una string puede ser indexado como una array de caracteres +"Esto es un string."[1] # => 'E' # Julia indexes from 1 # However, this is will not work well for UTF8 strings, # so iterating over strings is recommended (map, for loops, etc). +# Sin embargo, esto no va a funcionar bien para strings UTF8, +# Lo que se recomienda es la iteración (map, for, etc). -# $ can be used for string interpolation: +# Puede ser utilizado para la interpolación de strings: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" -# You can put any Julia expression inside the parenthesis. +# Se puede poner cualquier expresión de Julia dentro los paréntesis. -# Another way to format strings is the printf macro. -@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 +# Otro forma de formatear strings es el printf macro +@printf "%d es menor de %f" 4.5 5.3 # 5 es menor de 5.300000 -# Printing is easy -println("I'm Julia. Nice to meet you!") +# Imprimir es muy fácil +println("Soy Julia. ¡Encantado de conocerte!") #################################################### -## 2. Variables and Collections +## 2. Variables y Colecciones #################################################### -# You don't declare variables before assigning to them. -some_var = 5 # => 5 -some_var # => 5 +# No hay necesidad de declarar las variables antes de asignarlas. +una_variable = 5 # => 5 +una_variable # => 5 -# Accessing a previously unassigned variable is an error +# Acceder a variables no asignadas previamente es una excepción. try - some_other_var # => ERROR: some_other_var not defined + otra_variable # => ERROR: some_other_var not defined catch e println(e) end -# Variable names start with a letter. -# After that, you can use letters, digits, underscores, and exclamation points. -SomeOtherVar123! = 6 # => 6 +# Los nombres de variables comienzan con una letra. +# Después de eso, usted puede utilizar letras, dígitos, guiones y signos de exclamación. +OtraVariable123! = 6 # => 6 -# You can also use unicode characters +# También puede utilizar caracteres unicode ☃ = 8 # => 8 -# These are especially handy for mathematical notation +# Estos son especialmente útiles para la notación matemática 2 * π # => 6.283185307179586 -# A note on naming conventions in Julia: +# Una nota sobre las convenciones de nomenclatura de Julia: # -# * Names of variables are in lower case, with word separation indicated by -# underscores ('\_'). +# * Los nombres de las variables aparecen en minúsculas, con separación de +# palabra indicado por underscore ('\ _'). # -# * Names of Types begin with a capital letter and word separation is shown -# with CamelCase instead of underscores. +# * Los nombres de los tipos comienzan con una letra mayúscula y separación de +# palabras se muestra Con CamelCase en vez de underscore. # -# * Names of functions and macros are in lower case, without underscores. +# * Los nombres de las funciones y las macros están en minúsculas, sin +# underscore. # -# * Functions that modify their inputs have names that end in !. These -# functions are sometimes called mutating functions or in-place functions. +# * Funciones que modifican sus inputs tienen nombres que terminan en!. Estos +# funciones a veces se llaman mutating functions or in-place functions. -# Arrays store a sequence of values indexed by integers 1 through n: +# Los Arrays almacenan una secuencia de valores indexados entre 1 hasta n a = Int64[] # => 0-element Int64 Array -# 1-dimensional array literals can be written with comma-separated values. +# Literales de arrays 1-dimensionales se pueden escribir con valores separados por comas. b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] b[1] # => 4 b[end] # => 6 -# 2-dimentional arrays use space-separated values and semicolon-separated rows. +# Los arrays 2-dimensionales usan valores separados por espacios y filas separados por punto y coma. matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] -# Add stuff to the end of a list with push! and append! +# Añadir cosas a la final de una lista con push! y append! push!(a,1) # => [1] push!(a,2) # => [1,2] push!(a,4) # => [1,2,4] push!(a,3) # => [1,2,4,3] append!(a,b) # => [1,2,4,3,4,5,6] -# Remove from the end with pop -pop!(b) # => 6 and b is now [4,5] +# Eliminar de la final con pop +pop!(b) # => 6 y b ahora es [4,5] -# Let's put it back -push!(b,6) # b is now [4,5,6] again. +# Vamos a ponerlo de nuevo +push!(b, 6) # b es ahora [4,5,6] de nuevo. -a[1] # => 1 # remember that Julia indexes from 1, not 0! +a[1] # => 1 # recuerdan que los índices de Julia empiezan desde 1, no desde 0! -# end is a shorthand for the last index. It can be used in any -# indexing expression +# end es una abreviatura para el último índice. Se puede utilizar en cualquier +# expresión de indexación a[end] # => 6 -# we also have shift and unshift -shift!(a) # => 1 and a is now [2,4,3,4,5,6] +# tambien hay shift and unshift +shift!(a) # => 1 y a es ahora [2,4,3,4,5,6] unshift!(a,7) # => [7,2,4,3,4,5,6] -# Function names that end in exclamations points indicate that they modify -# their argument. +# Nombres de función que terminan en exclamaciones indican que modifican +# su argumento. arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] -sort(arr) # => [4,5,6]; arr is still [5,4,6] -sort!(arr) # => [4,5,6]; arr is now [4,5,6] +sort(arr) # => [4,5,6]; arr es todavía [5,4,6] +sort!(arr) # => [4,5,6]; arr es ahora [4,5,6] -# Looking out of bounds is a BoundsError +# Buscando fuera de límites es un BoundsError try a[0] # => ERROR: BoundsError() in getindex at array.jl:270 a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 @@ -184,34 +187,33 @@ catch e println(e) end -# Errors list the line and file they came from, even if it's in the standard -# library. If you built Julia from source, you can look in the folder base -# inside the julia folder to find these files. +# Errors dan la línea y el archivo de su procedencia, aunque sea en el standard +# library. Si construyes Julia de source, puedes buscar en la source para +# encontrar estos archivos. -# You can initialize arrays from ranges +# Se puede inicializar arrays de un range a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] -# You can look at ranges with slice syntax. +# Usted puede mirar en ranges con sintaxis slice. a[1:3] # => [1, 2, 3] -a[2:] # => [2, 3, 4, 5] a[2:end] # => [2, 3, 4, 5] -# Remove elements from an array by index with splice! +# Eliminar elementos de una array por índice con splice! arr = [3,4,5] -splice!(arr,2) # => 4 ; arr is now [3,5] +splice!(arr,2) # => 4 ; arr es ahora [3,5] -# Concatenate lists with append! +# Concatenar listas con append! b = [1,2,3] -append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] +append!(a,b) # ahroa a es [1, 2, 3, 4, 5, 1, 2, 3] -# Check for existence in a list with in +# Salida por la existencia de una lista con in in(1, a) # => true -# Examine the length with length +# Examinar la longitud con length length(a) # => 8 -# Tuples are immutable. -tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. +# Tuples son immutable. +tup = (1, 2, 3) # => (1,2,3) # un (Int64,Int64,Int64) tuple. tup[1] # => 1 try: tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) @@ -219,204 +221,197 @@ catch e println(e) end -# Many list functions also work on tuples +# Muchas funciones de lista también trabajan en las tuples length(tup) # => 3 tup[1:2] # => (1,2) in(2, tup) # => true -# You can unpack tuples into variables +# Se puede desempaquetar tuples en variables a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 -# Tuples are created even if you leave out the parentheses +# Los tuples se crean, incluso si se omite el paréntesis d, e, f = 4, 5, 6 # => (4,5,6) -# A 1-element tuple is distinct from the value it contains +# Un tuple 1-elemento es distinto del valor que contiene (1,) == 1 # => false (1) == 1 # => true -# Look how easy it is to swap two values +# Mira que fácil es cambiar dos valores e, d = d, e # => (5,4) # d is now 5 and e is now 4 -# Dictionaries store mappings -empty_dict = Dict() # => Dict{Any,Any}() +# Dictionaries almanecan mapeos +dict_vacio = Dict() # => Dict{Any,Any}() -# You can create a dictionary using a literal -filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +# Se puede crear un dictionary usando un literal +dict_lleno = ["one"=> 1, "two"=> 2, "three"=> 3] # => Dict{ASCIIString,Int64} -# Look up values with [] -filled_dict["one"] # => 1 +# Busca valores con [] +dict_lleno["one"] # => 1 -# Get all keys -keys(filled_dict) +# Obtén todas las claves +keys(dict_lleno) # => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) -# Note - dictionary keys are not sorted or in the order you inserted them. +# Nota - claves del dictionary no están ordenados ni en el orden en que se insertan. -# Get all values -values(filled_dict) +# Obtén todas las claves +values(dict_lleno) # => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) -# Note - Same as above regarding key ordering. +# Nota - Igual que el anterior en cuanto a ordenamiento de claves. -# Check for existence of keys in a dictionary with in, haskey -in(("one", 1), filled_dict) # => true -in(("two", 3), filled_dict) # => false -haskey(filled_dict, "one") # => true -haskey(filled_dict, 1) # => false +# Compruebe si hay existencia de claves en un dictionary con in y haskey +in(("one", 1), dict_lleno) # => true +in(("two", 3), dict_lleno) # => false +haskey(dict_lleno, "one") # => true +haskey(dict_lleno, 1) # => false -# Trying to look up a non-existant key will raise an error +# Tratando de buscar una clave inexistente producirá un error try - filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 + dict_lleno["four"] # => ERROR: key not found: four in getindex at dict.jl:489 catch e println(e) end -# Use the get method to avoid that error by providing a default value +# Utilice el método get para evitar ese error proporcionando un valor predeterminado # get(dictionary,key,default_value) -get(filled_dict,"one",4) # => 1 -get(filled_dict,"four",4) # => 4 - -# Use Sets to represent collections of unordered, unique values -empty_set = Set() # => Set{Any}() -# Initialize a set with values -filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) - -# Add more values to a set -push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) - -# Check if the values are in the set -in(2, filled_set) # => true -in(10, filled_set) # => false - -# There are functions for set intersection, union, and difference. -other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) -intersect(filled_set, other_set) # => Set{Int64}(3,4,5) -union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) +get(dict_lleno,"one",4) # => 1 +get(dict_lleno,"four",4) # => 4 + +# Usa Sets para representar colecciones (conjuntos) de valores únicos, no ordenadas +conjunto_vacio = Set() # => Set{Any}() +# Iniciar una set de valores +conjunto_lleno = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) + +# Añadir más valores a un conjunto +push!(conjunto_lleno,5) # => Set{Int64}(5,4,2,3,1) +push!(conjunto_lleno,5) # => Set{Int64}(5,4,2,3,1) + +# Compruebe si los valores están en el conjunto +in(2, conjunto_lleno) # => true +in(10, conjunto_lleno) # => false + +# Hay funciones de intersección de conjuntos, la unión, y la diferencia. +conjunto_otro= Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) +intersect(conjunto_lleno, conjunto_otro) # => Set{Int64}(3,4,5) +union(conjunto_lleno, conjunto_otro) # => Set{Int64}(1,2,3,4,5,6) setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) #################################################### -## 3. Control Flow +## 3. Control de Flujo #################################################### -# Let's make a variable -some_var = 5 - -# Here is an if statement. Indentation is not meaningful in Julia. -if some_var > 10 - println("some_var is totally bigger than 10.") -elseif some_var < 10 # This elseif clause is optional. - println("some_var is smaller than 10.") -else # The else clause is optional too. - println("some_var is indeed 10.") +# Hagamos una variable +una_variable = 5 + +# Aquí está una declaración de un 'if'. La indentación no es significativa en +# Julia +if una_variable > 10 + println("una_variable es completamente mas grande que 10.") +elseif una_variable < 10 # Este condición 'elseif' es opcional. + println("una_variable es mas chica que 10.") +else # Esto también es opcional. + println("una_variable es de hecho 10.") end -# => prints "some var is smaller than 10" +# => imprime "una_variable es mas chica que 10." - -# For loops iterate over iterables. -# Iterable types include Range, Array, Set, Dict, and String. -for animal=["dog", "cat", "mouse"] - println("$animal is a mammal") - # You can use $ to interpolate variables or expression into strings -end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal - -# You can use 'in' instead of '='. -for animal in ["dog", "cat", "mouse"] - println("$animal is a mammal") +# For itera sobre tipos iterables +# Tipos iterables incluyen Range, Array, Set, Dict, y String. +for animal=["perro", "gato", "raton"] + println("$animal es un mamifero") + # Se puede usar $ para interpolar variables o expresiónes en strings end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# imprime: +# perro es un mamifero +# gato es un mamifero +# raton es un mamifero -for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] - println("$(a[1]) is a $(a[2])") +for a in ["perro"=>"mamifero","gato"=>"mamifero","raton"=>"mamifero"] + println("$(a[1]) es un $(a[2])") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# imprime: +# perro es un mamifero +# gato es un mamifero +# raton es un mamifero -for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] - println("$k is a $v") +for (k,v) in ["perro"=>"mamifero","gato"=>"mamifero","raton"=>"mamifero"] + println("$k es un $v") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# imprime: +# perro es un mamifero +# gato es un mamifero +# raton es un mamifero -# While loops loop while a condition is true +# While itera hasta que una condición no se cumple. x = 0 while x < 4 println(x) - x += 1 # Shorthand for x = x + 1 + x += 1 # versión corta de x = x + 1 end -# prints: +# imprime: # 0 # 1 # 2 # 3 -# Handle exceptions with a try/catch block +# Maneja excepciones con un bloque try/except try - error("help") + error("ayuda") catch e - println("caught it $e") + println("capturando $e") end -# => caught it ErrorException("help") +# => capturando ErrorException("ayuda") #################################################### -## 4. Functions +## 4. Funciones #################################################### -# The keyword 'function' creates new functions -#function name(arglist) -# body... +# Usa 'function' para crear nuevas funciones + +#function nombre(arglist) +# cuerpo... #end -function add(x, y) - println("x is $x and y is $y") +function suma(x, y) + println("x es $x e y es $y") - # Functions return the value of their last statement + # Las funciones devuelven el valor de su última declaración x + y end -add(5, 6) # => 11 after printing out "x is 5 and y is 6" +suma(5, 6) # => 11 # después de imprimir "x es 5 e y es de 6" -# You can define functions that take a variable number of -# positional arguments +# Puedes definir funciones que toman un número variable de +# argumentos posicionales function varargs(args...) return args - # use the keyword return to return anywhere in the function + # Usa la palabra clave return para devolver en cualquier lugar de la función end # => varargs (generic function with 1 method) varargs(1,2,3) # => (1,2,3) -# The ... is called a splat. -# We just used it in a function definition. -# It can also be used in a fuction call, -# where it will splat an Array or Tuple's contents into the argument list. -Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays -Set([1,2,3]...) # => Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) +# El ... se llama un splat. +# Acabamos de utilizar lo en una definición de función. +# También se puede utilizar en una llamada de función, +# donde va splat un Array o el contenido de un Tuple en la lista de argumentos. +Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # Produce un Set de Arrays +Set([1,2,3]...) # => Set{Int64}(1,2,3) # esto es equivalente a Set(1,2,3) x = (1,2,3) # => (1,2,3) -Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # un Set de Tuples Set(x...) # => Set{Int64}(2,3,1) -# You can define functions with optional positional arguments +# Puede definir funciones con argumentos posicionales opcionales function defaults(a,b,x=5,y=6) - return "$a $b and $x $y" + return "$a $b y $x $y" end -defaults('h','g') # => "h g and 5 6" -defaults('h','g','j') # => "h g and j 6" -defaults('h','g','j','k') # => "h g and j k" +defaults('h','g') # => "h g y 5 6" +defaults('h','g','j') # => "h g y j 6" +defaults('h','g','j','k') # => "h g y j k" try defaults('h') # => ERROR: no method defaults(Char,) defaults() # => ERROR: no methods defaults() @@ -424,120 +419,122 @@ catch e println(e) end -# You can define functions that take keyword arguments -function keyword_args(;k1=4,name2="hello") # note the ; - return ["k1"=>k1,"name2"=>name2] +# Puede definir funciones que toman argumentos de palabra clave +function args_clave(;k1=4,nombre2="hola") # note the ; + return ["k1"=>k1,"nombre2"=>nombre2] end -keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] -keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] -keyword_args() # => ["name2"=>"hello","k1"=>4] +args_clave(nombre2="ness") # => ["nombre2"=>"ness","k1"=>4] +args_clave(k1="mine") # => ["k1"=>"mine","nombre2"=>"hola"] +args_clave() # => ["nombre2"=>"hola","k1"=>4] -# You can combine all kinds of arguments in the same function -function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") - println("normal arg: $normal_arg") - println("optional arg: $optional_positional_arg") - println("keyword arg: $keyword_arg") +# Se puede combinar todo tipo de argumentos en la misma función +function todos_los_args(arg_normal, arg_posicional_opcional=2; arg_clave="foo") + println("argumento normal: $arg_normal") + println("argumento optional: $arg_posicional_opcional") + println("argumento de clave: $arg_clave") end -all_the_args(1, 3, keyword_arg=4) -# prints: -# normal arg: 1 -# optional arg: 3 -# keyword arg: 4 +# todos_los_args(1, 3, arg_clave=4) +# imprime: +# argumento normal: 1 +# argumento optional: 3 +# argumento de clave: 4 -# Julia has first class functions -function create_adder(x) - adder = function (y) +# Julia tiene funciones de primera clase +function crear_suma(x) + suma = function (y) return x + y end - return adder + return suma end -# This is "stabby lambda syntax" for creating anonymous functions +# Esta es el sintaxis "stabby lambda" para crear funciones anónimas (x -> x > 2)(3) # => true -# This function is identical to create_adder implementation above. -function create_adder(x) +# Esta función es idéntica a la crear_suma implementación anterior. +function crear_suma(x) y -> x + y end -# You can also name the internal function, if you want -function create_adder(x) - function adder(y) +# También se puede nombrar la función interna, si quieres +function crear_suma(x) + function suma(y) x + y end - adder + suma end -add_10 = create_adder(10) -add_10(3) # => 13 +suma_10 = crear_suma(10) +suma_10(3) # => 13 -# There are built-in higher order functions -map(add_10, [1,2,3]) # => [11, 12, 13] +# Hay funciones integradas de orden superior +map(suma_10, [1,2,3]) # => [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] -# We can use list comprehensions for nicer maps -[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +# Podemos usar listas por comprensión para mapeos +[suma_10(i) for i=[1, 2, 3]] # => [11, 12, 13] +[suma_10(i) for i in [1, 2, 3]] # => [11, 12, 13] #################################################### -## 5. Types +## 5. Tipos #################################################### -# Julia has a type system. -# Every value has a type; variables do not have types themselves. -# You can use the `typeof` function to get the type of a value. +# Julia tiene sistema de tipos. +# Cada valor tiene un tipo y las variables no tienen propios tipos. +# Se puede utilizar la función `typeof` para obtener el tipo de un valor. typeof(5) # => Int64 -# Types are first-class values +# Los tipos son valores de primera clase typeof(Int64) # => DataType typeof(DataType) # => DataType -# DataType is the type that represents types, including itself. +# DataType es el tipo que representa los tipos, incluyéndose a sí mismo. -# Types are used for documentation, optimizations, and dispatch. -# They are not statically checked. +# Los tipos se usan para la documentación, optimizaciones, y envio. +# No están comprobados estáticamente. -# Users can define types -# They are like records or structs in other languages. -# New types are defined used the `type` keyword. +# Los usuarios pueden definir tipos +# Son como registros o estructuras en otros idiomas. +# Nuevos tipos se definen utilizado la palabra clave `type`. -# type Name +# type Nombre # field::OptionalType # ... # end -type Tiger - taillength::Float64 - coatcolor # not including a type annotation is the same as `::Any` +type Tigre + longituddecola::Float64 + colordelpelaje # no incluyendo una anotación de tipo es el mismo que `::Any` end -# The default constructor's arguments are the properties -# of the type, in the order they are listed in the definition -tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") +# Los argumentos del constructor por default son las propiedades +# del tipo, en el orden en que están listados en la definición +tigger = Tigre(3.5,"anaranjado") # => Tiger(3.5,"anaranjado") -# The type doubles as the constructor function for values of that type -sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") +# El tipo funciona como la función constructora de valores de ese tipo +sherekhan = typeof(tigger)(5.6,"fuego") # => Tiger(5.6,"fuego") # These struct-style types are called concrete types # They can be instantiated, but cannot have subtypes. # The other kind of types is abstract types. +# Este estilo de tipos son llamados tipos concrete +# Se pueden crear instancias, pero no pueden tener subtipos. +# La otra clase de tipos es tipos abstractos (abstract types). -# abstract Name -abstract Cat # just a name and point in the type hierarchy +# abstract Nombre +abstract Gato # sólo un nombre y un punto en la jerarquía de tipos -# Abstract types cannot be instantiated, but can have subtypes. -# For example, Number is an abstract type +# De los tipos Abstract no se pueden crear instancias, pero pueden tener +# subtipos. Por ejemplo, Number es un tipo abstracto. subtypes(Number) # => 6-element Array{Any,1}: # Complex{Float16} # Complex{Float32} # Complex{Float64} # Complex{T<:Real} - # ImaginaryUnit # Real -subtypes(Cat) # => 0-element Array{Any,1} +subtypes(Gato) # => 0-element Array{Any,1} -# Every type has a super type; use the `super` function to get it. +# Cada tipo tiene un supertipo, utilice la función `súper` para conseguirlo. typeof(5) # => Int64 super(Int64) # => Signed super(Signed) # => Real @@ -545,132 +542,136 @@ super(Real) # => Number super(Number) # => Any super(super(Signed)) # => Number super(Any) # => Any -# All of these type, except for Int64, are abstract. +# Todo de estos tipos, a excepción de Int64, son abstractos. -# <: is the subtyping operator -type Lion <: Cat # Lion is a subtype of Cat - mane_color - roar::String +# <: es el operador de subtipos +type Leon <: Gato # Leon es un subtipo de Gato + color_de_crin + rugido::String end -# You can define more constructors for your type -# Just define a function of the same name as the type -# and call an existing constructor to get a value of the correct type -Lion(roar::String) = Lion("green",roar) -# This is an outer constructor because it's outside the type definition - -type Panther <: Cat # Panther is also a subtype of Cat - eye_color - Panther() = new("green") - # Panthers will only have this constructor, and no default constructor. +# Se puede definir más constructores para su tipo. +# Sólo defina una función del mismo nombre que el tipo +# y llame a un constructor existente para obtener un valor del tipo correcto +Leon(rugido::String) = Leon("verde",rugido) +# Este es un constructor externo porque es fuera de la definición del tipo + +type Pantera <: Gato # Pantera tambien es un a subtipo de Cat + color_de_ojos + Pantera() = new("verde") + # Panteras sólo tendrán este constructor, y ningún constructor + # predeterminado. end -# Using inner constructors, like Panther does, gives you control -# over how values of the type can be created. -# When possible, you should use outer constructors rather than inner ones. +# Utilizar constructores internos, como Panther hace, le da control sobre cómo +# se pueden crear valores del tipo. Cuando sea posible, debe utilizar +# constructores exteriores en lugar de los internos. #################################################### -## 6. Multiple-Dispatch +## 6. Envio múltiple #################################################### -# In Julia, all named functions are generic functions -# This means that they are built up from many small methods -# Each constructor for Lion is a method of the generic function Lion. +# En Julia, todas las funciones nombradas son funciones genéricas. +# Esto significa que se construyen a partir de muchos métodos pequeños +# Cada constructor de León es un método de la función genérica León. -# For a non-constructor example, let's make a function meow: +# Por ejemplo no constructor, vamos a hacer un maullar función: -# Definitions for Lion, Panther, Tiger -function meow(animal::Lion) - animal.roar # access type properties using dot notation +# Definiciones para Leon, Pantera, y Tigre +function maullar(animal::Leon) + animal.rugido # acceso utilizando notación de puntos end -function meow(animal::Panther) +function maullar(animal::Pantera) "grrr" end -function meow(animal::Tiger) +function maullar(animal::Tigre) "rawwwr" end -# Testing the meow function -meow(tigger) # => "rawwr" -meow(Lion("brown","ROAAR")) # => "ROAAR" -meow(Panther()) # => "grrr" +# Prueba de la función maullar +maullar(tigger) # => "rawwr" +maullar(Leon("cafe","ROAAR")) # => "ROAAR" +maullar(Pantera()) # => "grrr" -# Review the local type hierarchy -issubtype(Tiger,Cat) # => false -issubtype(Lion,Cat) # => true -issubtype(Panther,Cat) # => true +# Revisar la jerarquía de tipos locales +issubtype(Tigre,Gato) # => false +issubtype(Leon,Gato) # => true +issubtype(Pantera,Gato) # => true -# Defining a function that takes Cats -function pet_cat(cat::Cat) - println("The cat says $(meow(cat))") +# Definición de una función que toma Gatos +function mascota(gato::Gato) + println("El gato dice $(maullar(gato))") end -pet_cat(Lion("42")) # => prints "The cat says 42" +mascota(Leon("42")) # => imprime "El gato dice 42" try - pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) + mascota(tigger) # => ERROR: no method mascota(Tigre)) catch e println(e) end -# In OO languages, single dispatch is common; -# this means that the method is picked based on the type of the first argument. -# In Julia, all of the argument types contribute to selecting the best method. +# En los lenguajes orientados a objetos, expedición única es común. Esto +# significa que el método se recogió basándose en el tipo del primer argumento. +# En Julia, todos los tipos de argumentos contribuyen a seleccionar el mejor +# método. -# Let's define a function with more arguments, so we can see the difference -function fight(t::Tiger,c::Cat) - println("The $(t.coatcolor) tiger wins!") +# Vamos a definir una función con más argumentos, para que podamos ver la +# diferencia +function pelear(t::Tigre,c::Gato) + println("¡El tigre $(t.colordelpelaje) gana!") end -# => fight (generic function with 1 method) +# => pelear (generic function with 1 method) -fight(tigger,Panther()) # => prints The orange tiger wins! -fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! +pelear(tigger,Pantera()) # => imprime ¡El tigre anaranjado gana! +pelear(tigger,Leon("ROAR")) # => ¡El tigre anaranjado gana! -# Let's change the behavior when the Cat is specifically a Lion -fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") -# => fight (generic function with 2 methods) +# Vamos a cambiar el comportamiento cuando el Gato es específicamente un Leon +pelear(t::Tigre,l::Leon) = println("!El león con melena $(l.color_de_crin) gana!") +# => pelear (generic function with 2 methods) -fight(tigger,Panther()) # => prints The orange tiger wins! -fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! +pelear(tigger,Pantera()) # => imprime ¡El tigre anaranjado gana! +pelear(tigger,Leon("ROAR")) # => imprime ¡El león con melena verde gana! -# We don't need a Tiger in order to fight -fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +# No necesitamos un tigre para poder luchar +pelear(l::Leon,c::Gato) = println("El gato victorioso dice $(maullar(c))") # => fight (generic function with 3 methods) -fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr +pelear(Leon("balooga!"),Pantera()) # => imprime El gato victorioso dice grrr try - fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) + pelear(Pantera(),Leon("RAWR")) # => ERROR: no method pelear(Pantera, Leon)) catch end -# Also let the cat go first -fight(c::Cat,l::Lion) = println("The cat beats the Lion") -# => Warning: New definition -# fight(Cat,Lion) at none:1 -# is ambiguous with -# fight(Lion,Cat) at none:2. -# Make sure -# fight(Lion,Lion) -# is defined first. -#fight (generic function with 4 methods) +# Permítanos dejar que el gato vaya primero +pelear(c::Gato,l::Leon) = println("El gato le gana al León") +# Warning: New definition +# pelear(Gato,Leon) at none:1 +# is ambiguous with: +# pelear(Leon,Gato) at none:1. +# To fix, define +# pelear(Leon,Leon) +# before the new definition. +# pelear (generic function with 4 methods) -# This warning is because it's unclear which fight will be called in: -fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr -# The result may be different in other versions of Julia +# Esta advertencia se debe a que no está claro que metodo de pelear será llamado +# en: +pelear(Leon("RAR"),Leon("brown","rarrr")) # => imprime El gato victorioso dice rarrr +# El resultado puede ser diferente en otras versiones de Julia -fight(l::Lion,l2::Lion) = println("The lions come to a tie") -fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie +pelear(l::Leon,l2::Leon) = println("Los leones llegan a un empate") +pelear(Leon("RAR"),Leon("brown","rarrr")) # => imprime Los leones llegan a un empate -# Under the hood -# You can take a look at the llvm and the assembly code generated. +# Bajo el capó +# Se puede echar un vistazo a la LLVM y el código ensamblador generado. -square_area(l) = l * l # square_area (generic function with 1 method) +area_cuadrada(l) = l * l # area_cuadrada (generic function with 1 method) -square_area(5) #25 +area_cuadrada(5) #25 -# What happens when we feed square_area an integer? -code_native(square_area, (Int32,)) +# ¿Qué sucede cuando damos square_area diferentes argumentos? +code_native(area_cuadrada, (Int32,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none # Source line: 1 # Prologue @@ -682,7 +683,7 @@ code_native(square_area, (Int32,)) # pop RBP # Restore old base pointer # ret # Result will still be in RAX -code_native(square_area, (Float32,)) +code_native(area_cuadrada, (Float32,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none # Source line: 1 @@ -693,7 +694,7 @@ code_native(square_area, (Float32,)) # pop RBP # ret -code_native(square_area, (Float64,)) +code_native(area_cuadrada, (Float64,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none # Source line: 1 @@ -704,13 +705,13 @@ code_native(square_area, (Float64,)) # pop RBP # ret # -# Note that julia will use floating point instructions if any of the -# arguements are floats. -# Let's calculate the area of a circle -circle_area(r) = pi * r * r # circle_area (generic function with 1 method) -circle_area(5) # 78.53981633974483 +# Tenga en cuenta que Julia usará instrucciones de "floating point" si alguno de +# los argumentos son "floats" +# Vamos a calcular el área de un círculo +area_circulo(r) = pi * r * r # circle_area (generic function with 1 method) +area_circulo(5) # 78.53981633974483 -code_native(circle_area, (Int32,)) +code_native(area_circulo, (Int32,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none # Source line: 1 @@ -725,7 +726,7 @@ code_native(circle_area, (Int32,)) # ret # -code_native(circle_area, (Float64,)) +code_native(area_circulo, (Float64,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none # Source line: 1 @@ -740,8 +741,9 @@ code_native(circle_area, (Float64,)) # ``` -## Further Reading +# # Lectura adicional + +Puedes obtener muchos más detalles en [The Julia Manual](http://docs.julialang.org/en/latest/manual/) -You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) +El mejor lugar para obtener ayuda con Julia es el (muy amable) [lista de correos](https://groups.google.com/forum/#!forum/julia-users). -The best place to get help with Julia is the (very friendly) [mailing list](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From 21bed16bba39002432403874bb0779c865d6aebd Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Wed, 19 Mar 2014 00:30:25 -0500 Subject: Translate introduction, too. --- es-es/julia-es.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 6c5a6428..3d131773 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -5,13 +5,13 @@ contributors: filename: learnjulia.jl --- -Julia is a new homoiconic functional language focused on technical computing. -While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. +Julia es un nuevo lenguaje funcional homoiconic enfocado en computación técnica. +Mientras que tiene todo el poder de macros homoiconic, funciones de primera clase, y control de bajo nivel, Julia es tan fácil de aprender y utilizar como Python. -This is based on the current development version of Julia, as of October 18th, 2013. +Esto se basa en la versión de desarrollo actual de Julia, del 18 de octubre de 2013. ```ruby - +j # Comentarios de una línea comienzan con una almohadilla (o signo gato) #= Commentarios multilinea pueden escribirse usando '#=' antes de que el texto and '=#' -- cgit v1.2.3 From 0b05a9db124988f37c82115837d1014703574edc Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Wed, 19 Mar 2014 00:39:44 -0500 Subject: Trim lines to 80 characters --- es-es/julia-es.html.markdown | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 3d131773..3897efff 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -6,9 +6,12 @@ filename: learnjulia.jl --- Julia es un nuevo lenguaje funcional homoiconic enfocado en computación técnica. -Mientras que tiene todo el poder de macros homoiconic, funciones de primera clase, y control de bajo nivel, Julia es tan fácil de aprender y utilizar como Python. +Mientras que tiene todo el poder de macros homoiconic, funciones de primera +clase, y control de bajo nivel, Julia es tan fácil de aprender y utilizar como +Python. -Esto se basa en la versión de desarrollo actual de Julia, del 18 de octubre de 2013. +Esto se basa en la versión de desarrollo actual de Julia, del 18 de octubre de +2013. ```ruby j @@ -53,7 +56,8 @@ div (5, 2) # => 2 # para un resultado truncado, usa div 2 >> 1 # => 1 # arithmetic shift right 2 << 1 # => 4 # logical/arithmetic shift left -# Se puede utilizar la función bits para ver la representación binaria de un número. +# Se puede utilizar la función bits para ver la representación binaria de un +# número. bits(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" bits(12345.0) @@ -117,7 +121,8 @@ catch e end # Los nombres de variables comienzan con una letra. -# Después de eso, usted puede utilizar letras, dígitos, guiones y signos de exclamación. +# Después de eso, usted puede utilizar letras, dígitos, guiones y signos de +# exclamación. OtraVariable123! = 6 # => 6 # También puede utilizar caracteres unicode @@ -142,12 +147,14 @@ OtraVariable123! = 6 # => 6 # Los Arrays almacenan una secuencia de valores indexados entre 1 hasta n a = Int64[] # => 0-element Int64 Array -# Literales de arrays 1-dimensionales se pueden escribir con valores separados por comas. +# Literales de arrays 1-dimensionales se pueden escribir con valores separados +# por comas. b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] b[1] # => 4 b[end] # => 6 -# Los arrays 2-dimensionales usan valores separados por espacios y filas separados por punto y coma. +# Los arrays 2-dimensionales usan valores separados por espacios y filas +# separados por punto y coma. matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] # Añadir cosas a la final de una lista con push! y append! @@ -253,7 +260,8 @@ dict_lleno["one"] # => 1 # Obtén todas las claves keys(dict_lleno) # => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) -# Nota - claves del dictionary no están ordenados ni en el orden en que se insertan. +# Nota - claves del dictionary no están ordenados ni en el orden en que se +# insertan. # Obtén todas las claves values(dict_lleno) @@ -261,24 +269,26 @@ values(dict_lleno) # Nota - Igual que el anterior en cuanto a ordenamiento de claves. # Compruebe si hay existencia de claves en un dictionary con in y haskey -in(("one", 1), dict_lleno) # => true -in(("two", 3), dict_lleno) # => false +in(("uno", 1), dict_lleno) # => true +in(("tres", 3), dict_lleno) # => false haskey(dict_lleno, "one") # => true haskey(dict_lleno, 1) # => false # Tratando de buscar una clave inexistente producirá un error try - dict_lleno["four"] # => ERROR: key not found: four in getindex at dict.jl:489 + dict_lleno["dos"] # => ERROR: key not found: dos in getindex at dict.jl:489 catch e println(e) end -# Utilice el método get para evitar ese error proporcionando un valor predeterminado +# Utilice el método get para evitar ese error proporcionando un valor +# predeterminado # get(dictionary,key,default_value) get(dict_lleno,"one",4) # => 1 get(dict_lleno,"four",4) # => 4 -# Usa Sets para representar colecciones (conjuntos) de valores únicos, no ordenadas +# Usa Sets para representar colecciones (conjuntos) de valores únicos, no +# ordenadas conjunto_vacio = Set() # => Set{Any}() # Iniciar una set de valores conjunto_lleno = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) @@ -627,11 +637,11 @@ pelear(tigger,Pantera()) # => imprime ¡El tigre anaranjado gana! pelear(tigger,Leon("ROAR")) # => ¡El tigre anaranjado gana! # Vamos a cambiar el comportamiento cuando el Gato es específicamente un Leon -pelear(t::Tigre,l::Leon) = println("!El león con melena $(l.color_de_crin) gana!") +pelear(t::Tigre,l::Leon) = println("El león con melena $(l.color_de_crin) gana") # => pelear (generic function with 2 methods) pelear(tigger,Pantera()) # => imprime ¡El tigre anaranjado gana! -pelear(tigger,Leon("ROAR")) # => imprime ¡El león con melena verde gana! +pelear(tigger,Leon("ROAR")) # => imprime El león con melena verde gana # No necesitamos un tigre para poder luchar pelear(l::Leon,c::Gato) = println("El gato victorioso dice $(maullar(c))") @@ -656,11 +666,11 @@ pelear(c::Gato,l::Leon) = println("El gato le gana al León") # Esta advertencia se debe a que no está claro que metodo de pelear será llamado # en: -pelear(Leon("RAR"),Leon("brown","rarrr")) # => imprime El gato victorioso dice rarrr +pelear(Leon("RAR"),Leon("cafe","rar")) # => imprime El gato victorioso dice rar # El resultado puede ser diferente en otras versiones de Julia pelear(l::Leon,l2::Leon) = println("Los leones llegan a un empate") -pelear(Leon("RAR"),Leon("brown","rarrr")) # => imprime Los leones llegan a un empate +pelear(Leon("GR"),Leon("cafe","rar")) # => imprime Los leones llegan a un empate # Bajo el capó -- cgit v1.2.3 From 82ac7779819b7117638b5d41d1adee8e9c4ab20d Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Wed, 19 Mar 2014 00:43:21 -0500 Subject: Fix header at beginning of file. --- es-es/julia-es.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 3897efff..2dcc915e 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -2,7 +2,9 @@ language: julia contributors: - ["Leah Hanson", "http://leahhanson.us"] -filename: learnjulia.jl + - ["Guillermo Garza" ] +filename: learnjulia-es.jl +lang: es-es --- Julia es un nuevo lenguaje funcional homoiconic enfocado en computación técnica. -- cgit v1.2.3 From 25fb918e9c0ef62205de86321d503aabf250f60a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 8 Jan 2014 21:27:42 -0600 Subject: Merge with master. --- objective-c.html.markdown | 195 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 191 insertions(+), 4 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 0f0165ec..59169b16 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -249,14 +249,17 @@ int main (int argc, const char * argv[]) // Your statements here @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; - } @catch (NSException * e) + } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects. { NSLog(@"Exception: %@", e); } @finally { - NSLog(@"Finally"); + NSLog(@"Finally. Time to clean up."); } // => prints "Exception: File Not Found on System" - // "Finally" + // "Finally. Time to clean up." + + // NSError objects are useful for function arguments to populate on user mistakes. + NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil]; /////////////////////////////////////// // Objects @@ -549,6 +552,116 @@ int main (int argc, const char * argv[]) { NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. } +// Categories +// A category is a group of methods designed to extend a class. They allow you to add new methods +// to an existing class for organizational purposes. This is not to be mistaken with subclasses. +// Subclasses are meant to CHANGE functionality of an object while categories instead ADD +// functionality to an object. +// Categories allow you to: +// -- Add methods to an existing class for organizational purposes. +// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods. +// -- Add ability to create protected and private methods to classes. +// NOTE: Do not override methods of the base class in a category even though you have the ability +// to. Overriding methods may cause compiler errors later between different categories and it +// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods. + +// Here is a simple Car base class. +@interface Car : NSObject + +@property NSString *make; +@property NSString *color; + +- (void)turnOn; +- (void)accelerate; + +@end + +// And the simple Car base class implementation: +#import "Car.h" + +@implementation Car + +@synthesize make = _make; +@synthesize color = _color; + +- (void)turnOn { + NSLog(@"Car is on."); +} +- (void)accelerate { + NSLog(@"Accelerating."); +} + +@end + +// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would +// be changing the functionality of the Car to behave like a truck. But lets say we want to just add +// functionality to this existing Car. A good example would be to clean the car. So we would create +// a category to add these cleaning methods: +// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h) +#import "Car.h" // Make sure to import base class to extend. + +@interface Car (Clean) // The category name is inside () following the name of the base class. + +- (void)washWindows; // Names of the new methods we are adding to our Car object. +- (void)wax; + +@end + +// @implementation filename: Car+Clean.m (BaseClassName+CategoryName.m) +#import "Car+Clean.h" // Import the Clean category's @interface file. + +@implementation Car (Clean) + +- (void)washWindows { + NSLog(@"Windows washed."); +} +- (void)wax { + NSLog(@"Waxed."); +} + +@end + +// Any Car object instance has the ability to use a category. All they need to do is import it: +#import "Car+Clean.h" // Import as many different categories as you want to use. +#import "Car.h" // Also need to import base class to use it's original functionality. + +int main (int argc, const char * argv[]) { + @autoreleasepool { + Car *mustang = [[Car alloc] init]; + mustang.color = @"Red"; + mustang.make = @"Ford"; + + [mustang turnOn]; // Use methods from base Car class. + [mustang washWindows]; // Use methods from Car's Clean category. + } + return 0; +} + +// Objective-C does not have protected method declarations but you can simulate them. +// Create a category containing all of the protected methods, then import it ONLY into the +// @implementation file of a class belonging to the Car class: +@interface Car (Protected) // Naming category 'Protected' to remember methods are protected. + +- (void)lockCar; // Methods listed here may only be created by Car objects. + +@end +//To use protected methods, import the category, then implement the methods: +#import "Car+Protected.h" // Remember, import in the @implementation file only. + +@implementation Car + +- (void)lockCar { + NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. +} + +@end + +// Protocols +// A protocol declares methods that can be implemented by any class. +// Protocols are not classes themselves. They simply define an interface +// that other objects are responsible for implementing. +@protocol MyProtocol + - (void)myProtocolMethod; @end /////////////////////////////////////// @@ -594,7 +707,7 @@ int main (int argc, const char * argv[]) { // A protocol declares methods that can be implemented by any class. // Protocols are not classes themselves. They simply define an interface // that other objects are responsible for implementing. - // @protocol filename: "CarUtilities.h" +// @protocol filename: "CarUtilities.h" @protocol CarUtilities // => Name of another protocol this protocol includes. @property BOOL engineOn; // Adopting class must @synthesize all defined @properties and - (void)turnOnEngine; // all defined methods. @@ -605,6 +718,7 @@ int main (int argc, const char * argv[]) { @interface Car : NSObject // Name of protocol goes inside <> // You don't need the @property or method names here for CarUtilities. Only @implementation does. - (void)turnOnEngineWithUtilities:(id )car; // You can use protocols as data too. +<<<<<<< HEAD @end // The @implementation needs to implement the @properties and methods for the protocol. @implementation Car : NSObject @@ -646,6 +760,49 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { - (void)beNiceToBrother:(id )brother; +======= +@end +// The @implementation needs to implement the @properties and methods for the protocol. +@implementation Car : NSObject + +@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property. + +- (void)turnOnEngine { // Implement turnOnEngine however you would like. Protocols do not define + _engineOn = YES; // how you implement a method, it just requires that you do implement it. +} +// You may use a protocol as data as you know what methods and variables it has implemented. +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { + [objectOfSomeKind engineOn]; // You have access to object variables + [objectOfSomeKind turnOnEngine]; // and the methods inside. + [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants. +} + +@end +// Instances of Car now have access to the protocol. +Car *carInstance = [[Car alloc] init]; +[[carInstance setEngineOn:NO]; +[carInstance turnOnEngine]; +if ([carInstance engineOn]) { + NSLog(@"Car engine is on."); // prints => "Car engine is on." +} +// Make sure to check if an object of type 'id' implements a protocol before calling protocol methods: +if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); +} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does run as the Car class implements the CarUtilities protocol."); +} +// Categories may implement protocols as well: @interface Car (CarCategory) +// You may implement many protocols: @interface Car : NSObject +// NOTE: If two or more protocols rely on each other, make sure to forward-declare them: +#import "Brother.h" + +@protocol Brother; // Forward-declare statement. Without it, compiler would through error. + +@protocol Sister + +- (void)beNiceToBrother:(id )brother; + +>>>>>>> 8c6f583... Add much more to the protocols section. @end // See the problem is that Sister relies on Brother, and Brother relies on Sister. #import "Sister.h" @@ -658,6 +815,36 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { @end + +/////////////////////////////////////// +// Blocks +/////////////////////////////////////// +// Blocks are statements of code, just like a function, that is able to be used as data. +// Below is a simple block with an integer argument that returns the argument plus 4. +int (^addUp)(int n); // Declare a variable to store the block. +void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments. +// Blocks have access to variables in the same scope. But the variables are readonly and the +// value passed to the block is the value of the variable when the block is created. +int outsideVar = 17; // If we edit outsideVar after declaring addUp, outsideVar is STILL 17. +__block long mutableVar = 3; // __block makes variables writable to blocks, unlike outsideVar. +addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters. + NSLog(@"You may have as many lines in a block as you would like."); + NSSet *blockSet; // Also, you can declare local variables. + mutableVar = 32; // Assigning new value to __block variable. + return n + outsideVar; // Return statements are optional. +} +int addUp = add(10 + 16); // Calls block code with arguments. +// Blocks are often used as arguments to functions to be called later, or for callbacks. +@implementation BlockExample : NSObject + + - (void)runBlock:(void (^)(NSString))block { + NSLog(@"Block argument returns nothing and takes in a NSString object."); + block(@"Argument given to block to execute."); // Calling block. + } + + @end + + /////////////////////////////////////// // Memory Management /////////////////////////////////////// -- cgit v1.2.3 From dcf7cd620d9e957d384e143eb2fb2cca7351cfae Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 10 Jan 2014 22:58:45 -0600 Subject: Add to exceptions section. Add NSError reference. --- objective-c.html.markdown | 3 --- 1 file changed, 3 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 59169b16..348a72d5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -718,7 +718,6 @@ int main (int argc, const char * argv[]) { @interface Car : NSObject // Name of protocol goes inside <> // You don't need the @property or method names here for CarUtilities. Only @implementation does. - (void)turnOnEngineWithUtilities:(id )car; // You can use protocols as data too. -<<<<<<< HEAD @end // The @implementation needs to implement the @properties and methods for the protocol. @implementation Car : NSObject @@ -760,7 +759,6 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { - (void)beNiceToBrother:(id )brother; -======= @end // The @implementation needs to implement the @properties and methods for the protocol. @implementation Car : NSObject @@ -802,7 +800,6 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { - (void)beNiceToBrother:(id )brother; ->>>>>>> 8c6f583... Add much more to the protocols section. @end // See the problem is that Sister relies on Brother, and Brother relies on Sister. #import "Sister.h" -- cgit v1.2.3 From 58bd9cbdaf97955fab0b6a0ae1f0827f84abdefa Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 19 Mar 2014 12:39:07 -0500 Subject: Remove duplicate Categories section. Fix small typo. --- objective-c.html.markdown | 152 +--------------------------------------------- 1 file changed, 1 insertion(+), 151 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 348a72d5..772e72ca 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -552,116 +552,6 @@ int main (int argc, const char * argv[]) { NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. } -// Categories -// A category is a group of methods designed to extend a class. They allow you to add new methods -// to an existing class for organizational purposes. This is not to be mistaken with subclasses. -// Subclasses are meant to CHANGE functionality of an object while categories instead ADD -// functionality to an object. -// Categories allow you to: -// -- Add methods to an existing class for organizational purposes. -// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods. -// -- Add ability to create protected and private methods to classes. -// NOTE: Do not override methods of the base class in a category even though you have the ability -// to. Overriding methods may cause compiler errors later between different categories and it -// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods. - -// Here is a simple Car base class. -@interface Car : NSObject - -@property NSString *make; -@property NSString *color; - -- (void)turnOn; -- (void)accelerate; - -@end - -// And the simple Car base class implementation: -#import "Car.h" - -@implementation Car - -@synthesize make = _make; -@synthesize color = _color; - -- (void)turnOn { - NSLog(@"Car is on."); -} -- (void)accelerate { - NSLog(@"Accelerating."); -} - -@end - -// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would -// be changing the functionality of the Car to behave like a truck. But lets say we want to just add -// functionality to this existing Car. A good example would be to clean the car. So we would create -// a category to add these cleaning methods: -// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h) -#import "Car.h" // Make sure to import base class to extend. - -@interface Car (Clean) // The category name is inside () following the name of the base class. - -- (void)washWindows; // Names of the new methods we are adding to our Car object. -- (void)wax; - -@end - -// @implementation filename: Car+Clean.m (BaseClassName+CategoryName.m) -#import "Car+Clean.h" // Import the Clean category's @interface file. - -@implementation Car (Clean) - -- (void)washWindows { - NSLog(@"Windows washed."); -} -- (void)wax { - NSLog(@"Waxed."); -} - -@end - -// Any Car object instance has the ability to use a category. All they need to do is import it: -#import "Car+Clean.h" // Import as many different categories as you want to use. -#import "Car.h" // Also need to import base class to use it's original functionality. - -int main (int argc, const char * argv[]) { - @autoreleasepool { - Car *mustang = [[Car alloc] init]; - mustang.color = @"Red"; - mustang.make = @"Ford"; - - [mustang turnOn]; // Use methods from base Car class. - [mustang washWindows]; // Use methods from Car's Clean category. - } - return 0; -} - -// Objective-C does not have protected method declarations but you can simulate them. -// Create a category containing all of the protected methods, then import it ONLY into the -// @implementation file of a class belonging to the Car class: -@interface Car (Protected) // Naming category 'Protected' to remember methods are protected. - -- (void)lockCar; // Methods listed here may only be created by Car objects. - -@end -//To use protected methods, import the category, then implement the methods: -#import "Car+Protected.h" // Remember, import in the @implementation file only. - -@implementation Car - -- (void)lockCar { - NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. -} - -@end - -// Protocols -// A protocol declares methods that can be implemented by any class. -// Protocols are not classes themselves. They simply define an interface -// that other objects are responsible for implementing. -@protocol MyProtocol - - (void)myProtocolMethod; @end /////////////////////////////////////// @@ -760,47 +650,7 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { - (void)beNiceToBrother:(id )brother; @end -// The @implementation needs to implement the @properties and methods for the protocol. -@implementation Car : NSObject - -@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property. - -- (void)turnOnEngine { // Implement turnOnEngine however you would like. Protocols do not define - _engineOn = YES; // how you implement a method, it just requires that you do implement it. -} -// You may use a protocol as data as you know what methods and variables it has implemented. -- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { - [objectOfSomeKind engineOn]; // You have access to object variables - [objectOfSomeKind turnOnEngine]; // and the methods inside. - [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants. -} - -@end -// Instances of Car now have access to the protocol. -Car *carInstance = [[Car alloc] init]; -[[carInstance setEngineOn:NO]; -[carInstance turnOnEngine]; -if ([carInstance engineOn]) { - NSLog(@"Car engine is on."); // prints => "Car engine is on." -} -// Make sure to check if an object of type 'id' implements a protocol before calling protocol methods: -if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { - NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); -} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { - NSLog(@"This does run as the Car class implements the CarUtilities protocol."); -} -// Categories may implement protocols as well: @interface Car (CarCategory) -// You may implement many protocols: @interface Car : NSObject -// NOTE: If two or more protocols rely on each other, make sure to forward-declare them: -#import "Brother.h" -@protocol Brother; // Forward-declare statement. Without it, compiler would through error. - -@protocol Sister - -- (void)beNiceToBrother:(id )brother; - -@end // See the problem is that Sister relies on Brother, and Brother relies on Sister. #import "Sister.h" @@ -816,7 +666,7 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { /////////////////////////////////////// // Blocks /////////////////////////////////////// -// Blocks are statements of code, just like a function, that is able to be used as data. +// Blocks are statements of code, just like a function, that are able to be used as data. // Below is a simple block with an integer argument that returns the argument plus 4. int (^addUp)(int n); // Declare a variable to store the block. void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments. -- cgit v1.2.3 From 464930ecf8c4638dc5e49f253062f02c26292748 Mon Sep 17 00:00:00 2001 From: Trevor Wennblom Date: Wed, 19 Mar 2014 20:09:48 -0500 Subject: WARNING: deprecated syntax "x[i:]". 0.3.0-prerelease+2077 --- julia.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 36c57b2a..665b4fd3 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -193,7 +193,6 @@ a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] # You can look at ranges with slice syntax. a[1:3] # => [1, 2, 3] -a[2:] # => [2, 3, 4, 5] a[2:end] # => [2, 3, 4, 5] # Remove elements from an array by index with splice! -- cgit v1.2.3 From 4480f889f8d87e6ccbe3c5536c0efd869be3f97f Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Thu, 20 Mar 2014 16:41:52 +0800 Subject: csharp: Chinese translation --- zh-cn/csharp-cn.html.markdown | 797 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 797 insertions(+) create mode 100644 zh-cn/csharp-cn.html.markdown diff --git a/zh-cn/csharp-cn.html.markdown b/zh-cn/csharp-cn.html.markdown new file mode 100644 index 00000000..618050a0 --- /dev/null +++ b/zh-cn/csharp-cn.html.markdown @@ -0,0 +1,797 @@ +--- +language: c# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] + - ["Max Yankov", "https://github.com/golergka"] + - ["Melvyn Laïly", "http://x2a.yt"] + - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] +translathors: + - ["Jakukyo Friel", "http://weakish.github.io"] +filename: LearnCSharp-cn.cs +--- + + +C#是一个优雅的、类型安全的面向对象语言。使用C#,开发者可以在.NET框架下构建安全、健壮的应用程序。 + +[更多关于C#的介绍](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) + +```c# +// 单行注释以 // 开始 +/* +多行注释是这样的 +*/ +/// +/// XML文档注释 +/// + +// 声明应用用到的命名空间 +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +using System.Net; +using System.Threading.Tasks; +using System.IO; + +// 定义作用域,将代码组织成包 +namespace Learning +{ + // 每个 .cs 文件至少需要包含一个和文件名相同的类 + // 你可以不这么干,但是这样不好。 + public class LearnCSharp + { + // 基本语法 - 如果你以前用过 Java 或 C++ 的话,可以直接跳到后文「有趣的特性」 + public static void Syntax() + { + // 使用 Console.WriteLine 打印信息 + Console.WriteLine("Hello World"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // 使用 Console.Write 打印,不带换行符号 + Console.Write("Hello "); + Console.Write("World"); + + /////////////////////////////////////////////////// + // 类型和变量 + // + // 使用 定义变量 + /////////////////////////////////////////////////// + + // Sbyte - 有符号 8-bit 整数 + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - 无符号 8-bit 整数 + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - 16-bit 整数 + // 有符号 - (-32,768 <= short <= 32,767) + // 无符号 - (0 <= ushort <= 65,535) + short fooShort = 10000; + ushort fooUshort = 10000; + + // Integer - 32-bit 整数 + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) + + // Long - 64-bit 整数 + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // 数字默认为 int 或 uint (取决于尺寸) + // 使用 L 标明变量值类型为long 或 ulong + + // Double - 双精度 64-bit IEEE 754 浮点数 + double fooDouble = 123.4; // 精度: 15-16 位 + + // Float - 单精度 32-bit IEEE 754 浮点数 + float fooFloat = 234.5f; // 精度: 7 位 + // 使用 f 标明变量值类型为float + + // Decimal - 128-bits 数据类型,比其他浮点类型精度更高 + // 适合财务、金融 + decimal fooDecimal = 150.3m; + + // 布尔值 - true & false + bool fooBoolean = true; // 或 false + + // Char - 单个 16-bit Unicode 字符 + char fooChar = 'A'; + + // 字符串 -- 和前面的基本类型不同,字符串不是值,而是引用。 + // 这意味着你可以将字符串设为null。 + string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; + Console.WriteLine(fooString); + + // 你可以通过索引访问字符串的每个字符: + char charFromString = fooString[1]; // => 'e' + // 字符串不可修改: fooString[1] = 'X' 是行不通的; + + // 根据当前的locale设定比较字符串,大小写不敏感 + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // 基于sprintf的字符串格式化 + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + + // 日期和格式 + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // 使用 @ 符号可以创建跨行的字符串。使用 "" 来表示 " + string bazString = @"Here's some stuff +on a new line! ""Wow!"", the masses cried"; + + // 使用const或read-only定义常量 + // 常量在编译期演算 + const int HOURS_I_WORK_PER_WEEK = 9001; + + /////////////////////////////////////////////////// + // 数据结构 + /////////////////////////////////////////////////// + + // 数组 - 从0开始计数 + // 声明数组时需要确定数组长度 + // 声明数组的格式如下: + // [] = new []; + int[] intArray = new int[10]; + + // 声明并初始化数组的其他方式: + int[] y = { 9000, 1000, 1337 }; + + // 访问数组的元素 + Console.WriteLine("intArray @ 0: " + intArray[0]); + // 数组可以修改 + intArray[1] = 1; + + // 列表 + // 列表比数组更常用,因为列表更灵活。 + // 声明列表的格式如下: + // List = new List(); + List intList = new List(); + List stringList = new List(); + List z = new List { 9000, 1000, 1337 }; // i + // <>用于泛型 - 参考下文 + + // 列表无默认值 + // 访问列表元素时必须首先添加元素 + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + // 其他数据结构: + // 堆栈/队列 + // 字典 (哈希表的实现) + // 哈希集合 + // 只读集合 + // 元组 (.Net 4+) + + /////////////////////////////////////// + // 操作符 + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // 多重声明的简写形式 + + // 算术直截了当 + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // 取余 + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // 比较操作符 + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // 位操作符 + /* + ~ 取反 + << 左移(有符号) + >> 右移(有符号) + & 与 + ^ 异或 + | 或 + */ + + // 自增、自减 + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. 事后自增 + Console.WriteLine(++i); //i = 2. 事先自增 + Console.WriteLine(i--); //i = 1. 事后自减 + Console.WriteLine(--i); //i = 0. 事先自减 + + /////////////////////////////////////// + // 控制结构 + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // 类似C的if语句 + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // 三元表达式 + // 简单的 if/else 语句可以写成: + // <条件> ? <真> : <假> + string isTrue = (true) ? "True" : "False"; + + // While 循环 + int fooWhile = 0; + while (fooWhile < 100) + { + //迭代 100 次, fooWhile 0->99 + fooWhile++; + } + + // Do While 循环 + int fooDoWhile = 0; + do + { + //迭代 100 次, fooDoWhile 0->99 + fooDoWhile++; + } while (fooDoWhile < 100); + + //for 循环结构 => for(<初始条件>; <条件>; <步>) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + //迭代10次, fooFor 0->9 + } + + // foreach循环 + // foreach 循环结构 => foreach(<迭代器类型> <迭代器> in <可枚举结构>) + // foreach 循环适用于任何实现了 IEnumerable 或 IEnumerable 的对象。 + // .Net 框架下的集合类型(数组, 列表, 字典...) + // 都实现了这些接口 + // (下面的代码中,ToCharArray()可以删除,因为字符串同样实现了IEnumerable) + foreach (char character in "Hello World".ToCharArray()) + { + //迭代字符串中的所有字符 + } + + // Switch 语句 + // switch 适用于 byte、short、char和int 数据类型。 + // 同样适用于可枚举的类型 + // 包括字符串类, 以及一些封装了原始值的类: + // Character、Byte、Short和Integer。 + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + // 你可以一次匹配多个case语句 + // 但是你在添加case语句后需要使用break + // (否则你需要显式地使用goto case x语句) + case 6: + case 7: + case 8: + monthString = "Summer time!!"; + break; + default: + monthString = "Some other month"; + break; + } + + /////////////////////////////////////// + // 转换、指定数据类型 + /////////////////////////////////////// + + // 转换类型 + + // 转换字符串为整数 + // 转换失败会抛出异常 + int.Parse("123");//返回整数类型的"123" + + // TryParse会尝试转换类型,失败时会返回缺省类型 + // 例如 0 + int tryInt; + if (int.TryParse("123", out tryInt)) // Funciton is boolean + Console.WriteLine(tryInt); // 123 + + // 转换整数为字符串 + // Convert类提供了一系列便利转换的方法 + Convert.ToString(123); + // or + tryInt.ToString(); + } + + /////////////////////////////////////// + // 类 + /////////////////////////////////////// + public static void Classes() + { + // 参看文件尾部的对象声明 + + // 使用new初始化对象 + Bicycle trek = new Bicycle(); + + // 调用对象的方法 + trek.SpeedUp(3); // 你应该一直使用setter和getter方法 + trek.Cadence = 100; + + // 查看对象的信息. + Console.WriteLine("trek info: " + trek.Info()); + + // 实例化一个新的Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.Info()); + + Console.Read(); + } // 结束main方法 + + // 终端程序 终端程序必须有一个main方法作为入口 + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // 有趣的特性 + // + + // 默认方法签名 + + public // 可见性 + static // 允许直接调用类,无需先创建实例 + int, //返回值 + MethodSignatures( + int maxCount, // 第一个变量,类型为整型 + int count = 0, // 如果没有传入值,则缺省值为0 + int another = 3, + params string[] otherParams // 捕获其他参数 + ) + { + return -1; + } + + // 方法可以重名,只要签名不一样 + public static void MethodSignature(string maxCount) + { + } + + //泛型 + // TKey和TValue类由用用户调用函数时指定。 + // 以下函数模拟了Python的SetDefault + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // 你可以限定传入值的范围 + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // 我们可以进行迭代,因为T是可枚举的 + foreach (var item in toPrint) + // ittm为整数 + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // 可选参数 + MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); + MethodSignatures(3, another: 3); // 显式指定参数,忽略可选参数 + + // 扩展方法 + int i = 3; + i.Print(); // 参见下面的定义 + + // 可为null的类型 对数据库交互、返回值很有用 + // 任何值类型 (i.e. 不为类) 添加后缀 ? 后会变为可为null的值 + // <类型>? <变量名> = <值> + int? nullable = null; // Nullable 的简写形式 + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // 不为null时返回真 + // ?? 是用于指定默认值的语法糖 + // 以防变量为null的情况 + int notNullable = nullable ?? 0; // 0 + + // 变量类型推断 - 你可以让编译器推断变量类型: + var magic = "编译器确定magic是一个字符串,所以仍然是类型安全的"; + // magic = 9; // 不工作,因为magic是字符串,而不是整数。 + + // 泛型 + // + var phonebook = new Dictionary() { + {"Sarah", "212 555 5555"} // 在电话簿中加入新条目 + }; + + // 调用上面定义为泛型的SETDEFAULT + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // 没有电话 + // 你不用指定TKey、TValue,因为它们会被隐式地推导出来 + Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 + + // lambda表达式 - 允许你用一行代码搞定函数 + Func square = (x) => x * x; // 最后一项为返回值 + Console.WriteLine(square(3)); // 9 + + // 可抛弃的资源管理 - 让你很容易地处理未管理的资源 + // 大多数访问未管理资源 (文件操作符、设备上下文, etc.)的对象 + // 都实现了IDisposable接口。 + // using语句会为你清理IDisposable对象。 + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("这里没有什么可疑的东西"); + // 在作用域的结尾,资源会被回收 + // (即使有异常抛出,也一样会回收) + } + + // 并行框架 + // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary(); + + // 为每个请求新开一个线程 + // 在运行下一步前合并结果 + Parallel.ForEach(websites, + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads + website => + { + // Do something that takes a long time on the file + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // 直到所有的请求完成后才会运行下面的代码 + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // 动态对象(配合其他语言使用很方便) + dynamic student = new ExpandoObject(); + student.FirstName = "First Name"; // 不需要先定义类! + + // 你甚至可以添加方法(接受一个字符串,输出一个字符串) + student.Introduce = new Func( + (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE - 几乎所有的集合都实现了它, + // 带给你 Map / Filter / Reduce 风格的方法 + var bikes = new List(); + bikes.Sort(); // Sorts the array + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // 根据车轮数排序 + var result = bikes + .Where(b => b.Wheels > 3) // 筛选 - 可以连锁使用 (返回IQueryable) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // Map - 这里我们使用了select,所以结果是IQueryable + + var sum = bikes.Sum(b => b.Wheels); // Reduce - 计算集合中的轮子总数 + + // 创建一个包含基于自行车的一些参数生成的隐式对象的列表 + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // 很难演示,但是编译器在代码编译完成前就能推导出以上对象的类型 + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + // ASPARALLEL + // 邪恶的特性 —— 组合了linq和并行操作 + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // 以上代码会并发地运行。会自动新开线程,分别计算结果。 + // 适用于多核、大数据量的场景。 + + // LINQ - 将IQueryable映射到存储,延缓执行 + // 例如 LinqToSql 映射数据库, LinqToXml 映射XML文档 + var db = new BikeRespository(); + + // 执行被延迟了,这对于查询数据库来说很好 + var filter = db.Bikes.Where(b => b.HasTassles); // 不运行查询 + if (42 > 6) // 你可以不断地增加筛选,包括有条件的筛选,例如用于“高级搜索”功能 + filter = filter.Where(b => b.IsBroken); // 不运行查询 + + var query = filter + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // 仍然不运行查询 + + // 现在运行查询,运行查询的时候会打开一个读取器,所以你迭代的是一个副本 + foreach (string bike in query) + Console.WriteLine(result); + + + + } + + } // 结束LearnCSharp类 + + // 你可以在同一个 .cs 文件中包含其他类 + + public static class Extensions + { + // 扩展函数 + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } + // 声明类的语法: + // class <类名>{ + // //数据字段, 构造器, 内部函数. + / // 在Java中函数被称为方法。 + // } + + public class Bicycle + { + // 自行车的字段、变量 + public int Cadence // Public: 任何地方都可以访问 + { + get // get - 定义获取属性的方法 + { + return _cadence; + } + set // set - 定义设置属性的方法 + { + _cadence = value; // value是被传递给setter的值 + } + } + private int _cadence; + + protected virtual int Gear // 类和子类可以访问 + { + get; // 创建一个自动属性,无需成员字段 + set; + } + + internal int Wheels // Internal:在同一程序集内可以访问 + { + get; + private set; // 可以给get/set方法添加修饰符 + } + + int _speed; // 默认为private: 只可以在这个类内访问,你也可以使用`private`关键词 + public string Name { get; set; } + + // enum类型包含一组常量 + // 它将名称映射到值(除非特别说明,是一个整型) + // enmu元素的类型可以是byte、sbyte、short、ushort、int、uint、long、ulong。 + // enum不能包含相同的值。 + public enum BikeBrand + { + AIST, + BMC, + Electra = 42, //你可以显式地赋值 + Gitane // 43 + } + // 我们在Bicycle类中定义的这个类型,所以它是一个内嵌类型。 + // 这个类以外的代码应当使用`Bicycle.Brand`来引用。 + + public BikeBrand Brand; // 声明一个enum类型之后,我们可以声明这个类型的字段 + + // 静态方法的类型为自身,不属于特定的对象。 + // 你无需引用对象就可以访问他们。 + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + static public int BicyclesCreated = 0; + + // 只读值在运行时确定 + // 它们只能在声明或构造器内被赋值 + readonly bool _hasCardsInSpokes = false; // read-only private + + // 构造器是创建类的一种方式 + // 下面是一个默认的构造器 + public Bicycle() + { + this.Gear = 1; // 你可以使用关键词this访问对象的成员 + Cadence = 50; // 不过你并不总是需要它 + _speed = 5; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; + } + + // 另一个构造器的例子(包含参数) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // 首先调用base + { + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; + } + + // 构造器可以连锁使用 + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) + { + } + + // 函数语法 + // <返回值> <函数名称>(<参数>) + + // 类可以为字段实现 getters 和 setters 方法 for their fields + // 或者可以实现属性(C#推荐使用这个) + // 方法的参数可以有默认值 + // 在有默认值的情况下,调用方法的时候可以省略相应的参数 + public void SpeedUp(int increment = 1) + { + _speed += increment; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // 属性可以访问和设置值 + // 当只需要访问数据的时候,考虑使用属性。 + // 属性可以定义get和set,或者是同时定义两者 + private bool _hasTassles; // private variable + public bool HasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + // 你可以在一行之内定义自动属性 + // 这个语法会自动创建后备字段 + // 你可以给getter或setter设置访问修饰符 + // 以便限制它们的访问 + public bool IsBroken { get; private set; } + + // 属性的实现可以是自动的 + public int FrameSize + { + get; + // 你可以给get或set指定访问修饰符 + // 以下代码意味着只有Bicycle类可以调用Framesize的set + private set; + } + + //显示对象属性的方法 + public virtual string Info() + { + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + + // 方法可以是静态的。通常用于辅助方法。 + public static bool DidWeCreateEnoughBycles() + { + // 在静态方法中,你只能引用类的静态成员 + return BicyclesCreated > 9000; + } // 如果你的类只需要静态成员,考虑将整个类作为静态类。 + + + } // Bicycle类结束 + + // PennyFarthing是Bicycle的一个子类 + class PennyFarthing : Bicycle + { + // (Penny Farthings是一种前轮很大的自行车。没有齿轮。) + + // 调用父构造器 + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) + { + } + + protected override int Gear + { + get + { + return 0; + } + set + { + throw new ArgumentException("你不可能在PennyFarthing上切换齿轮"); + } + } + + public override string Info() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // 调用父方法 + return result; + } + } + + // 接口只包含成员的签名,而没有实现。 + interface IJumpable + { + void Jump(int meters); // 所有接口成员是隐式地公开的 + } + + interface IBreakable + { + bool Broken { get; } // 接口可以包含属性、方法和事件 + } + + // 类只能继承一个类,但是可以实现任意数量的接口 + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public bool Broken + { + get + { + return damage > 100; + } + } + } + + /// + /// 连接数据库,一个 LinqToSql的示例。 + /// EntityFramework Code First 很棒 (类似 Ruby的 ActiveRecord, 不过是双向的) + /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// + public class BikeRespository : DbSet + { + public BikeRespository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // 结束 Namespace +``` + +## 没有涉及到的主题 + + * Flags + * Attributes + * 静态属性 + * Exceptions, Abstraction + * ASP.NET (Web Forms/MVC/WebMatrix) + * Winforms + * Windows Presentation Foundation (WPF) + +## 扩展阅读 + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) -- cgit v1.2.3 From 0622062e2a42069af92b549d9774addb4ffc1f0a Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Thu, 20 Mar 2014 18:01:56 +0800 Subject: csharp: typos combine #574 #575 #576 to one pr --- csharp.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index a689fe97..81eb467d 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -558,7 +558,7 @@ on a new line! ""Wow!"", the masses cried"; } set // set - define a method to set a proprety { - _cadence = value; // Value is the value passed in to to the setter + _cadence = value; // Value is the value passed in to the setter } } private int _cadence; @@ -576,7 +576,7 @@ on a new line! ""Wow!"", the masses cried"; } int _speed; // Everything is private by default: Only accessible from within this class. - // can also use keyword privatee + // can also use keyword private public string Name { get; set; } // Enum is a value type that consists of a set of named constants @@ -608,7 +608,7 @@ on a new line! ""Wow!"", the masses cried"; // This is a default constructor public Bicycle() { - this.Gear = 1; // you can access mmebers of the object with the keyword this + this.Gear = 1; // you can access members of the object with the keyword this Cadence = 50; // but you don't always need it _speed = 5; Name = "Bontrager"; -- cgit v1.2.3 From f2575c7f3835eba041b525d57a2049a062617581 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 20 Mar 2014 12:37:13 -0500 Subject: Fix typos from issue 447. --- racket.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/racket.html.markdown b/racket.html.markdown index eddc00bf..6abc8759 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -196,7 +196,7 @@ my-pet ; => # (hash-ref m 'd 0) ; => 0 ;; Use `hash-set' to extend an immutable hash table -;; (Returns the extended hash instdead of mutating it) +;; (Returns the extended hash instead of mutating it) (define m2 (hash-set m 'd 4)) m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) @@ -224,7 +224,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' (define hello-world (lambda () "Hello World")) (hello-world) ; => "Hello World" -;; You can shorten this using the function definition syntatcic sugae: +;; You can shorten this using the function definition syntactic sugar: (define (hello-world2) "Hello World") ;; The () in the above is the list of arguments for the function @@ -496,7 +496,7 @@ vec ; => #(1 2 3 4) ;; 8. Classes and Objects ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Create a class fish% (-% is idomatic for class bindings) +;; Create a class fish% (-% is idiomatic for class bindings) (define fish% (class object% (init size) ; initialization argument @@ -552,7 +552,7 @@ vec ; => #(1 2 3 4) (set! i (add1 i)))) ;; Macros are hygienic, you cannot clobber existing variables! -(define-syntax-rule (swap! x y) ; -! is idomatic for mutation +(define-syntax-rule (swap! x y) ; -! is idiomatic for mutation (let ([tmp x]) (set! x y) (set! y tmp))) -- cgit v1.2.3 From 7db61d1ce143bb8c38eeee662f17754a3f7d5da9 Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Fri, 21 Mar 2014 18:14:55 -0500 Subject: Modify python to be pep8 compliant This mostly adds spaces. --- python.html.markdown | 209 ++++++++++++++++++++++++++------------------------- 1 file changed, 108 insertions(+), 101 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 908a0638..ced01910 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -16,7 +16,9 @@ Note: This article applies to Python 2.7 specifically, but should be applicable to Python 2.x. Look for another tour of Python 3 soon! ```python + # Single line comments start with a hash. + """ Multiline strings can be written using three "'s, and are often used as comments @@ -27,60 +29,60 @@ to Python 2.x. Look for another tour of Python 3 soon! #################################################### # You have numbers -3 #=> 3 +3 # => 3 # Math is what you would expect -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 # Division is a bit tricky. It is integer division and floors the results # automatically. -5 / 2 #=> 2 +5 / 2 # => 2 # To fix division we need to learn about floats. 2.0 # This is a float -11.0 / 4.0 #=> 2.75 ahhh...much better +11.0 / 4.0 # => 2.75 ahhh...much better # Enforce precedence with parentheses -(1 + 3) * 2 #=> 8 +(1 + 3) * 2 # => 8 # Boolean values are primitives True False # negate with not -not True #=> False -not False #=> True +not True # => False +not False # => True # Equality is == -1 == 1 #=> True -2 == 1 #=> False +1 == 1 # => True +2 == 1 # => False # Inequality is != -1 != 1 #=> False -2 != 1 #=> True +1 != 1 # => False +2 != 1 # => True # More comparisons -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True # Comparisons can be chained! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False +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! -"Hello " + "world!" #=> "Hello world!" +"Hello " + "world!" # => "Hello world!" # A string can be treated like a list of characters -"This is a string"[0] #=> 'T' +"This is a string"[0] # => 'T' # % can be used to format strings, like this: "%s can be %s" % ("strings", "interpolated") @@ -92,12 +94,12 @@ not False #=> True "{name} wants to eat {food}".format(name="Bob", food="lasagna") # None is an object -None #=> None +None # => None # Don't use the equality "==" symbol to compare objects to None # Use "is" instead -"etc" is None #=> False -None is None #=> True +"etc" is None # => False +None is None # => True # The 'is' operator tests for object identity. This isn't # very useful when dealing with primitive values, but is @@ -105,8 +107,8 @@ None is None #=> True # None, 0, and empty strings/lists all evaluate to False. # All other values are True -bool(0) #=> False -bool("") #=> False +bool(0) # => False +bool("") # => False #################################################### @@ -121,14 +123,14 @@ print "I'm also Python!" # No need to declare variables before assigning to them. some_var = 5 # 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_other_var # Raises a name error # if can be used as an expression -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" +"yahoo!" if 3 > 2 else 2 # => "yahoo!" # Lists store sequences li = [] @@ -136,63 +138,63 @@ li = [] 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] +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] +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 +li[0] # => 1 # Look at the last element -li[-1] #=> 3 +li[-1] # => 3 # Looking out of bounds is an IndexError -li[4] # Raises 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] +li[1:3] # => [2, 4] # Omit the beginning -li[2:] #=> [4, 3] +li[2:] # => [4, 3] # Omit the end -li[:3] #=> [1, 2, 4] +li[:3] # => [1, 2, 4] # Select every second entry -li[::2] #=>[1,4] +li[::2] # =>[1, 4] # Revert the list -li[::-1] #=> [3, 4, 2, 1] +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] +del li[2] # li is now [1, 2, 3] # You can add lists -li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li and other_li is left alone +li + other_li # => [1, 2, 3, 4, 5, 6] - Note: li and other_li is left alone # Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] +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 +1 in li # => True # Examine the length with "len()" -len(li) #=> 6 +len(li) # => 6 # Tuples are like lists but are immutable. tup = (1, 2, 3) -tup[0] #=> 1 +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 +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 @@ -208,60 +210,60 @@ empty_dict = {} filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with [] -filled_dict["one"] #=> 1 +filled_dict["one"] # => 1 # Get all keys as a list with "keys()" -filled_dict.keys() #=> ["three", "two", "one"] +filled_dict.keys() # => ["three", "two", "one"] # Note - Dictionary key ordering is not guaranteed. # Your results might not match this exactly. # Get all values as a list with "values()" -filled_dict.values() #=> [3, 2, 1] +filled_dict.values() # => [3, 2, 1] # Note - Same as above regarding key ordering. # Check for existence of keys in a dictionary with "in" -"one" in filled_dict #=> True -1 in filled_dict #=> False +"one" in filled_dict # => True +1 in filled_dict # => False # Looking up a non-existing key is a KeyError -filled_dict["four"] # KeyError +filled_dict["four"] # KeyError # Use "get()" method to avoid the KeyError -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None +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 +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 +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 # Sets store ... well sets empty_set = set() # Initialize a "set()" with a bunch of values -some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4]) +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} +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} +filled_set & other_set # => {3, 4, 5} # Do set union with | -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} +filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Do set difference with - -{1,2,3,4} - {2,3,5} #=> {1, 4} +{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 +2 in filled_set # => True +10 in filled_set # => False #################################################### @@ -337,17 +339,18 @@ def add(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 +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) +varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of @@ -356,7 +359,8 @@ def keyword_args(**kwargs): return kwargs # Let's call it to see what happens -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} +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): @@ -372,9 +376,10 @@ all_the_args(1, 2, a=3, b=4) prints: # 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) +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) + # Python has first class functions def create_adder(x): @@ -383,23 +388,24 @@ def create_adder(x): return adder add_10 = create_adder(10) -add_10(3) #=> 13 +add_10(3) # => 13 # There are also anonymous functions -(lambda x: x > 2)(3) #=> True +(lambda x: x > 2)(3) # => True # 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] +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 -[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] +[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): @@ -413,7 +419,7 @@ class Human(object): # An instance method. All methods take "self" as the first argument def say(self, msg): - return "%s: %s" % (self.name, msg) + return "%s: %s" % (self.name, msg) # A class method is shared among all instances # They are called with the calling class as the first argument @@ -432,18 +438,18 @@ i = Human(name="Ian") 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" +i.get_species() # => "H. sapiens" # Change the shared attribute Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" # Call the static method -Human.grunt() #=> "*grunt*" +Human.grunt() # => "*grunt*" #################################################### @@ -452,12 +458,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 @@ -465,7 +471,7 @@ from math import * # You can shorten module names import math as m -math.sqrt(16) == m.sqrt(16) #=> True +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 @@ -486,10 +492,12 @@ def double_numbers(iterable): for i in iterable: yield i + i -# generator creates the value 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 +# 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 _range = range(1, 900000000) # will double all numbers until a result >=30 found for i in double_numbers(_range): @@ -500,7 +508,8 @@ for i in double_numbers(_range): # Decorators # in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned message +# Beg will call say. If say_please is True then it will change the returned +# message from functools import wraps @@ -523,8 +532,6 @@ def say(say_please=False): 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? -- cgit v1.2.3 From bba7307611c5b0e6656c41c284a18249b6f86c86 Mon Sep 17 00:00:00 2001 From: lidashuang Date: Mon, 31 Mar 2014 17:57:19 +0800 Subject: Create elixir-cn.html.markdown --- zh-cn/elixir-cn.html.markdown | 398 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 398 insertions(+) create mode 100644 zh-cn/elixir-cn.html.markdown diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown new file mode 100644 index 00000000..8ea499ff --- /dev/null +++ b/zh-cn/elixir-cn.html.markdown @@ -0,0 +1,398 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] +filename: learnelixir.ex +--- + +Elixir is a modern functional language built on top of the Erlang VM. +It's fully compatible with Erlang, but features a more standard syntax +and many more features. + +```ruby + +# Single line comments start with a hashtag. + +# There's no multi-line comment, +# but you can stack multiple comments. + +# To use the elixir shell use the `iex` command. +# Compile your modules with the `elixirc` command. + +# Both should be in your path if you installed elixir correctly. + +## --------------------------- +## -- Basic types +## --------------------------- + +# There are numbers +3 # integer +0x1F # integer +3.0 # float + +# Atoms, that are literals, a constant with name. They start with `:`. +:hello # atom + +# Tuples that are stored contiguously in memory. +{1,2,3} # tuple + +# We can access a tuple element with the `elem` function: +elem({1, 2, 3}, 0) #=> 1 + +# Lists that are implemented as linked lists. +[1,2,3] # list + +# We can access the head and tail of a list as follows: +[head | tail] = [1,2,3] +head #=> 1 +tail #=> [2,3] + +# In elixir, just like in Erlang, the `=` denotes pattern matching and +# not an assignment. +# +# This means that the left-hand side (pattern) is matched against a +# right-hand side. +# +# This is how the above example of accessing the head and tail of a list works. + +# A pattern match will error when the sides don't match, in this example +# the tuples have different sizes. +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# There's also binaries +<<1,2,3>> # binary + +# Strings and char lists +"hello" # string +'hello' # char list + +# Multi-line strings +""" +I'm a multi-line +string. +""" +#=> "I'm a multi-line\nstring.\n" + +# Strings are all encoded in UTF-8: +"héllò" #=> "héllò" + +# Strings are really just binaries, and char lists are just lists. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` in elixir returns the ASCII integer for the letter `a` +?a #=> 97 + +# To concatenate lists use `++`, for binaries use `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'hello ' ++ 'world' #=> 'hello world' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"hello " <> "world" #=> "hello world" + +## --------------------------- +## -- Operators +## --------------------------- + +# Some math +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# In elixir the operator `/` always returns a float. + +# To do integer division use `div` +div(10, 2) #=> 5 + +# To get the division remainder use `rem` +rem(10, 3) #=> 1 + +# There's also boolean operators: `or`, `and` and `not`. +# These operators expect a boolean as their first argument. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir also provides `||`, `&&` and `!` which accept arguments of any type. +# All values except `false` and `nil` will evaluate to true. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil + +!true #=> false + +# For comparisons we have: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` and `!==` are more strict when comparing integers and floats: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# We can also compare two different data types: +1 < :hello #=> true + +# The overall sorting order is defined below: +# number < atom < reference < functions < port < pid < tuple < list < bit string + +# To quote Joe Armstrong on this: "The actual order is not important, +# but that a total ordering is well defined is important." + +## --------------------------- +## -- Control Flow +## --------------------------- + +# `if` expression +if false do + "This will never be seen" +else + "This will" +end + +# There's also `unless` +unless true do + "This will never be seen" +else + "This will" +end + +# Remember pattern matching? Many control-flow structures in elixir rely on it. + +# `case` allows us to compare a value against many patterns: +case {:one, :two} do + {:four, :five} -> + "This won't match" + {:one, x} -> + "This will match and assign `x` to `:two`" + _ -> + "This will match any value" +end + +# It's common practice to assign a value to `_` if we don't need it. +# For example, if only the head of a list matters to us: +[head | _] = [1,2,3] +head #=> 1 + +# For better readability we can do the following: +[head | _tail] = [:a, :b, :c] +head #=> :a + +# `cond` lets us check for many conditions at the same time. +# Use `cond` instead of nesting many `if` expressions. +cond do + 1 + 1 == 3 -> + "I will never be seen" + 2 * 5 == 12 -> + "Me neither" + 1 + 2 == 3 -> + "But I will" +end + +# It is common to see a last condition equal to `true`, which will always match. +cond do + 1 + 1 == 3 -> + "I will never be seen" + 2 * 5 == 12 -> + "Me neither" + true -> + "But I will (this is essentially an else)" +end + +# `try/catch` is used to catch values that are thrown, it also supports an +# `after` clause that is invoked whether or not a value is catched. +try do + throw(:hello) +catch + message -> "Got #{message}." +after + IO.puts("I'm the after clause.") +end +#=> I'm the after clause +# "Got :hello" + +## --------------------------- +## -- Modules and Functions +## --------------------------- + +# Anonymous functions (notice the dot) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# They also accept many clauses and guards. +# Guards let you fine tune pattern matching, +# they are indicated by the `when` keyword: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir also provides many built-in functions. +# These are available in the current scope. +is_number(10) #=> true +is_list("hello") #=> false +elem({1,2,3}, 0) #=> 1 + +# You can group several functions into a module. Inside a module use `def` +# to define your functions. +defmodule Math do + def sum(a, b) do + a + b + end + + def square(x) do + x * x + end +end + +Math.sum(1, 2) #=> 3 +Math.square(3) #=> 9 + +# To compile our simple Math module save it as `math.ex` and use `elixirc` +# in your terminal: elixirc math.ex + +# Inside a module we can define functions with `def` and private functions with `defp`. +# A function defined with `def` is available to be invoked from other modules, +# a private function can only be invoked locally. +defmodule PrivateMath do + def sum(a, b) do + do_sum(a, b) + end + + defp do_sum(a, b) do + a + b + end +end + +PrivateMath.sum(1, 2) #=> 3 +# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) + +# Function declarations also support guards and multiple clauses: +defmodule Geometry do + def area({:rectangle, w, h}) do + w * h + end + + def area({:circle, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometry.area({:rectangle, 2, 3}) #=> 6 +Geometry.area({:circle, 3}) #=> 28.25999999999999801048 +# Geometry.area({:circle, "not_a_number"}) +#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 + +# Due to immutability, recursion is a big part of elixir +defmodule Recursion do + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end + + def sum_list([], acc) do + acc + end +end + +Recursion.sum_list([1,2,3], 0) #=> 6 + +# Elixir modules support attributes, there are built-in attributes and you +# may also add custom attributes. +defmodule MyMod do + @moduledoc """ + This is a built-in attribute on a example module. + """ + + @my_data 100 # This is a custom attribute. + IO.inspect(@my_data) #=> 100 +end + +## --------------------------- +## -- Records and Exceptions +## --------------------------- + +# Records are basically structures that allow you to associate a name with +# a particular value. +defrecord Person, name: nil, age: 0, height: 0 + +joe_info = Person.new(name: "Joe", age: 30, height: 180) +#=> Person[name: "Joe", age: 30, height: 180] + +# Access the value of name +joe_info.name #=> "Joe" + +# Update the value of age +joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] + +# The `try` block with the `rescue` keyword is used to handle exceptions +try do + raise "some error" +rescue + RuntimeError -> "rescued a runtime error" + _error -> "this will rescue any error" +end + +# All exceptions have a message +try do + raise "some error" +rescue + x in [RuntimeError] -> + x.message +end + +## --------------------------- +## -- Concurrency +## --------------------------- + +# Elixir relies on the actor model for concurrency. All we need to write +# concurrent programs in elixir are three primitives: spawning processes, +# sending messages and receiving messages. + +# To start a new process we use the `spawn` function, which takes a function +# as argument. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` returns a pid (process identifier), you can use this pid to send +# messages to the process. To do message passing we use the `<-` operator. +# For all of this to be useful we need to be able to receive messages. This is +# achived with the `receive` mechanism: +defmodule Geometry do + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Area = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Area = #{3.14 * r * r}") + area_loop() + end + end +end + +# Compile the module and create a process that evaluates `area_loop` in the shell +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> + +# Send a message to `pid` that will match a pattern in the receive statement +pid <- {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +pid <- {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} + +# The shell is also a process, you can use `self` to get the current pid +self() #=> #PID<0.27.0> +``` + +## References + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org) +* [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) by Fred Hebert +* "Programming Erlang: Software for a Concurrent World" by Joe Armstrong -- cgit v1.2.3 From 09044470a089c4ccc896edf846b7ae54264cceae Mon Sep 17 00:00:00 2001 From: lidashuang Date: Mon, 31 Mar 2014 18:00:57 +0800 Subject: Update elixir.html.markdown --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 8ea499ff..df586649 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -9,7 +9,7 @@ Elixir is a modern functional language built on top of the Erlang VM. It's fully compatible with Erlang, but features a more standard syntax and many more features. -```ruby +```elixir # Single line comments start with a hashtag. -- cgit v1.2.3 From 708fd4a65b9a3c9dc216f23e1906de2421e657fd Mon Sep 17 00:00:00 2001 From: lidashuang Date: Mon, 31 Mar 2014 19:49:46 +0800 Subject: Update elixir-cn.html.markdown --- zh-cn/elixir-cn.html.markdown | 127 +++++++++++++++++++++--------------------- 1 file changed, 63 insertions(+), 64 deletions(-) diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown index 8ea499ff..2c8f5fb5 100644 --- a/zh-cn/elixir-cn.html.markdown +++ b/zh-cn/elixir-cn.html.markdown @@ -2,88 +2,88 @@ language: elixir contributors: - ["Joao Marques", "http://github.com/mrshankly"] + - ["lidashuang", "http://github.com/lidashuang"] filename: learnelixir.ex --- -Elixir is a modern functional language built on top of the Erlang VM. -It's fully compatible with Erlang, but features a more standard syntax -and many more features. +Elixir 是一门构建在Elang VM 之上的函数式编程语言。Elixir 完全兼容 Eralng, +另外还提供了更标准的语法,特性。 -```ruby +```elixir -# Single line comments start with a hashtag. +# 这是单行注释, 注释以井号开头 -# There's no multi-line comment, -# but you can stack multiple comments. +# 没有多行注释 +# 但你可以堆叠多个注释。 -# To use the elixir shell use the `iex` command. -# Compile your modules with the `elixirc` command. +# elixir shell 使用命令 `iex` 进入。 +# 编译模块使用 `elixirc` 命令。 -# Both should be in your path if you installed elixir correctly. +# 如果安装正确,这些命令都会在环境变量里 ## --------------------------- -## -- Basic types +## -- 基本类型 ## --------------------------- -# There are numbers -3 # integer -0x1F # integer -3.0 # float +# 数字 +3 # 整型 +0x1F # 整型 +3.0 # 浮点类型 -# Atoms, that are literals, a constant with name. They start with `:`. +# 原子(Atoms),以 `:`开头 :hello # atom # Tuples that are stored contiguously in memory. {1,2,3} # tuple -# We can access a tuple element with the `elem` function: +# 使用`elem`函数访问元组(tuple)里的元素: elem({1, 2, 3}, 0) #=> 1 -# Lists that are implemented as linked lists. +# 列表(list) [1,2,3] # list -# We can access the head and tail of a list as follows: +# 可以用下面的方法访问列表的头尾元素: [head | tail] = [1,2,3] head #=> 1 tail #=> [2,3] -# In elixir, just like in Erlang, the `=` denotes pattern matching and -# not an assignment. +# 在elixir,就像在Erlang, `=` 表示模式匹配 (pattern matching) +# 不是赋值。 # # This means that the left-hand side (pattern) is matched against a # right-hand side. # # This is how the above example of accessing the head and tail of a list works. -# A pattern match will error when the sides don't match, in this example -# the tuples have different sizes. +# 当左右两边不匹配时,会返回error, 在这个 +# 例子中,元组大小不一样。 # {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} -# There's also binaries +# 还有二进制类型 (binaries) <<1,2,3>> # binary -# Strings and char lists +# 字符串(Strings) 和 字符列表(char lists) "hello" # string 'hello' # char list -# Multi-line strings +# 多行字符串 """ I'm a multi-line string. """ #=> "I'm a multi-line\nstring.\n" -# Strings are all encoded in UTF-8: +# 所有的字符串(Strings)以UTF-8编码: "héllò" #=> "héllò" -# Strings are really just binaries, and char lists are just lists. +# 字符串(Strings)本质就是二进制类型(binaries), 字符列表(char lists)本质是列表(lists) <> #=> "abc" [?a, ?b, ?c] #=> 'abc' -# `?a` in elixir returns the ASCII integer for the letter `a` +# 在 elixir中,`?a`返回 `a` 的 ASCII 整型值 ?a #=> 97 -# To concatenate lists use `++`, for binaries use `<>` +# 合并列表使用 `++`, 对于二进制类型则使用 `<>` [1,2,3] ++ [4,5] #=> [1,2,3,4,5] 'hello ' ++ 'world' #=> 'hello world' @@ -91,67 +91,67 @@ string. "hello " <> "world" #=> "hello world" ## --------------------------- -## -- Operators +## -- 操作符(Operators) ## --------------------------- -# Some math +# 一些数学运算 1 + 1 #=> 2 10 - 5 #=> 5 5 * 2 #=> 10 10 / 2 #=> 5.0 -# In elixir the operator `/` always returns a float. +# 在 elixir 操作符 `/` 返回值总是浮点数。 -# To do integer division use `div` +# 做整数除法使用 `div` div(10, 2) #=> 5 -# To get the division remainder use `rem` +# 为了得到余数使用 `rem` rem(10, 3) #=> 1 -# There's also boolean operators: `or`, `and` and `not`. -# These operators expect a boolean as their first argument. +# 还有 boolean 操作符: `or`, `and` and `not`. +# 第一个参数必须是boolean 类型 true and true #=> true false or true #=> true # 1 and true #=> ** (ArgumentError) argument error -# Elixir also provides `||`, `&&` and `!` which accept arguments of any type. -# All values except `false` and `nil` will evaluate to true. +# Elixir 也提供了 `||`, `&&` 和 `!` 可以接受任意的类型 +# 除了`false` 和 `nil` 其它都会被当作true. 1 || true #=> 1 false && 1 #=> false nil && 20 #=> nil !true #=> false -# For comparisons we have: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>` +# 比较有: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` 和 `>` 1 == 1 #=> true 1 != 1 #=> false 1 < 2 #=> true -# `===` and `!==` are more strict when comparing integers and floats: +# `===` 和 `!==` 在比较整型和浮点类型时更为严格: 1 == 1.0 #=> true 1 === 1.0 #=> false -# We can also compare two different data types: +# 我们也可以比较两种不同的类型: 1 < :hello #=> true -# The overall sorting order is defined below: +# 总的排序顺序定义如下: # number < atom < reference < functions < port < pid < tuple < list < bit string # To quote Joe Armstrong on this: "The actual order is not important, # but that a total ordering is well defined is important." ## --------------------------- -## -- Control Flow +## -- 控制结构(Control Flow) ## --------------------------- -# `if` expression +# `if` 表达式 if false do "This will never be seen" else "This will" end -# There's also `unless` +# 还有 `unless` unless true do "This will never be seen" else @@ -170,12 +170,12 @@ case {:one, :two} do "This will match any value" end -# It's common practice to assign a value to `_` if we don't need it. -# For example, if only the head of a list matters to us: +# 模式匹配时,如果不需要某个值,通用的做法是把值 匹配到 `_` +# 例如,我们只需要要列表的头元素: [head | _] = [1,2,3] head #=> 1 -# For better readability we can do the following: +# 下面的方式效果一样,但可读性更好 [head | _tail] = [:a, :b, :c] head #=> :a @@ -213,10 +213,10 @@ end # "Got :hello" ## --------------------------- -## -- Modules and Functions +## -- 模块和函数(Modules and Functions) ## --------------------------- -# Anonymous functions (notice the dot) +# 匿名函数 (注意点) square = fn(x) -> x * x end square.(5) #=> 25 @@ -231,14 +231,13 @@ end f.(1, 3) #=> 4 f.(-1, 3) #=> -3 -# Elixir also provides many built-in functions. -# These are available in the current scope. +# Elixir 提供了很多内建函数 +# 在默认作用域都是可用的 is_number(10) #=> true is_list("hello") #=> false elem({1,2,3}, 0) #=> 1 -# You can group several functions into a module. Inside a module use `def` -# to define your functions. +# 你可以在一个模块里定义多个函数,定义函数使用 `def` defmodule Math do def sum(a, b) do a + b @@ -252,12 +251,12 @@ end Math.sum(1, 2) #=> 3 Math.square(3) #=> 9 -# To compile our simple Math module save it as `math.ex` and use `elixirc` -# in your terminal: elixirc math.ex +# 保存到 `math.ex`,使用 `elixirc` 编译你的 Math 模块 +# 在终端里: elixirc math.ex -# Inside a module we can define functions with `def` and private functions with `defp`. -# A function defined with `def` is available to be invoked from other modules, -# a private function can only be invoked locally. +# 在模块中可以使用`def`定义函数,使用 `defp` 定义私有函数 +# 使用`def` 定义的函数可以被其它模块调用 +# 私有函数只能在本模块内调用 defmodule PrivateMath do def sum(a, b) do do_sum(a, b) @@ -287,7 +286,7 @@ Geometry.area({:circle, 3}) #=> 28.25999999999999801048 # Geometry.area({:circle, "not_a_number"}) #=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 -# Due to immutability, recursion is a big part of elixir +#由于不变性,递归是Elixir的重要组成部分 defmodule Recursion do def sum_list([head | tail], acc) do sum_list(tail, acc + head) @@ -322,7 +321,7 @@ defrecord Person, name: nil, age: 0, height: 0 joe_info = Person.new(name: "Joe", age: 30, height: 180) #=> Person[name: "Joe", age: 30, height: 180] -# Access the value of name +# 访问name的值 joe_info.name #=> "Joe" # Update the value of age @@ -345,7 +344,7 @@ rescue end ## --------------------------- -## -- Concurrency +## -- 并发(Concurrency) ## --------------------------- # Elixir relies on the actor model for concurrency. All we need to write @@ -386,7 +385,7 @@ pid <- {:circle, 2} #=> Area = 12.56000000000000049738 # {:circle,2} -# The shell is also a process, you can use `self` to get the current pid +# shell也是一个进程(process), 你可以使用`self`获取当前 pid self() #=> #PID<0.27.0> ``` -- cgit v1.2.3 From 816ba7d7e6f3e6b7b93275c6041498eabcf41c84 Mon Sep 17 00:00:00 2001 From: lidashuang Date: Mon, 31 Mar 2014 22:12:03 +0800 Subject: Update elixir-cn.html.markdown --- zh-cn/elixir-cn.html.markdown | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown index 2c8f5fb5..a2e5f4aa 100644 --- a/zh-cn/elixir-cn.html.markdown +++ b/zh-cn/elixir-cn.html.markdown @@ -311,7 +311,7 @@ defmodule MyMod do end ## --------------------------- -## -- Records and Exceptions +## -- 记录和异常(Records and Exceptions) ## --------------------------- # Records are basically structures that allow you to associate a name with @@ -324,7 +324,7 @@ joe_info = Person.new(name: "Joe", age: 30, height: 180) # 访问name的值 joe_info.name #=> "Joe" -# Update the value of age +# 更新age的值 joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] # The `try` block with the `rescue` keyword is used to handle exceptions @@ -351,8 +351,7 @@ end # concurrent programs in elixir are three primitives: spawning processes, # sending messages and receiving messages. -# To start a new process we use the `spawn` function, which takes a function -# as argument. +# 启动一个新的进程使用`spawn`函数,接收一个函数作为参数 f = fn -> 2 * 2 end #=> #Function spawn(f) #=> #PID<0.40.0> @@ -373,10 +372,10 @@ defmodule Geometry do end end -# Compile the module and create a process that evaluates `area_loop` in the shell +# 编译这个模块,在shell中创建一个进程,并执行 `area_looop` 函数。 pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> -# Send a message to `pid` that will match a pattern in the receive statement +# 发送一个消息给 `pid`, 会在receive语句进行模式匹配 pid <- {:rectangle, 2, 3} #=> Area = 6 # {:rectangle,2,3} @@ -389,7 +388,7 @@ pid <- {:circle, 2} self() #=> #PID<0.27.0> ``` -## References +## 参考文献 * [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org) * [Elixir Documentation](http://elixir-lang.org/docs/master/) -- cgit v1.2.3 From c9bc93c261e74cfd3f5b9fedaade75aec91ec253 Mon Sep 17 00:00:00 2001 From: lidashuang Date: Mon, 31 Mar 2014 22:24:09 +0800 Subject: Update elixir-cn.html.markdown --- zh-cn/elixir-cn.html.markdown | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown index a2e5f4aa..1f8e3e2c 100644 --- a/zh-cn/elixir-cn.html.markdown +++ b/zh-cn/elixir-cn.html.markdown @@ -299,14 +299,13 @@ end Recursion.sum_list([1,2,3], 0) #=> 6 -# Elixir modules support attributes, there are built-in attributes and you -# may also add custom attributes. +# Elixir 模块支持属性,模块内建了一些属性,你也可以自定义属性 defmodule MyMod do @moduledoc """ - This is a built-in attribute on a example module. + 内置的属性,模块文档 """ - @my_data 100 # This is a custom attribute. + @my_data 100 # 自定义属性 IO.inspect(@my_data) #=> 100 end @@ -327,7 +326,7 @@ joe_info.name #=> "Joe" # 更新age的值 joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] -# The `try` block with the `rescue` keyword is used to handle exceptions +# 使用 `try` `rescue` 进行异常处理 try do raise "some error" rescue @@ -335,7 +334,7 @@ rescue _error -> "this will rescue any error" end -# All exceptions have a message +# 所有的异常都有一个message try do raise "some error" rescue @@ -347,18 +346,19 @@ end ## -- 并发(Concurrency) ## --------------------------- -# Elixir relies on the actor model for concurrency. All we need to write -# concurrent programs in elixir are three primitives: spawning processes, -# sending messages and receiving messages. +# Elixir 依赖与actor并发模型。在Elixir编写并发程序的三要素: +# 创建进程,发送消息,接收消息 # 启动一个新的进程使用`spawn`函数,接收一个函数作为参数 + f = fn -> 2 * 2 end #=> #Function spawn(f) #=> #PID<0.40.0> -# `spawn` returns a pid (process identifier), you can use this pid to send -# messages to the process. To do message passing we use the `<-` operator. -# For all of this to be useful we need to be able to receive messages. This is -# achived with the `receive` mechanism: + +# `spawn` 函数返回一个pid(进程标识符),你可以使用pid向进程发送消息。 +# 使用 `<-` 操作符发送消息。 +# 我们需要在进程内接收消息,要用到 `receive` 机制。 + defmodule Geometry do def area_loop do receive do -- cgit v1.2.3 From d6bd212e433df381be331a512796b2572d023cb1 Mon Sep 17 00:00:00 2001 From: lidashuang Date: Mon, 31 Mar 2014 23:25:19 +0800 Subject: Update elixir-cn.html.markdown --- zh-cn/elixir-cn.html.markdown | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown index 1f8e3e2c..a624f6b1 100644 --- a/zh-cn/elixir-cn.html.markdown +++ b/zh-cn/elixir-cn.html.markdown @@ -33,7 +33,7 @@ Elixir 是一门构建在Elang VM 之上的函数式编程语言。Elixir 完全 # 原子(Atoms),以 `:`开头 :hello # atom -# Tuples that are stored contiguously in memory. +# 元组(Tuple) 在内存中的存储是连续的 {1,2,3} # tuple # 使用`elem`函数访问元组(tuple)里的元素: @@ -50,10 +50,9 @@ tail #=> [2,3] # 在elixir,就像在Erlang, `=` 表示模式匹配 (pattern matching) # 不是赋值。 # -# This means that the left-hand side (pattern) is matched against a -# right-hand side. -# -# This is how the above example of accessing the head and tail of a list works. +# 这表示会用左边的模式(pattern)匹配右侧 +# +# 这是上面的例子中访问列列表的头部和尾部的就是这样工作的。 # 当左右两边不匹配时,会返回error, 在这个 # 例子中,元组大小不一样。 @@ -137,8 +136,8 @@ nil && 20 #=> nil # 总的排序顺序定义如下: # number < atom < reference < functions < port < pid < tuple < list < bit string -# To quote Joe Armstrong on this: "The actual order is not important, -# but that a total ordering is well defined is important." +# 引用Joe Armstrong :”实际的顺序并不重要, +# 但是,一个整体排序是否经明确界定是非常重要的“。 ## --------------------------- ## -- 控制结构(Control Flow) @@ -158,9 +157,9 @@ else "This will" end -# Remember pattern matching? Many control-flow structures in elixir rely on it. +# 在Elixir中,很多控制结构都依赖于模式匹配 -# `case` allows us to compare a value against many patterns: +# `case` 允许我们把一个值与多种模式进行比较: case {:one, :two} do {:four, :five} -> "This won't match" @@ -179,8 +178,8 @@ head #=> 1 [head | _tail] = [:a, :b, :c] head #=> :a -# `cond` lets us check for many conditions at the same time. -# Use `cond` instead of nesting many `if` expressions. +# `cond` 可以检测多种不同的分支 +# 使用 `cond` 代替多个`if` 表达式嵌套 cond do 1 + 1 == 3 -> "I will never be seen" @@ -190,7 +189,7 @@ cond do "But I will" end -# It is common to see a last condition equal to `true`, which will always match. +# 经常可以看到最后一个条件等于'true',这将总是匹配。 cond do 1 + 1 == 3 -> "I will never be seen" @@ -200,8 +199,9 @@ cond do "But I will (this is essentially an else)" end -# `try/catch` is used to catch values that are thrown, it also supports an -# `after` clause that is invoked whether or not a value is catched. +# `try/catch` 用于捕获被抛出的值, 它也支持 `after` 子句, +# 无论是否值被捕获,after 子句都会被调用 +# `try/catch` try do throw(:hello) catch @@ -220,9 +220,10 @@ end square = fn(x) -> x * x end square.(5) #=> 25 -# They also accept many clauses and guards. -# Guards let you fine tune pattern matching, -# they are indicated by the `when` keyword: + +# 也支持接收多个子句和卫士(guards). +# Guards可以进行模式匹配 +# Guards只有`when` 关键字指明: f = fn x, y when x > 0 -> x + y x, y -> x * y @@ -313,8 +314,7 @@ end ## -- 记录和异常(Records and Exceptions) ## --------------------------- -# Records are basically structures that allow you to associate a name with -# a particular value. +# 记录就是把特定值关联到某个名字的结构体 defrecord Person, name: nil, age: 0, height: 0 joe_info = Person.new(name: "Joe", age: 30, height: 180) -- cgit v1.2.3 From ff4a2728e8469f62f5fc4e8be81dd5fdd46f9195 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 31 Mar 2014 13:19:56 -0700 Subject: Update elixir-cn.html.markdown Fix header things --- zh-cn/elixir-cn.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown index a624f6b1..50f0e350 100644 --- a/zh-cn/elixir-cn.html.markdown +++ b/zh-cn/elixir-cn.html.markdown @@ -2,8 +2,10 @@ language: elixir contributors: - ["Joao Marques", "http://github.com/mrshankly"] +translators: - ["lidashuang", "http://github.com/lidashuang"] -filename: learnelixir.ex +filename: learnelixir-cn.ex +lang: zh-cn --- Elixir 是一门构建在Elang VM 之上的函数式编程语言。Elixir 完全兼容 Eralng, -- cgit v1.2.3 From 4f71e1574229fea8e37f5e67f3469f768b02d474 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Wed, 2 Apr 2014 23:08:39 +0800 Subject: css: add Chinese (zh_CN) translation --- zh-cn/css-cn.html.markdown | 211 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 zh-cn/css-cn.html.markdown diff --git a/zh-cn/css-cn.html.markdown b/zh-cn/css-cn.html.markdown new file mode 100644 index 00000000..a188ee9b --- /dev/null +++ b/zh-cn/css-cn.html.markdown @@ -0,0 +1,211 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Jakukyo Friel", "https://weakish.github.io"] +filename: learncss.css +--- + +早期的web没有样式,只是单纯的文本。通过CSS,可以实现网页样式和内容的分离。 + +简单来说,CSS可以指定HTML页面上的元素所使用的样式。 + +和其他语言一样,CSS有很多版本。最新的版本是CSS 3. CSS 2.0兼容性最好。 + +你可以使用[dabblet](http://dabblet.com/)来在线测试CSS的效果。 + +```css +/* 注释 */ + +/* #################### + ## 选择器 + ####################*/ + +/* 一般而言,CSS的声明语句非常简单。 */ +选择器 { 属性: 值; /* 更多属性...*/ } + +/* 选择器用于指定页面上的元素。 + +针对页面上的所有元素。 */ +* { color:red; } + +/* +假定页面上有这样一个元素 + +
+*/ + +/* 你可以通过类名来指定它 */ +.some-class { } + +/* 给出所有类名 */ +.some-class.class2 { } + +/* 标签名 */ +div { } + +/* id */ +#someId { } + +/* 由于元素包含attr属性,因此也可以通过这个来指定 */ +[attr] { font-size:smaller; } + +/* 以及有特定值的属性 */ +[attr='value'] { font-size:smaller; } + +/* 通过属性的值的开头指定 */ +[attr^='val'] { font-size:smaller; } + +/* 通过属性的值的结尾来指定 */ +[attr$='ue'] { font-size:smaller; } + +/* 通过属性的值的部分来指定 */ +[attr~='lu'] { font-size:smaller; } + + +/* 你可以把这些全部结合起来,注意不同部分间不应该有空格,否则会改变语义 */ +div.some-class[attr$='ue'] { } + +/* 你也可以通过父元素来指定。*/ + +/* 某个元素是另一个元素的直接子元素 */ +div.some-parent > .class-name {} + +/* 或者通过该元素的祖先元素 */ +div.some-parent .class-name {} + +/* 注意,去掉空格后语义就不同了。 +你能说出哪里不同么? */ +div.some-parent.class-name {} + +/* 你可以选择某元素前的相邻元素 */ +.i-am-before + .this-element { } + +/* 某元素之前的同级元素(相邻或不相邻) */ +.i-am-any-before ~ .this-element {} + +/* 伪类允许你基于页面的行为指定元素(而不是基于页面结构) */ + +/* 例如,当鼠标悬停在某个元素上时 */ +:hover {} + +/* 已访问过的链接*/ +:visited {} + +/* 未访问过的链接*/ +:link {} + +/* 当前焦点的input元素 */ +:focus {} + + +/* #################### + ## 属性 + ####################*/ + +选择器 { + + /* 单位 */ + width: 50%; /* 百分比 */ + font-size: 2em; /* 当前字体大小的两倍 */ + width: 200px; /* 像素 */ + font-size: 20pt; /* 点 */ + width: 5cm; /* 厘米 */ + width: 50mm; /* 毫米 */ + width: 5in; /* 英尺 */ + + /* 颜色 */ + background-color: #F6E; /* 短16位 */ + background-color: #F262E2; /* 长16位 */ + background-color: tomato; /* 颜色名称 */ + background-color: rgb(255, 255, 255); /* rgb */ + background-color: rgb(10%, 20%, 50%); /* rgb 百分比 */ + background-color: rgba(255, 0, 0, 0.3); /* rgb 加透明度 */ + + /* 图片 */ + background-image: url(/path-to-image/image.jpg); + + /* 字体 */ + font-family: Arial; + font-family: "Courier New"; /* 使用双引号包裹含空格的字体名称 */ + font-family: "Courier New", Trebuchet, Arial; /* 如果第一个 + 字体没找到,浏览器会使用第二个字体,一次类推 */ +} + +``` + +## 使用 + +CSS文件使用 `.css` 后缀。 + +```xml + + + + + + + +
+
+ +``` + +## 优先级 + +同一个元素可能被多个不同的选择器指定,因此可能会有冲突。 + +假定CSS是这样的: + +```css +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +然后标记语言为: + +```xml +

+

+``` + +那么将会按照下面的顺序应用风格: + + +* `E` 优先级最高,因为它使用了 `!important`,除非很有必要,尽量避免使用这个。 +* `F` 其次,因为它是嵌入的风格。 +* `A` 其次,因为它比其他指令更具体。 +* `C` 其次,虽然它的具体程度和`B`一样,但是它在`B`之后。 +* 接下来是 `B`。 +* 最后是 `D`。 + +## 兼容性 + +CSS2 的绝大部分特性兼容各种浏览器和设备。现在 CSS3 的兼容性也越来越好了。 +但是兼容性问题仍然是需要留意的一个问题。 + +[QuirksMode CSS](http://www.quirksmode.org/css/)是关于这方面最好的资源。 + +## 扩展阅读 + +* [理解CSS的风格优先级: 特定性, 继承和层叠](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) -- cgit v1.2.3 From e5d15eec06f7708e2ff423ac78f3effbd29f051b Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Fri, 21 Mar 2014 14:29:30 -0500 Subject: Fix typos in Spanish Julia --- es-es/julia-es.html.markdown | 90 ++++++++++++++++++++++---------------------- 1 file changed, 44 insertions(+), 46 deletions(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 2dcc915e..4b79674d 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -8,19 +8,20 @@ lang: es-es --- Julia es un nuevo lenguaje funcional homoiconic enfocado en computación técnica. -Mientras que tiene todo el poder de macros homoiconic, funciones de primera +Aunque que tiene todo el poder de macros homoiconic, funciones de primera clase, y control de bajo nivel, Julia es tan fácil de aprender y utilizar como Python. Esto se basa en la versión de desarrollo actual de Julia, del 18 de octubre de 2013. -```ruby -j +```julia + # Comentarios de una línea comienzan con una almohadilla (o signo gato) + #= Commentarios multilinea pueden escribirse - usando '#=' antes de que el texto and '=#' - después del texto. También se pueden anidar. + usando '#=' antes de el texto y '=#' + después del texto. También se pueden anidar. =# #################################################### @@ -40,10 +41,10 @@ j 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7.0 -5/2 # => 2.5 # dividir un Int por un Int siempre resulta en un Fload +5/2 # => 2.5 # dividir un Int por un Int siempre resulta en un Float div (5, 2) # => 2 # para un resultado truncado, usa div 5 \ 35 # => 7.0 -2 ^ 2 # => 4 # exponente, no exclusivo bit a bit +2 ^ 2 # => 4 # exponente, no es xor 12 % 10 # => 2 # Refuerza la precedencia con paréntesis @@ -91,17 +92,15 @@ false 'a' # Una string puede ser indexado como una array de caracteres -"Esto es un string."[1] # => 'E' # Julia indexes from 1 -# However, this is will not work well for UTF8 strings, -# so iterating over strings is recommended (map, for loops, etc). +"Esto es un string."[1] # => 'E' # Índices en Julia empiezen del 1 # Sin embargo, esto no va a funcionar bien para strings UTF8, # Lo que se recomienda es la iteración (map, for, etc). -# Puede ser utilizado para la interpolación de strings: +# $ puede ser utilizado para la interpolación de strings: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" # Se puede poner cualquier expresión de Julia dentro los paréntesis. -# Otro forma de formatear strings es el printf macro +# Otro forma de formatear strings es el macro printf @printf "%d es menor de %f" 4.5 5.3 # 5 es menor de 5.300000 # Imprimir es muy fácil @@ -123,7 +122,7 @@ catch e end # Los nombres de variables comienzan con una letra. -# Después de eso, usted puede utilizar letras, dígitos, guiones y signos de +# Después de eso, puedes utilizar letras, dígitos, guiones y signos de # exclamación. OtraVariable123! = 6 # => 6 @@ -138,13 +137,13 @@ OtraVariable123! = 6 # => 6 # palabra indicado por underscore ('\ _'). # # * Los nombres de los tipos comienzan con una letra mayúscula y separación de -# palabras se muestra Con CamelCase en vez de underscore. +# palabras se muestra con CamelCase en vez de underscore. # -# * Los nombres de las funciones y las macros están en minúsculas, sin +# * Los nombres de las funciones y los macros están en minúsculas, sin # underscore. # # * Funciones que modifican sus inputs tienen nombres que terminan en!. Estos -# funciones a veces se llaman mutating functions or in-place functions. +# funciones a veces se llaman mutating functions o in-place functions. # Los Arrays almacenan una secuencia de valores indexados entre 1 hasta n a = Int64[] # => 0-element Int64 Array @@ -159,7 +158,7 @@ b[end] # => 6 # separados por punto y coma. matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] -# Añadir cosas a la final de una lista con push! y append! +# Añadir cosas al final de una lista con push! y append! push!(a,1) # => [1] push!(a,2) # => [1,2] push!(a,4) # => [1,2,4] @@ -178,11 +177,11 @@ a[1] # => 1 # recuerdan que los índices de Julia empiezan desde 1, no desde 0! # expresión de indexación a[end] # => 6 -# tambien hay shift and unshift +# tambien hay shift y unshift shift!(a) # => 1 y a es ahora [2,4,3,4,5,6] unshift!(a,7) # => [7,2,4,3,4,5,6] -# Nombres de función que terminan en exclamaciones indican que modifican +# Nombres de funciónes que terminan en exclamaciones indican que modifican # su argumento. arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] sort(arr) # => [4,5,6]; arr es todavía [5,4,6] @@ -197,13 +196,13 @@ catch e end # Errors dan la línea y el archivo de su procedencia, aunque sea en el standard -# library. Si construyes Julia de source, puedes buscar en la source para +# library. Si construyes Julia de source, puedes buscar en el source para # encontrar estos archivos. # Se puede inicializar arrays de un range a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] -# Usted puede mirar en ranges con sintaxis slice. +# Puedes mirar en ranges con sintaxis slice. a[1:3] # => [1, 2, 3] a[2:end] # => [2, 3, 4, 5] @@ -215,10 +214,10 @@ splice!(arr,2) # => 4 ; arr es ahora [3,5] b = [1,2,3] append!(a,b) # ahroa a es [1, 2, 3, 4, 5, 1, 2, 3] -# Salida por la existencia de una lista con in +# Comprobamos la existencia en una lista con in in(1, a) # => true -# Examinar la longitud con length +# Examina la longitud con length length(a) # => 8 # Tuples son immutable. @@ -235,7 +234,7 @@ length(tup) # => 3 tup[1:2] # => (1,2) in(2, tup) # => true -# Se puede desempaquetar tuples en variables +# Se puede desempacar tuples en variables a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 # Los tuples se crean, incluso si se omite el paréntesis @@ -259,13 +258,13 @@ dict_lleno = ["one"=> 1, "two"=> 2, "three"=> 3] # Busca valores con [] dict_lleno["one"] # => 1 -# Obtén todas las claves +# Obtén todas las claves keys(dict_lleno) # => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Nota - claves del dictionary no están ordenados ni en el orden en que se # insertan. -# Obtén todas las claves +# Obtén todos los valores values(dict_lleno) # => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Nota - Igual que el anterior en cuanto a ordenamiento de claves. @@ -276,7 +275,7 @@ in(("tres", 3), dict_lleno) # => false haskey(dict_lleno, "one") # => true haskey(dict_lleno, 1) # => false -# Tratando de buscar una clave inexistente producirá un error +# Tratando de buscar una clave que no existe producirá un error try dict_lleno["dos"] # => ERROR: key not found: dos in getindex at dict.jl:489 catch e @@ -347,7 +346,7 @@ end # gato es un mamifero # raton es un mamifero -for (k,v) in ["perro"=>"mamifero","gato"=>"mamifero","raton"=>"mamifero"] +for (k,v) in ["perro"=>"mamifero", "gato"=>"mamifero", "raton"=>"mamifero"] println("$k es un $v") end # imprime: @@ -367,7 +366,7 @@ end # 2 # 3 -# Maneja excepciones con un bloque try/except +# Maneja excepciones con un bloque try/catch try error("ayuda") catch e @@ -431,7 +430,7 @@ catch e println(e) end -# Puede definir funciones que toman argumentos de palabra clave +# Puedes definir funciones que toman argumentos de palabra clave function args_clave(;k1=4,nombre2="hola") # note the ; return ["k1"=>k1,"nombre2"=>nombre2] end @@ -440,14 +439,14 @@ args_clave(nombre2="ness") # => ["nombre2"=>"ness","k1"=>4] args_clave(k1="mine") # => ["k1"=>"mine","nombre2"=>"hola"] args_clave() # => ["nombre2"=>"hola","k1"=>4] -# Se puede combinar todo tipo de argumentos en la misma función +# Puedes combinar todo tipo de argumentos en la misma función function todos_los_args(arg_normal, arg_posicional_opcional=2; arg_clave="foo") println("argumento normal: $arg_normal") println("argumento optional: $arg_posicional_opcional") println("argumento de clave: $arg_clave") end -# todos_los_args(1, 3, arg_clave=4) +todos_los_args(1, 3, arg_clave=4) # imprime: # argumento normal: 1 # argumento optional: 3 @@ -469,7 +468,7 @@ function crear_suma(x) y -> x + y end -# También se puede nombrar la función interna, si quieres +# También puedes nombrar la función interna, si quieres function crear_suma(x) function suma(y) x + y @@ -526,9 +525,7 @@ tigger = Tigre(3.5,"anaranjado") # => Tiger(3.5,"anaranjado") # El tipo funciona como la función constructora de valores de ese tipo sherekhan = typeof(tigger)(5.6,"fuego") # => Tiger(5.6,"fuego") -# These struct-style types are called concrete types -# They can be instantiated, but cannot have subtypes. -# The other kind of types is abstract types. + # Este estilo de tipos son llamados tipos concrete # Se pueden crear instancias, pero no pueden tener subtipos. # La otra clase de tipos es tipos abstractos (abstract types). @@ -574,8 +571,8 @@ type Pantera <: Gato # Pantera tambien es un a subtipo de Cat # Panteras sólo tendrán este constructor, y ningún constructor # predeterminado. end -# Utilizar constructores internos, como Panther hace, le da control sobre cómo -# se pueden crear valores del tipo. Cuando sea posible, debe utilizar +# Utilizar constructores internos, como Panther hace, te da control sobre cómo +# se pueden crear valores del tipo. Cuando sea posible, debes utilizar # constructores exteriores en lugar de los internos. #################################################### @@ -584,9 +581,9 @@ end # En Julia, todas las funciones nombradas son funciones genéricas. # Esto significa que se construyen a partir de muchos métodos pequeños -# Cada constructor de León es un método de la función genérica León. +# Cada constructor de Leon es un método de la función genérica Leon. -# Por ejemplo no constructor, vamos a hacer un maullar función: +# Por ejemplo, vamos a hacer un maullar función: # Definiciones para Leon, Pantera, y Tigre function maullar(animal::Leon) @@ -655,7 +652,7 @@ try catch end -# Permítanos dejar que el gato vaya primero +# Un metodo con el gato primero pelear(c::Gato,l::Leon) = println("El gato le gana al León") # Warning: New definition # pelear(Gato,Leon) at none:1 @@ -675,14 +672,14 @@ pelear(l::Leon,l2::Leon) = println("Los leones llegan a un empate") pelear(Leon("GR"),Leon("cafe","rar")) # => imprime Los leones llegan a un empate -# Bajo el capó +# Un vistazo al nivel bajo # Se puede echar un vistazo a la LLVM y el código ensamblador generado. area_cuadrada(l) = l * l # area_cuadrada (generic function with 1 method) -area_cuadrada(5) #25 +area_cuadrada(5) # => 25 -# ¿Qué sucede cuando damos square_area diferentes argumentos? +# ¿Qué sucede cuando damos area_cuadrada diferentes argumentos? code_native(area_cuadrada, (Int32,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none @@ -717,7 +714,8 @@ code_native(area_cuadrada, (Float64,)) # pop RBP # ret # -# Tenga en cuenta que Julia usará instrucciones de "floating point" si alguno de + +# Ten en cuenta que Julia usará instrucciones de "floating point" si alguno de # los argumentos son "floats" # Vamos a calcular el área de un círculo area_circulo(r) = pi * r * r # circle_area (generic function with 1 method) @@ -753,7 +751,7 @@ code_native(area_circulo, (Float64,)) # ``` -# # Lectura adicional +## ¿Listo para más? Puedes obtener muchos más detalles en [The Julia Manual](http://docs.julialang.org/en/latest/manual/) -- cgit v1.2.3 From 4e85becf286cafe347d3e36e6b2c5e4f31a56819 Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Fri, 21 Mar 2014 14:45:13 -0500 Subject: Change lang declaration back to ruby from julia --- es-es/julia-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 4b79674d..7303bb40 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -15,7 +15,7 @@ Python. Esto se basa en la versión de desarrollo actual de Julia, del 18 de octubre de 2013. -```julia +```ruby # Comentarios de una línea comienzan con una almohadilla (o signo gato) -- cgit v1.2.3 From 764f5967da3d0b8ca0c0af2183abc1a05c6973f6 Mon Sep 17 00:00:00 2001 From: Guillermo Garza Date: Wed, 2 Apr 2014 22:41:12 -0500 Subject: More fixes to Spanish Julia. --- es-es/julia-es.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 7303bb40..41a7c68b 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -158,7 +158,7 @@ b[end] # => 6 # separados por punto y coma. matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] -# Añadir cosas al final de una lista con push! y append! +# Añadir cosas a la final de una lista con push! y append! push!(a,1) # => [1] push!(a,2) # => [1,2] push!(a,4) # => [1,2,4] @@ -214,7 +214,7 @@ splice!(arr,2) # => 4 ; arr es ahora [3,5] b = [1,2,3] append!(a,b) # ahroa a es [1, 2, 3, 4, 5, 1, 2, 3] -# Comprobamos la existencia en una lista con in +# Comprueba la existencia en una lista con in in(1, a) # => true # Examina la longitud con length -- cgit v1.2.3 From b5e4d6dd01eefafa5b17db04c30ea2a479b1c63e Mon Sep 17 00:00:00 2001 From: Joram Schrijver Date: Thu, 3 Apr 2014 10:39:32 +0200 Subject: Fix invalid characters for Common Lisp symbols The characters [ ] { and } are perfectly fine to use in variable names. (defparameter b{l}a[b[l]]a "test") ; => B{L}A[B[L]]A b{l}a[b[l]]a ; => "test" --- common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index dda60797..c842afe5 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -140,7 +140,7 @@ nil ; for false - and the empty list ;; 2. Variables ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; You can create a global (dynamically scoped) using defparameter -;; a variable name can use any character except: ()[]{}",'`;#|\ +;; a variable name can use any character except: ()",'`;#|\ ;; Dynamically scoped variables should have earmuffs in their name! -- cgit v1.2.3 From 5c70a9fa19ef1005c31d0cd878bcef8a3e1d3ccd Mon Sep 17 00:00:00 2001 From: Joram Schrijver Date: Thu, 3 Apr 2014 10:45:19 +0200 Subject: Fix typo in Common Lisp introduction. --- common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index c842afe5..8de81549 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -8,7 +8,7 @@ contributors: ANSI Common Lisp is a general purpose, multi-paradigm programming language suited for a wide variety of industry applications. It is -frequently referred to a programmable programming language. +frequently referred to as a programmable programming language. The classic starting point is [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/) -- cgit v1.2.3 From 77f28824af30ae86c89a4785439c65bd5a623a8a Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 6 Apr 2014 19:46:58 -0700 Subject: Fix syntax highlight. Fixes #587 (Instead of using #588) --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 15ff2303..9baefe68 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -181,7 +181,7 @@ size(A) % ans = 3 3 A(1, :) =[] % Delete the first row of the matrix -A' % Hermitian transpose the matrix +ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) transpose(A) % Transpose the matrix, without taking complex conjugate -- cgit v1.2.3 From d2f6623cf67468d502fb4c243931687a879c5813 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 10 Apr 2014 23:48:34 +0000 Subject: Updated some headers --- zh-cn/csharp-cn.html.markdown | 3 ++- zh-cn/css-cn.html.markdown | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/zh-cn/csharp-cn.html.markdown b/zh-cn/csharp-cn.html.markdown index 618050a0..a3cda5b3 100644 --- a/zh-cn/csharp-cn.html.markdown +++ b/zh-cn/csharp-cn.html.markdown @@ -5,9 +5,10 @@ contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Melvyn Laïly", "http://x2a.yt"] - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] -translathors: +translators: - ["Jakukyo Friel", "http://weakish.github.io"] filename: LearnCSharp-cn.cs +lang: zh-cn --- diff --git a/zh-cn/css-cn.html.markdown b/zh-cn/css-cn.html.markdown index a188ee9b..dc6dcc4f 100644 --- a/zh-cn/css-cn.html.markdown +++ b/zh-cn/css-cn.html.markdown @@ -5,7 +5,8 @@ contributors: - ["Marco Scannadinari", "https://github.com/marcoms"] translators: - ["Jakukyo Friel", "https://weakish.github.io"] -filename: learncss.css +lang: zh-cn +filename: learncss-cn.css --- 早期的web没有样式,只是单纯的文本。通过CSS,可以实现网页样式和内容的分离。 -- cgit v1.2.3 From 777c333ff078a7095f9b7ac303829b249f499b21 Mon Sep 17 00:00:00 2001 From: Sam Dodrill Date: Mon, 14 Apr 2014 11:04:44 -0700 Subject: Remove references to hash and hashtag in favor of number symbol --- coffeescript.html.markdown | 2 +- elixir.html.markdown | 2 +- julia.html.markdown | 2 +- livescript.html.markdown | 2 +- perl.html.markdown | 2 +- python.html.markdown | 2 +- r.html.markdown | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index 82c6024c..4fdf5903 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -14,7 +14,7 @@ See also [the CoffeeScript website](http://coffeescript.org/), which has a compl ``` coffeescript # CoffeeScript is a hipster language. # It goes with the trends of many modern languages. -# So comments are like Ruby and Python, they use hashes. +# So comments are like Ruby and Python, they use number symbols. ### Block comments are like these, and they translate directly to '/ *'s and '* /'s diff --git a/elixir.html.markdown b/elixir.html.markdown index df586649..0892deb7 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -11,7 +11,7 @@ and many more features. ```elixir -# Single line comments start with a hashtag. +# Single line comments start with a number symbol. # There's no multi-line comment, # but you can stack multiple comments. diff --git a/julia.html.markdown b/julia.html.markdown index 665b4fd3..15b4be90 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -12,7 +12,7 @@ This is based on the current development version of Julia, as of October 18th, 2 ```ruby -# Single line comments start with a hash. +# Single line comments start with a number symbol. #= Multiline comments can be written by putting '#=' before the text and '=#' after the text. They can also be nested. diff --git a/livescript.html.markdown b/livescript.html.markdown index 5fd61f49..429b91cb 100644 --- a/livescript.html.markdown +++ b/livescript.html.markdown @@ -23,7 +23,7 @@ Feedback is always welcome, so feel free to reach me over at ```coffeescript -# Just like its CoffeeScript cousin, LiveScript uses hash symbols for +# Just like its CoffeeScript cousin, LiveScript uses number symbols for # single-line comments. /* diff --git a/perl.html.markdown b/perl.html.markdown index ad9155e4..da2e0cdf 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -12,7 +12,7 @@ Perl 5 is a highly capable, feature-rich programming language with over 25 years Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects. ```perl -# Single line comments start with a hash. +# Single line comments start with a number symbol. #### Perl variable types diff --git a/python.html.markdown b/python.html.markdown index ced01910..bbc1bd92 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -17,7 +17,7 @@ to Python 2.x. Look for another tour of Python 3 soon! ```python -# Single line comments start with a hash. +# Single line comments start with a number symbol. """ Multiline strings can be written using three "'s, and are often used diff --git a/r.html.markdown b/r.html.markdown index 9c17e8ca..ea94ae42 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -10,7 +10,7 @@ R is a statistical computing language. It has lots of libraries for uploading an ```python -# Comments start with hashtags. +# Comments start with number symbols. # You can't make a multi-line comment per se, # but you can stack multiple comments like so. -- cgit v1.2.3 From be55775d5a7b278048b08474e42aa9703bf3905b Mon Sep 17 00:00:00 2001 From: Arnaud Date: Tue, 15 Apr 2014 16:15:07 +0200 Subject: Escaped a quote --- fr-fr/python-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 9dbdafe1..58a036ba 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -75,7 +75,7 @@ not False #=> True # Les chaînes de caractères sont créées avec " ou ' "C'est une chaîne." -'C'est aussi une chaîne.' +'C\'est aussi une chaîne.' # On peut aussi les "additioner" ! "Hello " + "world!" #=> "Hello world!" -- cgit v1.2.3 From 07b229a425d9181810b947c5c9380f7a48fe64ba Mon Sep 17 00:00:00 2001 From: Qumeric Date: Wed, 16 Apr 2014 18:06:58 +0400 Subject: Fix Go tutorial, especially ru translation --- go.html.markdown | 16 ++--- ru-ru/go-ru.html.markdown | 170 +++++++++++++++++++++++++++------------------- 2 files changed, 107 insertions(+), 79 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index a66e8c4b..fa4c8d0b 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -171,10 +171,10 @@ func learnFlowControl() { } // Function literals are closures. xBig := func() bool { - return x > 100 // References x declared above switch statement. + return x > 10000 // References x declared above switch statement. } - fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x). - x /= m.Exp(9) // This makes x == e. + fmt.Println("xBig:", xBig()) // true (we last assigned e^10 to x). + x = 1.3e3 // This makes x == 1300 fmt.Println("xBig:", xBig()) // false now. // When you need it, you'll love it. @@ -185,13 +185,11 @@ love: learnInterfaces() // Good stuff coming up! } - - func learnDefer() (ok bool) { - // deferred statements are executed just before the function returns. + // Deferred statements are executed just before the function returns. defer fmt.Println("deferred statements execute in reverse (LIFO) order.") defer fmt.Println("\nThis line is being printed first because") - // defer is commonly used to close a file, so the function closing the file + // Defer is commonly used to close a file, so the function closing the file // stays close to the function opening the file return true } @@ -237,7 +235,7 @@ func learnVariadicParams(myStrings ...interface{}) { for _, param := range myStrings { fmt.Println("param:", param) } - + // Pass variadic value as a variadic parameter. fmt.Println("params:", fmt.Sprintln(myStrings...)) @@ -299,7 +297,7 @@ func learnConcurrency() { // At this point a value was taken from either c or cs. One of the two // goroutines started above has completed, the other will remain blocked. - learnWebProgramming() // Go does it. You want to do it too. + learnWebProgramming() // Go does it. You want to do it too. } // A single function from package http starts a web server. diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index e9892952..a4f9fd4a 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -3,8 +3,12 @@ language: Go filename: learngo-ru.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"] translators: - ["Artem Medeusheyev", "https://github.com/armed"] + - ["Valery Cherepanov", "https://github.com/qumeric"] lang: ru-ru --- @@ -31,8 +35,9 @@ package main // Import предназначен для указания зависимостей этого файла. import ( "fmt" // Пакет в стандартной библиотеке Go - "net/http" // Да, это web server! + "net/http" // Да, это веб-сервер! "strconv" // Конвертирование типов в строки и обратно + m "math" // Импортировать math под локальным именем m. ) // Объявление функции. Main это специальная функция, служащая точкой входа для @@ -40,7 +45,7 @@ import ( // скобки. func main() { // Println выводит строку в stdout. - // В данном случае фигурирует вызов функции из пакета fmt. + // Данная функция находится в пакете fmt. fmt.Println("Hello world!") // Вызов другой функции из текущего пакета. @@ -55,57 +60,57 @@ func beyondHello() { // Краткое определение := позволяет объявить перменную с автоматической // подстановкой типа из значения. y := 4 - sum, prod := learnMultiple(x, y) // функция возвращает два значения - fmt.Println("sum:", sum, "prod:", prod) // простой вывод + sum, prod := learnMultiple(x, y) // Функция возвращает два значения. + fmt.Println("sum:", sum, "prod:", prod) // Простой вывод. learnTypes() // < y minutes, learn more! } // Функция имеющая входные параметры и возврат нескольких значений. func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // возврат двух результатов + return x + y, x * y // Возврат двух значений. } // Некотрые встроенные типы и литералы. func learnTypes() { // Краткое определение переменной говорит само за себя. - s := "Learn Go!" // тип string + s := "Learn Go!" // Тип string. s2 := `"Чистый" строковой литерал -может содержать переносы строк` // тоже тип данных string +может содержать переносы строк` // Тоже тип данных string - // символ не из ASCII. Исходный код Go в кодировке UTF-8. - g := 'Σ' // тип rune, это алиас для типа uint32, содержит юникод символ + // Символ не из ASCII. Исходный код Go в кодировке UTF-8. + g := 'Σ' // тип rune, это алиас для типа uint32, содержит символ юникода. - f := 3.14195 // float64, 64-х битное число с плавающей точкой (IEEE-754) - c := 3 + 4i // complex128, внутри себя содержит два float64 + f := 3.14195 // float64, 64-х битное число с плавающей точкой (IEEE-754). + c := 3 + 4i // complex128, внутри себя содержит два float64. - // Синтаксис var с инициализациями - var u uint = 7 // беззнаковое, но размер зависит от реализации, как и у int + // Синтаксис var с инициализациями. + var u uint = 7 // Беззнаковое, но размер зависит от реализации, как и у int. var pi float32 = 22. / 7 // Синтаксис приведения типа с кратким определением - n := byte('\n') // byte алиас для uint8 + n := byte('\n') // byte – это алиас для uint8. - // Массивы (Array) имеют фиксированный размер на момент компиляции. - var a4 [4]int // массив из 4-х int, проинициализирован нулями - a3 := [...]int{3, 1, 5} // массив из 3-х int, ручная инициализация + // Массивы имеют фиксированный размер на момент компиляции. + var a4 [4]int // массив из 4-х int, инициализирован нулями. + a3 := [...]int{3, 1, 5} // массив из 3-х int, ручная инициализация. - // Slice имеют динамическую длину. И массивы и slice-ы имеют каждый свои - // преимущества, но slice-ы используются гораздо чаще. - s3 := []int{4, 5, 9} // по сравнению с a3 тут нет троеточия - s4 := make([]int, 4) // выделение памяти для slice из 4-х int (нули) - var d2 [][]float64 // только объявление, память не выделяется - bs := []byte("a slice") // конвертирование строки в slice байтов + // Слайсы (slices) имеют динамическую длину. И массивы, и слайсы имеют свои + // преимущества, но слайсы используются гораздо чаще. + s3 := []int{4, 5, 9} // Сравните с a3. Тут нет троеточия. + s4 := make([]int, 4) // Выделение памяти для слайса из 4-х int (нули). + var d2 [][]float64 // Только объявление, память не выделяется. + bs := []byte("a slice") // Синтаксис приведения типов. - p, q := learnMemory() // объявление p и q как указателей на int. + p, q := learnMemory() // Объявление p и q как указателей на int. fmt.Println(*p, *q) // * извлекает указатель. Печатает два int-а. - // Map как словарь или хеш теблица из других языков является ассоциативным - // массивом с динамически изменяемым размером. + // Map, также как и словарь или хеш из некоторых других языков, является + // ассоциативным массивом с динамически изменяемым размером. m := map[string]int{"three": 3, "four": 4} m["one"] = 1 - delete(m, "three") // встроенная функция, удаляет элемент из map-а. + delete(m, "three") // Встроенная функция, удаляет элемент из map-а. // Неиспользуемые переменные в Go являются ошибкой. // Нижнее подчеркивание позволяет игнорировать такие переменные. @@ -113,79 +118,91 @@ func learnTypes() { // Вывод считается использованием переменной. fmt.Println(s, c, a4, s3, d2, m) - learnFlowControl() // идем далее + learnFlowControl() // Идем дальше. } // У Go есть полноценный сборщик мусора. В нем есть указатели но нет арифметики -// указатеей. Вы можете допустить ошибку с указателем на nil, но не с его -// инкрементацией. +// указатеей. Вы можете допустить ошибку с указателем на nil, но не с +// инкрементацией указателя. func learnMemory() (p, q *int) { // Именованные возвращаемые значения p и q являются указателями на int. - p = new(int) // встроенная функция new выделяет память. + p = new(int) // Встроенная функция new выделяет память. // Выделенный int проинициализирован нулем, p больше не содержит nil. - s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов, - s[3] = 7 // назначение одному из них, - r := -2 // опредление еще одной локальной переменной, - return &s[3], &r // амперсанд обозначает получение адреса переменной. + s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов. + s[3] = 7 // Присвоить значение одному из них. + r := -2 // Опредление еще одну локальную переменную. + return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной. } -func expensiveComputation() int { - return 1e6 +func expensiveComputation() float64 { + return m.Exp(10) } func learnFlowControl() { - // If-ы всегда требуют наличине фигурных скобок, но круглые скобки - // необязательны. + // If-ы всегда требуют наличине фигурных скобок, но не круглых. if true { fmt.Println("told ya") } // Форматирование кода стандартизировано утилитой "go fmt". if false { - // все тлен + // Будущего нет. } else { - // жизнь прекрасна + // Жизнь прекрасна. } - // Использоване switch на замену нескольким if-else - x := 1 + // Используйте switch вместо нескольких if-else. + x := 42.0 switch x { case 0: case 1: - // case-ы в Go не проваливаются, т.е. break по умолчанию - case 2: - // не выполнится + case 42: + // Case-ы в Go не "проваливаются" (неявный break). + case 43: + // Не выполнится. } // For, как и if не требует круглых скобок - for x := 0; x < 3; x++ { // ++ это операция + // Переменные, объявленные в for и if являются локальными. + for x := 0; x < 3; x++ { // ++ – это операция. fmt.Println("итерация", x) } - // тут x == 1. + // Здесь x == 42. - // For это единственный цикл в Go, но у него несколько форм. - for { // бесконечный цикл - break // не такой уж и бесконечный - continue // не выполнится + // For – это единственный цикл в Go, но у него есть альтернативные формы. + for { // Бесконечный цикл. + break // Не такой уж и бесконечный. + continue // Не выполнится. } // Как и в for, := в if-е означает объявление и присвоение значения y, - // затем проверка y > x. + // проверка y > x происходит после. if y := expensiveComputation(); y > x { x = y } // Функции являются замыканиями. xBig := func() bool { - return x > 100 // ссылается на x, объявленый выше switch. + return x > 10000 // Ссылается на x, объявленый выше switch. } - fmt.Println("xBig:", xBig()) // true (т.к. мы присвоили x = 1e6) - x /= 1e5 // тут х == 10 - fmt.Println("xBig:", xBig()) // теперь false + fmt.Println("xBig:", xBig()) // true (т.к. мы присвоили x = e^10). + x = 1.3e3 // Тут х == 1300 + fmt.Println("xBig:", xBig()) // Теперь false. // Метки, куда же без них, их все любят. goto love love: + learnDefer() // Быстрый обзор важного ключевого слова. learnInterfaces() // О! Интерфейсы, идем далее. } -// Объявление Stringer как интерфейса с одним мметодом, String. +func learnDefer() (ok bool) { + // Отложенные(deferred) выражения выполняются сразу перед тем, как функция + // возвратит значение. + defer fmt.Println("deferred statements execute in reverse (LIFO) order.") + defer fmt.Println("\nThis line is being printed first because") + // defer широко используется для закрытия файлов, чтобы закрывающая файл + // функция находилась близко к открывающей. + return true +} + +// Объявление Stringer как интерфейса с одним методом, String. type Stringer interface { String() string } @@ -196,35 +213,48 @@ type pair struct { } // Объявление метода для типа pair. Теперь pair реализует интерфейс Stringer. -func (p pair) String() string { // p в данном случае называют receiver-ом - // Sprintf - еще одна функция из пакета fmt. +func (p pair) String() string { // p в данном случае называют receiver-ом. + // Sprintf – еще одна функция из пакета fmt. // Обращение к полям p через точку. return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { // Синтаксис с фигурными скобками это "литерал структуры". Он возвращает - // проинициализированную структуру, а оператор := присваивает ее в p. + // проинициализированную структуру, а оператор := присваивает её p. p := pair{3, 4} - fmt.Println(p.String()) // вызов метода String у p, типа pair. - var i Stringer // объявление i как типа с интерфейсом Stringer. - i = p // валидно, т.к. pair реализует Stringer. - // Вызов метода String у i, типа Stringer. Вывод такой же что и выше. + fmt.Println(p.String()) // Вызов метода String у p. + var i Stringer // Объявление i как типа с интерфейсом Stringer. + i = p // Валидно, т.к. pair реализует Stringer. + // Вызов метода String у i, типа Stringer. Вывод такой же, что и выше. fmt.Println(i.String()) // Функции в пакете fmt сами всегда вызывают метод String у объектов для // получения строкового представления о них. - fmt.Println(p) // Вывод такой же что и выше. Println вызывает метод String. - fmt.Println(i) // тоже самое + fmt.Println(p) // Вывод такой же, что и выше. Println вызывает метод String. + fmt.Println(i) // Вывод такой же, что и выше. + + learnVariadicParams("Учиться", "учиться", "и еще раз учиться!") +} + +// Функции могут иметь варьируемое количество параметров. +func learnVariadicParams(myStrings ...interface{}) { + // Вывести все параметры с помощью итерации. + for _, param := range myStrings { + fmt.Println("param:", param) + } + + // Передать все варьируемые параметры. + fmt.Println("params:", fmt.Sprintln(myStrings...)) learnErrorHandling() } func learnErrorHandling() { - // Идиома ", ok" служит для обозначения сработало что-то или нет. + // Идиома ", ok" служит для обозначения корректного срабатывания чего-либо. m := map[int]string{3: "three", 4: "four"} if x, ok := m[1]; !ok { // ok будет false, потому что 1 нет в map-е. - fmt.Println("тут никого") + fmt.Println("тут никого нет") } else { fmt.Print(x) // x содержал бы значение, если бы 1 был в map-е. } @@ -237,7 +267,7 @@ func learnErrorHandling() { learnConcurrency() } -// c это тип данных channel (канал), объект для конкуррентного взаимодействия. +// c – это тип данных channel (канал), объект для конкуррентного взаимодействия. func inc(i int, c chan int) { c <- i + 1 // когда channel слева, <- являтся оператором "отправки". } -- cgit v1.2.3 From 40e320a7546e8c53d174a6b052ff7cce952c9db6 Mon Sep 17 00:00:00 2001 From: Qumeric Date: Wed, 16 Apr 2014 18:13:30 +0400 Subject: Fix typos --- ru-ru/go-ru.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index a4f9fd4a..ffda01b7 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -122,7 +122,7 @@ func learnTypes() { } // У Go есть полноценный сборщик мусора. В нем есть указатели но нет арифметики -// указатеей. Вы можете допустить ошибку с указателем на nil, но не с +// указателей. Вы можете допустить ошибку с указателем на nil, но не с // инкрементацией указателя. func learnMemory() (p, q *int) { // Именованные возвращаемые значения p и q являются указателями на int. @@ -130,7 +130,7 @@ func learnMemory() (p, q *int) { // Выделенный int проинициализирован нулем, p больше не содержит nil. s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов. s[3] = 7 // Присвоить значение одному из них. - r := -2 // Опредление еще одну локальную переменную. + r := -2 // Определить еще одну локальную переменную. return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной. } @@ -223,10 +223,10 @@ func learnInterfaces() { // Синтаксис с фигурными скобками это "литерал структуры". Он возвращает // проинициализированную структуру, а оператор := присваивает её p. p := pair{3, 4} - fmt.Println(p.String()) // Вызов метода String у p. + fmt.Println(p.String()) // Вызов метода String у переменной p типа pair. var i Stringer // Объявление i как типа с интерфейсом Stringer. i = p // Валидно, т.к. pair реализует Stringer. - // Вызов метода String у i, типа Stringer. Вывод такой же, что и выше. + // Вызов метода String у i типа Stringer. Вывод такой же, что и выше. fmt.Println(i.String()) // Функции в пакете fmt сами всегда вызывают метод String у объектов для -- cgit v1.2.3 From ca6e9fefcc04a443725f51a214f92543650dbf3b Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Mon, 28 Apr 2014 17:20:58 +0800 Subject: elisp_CN: typo --- zh-cn/elisp-cn.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zh-cn/elisp-cn.html.markdown b/zh-cn/elisp-cn.html.markdown index d303c2e8..06f38d77 100644 --- a/zh-cn/elisp-cn.html.markdown +++ b/zh-cn/elisp-cn.html.markdown @@ -132,7 +132,7 @@ lang: zh-cn ;; `C-xC-e' 这时屏幕上会显示两个窗口,而光标此时位于*test* buffer内 ;; 用鼠标单击上面的buffer就会使光标移回。 -;; 或者你可以使用 `C-xo' 是的光标跳到另一个窗口中 +;; 或者你可以使用 `C-xo' 使得光标跳到另一个窗口中 ;; 你可以用 `progn'命令将s式结合起来: (progn @@ -219,7 +219,7 @@ lang: zh-cn ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; -;; 我们将一些名字存到列表中; +;; 我们将一些名字存到列表中: (setq list-of-names '("Sarah" "Chloe" "Mathilde")) ;; 用 `car'来取得第一个名字: -- cgit v1.2.3 From 4d626256605cf42ec45d064f7242d4c2146bdf96 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Tue, 29 Apr 2014 15:11:59 +0800 Subject: elixir-cn: fix typos & complete translation --- zh-cn/elixir-cn.html.markdown | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown index 50f0e350..7a1ca084 100644 --- a/zh-cn/elixir-cn.html.markdown +++ b/zh-cn/elixir-cn.html.markdown @@ -54,7 +54,7 @@ tail #=> [2,3] # # 这表示会用左边的模式(pattern)匹配右侧 # -# 这是上面的例子中访问列列表的头部和尾部的就是这样工作的。 +# 上面的例子中访问列表的头部和尾部就是这样工作的。 # 当左右两边不匹配时,会返回error, 在这个 # 例子中,元组大小不一样。 @@ -101,7 +101,7 @@ string. 5 * 2 #=> 10 10 / 2 #=> 5.0 -# 在 elixir 操作符 `/` 返回值总是浮点数。 +# 在 elixir 中,操作符 `/` 返回值总是浮点数。 # 做整数除法使用 `div` div(10, 2) #=> 5 @@ -138,8 +138,8 @@ nil && 20 #=> nil # 总的排序顺序定义如下: # number < atom < reference < functions < port < pid < tuple < list < bit string -# 引用Joe Armstrong :”实际的顺序并不重要, -# 但是,一个整体排序是否经明确界定是非常重要的“。 +# 引用Joe Armstrong :“实际的顺序并不重要, +# 但是,一个整体排序是否经明确界定是非常重要的。” ## --------------------------- ## -- 控制结构(Control Flow) @@ -224,8 +224,8 @@ square.(5) #=> 25 # 也支持接收多个子句和卫士(guards). -# Guards可以进行模式匹配 -# Guards只有`when` 关键字指明: +# Guards 可以进行模式匹配 +# Guards 使用 `when` 关键字指明: f = fn x, y when x > 0 -> x + y x, y -> x * y @@ -273,7 +273,8 @@ end PrivateMath.sum(1, 2) #=> 3 # PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) -# Function declarations also support guards and multiple clauses: + +# 函数定义同样支持 guards 和 多重子句: defmodule Geometry do def area({:rectangle, w, h}) do w * h @@ -348,7 +349,7 @@ end ## -- 并发(Concurrency) ## --------------------------- -# Elixir 依赖与actor并发模型。在Elixir编写并发程序的三要素: +# Elixir 依赖于 actor并发模型。在Elixir编写并发程序的三要素: # 创建进程,发送消息,接收消息 # 启动一个新的进程使用`spawn`函数,接收一个函数作为参数 -- cgit v1.2.3 From 913ab2bc2ed570eb4890feb979db9aa2ce21e7ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jostein=20Kj=C3=B8nigsen?= Date: Tue, 29 Apr 2014 22:10:55 +0200 Subject: Syntax errors. Regexp needs to be greedier. --- elisp.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/elisp.html.markdown b/elisp.html.markdown index d3910759..3208ffb8 100644 --- a/elisp.html.markdown +++ b/elisp.html.markdown @@ -280,10 +280,10 @@ filename: learn-emacs-lisp.el ;; should stop searching at some point in the buffer, and whether it ;; should silently fail when nothing is found: -;; (search-forward "Hello" nil t) does the trick: +;; (search-forward "Hello" nil 't) does the trick: ;; The `nil' argument says: the search is not bound to a position. -;; The `t' argument says: silently fail when nothing is found. +;; The `'t' argument says: silently fail when nothing is found. ;; We use this sexp in the function below, which doesn't throw an error: @@ -294,7 +294,7 @@ filename: learn-emacs-lisp.el (mapcar 'hello list-of-names) (goto-char (point-min)) ;; Replace "Hello" by "Bonjour" - (while (search-forward "Hello" nil t) + (while (search-forward "Hello" nil 't) (replace-match "Bonjour")) (other-window 1)) @@ -305,7 +305,7 @@ filename: learn-emacs-lisp.el (defun boldify-names () (switch-to-buffer-other-window "*test*") (goto-char (point-min)) - (while (re-search-forward "Bonjour \\(.+\\)!" nil t) + (while (re-search-forward "Bonjour \\([^!]+\\)!" nil 't) (add-text-properties (match-beginning 1) (match-end 1) (list 'face 'bold))) @@ -317,9 +317,9 @@ filename: learn-emacs-lisp.el ;; The regular expression is "Bonjour \\(.+\\)!" and it reads: ;; the string "Bonjour ", and -;; a group of | this is the \\( ... \\) construct -;; any character | this is the . -;; possibly repeated | this is the + +;; a group of | this is the \\( ... \\) construct +;; any character not ! | this is the [^!] +;; possibly repeated | this is the + ;; and the "!" string. ;; Ready? Test it! -- cgit v1.2.3 From 61309e0edfd9ee20a79f2119a31a66bf87b2ee72 Mon Sep 17 00:00:00 2001 From: Matt Lucas Date: Wed, 30 Apr 2014 20:00:53 -0400 Subject: Update css.html.markdown 'It's' reflected a grammatical mistake, I adjusted the sentence for a bit of clarity. --- css.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/css.html.markdown b/css.html.markdown index 76319340..9b424a1e 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -44,7 +44,7 @@ Given an element like this on the page:
*/ -/* you can target it by it's class name */ +/* you can target it by a class name */ .some-class { } /*or by both classes! */ -- cgit v1.2.3 From 4095671c9250aab8e15473bc73b5db2cdbc95229 Mon Sep 17 00:00:00 2001 From: Matt Lucas Date: Thu, 1 May 2014 13:02:04 -0400 Subject: Update css.html.markdown --- css.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index 9b424a1e..cdef50cc 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -44,16 +44,16 @@ Given an element like this on the page:
*/ -/* you can target it by a class name */ +/* you can target it by its name */ .some-class { } /*or by both classes! */ .some-class.class2 { } -/* or by it's tag name */ +/* or by its element name */ div { } -/* or it's id */ +/* or its id */ #someId { } /* or by the fact that it has an attribute! */ @@ -77,12 +77,12 @@ any spaaace between different parts because that makes it to have another meaning.*/ div.some-class[attr$='ue'] { } -/* you can also select an element based on how it's parent is.*/ +/* you can also select an element based on its parent.*/ /*an element which is direct child of an element (selected the same way) */ div.some-parent > .class-name {} -/* or any of it's parents in the tree */ +/* or any of its parents in the tree */ /* the following basically means any element that has class "class-name" and is child of a div with class name "some-parent" IN ANY DEPTH */ div.some-parent .class-name {} @@ -91,7 +91,7 @@ div.some-parent .class-name {} can you say what? */ div.some-parent.class-name {} -/* you also might choose to select an element based on it's direct +/* you also might choose to select an element based on its direct previous sibling */ .i-am-before + .this-element { } @@ -99,7 +99,7 @@ previous sibling */ .i-am-any-before ~ .this-element {} /* There are some pseudo classes that allows you to select an element -based on it's page behaviour (rather than page structure) */ +based on its page behaviour (rather than page structure) */ /* for example for when an element is hovered */ :hover {} -- cgit v1.2.3 From fce8598a749fe885157c9582fc437f57fa111f3d Mon Sep 17 00:00:00 2001 From: Juan David Pastas Date: Thu, 1 May 2014 13:53:01 -0500 Subject: Python: clearer add lists note. --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index bbc1bd92..210c9619 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -173,7 +173,7 @@ li[::-1] # => [3, 4, 2, 1] del li[2] # li is now [1, 2, 3] # You can add lists -li + other_li # => [1, 2, 3, 4, 5, 6] - Note: li and other_li is left alone +li + other_li # => [1, 2, 3, 4, 5, 6] - Note: values for li and for other_li are not modified. # Concatenate lists with "extend()" li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] -- cgit v1.2.3 From 55660ce3c7be442cbe83e98fd33edbf40210669b Mon Sep 17 00:00:00 2001 From: Louie Dinh Date: Sat, 3 May 2014 17:17:43 -0700 Subject: Add Python 3 tutorial --- python3.html.markdown | 578 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 578 insertions(+) create mode 100644 python3.html.markdown diff --git a/python3.html.markdown b/python3.html.markdown new file mode 100644 index 00000000..3a1bc1c3 --- /dev/null +++ b/python3.html.markdown @@ -0,0 +1,578 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] +filename: learnpython.py +--- + +Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular +languages in existence. I fell in love with Python for its syntactic clarity. It's basically +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 + +```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 + +# When you use a float, results are floats +3 * 2.0 # => 6.0 + +# Enforce precedence with parentheses +(1 + 3) * 2 # => 8 + + +# Boolean values are primitives +True +False + +# negate with not +not True # => False +not False # => 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" + + +# 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 +li + other_li # => [1, 2, 3, 4, 5, 6] - Note: values for li and for other_li are not modified. + +# 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. +list(filled_dict.keys()) # => ["three", "two", "one"] +# Note - Dictionary key ordering is not guaranteed. +# Your results might not match this exactly. + +# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable. +list(filled_dict.values()) # => [3, 2, 1] +# Note - Same as above regarding key ordering. + +# 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 + +# 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} + +# Add more items to a 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 % 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. + + +# Python's 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 + +i 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 %s and y is %s" % (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) + + +# 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 +[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 + 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}" % (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 +_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(_say): + @wraps(_say) + def wrapper(*args, **kwargs): + msg, say_please = _say(*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/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### 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 a4e05441673bddea21a336920f12d9c659d4900f Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sat, 3 May 2014 22:46:28 -0230 Subject: Update python->python3 so things don't get mixed up. --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 3a1bc1c3..54f425ed 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -1,8 +1,8 @@ --- -language: python +language: python3 contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] -filename: learnpython.py +filename: learnpython3.py --- Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular -- cgit v1.2.3 From c50d1f613f1407c244e2257169087c976901b6a4 Mon Sep 17 00:00:00 2001 From: Astynax84 Date: Tue, 6 May 2014 14:58:45 +0400 Subject: russian translation of haskell tutorial --- ru-ru/haskell-ru.html.markdown | 544 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 544 insertions(+) create mode 100644 ru-ru/haskell-ru.html.markdown diff --git a/ru-ru/haskell-ru.html.markdown b/ru-ru/haskell-ru.html.markdown new file mode 100644 index 00000000..1747c393 --- /dev/null +++ b/ru-ru/haskell-ru.html.markdown @@ -0,0 +1,544 @@ +--- +language: haskell +contributors: + - ["Adit Bhargava", "http://adit.io"] + - ["Aleksey Pirogov", "http://astynax.github.io"] +--- + +Haskell разрабатывался, как чистый функциональный язык программирования, применимый на практике. Язык известен благодаря своей системе типов, и "знаменит" благодаря монадам. Меня[^1] же Haskell заставляет возвращаться к себе снова и снова именно своей элегантностью и я[^1] получаю истинное удовольствие, программируя на Haskell. + +```haskell +-- Однострочные комментарии начинаются с двух дефисов +{- Многострочный комментарий +заключается в пару фигурных скобок с дефисами с внутренней стороны. +-} + +------------------------------------------------------- +-- 1. Примитивные типы и простейшие операции над ними +------------------------------------------------------- + +-- Числа объявляются просто +3 -- 3 + +-- Арифметика тоже выглядит вполне ожидаемо +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- Операция деления всегда возвращает действительное число +35 / 4 -- 8.75 + +-- Делим нацело так +35 `div` 4 -- 8 + +-- Булевы значения - тоже примитивные значения +True +False + +-- Булева алгебра +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- В примере выше `not`, это функция, принимающая один аргумент. +-- При вызове функции в Haskell список аргументов +-- не нужно заключать в скобки - аргументы просто +-- перечисляются через пробелы сразу после имени функции. +-- Т.о. типичный вызов выглядит так: +-- func arg1 arg2 arg3... +-- Ниже же будет показано, как определять свои функции. + +-- Строки и символы +"Это строка." +'ы' -- а это символ +'Нельзя заключать длинные строки в одинарные кавычки.' -- ошибка! + +-- Строки можно конкатенировать +"Привет" ++ ", Мир!" -- "Привет, Мир!" + +-- При этом строки - это просто списки символов! +"Я - строка!" !! 0 -- 'Я' + + +---------------------------------------------------- +-- Списки и Кортежи +---------------------------------------------------- + +-- Все элементы списка в Haskell +-- должны иметь один и тот же тип. + +-- Эти два списка - эквивалентны: +[1, 2, 3, 4, 5] +[1..5] + +-- Haskell позволяет определять даже бесконечные списки! +[1..] -- список всех натуральных чисел! + +-- Бесконечные списки возможно в Haskell потому, что он "ленив". +-- В Haskell все вычисления производятся тогда и только тогда, +-- когда их результат потребуется. +-- Эта стратегия так и называется - "lazy evaluation". +-- Скажем, если вам нужен тысячный элемент из +-- списка натуральных чисел (бесконечного) и вы напишете так: + +[1..] !! 999 -- 1000 + +-- То Haskell вычислит элементы этого списка от 1 до 1000... +-- ... и остановится, ведь последующие элементы пока не нужны. +-- Это значит, что остальные элементы нашего +-- "бесконечного" списка не будут вычисляться! По крайней мере, +-- пока не понадобятся и они. + +-- Списки можно объединять +[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 + +-- list comprehensions - "формулы" для описания списков +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- можно указать условие попадания элементов в список +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Списки могут даже состоять из других списков +[[1,2,3],[4,5,6]] !! 1 !! 2 -- 6 (вторая строка, третий столбец) + +-- Кортежи позволяют своим элементам иметь различные типы, +-- но при этом кортежи имеют фиксированную длину. +-- Кортеж: +("haskell", 1) + +-- Часто кортежи из двух элементов называются "парами". +-- Элементы пары можно получать так: +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Функции +---------------------------------------------------- +-- Простая функция, принимающая два аргумента +add a b = a + b + +-- Внимание! +-- Если вы используете ghci (интерактивный интерпретатор Haskell), +-- вам нужно использовать ключевое слово `let`, примерно так: +-- let add a b = a + b + +-- Вызовем нашу функцию +add 1 2 -- 3 + +-- Функцию можно поместить между первым и вторым аргументами, +-- если заключить её имя в обратные кавычки +1 `add` 2 -- 3 + +{- Вы можете также определять функции, имя которых +вообще не содержит букв! Таки функции и называются "операторами", +и, да, вы можете определять свои операторы! +Скажем, оператор целочисленного деления можно определить так -} +(//) a b = a `div` b +35 // 4 -- 8 +{- Здесь оператор заключен в скобки - как говорят, +поставлен в префиксную позицию. +В префиксной позиции оператор можно не только определять, +но и вызывать -} +(+) 1 2 -- 3 + +-- Охранные выражения (guards) порой удобны, +-- если наша функция ветвится +fib x + | x < 2 = x + | otherwise = fib (x - 1) + fib (x - 2) + +{- Сопоставление с образцом (pattern matching) +чем-то напоминает охранные выражения. +Здесь мы видим три определения функции fib. +При вызове функции по имени Haskell использует +первое определение, к образцу которого +"подойдет" набор аргументов -} +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Pattern matching для кортежей выглядит так +foo (x, y) = (x + 1, y + 2) + +{- Pattern matching для списков устроен чуть сложнее. +Пусть `x` - первый элемент списка, а `xs` - остальные элементы. +Тогда операции `head` и `tail` могут быть определены так -} +myHead (x:xs) = x +myTail (x:xs) = xs + +-- Функцию отображения мы можем написать так +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- При сопоставлении происходит привязка +-- элементов значения с именами в образце +fstPlusThird (a : _ : b : _) = a + b +fstPlusThird [1,2,3,4,5] -- 4 +-- Значения, для которых вместо имени указано `_`, +-- игнорируются. Это удобно, когда важен сам факт +-- совпадения образца +oneElem [_] = True +oneElem _ = False + +startsWith x (y:_) = x == y +startsWith _ _ = False + +startsWith 'H' "Hello!" -- True +startsWith 'H' "hello!" -- False + +{- Обратите внимание на тот факт, +что первый аргумент нашей функции `myMap` - тоже функция! +Функции, подобно `myMap`, принимающие другие функции +в качестве параметров, или, скажем, возвращающие функции +в качестве результата, называются +Функциями Высших Порядков (ФВП, High Order Functions, HOF) +-} + +-- Вместе с ФВП часто используются анонимные функции +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] +-- Такие функции описываются в виде +-- \arg1 arg1 .. -> expression + +-- Популярные в других языках ФВП присутствуют и в Haskell +map (\x -> x * 10) [1..5] -- [10, 20, 30, 40, 50] +filter (\x -> x > 2) [1..5] -- [3, 4, 5] + +{- Функция свертки +(она же `reduce` или `inject` в других языках) +в Haskell представлены функциями `foldr` и `foldl`. +Суть свертки можно представить так: + +foldl f x0 [x1,x2,x3] -> (f (f (f x0 x1) x2) x3) +foldr f x0 [x1,x2,x3] -> (f x1 (f x2 (f x3 x0))) + +Здесь x0 - начальное значения так называемого "аккумулятора" +-} +-- Эти два вызова дают одинаковый результат +foldr (\x acc -> acc + x) 0 [1..5] -- 15 +foldl (\acc x -> acc + x) 0 [1..5] -- 15 +-- Тут можно даже заменить анонимную функцию на оператор +foldr (+) 0 [1..5] -- 15 +foldl (+) 0 [1..5] -- 15 + +-- Зато здесь разница видна +foldr (\x acc -> (x + 10) : acc) [] [1..3] -- [11, 12, 13] +foldl (\acc x -> (x + 10) : acc) [] [1..3] -- [13, 12, 11] + +{- Часто в качестве начального значения +удобно брать крайнее значение списка (крайнее слева или справа). +Для этого есть пара функций - `foldr1` и `foldl1` -} +foldr1 (+) [1..5] -- 15 +foldl1 (+) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Больше о функциях +---------------------------------------------------- + +{- Каррирование (currying) +Если в Haskell при вызове функции передать не все аргументы, +Функция становится "каррированой" - результатом вызова станет +новая функция, которая при вызове и примет оставшиеся аргументы -} + +add a b = a + b +foo = add 10 -- теперь foo будет принимать число + -- и добавлять к нему 10 +foo 5 -- 15 + +-- Для операторов можно "опустить" любой из двух аргументов +-- Используя этот факт можно определить +-- функцию `foo` из кода выше несколько иначе +foo = (+10) +foo 5 -- 15 + +-- Поупражняемся +map (10-) [1..3] -- [9, 8, 7] +filter (<5) [1..10] -- [1, 2, 3, 4] + +{- Композиция функций +Функция (.) соединяет пару функций в цепочку. +К примеру, можно соединить функцию, добавляющую 10, +с функцией, умножающей на 5 -} +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +{- Управление приоритетом вычисления +В Haskell есть функция `$`, которая применяет +свой первый аргумент ко второму с наименьшим приоритетом +(обычное применение функций имеет наивысший приоритет) +Эта функция часто позволяет избежать использования +"лишних" скобок -} +head (tail (tail "abcd")) -- 'c' +head $ tail $ tail "abcd" -- 'c' +-- того же эффекта иногда можно достичь использованием композиции +(head . tail . tail) "abcd" -- 'c' +head . tail . tail $ "abcd" -- 'c' +{- Тут стоит сразу запомнить, что композиция функций +возвращает именно новую функцию, как в последнем примере. +Т.е. можно делать так -} +third = head . tail . tail +-- но не так +third = head $ tail $ tail -- (head (tail (tail))) - ошибка! + +---------------------------------------------------- +-- 5. Сигнатуры типов +---------------------------------------------------- + +{- Haskell обладает очень сильной системой типов. +И типизация в Haskell - строгая. Каждое выражение имеет тип, +который может быть описан сигнатурой. +Сигнатура записывается в форме +expression :: type signature +-} + +-- Типы примитивов +5 :: Integer +"hello" :: String +True :: Bool + +{- Функции тоже имеют тип +`not` принимает булево значение и возвращает булев результат +not :: Bool -> Bool + +Вот функция двух аргументов +add :: Integer -> Integer -> Integer + +Тут то мы и видим предпосылки к каррированию: тип +на самом деле выглядит так (скобки просто обычно опускаются) +add :: (Integer -> Integer) -> Integer +т.е. функция принимает аргумент, +и возвращает функцию от второго аргумента! -} + +-- Считается хорошим тоном указывать сигнатуру определений, +-- которые доступны другим разработчикам (публичны). Пример: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Управление потоком исполнения +---------------------------------------------------- + +-- Выражение `if` +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- Выражение `if` можно записать и в несколько строк. +-- Соблюдайте отступы! +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- Так как `if` - выражение, ветка `else` обязательна! +-- И более того, результаты выражений в ветках `then` и `else` +-- должны иметь одинаковый тип! + +-- `case`-выражение выглядит так +case args of -- парсим аргументы командной строки + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- При вычислении результата `case`-выражения производится +-- сопоставление с образцом: +fib x = case x of + 1 -> 1 + 2 -> 1 + _ -> fib (x - 1) + fib (x - 2) + +-- В Haskell нет циклов - вместо них используются рекурсия, +-- отображение, фильтрация и свертка (map/filter/fold) +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +for array func = map func array +for [0..3] $ \i -> show i -- ["0", "1", "2", "3"] +for [0..3] show -- ["0", "1", "2", "3"] + +---------------------------------------------------- +-- 7. Пользовательские типы данных +---------------------------------------------------- + +-- Создадим свой 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` +Just "hello" -- :: `Maybe String` +Just 1 -- :: `Maybe Int` +Nothing -- :: `Maybe a` для любого `a` + +-- Типы могут быть достаточно сложными +data Figure = Rectangle (Int, Int) Int Int + | Square (Int, Int) Int + | Point (Int, Int) + +area :: Figure -> Int +area (Point _) = 0 +area (Square _ s) = s * s +area (Rectangle _ w h) = w * h + +---------------------------------------------------- +-- 8. Ввод-вывод в Haskell +---------------------------------------------------- + +-- Полноценно объяснить тему ввода-вывода невозможно +-- без объяснения монад, но для использования в простых случаях +-- вводного описания будет достаточно. + +-- Когда программа на Haskell выполняется, +-- вызывается функция с именем `main`. +-- Эта функция должна вернуть значение типа `IO ()` +-- Например + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- `putStrLn` имеет тип `String -> IO ()` + +-- Проще всего реализовать программу с вводом-выводом (IO), +-- если вы реализуете функцию с типом `String -> String`. +-- Далее ФВП +-- interact :: (String -> String) -> IO () +-- сделает всё за нас! + +countLines :: String -> String +countLines = show . length . lines +-- здесь `lines` разделяет строку на список строк +-- по символу перевода строки + +main' :: IO () +main' = interact countLines + +{- Вы можете думать о типе `IO ()`, +как о некотором представлении последовательности +действий, которые должен совершить компьютер. +Такое представление напоминает программу +на императивном языке программирования. Для описания +такой последовательности используется `do`-нотация -} + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + name <- getLine -- запрашиваем строку и связываем с "name" + putStrLn $ "Hello, " ++ name + +-- Упражнение: +-- напишите свою реализацию функции `interact`, +-- которая запрашивает и обрабатывает только одну строку + +{- Код функции `sayHello` не будет исполняться +при её определении. Единственное место, где IO-действия +могут быть произведены - функция `main`! +Чтобы эта программа выполнила действия в функции `sayHello`, +закомментируйте предыдущее определение функции `main` +и добавьте новое определение: + +main = sayHello -} + +{- Давайте подробнее рассмотрим, как работает функция `getLine` +Её тип: + getLine :: IO String +Вы можете думать, что значение типа `IO a` представляет +собой компьютерную программу, в результате выполнения которой +генерируется значение типа `a`, в дополнение +к остальным эффектам, производимым при выполнении - таким как +печать текста на экран. Это значение типа `a` мы можем +сохранить с помощью оператора `<-`. Мы даже можем реализовать +свое действие, возвращающее значение: -} + +action :: IO String +action = do + putStrLn "This is a line. Duh" + input1 <- getLine + input2 <- getLine + -- Тип блока `do` будет соответствовать типу последнего + -- выполненного в блоке выражения. + -- Заметим, что `return` - не ключевое слово, а функция + -- типа `a -> IO a` + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- Теперь это действие можно использовать вместо `getLine`: + +main'' = do + putStrLn "I will echo two lines!" + result <- action + putStrLn result + putStrLn "This was all, folks!" + +{- Тип `IO` - пример "монады". Языку Haskell нужны монады, +чтобы оставаться преимущественно чистым функциональным языком. +Любые функции, взаимодействующие с внешним миром +(производящие ввод-вывод) имеют `IO` в своих сигнатурах. +Это позволяет судить о функции как о "чистой" - такая не будет +производить ввод-вывод. В ином случая функция - не "чистая". + +Такой подход позволяет очень просто разрабатывать многопоточные +программы - чистые функции, запущенные параллельно +не будут конфликтовать между собой в борьбе за ресурсы. -} + +---------------------------------------------------- +-- 9. Haskell REPL +---------------------------------------------------- + +{- Интерактивная консоль Haskell запускается командой `ghci`. +Теперь можно вводить строки кода на Haskell. +Связывание значений с именами производится +с помощью выражения `let`: -} + +let foo = 5 + +-- Тип значения или выражения можно узнать +-- с помощью команды `:t`: + +>:t foo +foo :: Integer + +-- Также можно выполнять действия с типом `IO ()` + +> sayHello +What is your name? +Friend! +Hello, Friend! + +``` + +Многое о Haskell, например классы типов и монады невозможно уместить в столь короткую статью. Огромное количество очень интересных идей лежит в основе языка, и именно благодаря этому фундаменту на языке так приятно писать код. Позволю себе привести ещё один маленький пример кода на Haskell - реализацию быстрой сортировки: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell прост в установке, забирайте [здесь](http://www.haskell.org/platform/) и пробуйте! Это же так интересно!. + +Более глубокое погрузиться в язык позволят прекрасные книги +[Learn you a Haskell](http://learnyouahaskell.com/) и +[Real World Haskell](http://book.realworldhaskell.org/). + +[^1]: имеется в виду автор оригинального текста - Adit Bhargava *(примечание переводчика)* -- cgit v1.2.3 From 88be5767a789adc42891da32aa1d7a8abd68404c Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Tue, 6 May 2014 21:24:11 +0800 Subject: elixir-cn: fix typos --- zh-cn/elixir-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown index 7a1ca084..daee8d3c 100644 --- a/zh-cn/elixir-cn.html.markdown +++ b/zh-cn/elixir-cn.html.markdown @@ -8,7 +8,7 @@ filename: learnelixir-cn.ex lang: zh-cn --- -Elixir 是一门构建在Elang VM 之上的函数式编程语言。Elixir 完全兼容 Eralng, +Elixir 是一门构建在Erlang VM 之上的函数式编程语言。Elixir 完全兼容 Erlang, 另外还提供了更标准的语法,特性。 ```elixir -- cgit v1.2.3 From 6f9c10e6db623a715035ade02c8b68a380dc1fe8 Mon Sep 17 00:00:00 2001 From: Aleksey Pirogov Date: Tue, 6 May 2014 20:48:13 +0400 Subject: language code and some markup fixes --- ru-ru/haskell-ru.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ru-ru/haskell-ru.html.markdown b/ru-ru/haskell-ru.html.markdown index 1747c393..85c2eb8e 100644 --- a/ru-ru/haskell-ru.html.markdown +++ b/ru-ru/haskell-ru.html.markdown @@ -2,10 +2,12 @@ language: haskell contributors: - ["Adit Bhargava", "http://adit.io"] +translators: - ["Aleksey Pirogov", "http://astynax.github.io"] +lang: ru-ru --- -Haskell разрабатывался, как чистый функциональный язык программирования, применимый на практике. Язык известен благодаря своей системе типов, и "знаменит" благодаря монадам. Меня[^1] же Haskell заставляет возвращаться к себе снова и снова именно своей элегантностью и я[^1] получаю истинное удовольствие, программируя на Haskell. +Haskell разрабатывался, как чистый функциональный язык программирования, применимый на практике. Язык известен благодаря своей системе типов, и "знаменит" благодаря монадам. [autor][Меня] же Haskell заставляет возвращаться к себе снова и снова именно своей элегантностью и [autor][я] получаю истинное удовольствие, программируя на Haskell. ```haskell -- Однострочные комментарии начинаются с двух дефисов @@ -541,4 +543,4 @@ Haskell прост в установке, забирайте [здесь](http:/ [Learn you a Haskell](http://learnyouahaskell.com/) и [Real World Haskell](http://book.realworldhaskell.org/). -[^1]: имеется в виду автор оригинального текста - Adit Bhargava *(примечание переводчика)* +[autor]: http://adit.io имеется в виду автор оригинального текста Adit Bhargava *(примечание переводчика)* -- cgit v1.2.3 From ee67fe2f3aa19d4540de348f4e35f690be87fea8 Mon Sep 17 00:00:00 2001 From: Aleksey Pirogov Date: Tue, 6 May 2014 20:51:09 +0400 Subject: links fixes --- ru-ru/haskell-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/haskell-ru.html.markdown b/ru-ru/haskell-ru.html.markdown index 85c2eb8e..03e66d05 100644 --- a/ru-ru/haskell-ru.html.markdown +++ b/ru-ru/haskell-ru.html.markdown @@ -7,7 +7,7 @@ translators: lang: ru-ru --- -Haskell разрабатывался, как чистый функциональный язык программирования, применимый на практике. Язык известен благодаря своей системе типов, и "знаменит" благодаря монадам. [autor][Меня] же Haskell заставляет возвращаться к себе снова и снова именно своей элегантностью и [autor][я] получаю истинное удовольствие, программируя на Haskell. +Haskell разрабатывался, как чистый функциональный язык программирования, применимый на практике. Язык известен благодаря своей системе типов, и "знаменит" благодаря монадам. [Меня][autor] же Haskell заставляет возвращаться к себе снова и снова именно своей элегантностью и [я][autor] получаю истинное удовольствие, программируя на Haskell. ```haskell -- Однострочные комментарии начинаются с двух дефисов -- cgit v1.2.3 From e8264c3fa95dd8bf457c7f4ebe0c1b20db0506b8 Mon Sep 17 00:00:00 2001 From: Adrian Bordinc Date: Wed, 7 May 2014 18:53:23 +0200 Subject: fixed typos, a little bit of formatting --- ro-ro/bash-ro.html.markdown | 42 ++++++++++++++++++++++++------------------ ro-ro/ruby-ro.html.markdown | 44 ++++++++++++++++++++++++++++---------------- 2 files changed, 52 insertions(+), 34 deletions(-) diff --git a/ro-ro/bash-ro.html.markdown b/ro-ro/bash-ro.html.markdown index fa91cca4..debeb67a 100644 --- a/ro-ro/bash-ro.html.markdown +++ b/ro-ro/bash-ro.html.markdown @@ -12,16 +12,18 @@ lang: ro-ro filename: LearnBash-ro.sh --- -Bash este numele shell-ului unix, care a fost de asemenea distribuit drept shell pentru pentru sistemul de operare GNU si ca shell implicit pentru Linux si Mac OS X. +Bash este numele shell-ului unix, care a fost de asemenea distribuit drept shell pentru sistemul de operare GNU si ca shell implicit pentru Linux si Mac OS X. Aproape toate exemplele de mai jos pot fi parte dintr-un script sau pot fi executate direct in linia de comanda. [Citeste mai multe:](http://www.gnu.org/software/bash/manual/bashref.html) ```bash #!/bin/bash -# Prima linie din script se numeste "shebang" care spune systemului cum sa execute scriptul +# Prima linie din script se numeste "shebang" +# care spune systemului cum sa execute scriptul # http://en.wikipedia.org/wiki/Shebang_(Unix) -# Dupa cum te-ai prins deja, comentariile incep cu #. Shebang este de asemenea un comentariu. +# Dupa cum te-ai prins deja, comentariile incep cu #. +# Shebang este de asemenea un comentariu. # Exemplu simplu de hello world: echo Hello world! @@ -41,7 +43,8 @@ VARIABLE = "Niste text" echo $VARIABLE echo "$VARIABLE" echo '$VARIABLE' -# Atunci cand folosesti variabila, o atribui, o exporti sau altfel, numele ei se scrie fara $. +# Atunci cand folosesti variabila, o atribui, o exporti sau altfel, +# numele ei se scrie fara $. # Daca vrei sa folosesti valoarea variabilei, atunci trebuie sa folosesti $. # Atentie la faptul ca ' (apostrof) nu va inlocui variabla cu valoarea ei. @@ -55,7 +58,8 @@ echo ${VARIABLE:0:7} # Valoarea implicita a unei variabile: echo ${FOO:-"ValoareaImplicitaDacaFOOLipsesteSauEGoala"} -# Asta functioneaza pentru null (FOO=), sir de caractere gol (FOO=""), zero (FOO=0) returneaza 0 +# Asta functioneaza pentru null (FOO=), +# sir de caractere gol (FOO=""), zero (FOO=0) returneaza 0 # Variabile pre-existente echo "Ulima valoare returnata de ultimul program rulat: $?" @@ -70,7 +74,8 @@ read NAME # Observa faptul ca nu a trebuit sa declaram o variabila noua echo Salut, $NAME! # Avem obisnuita instructiune "if" -# Foloseste "man test" pentru mai multe informatii despre instructinea conditionala +# Foloseste "man test" pentru mai multe informatii +# despre instructinea conditionala if [ $NAME -ne $USER ] then echo "Numele tau este username-ul tau" @@ -79,8 +84,8 @@ else fi # Este de asemenea si executarea conditionala de comenzi -echo "Intotdeauna executat" || echo "Executat numai daca prima instructiune esueaza" -echo "Intotdeauna executat" && echo "Executat numai daca prima instructiune NU esueaza" +echo "Intotdeauna executat" || echo "Executat daca prima instructiune esueaza" +echo "Intotdeauna executat" && echo "Executat daca prima instructiune NU esueaza" # Expresiile apar in urmatorul format echo $(( 10 + 5 )) @@ -93,9 +98,10 @@ ls # Aceste comenzi au optiuni care la controleaza executia ls -l # Listeaza fiecare fisier si director pe o linie separata -# Rezultatele comenzii precedente poate fi trimis urmatoarei comenzi drept argument -# Comanda grep filtreaza argumentele trimise cu sabloane. Astfel putem vedea fiserele -# .txt din directorul curent. +# Rezultatele comenzii anterioare pot fi +# trimise urmatoarei comenzi drept argument +# Comanda grep filtreaza argumentele trimise cu sabloane. +# Astfel putem vedea fiserele .txt din directorul curent. ls -l | grep "\.txt" # De asemenea poti redirectiona o comanda, input si error output @@ -106,17 +112,17 @@ python2 hello.py 2> "error.err" # Daca vrei sa fie concatenate poti folosi ">>" # Comenzile pot fi inlocuite in interiorul altor comenzi folosind $( ): -# Urmatoarea comanda afiseaza numarul de fisiere si directoare din directorul curent +# Urmatoarea comanda afiseaza numarul de fisiere +# si directoare din directorul curent echo "Sunt $(ls | wc -l) fisiere aici." -# The same can be done using backticks `` but they can't be nested - the preferred way -# is to use $( ). -# Acelasi lucru se poate obtine folosind apostrf-ul inversat ``, dar nu pot fi folosite -# unele in interiorul celorlalte asa ca modalitatea preferata este de a folosi $( ) +# Acelasi lucru se poate obtine folosind apostrf-ul inversat ``, +# dar nu pot fi folosite unele in interiorul celorlalte asa ca modalitatea +# preferata este de a folosi $( ) echo "Sunt `ls | wc -l` fisiere aici." -# Bash foloseste o instructiune 'case' care functioneaza in mod similar cu instructiunea -# switch din Java si C++ +# Bash foloseste o instructiune 'case' care functioneaza +# in mod similar cu instructiunea switch din Java si C++ case "$VARIABLE" in 0) echo "Este un zero.";; 1) echo "Este un unu.";; diff --git a/ro-ro/ruby-ro.html.markdown b/ro-ro/ruby-ro.html.markdown index 27c6c462..12672b68 100644 --- a/ro-ro/ruby-ro.html.markdown +++ b/ro-ro/ruby-ro.html.markdown @@ -78,9 +78,9 @@ false.class #=> FalseClass 'Sunt un sir de caractere'.class #=> String "Si eu sunt un sir de caractere".class #=> String -fi_inlocuit = "inlocui o valoare in string" +fi_inlocuit = "fi inlocuit" "Pot #{fi_inlocuit} atunci cand folosesc dublu apostrof" -#=> "Pot inlocui o valoare intr-un sir de caractere atunci cand folosesc dublu apostrof" +#=> "Pot fi inlocuit atunci cand folosesc dublu apostrof" # Printeaza @@ -106,7 +106,8 @@ adresa = '/nume/nu atat de bun/' # Simbolurile (sunt obiecte) # Simbolurile sunt constante imutabile, reutilizabile, reprezentate intern -# de o valoare numerica. Sunt deseori folosite in locul sirurilor de caractere pentru a da un nume reprezentativ unei valori +# de o valoare numerica. Sunt deseori folosite in locul sirurilor de caractere +# pentru a da un nume reprezentativ unei valori :exemplu_simbol.class #=> Symbol @@ -160,10 +161,12 @@ hash.keys #=> ['culoare', 'numar'] hash['culoare'] #=> 'verde' hash['numar'] #=> 5 -# Incercand sa accesezi un element dintr-un hash printr-o cheie care nu exista va returna "nil". +# Incercand sa accesezi un element dintr-un hash +# printr-o cheie care nu exista va returna "nil". hash['nimic_aici'] #=> nil -# Incepand cu Ruby 1.9, este o sintaxa speciala pentru atunci cand se folosesc simboluri drept chei: +# Incepand cu Ruby 1.9, este o sintaxa speciala +# pentru atunci cand se folosesc simboluri drept chei: hash_nou = { defcon: 3, actiune: true} @@ -195,10 +198,11 @@ end # TOTUSI, Nici una nu foloseste instructiunea for # In locul acesteia ar trebui sa folosesti metoda "each" si sa ii trimiti un block # Un bloc este o bucata de cod pe care o poti trimite unei metode precum "each". -# Este analog pentru "lambda", functii anonime, sau closures in alte limbaje de programare. +# Este analog pentru "lambda", functii anonime, +# sau closures in alte limbaje de programare. # -# The "each" method of a range runs the block once for each element of the range. -# Metoda "each" a unui interval, ruleaza block-ul o data pentru fiecare element din interval. +# Metoda "each" a unui interval, ruleaza block-ul o data +# pentru fiecare element din interval. # Block-ul primeste ca si parametru un index # Invocand metoda "each" cu un block, arata in urmatorul fel: @@ -256,7 +260,8 @@ def dublu(x) x * 2 end -# Functille (si toate block-urile) returneaza implicit valoarea ultimei instructiuni +# Functille (si toate block-urile) +# returneaza implicit valoarea ultimei instructiuni dublu(2) #=> 4 # Parantezele sunt optionale cand rezultatul nu este ambiguu @@ -312,7 +317,8 @@ class Om def initialize(nume, varsta=0) # Atribuie argumentul, variabilei "nume", care apartine doar unei instante @nume = nume - # Daca varsta nu este data, o sa ii atribuim valoarea implicita din lista de argumente (0, in cazul nostru) + # Daca varsta nu este data, o sa ii atribuim valoarea implicita + # din lista de argumente (0, in cazul nostru) @varsta = varsta end @@ -326,14 +332,17 @@ class Om @nume end - # Functionalitatea de mai sus poate fi obtinuta folosing metoda "attr_accessor" dupa cum urmeaza: + # Functionalitatea de mai sus poate fi obtinuta + # folosing metoda "attr_accessor" dupa cum urmeaza: attr_accessor :nume - # Metodele pentru a lua si a seta valoarea unei variabile pot fi de asemenea obtinute individial: + # Metodele pentru a lua si a seta valoarea unei variabile + # pot fi de asemenea obtinute individial: attr_reader :nume attr_writer :nume - # O metoda apartinand unei clase foloseste "self" pentru a se diferentia de metodele unei instante ale clasei respective + # O metoda apartinand unei clase foloseste "self" pentru a se diferentia + # de metodele unei instante ale clasei respective # Poate fi invocata doar pe clasa, si nu pe o instanta a acesteia def self.spune(msg) puts "#{msg}" @@ -380,8 +389,10 @@ defined? @@var #=> "class variable" Var = "Sunt o constanta" defined? Var #=> "constant" -# Clasele sunt de asemenea obiecte in ruby. Astfel incat clasele pot avea variabile care apartin unei instante -# O variabila care apartine unei clase poate fi accesata de toate instantele acesteia si de clasele care o extind +# Clasele sunt de asemenea obiecte in ruby. Astfel incat clasele +# pot avea variabile care apartin unei instante +# O variabila care apartine unei clase poate fi accesata de toate +# instantele acesteia si de clasele care o extind # clasa parinte class Om @@ -406,7 +417,8 @@ Muncitor.foo # 0 Om.foo = 2 # 2 Muncitor.foo # 2 -# Variabilele care apartin unei instante ale unei clase, nu sunt impartite de (copii acesteia) clasele care o extind +# Variabilele care apartin unei instante ale unei clase, +# nu sunt impartite de (copii acesteia) clasele care o extind class Om @bar = 0 -- cgit v1.2.3 From 163d97c162aaaa58ef8620e8c47584baba50ebe0 Mon Sep 17 00:00:00 2001 From: Jose Donizetti Date: Sun, 11 May 2014 16:33:08 -0400 Subject: [go/en] add range index explication, and new learn source --- go.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/go.html.markdown b/go.html.markdown index fa4c8d0b..bb6b04eb 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Christopher Bess", "https://github.com/cbess"] - ["Jesse Johnson", "https://github.com/holocronweaver"] - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] --- Go was created out of the need to get work done. It's not the latest trend @@ -232,6 +233,7 @@ func learnInterfaces() { // Functions can have variadic parameters. func learnVariadicParams(myStrings ...interface{}) { // Iterate each value of the variadic. + // The underbar here is ignoring the index argument of the array. for _, param := range myStrings { fmt.Println("param:", param) } @@ -329,3 +331,4 @@ demonstrates the best of readable and understandable Go, Go style, and Go idioms. Or you can click on a function name in [the documentation](http://golang.org/pkg/) and the source code comes up! +Another great resource to learn Go is [Go by example](https://gobyexample.com/). -- cgit v1.2.3 From 4f540a6f6e4bb5a520988fe8a8822c259dc3d495 Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 11 May 2014 20:56:22 -0230 Subject: Fix xml --- xml.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xml.html.markdown b/xml.html.markdown index 349d4763..c072e0c7 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -11,7 +11,7 @@ Unlike HTML, XML does not specifies how to display or to format data, just carry * XML Syntax -```XML +```xml @@ -72,7 +72,7 @@ regarding that document. With this tool, you can check the XML data outside the application logic. -```XML +```xml -- cgit v1.2.3 From 58a5885da076edeccba8a0bfcefc049cdf03f4af Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 11 May 2014 21:44:07 -0230 Subject: Fixed up line lengths, and removed syntax highlighting because it sucked. --- markdown.html.markdown | 68 +++++++++++++++++++++++++++++++++----------------- 1 file changed, 45 insertions(+), 23 deletions(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index 8820c555..606840d3 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -5,18 +5,25 @@ contributors: filename: markdown.md --- -Markdown was created by JohnGruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). +Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). Give me as much feedback as you want! / Feel free to fork and pull request! -```markdown - +``` + - + - + # This is an

## This is an

### This is an

@@ -30,7 +37,7 @@ This is an h1 This is an h2 ------------- - + @@ -44,11 +51,13 @@ __And so is this text.__ **_As is this!_** *__And this!__* - + ~~This text is rendered with strikethrough.~~ - + This is a paragraph. I'm tryping in a paragraph isn't this fun? @@ -58,7 +67,8 @@ I'm still in paragraph 2 too! I'm in paragraph three! - + I end with two spaces (highlight me to see them). @@ -67,7 +77,8 @@ There's a
above me! > This is a block quote. You can either -> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrapp on their own and it doesn't make a difference so long as they start with a `>`. +> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. +> It doesn't make a difference so long as they start with a `>`. > You can also use more than one level >> of indentation? @@ -98,7 +109,8 @@ or 2. Item two 3. Item three - + 1. Item one 1. Item two @@ -115,12 +127,14 @@ or 4. Item four - + This is code So is this - + my_array.each do |item| puts item @@ -138,10 +152,12 @@ def foobar end \`\`\` -<-- The above text doesn't require indenting, plus Github will use syntax highlighting of the language you specify after the ``` --> +<-- The above text doesn't require indenting, plus Github will use syntax +highlighting of the language you specify after the ``` --> - + *** --- @@ -149,8 +165,8 @@ end **************** - - + [Click me!](http://test.com/) @@ -164,12 +180,15 @@ end -[Click this link][link1] for more info about it! [Also check out this link][foobar] if you want to. +[Click this link][link1] for more info about it! +[Also check out this link][foobar] if you want to. [link1]: http://test.com/ "Cool!" [foobar]: http://foobar.biz/ "Alright!" - + @@ -193,7 +212,8 @@ end - is equivalent to [http://testwebsite.com/](http://testwebsite.com/) + is equivalent to +[http://testwebsite.com/](http://testwebsite.com/) @@ -201,17 +221,19 @@ end -I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. +I want to type *this text surrounded by asterisks* but I don't want it to be +in italics, so I do this: \*this text surrounded by asterisks\*. - + | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Left-aligned | Centered | Right-aligned | | blah | blah | blah | -or, for the same results + Col 1 | Col2 | Col3 :-- | :-: | --: -- cgit v1.2.3 From 204ff03ec99f8db5b3eef64ff9c264e3a81bafc3 Mon Sep 17 00:00:00 2001 From: Jose Donizetti Date: Mon, 12 May 2014 01:17:59 -0400 Subject: [go/pt-br] add new learn source --- pt-br/go-pt.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown index cca58b16..32c8fbdd 100644 --- a/pt-br/go-pt.html.markdown +++ b/pt-br/go-pt.html.markdown @@ -6,6 +6,7 @@ filename: learngo-pt.go lang: pt-br contributors: - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] translators: - ["Nuno Antunes", "https://github.com/ntns"] --- @@ -306,3 +307,6 @@ a melhor demonstração de código fácil de ler e de perceber, do estilo Go, e sua escrita idiomática. Ou então clique no nome de uma função na [documentação] (http://golang.org/pkg/) e veja o código fonte aparecer! +Outra ótima fonte para aprender Go é o [Go by example](https://gobyexample.com/). +Apesar de ser em inglês, é possível recodificar os exemplos para aprender sobre +a linguagem. -- cgit v1.2.3 From 351263a6f47df080e6a0a8e351084e950c9c88c7 Mon Sep 17 00:00:00 2001 From: Gabriel Ruiz Date: Mon, 12 May 2014 12:47:35 -0700 Subject: added additional resources to coffeescript file --- coffeescript.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index 4fdf5903..8fa2e81f 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -95,3 +95,9 @@ eat food for food in foods when food isnt 'chocolate' # } #} ``` + +## Additional resources + +- [The Little Book on CoffeeScript](http://arcturo.github.io/library/coffeescript/) +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto) -- cgit v1.2.3 From 14807c0eb73cd6bdd9ff291823d869fc337062e9 Mon Sep 17 00:00:00 2001 From: Gabriel Ruiz Date: Mon, 12 May 2014 14:12:39 -0700 Subject: removed little book on coffeescript --- coffeescript.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index 8fa2e81f..d96eed39 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -98,6 +98,5 @@ eat food for food in foods when food isnt 'chocolate' ## Additional resources -- [The Little Book on CoffeeScript](http://arcturo.github.io/library/coffeescript/) - [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) -- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) -- cgit v1.2.3 From 7487e48d0357b7b383ae999d1b01e426dd6d6959 Mon Sep 17 00:00:00 2001 From: hirohope Date: Sun, 18 May 2014 22:58:35 -0400 Subject: typo fixes and version in docs --- es-es/python-es.html.markdown | 4 ++-- python3.html.markdown | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown index f92f5cde..f7a0ec02 100644 --- a/es-es/python-es.html.markdown +++ b/es-es/python-es.html.markdown @@ -130,7 +130,7 @@ otra_variable # Levanta un error de nombre # 'if' puede ser usado como una expresión "yahoo!" if 3 > 2 else 2 #=> "yahoo!" -# Listas sobre secuencias +# Listas almacenan secuencias lista = [] # Puedes empezar con una lista prellenada otra_lista = [4, 5, 6] @@ -254,7 +254,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} # Haz diferencia de conjuntos con - {1,2,3,4} - {2,3,5} #=> {1, 4} -# CHequea la existencia en un conjunto con 'in' +# Chequea la existencia en un conjunto con 'in' 2 in conjunto_lleno #=> True 10 in conjunto_lleno #=> False diff --git a/python3.html.markdown b/python3.html.markdown index 54f425ed..77811535 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -318,7 +318,7 @@ except IndexError as e: # Python's offers a fundamental abstraction called the Iterable. -# An iterable is an object that can be treated as a sequence. +# 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} @@ -336,7 +336,7 @@ our_iterable[1] # Raises a TypeError 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. +# We get the next object by calling the __next__ function. our_iterator.__next__() #=> "one" # It maintains state as we call __next__. @@ -357,7 +357,7 @@ list(filled_dict.keys()) #=> Returns ["one", "two", "three"] # Use "def" to create new functions def add(x, y): - print("x is %s and y is %s" % (x, y)) + print("x is {} and y is {}".format(x, y)) return x + y # Return values with a return statement # Calling functions with parameters @@ -565,9 +565,9 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [Dive Into Python](http://www.diveintopython.net/) * [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/2.6/) +* [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) +* [Python Module of the Week](http://pymotw.com/3/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) ### Dead Tree -- cgit v1.2.3 From 6b915b73938dd5db5922173239f9bfd08ab76709 Mon Sep 17 00:00:00 2001 From: hirohope Date: Sun, 18 May 2014 22:59:05 -0400 Subject: added python3 in spanish --- es-es/python3-es.html.markdown | 570 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 570 insertions(+) create mode 100644 es-es/python3-es.html.markdown diff --git a/es-es/python3-es.html.markdown b/es-es/python3-es.html.markdown new file mode 100644 index 00000000..71c38670 --- /dev/null +++ b/es-es/python3-es.html.markdown @@ -0,0 +1,570 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] +translators: + - ["Camilo Garrido", "http://twitter.com/hirohope"] +lang: es-es +filename: learnpython3.py +--- + +Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno +de los lenguajes más populares en existencia. Me enamoré de Python por su claridad sintáctica. +Es básicamente pseudocódigo ejecutable. + +¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google] + +Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser aplicable a Python 2.x. ¡Pronto un recorrido por Python 3! + +```python + +# Comentarios de una línea comienzan con una almohadilla (o signo gato) + +""" Strings multilinea pueden escribirse + usando tres "'s, y comunmente son usados + como comentarios. +""" + +#################################################### +## 1. Tipos de datos primitivos y operadores. +#################################################### + +# Tienes números +3 #=> 3 + +# Matemática es lo que esperarías +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 + +# Excepto la división la cual por defecto retorna un número 'float' (número de coma flotante) +35 / 5 # => 7.0 + +# Cuando usas un float, los resultados son floats +3 * 2.0 # => 6.0 + +# Refuerza la precedencia con paréntesis +(1 + 3) * 2 # => 8 + + +# Valores 'boolean' (booleanos) son primitivos +True +False + +# Niega con 'not' +not True # => False +not False # => True + + +# Igualdad es == +1 == 1 # => True +2 == 1 # => False + +# Desigualdad es != +1 != 1 # => False +2 != 1 # => True + +# Más comparaciones +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# ¡Las comparaciones pueden ser concatenadas! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Strings se crean con " o ' +"Esto es un string." +'Esto también es un string' + +# ¡Strings también pueden ser sumados! +"Hola " + "mundo!" #=> "Hola mundo!" + +# Un string puede ser tratado como una lista de caracteres +"Esto es un string"[0] #=> 'E' + +# .format puede ser usaro para darle formato a los strings, así: +"{} pueden ser {}".format("strings", "interpolados") + +# Puedes repetir los argumentos de formateo para ahorrar tipeos. +"{0} sé ligero, {0} sé rápido, {0} brinca sobre la {1}".format("Jack", "vela") #=> "Jack sé ligero, Jack sé rápido, Jack brinca sobre la vela" +# Puedes usar palabras claves si no quieres contar. +"{nombre} quiere comer {comida}".format(nombre="Bob", food="lasaña") #=> "Bob quiere comer lasaña" + + +# None es un objeto +None # => None + +# No uses el símbolo de igualdad `==` para comparar objetos con None +# Usa `is` en lugar de +"etc" is None #=> False +None is None #=> True + +# None, 0, y strings/listas/diccionarios vacíos(as) todos se evalúan como False. +# Todos los otros valores son True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variables y Colecciones +#################################################### + +# Python tiene una función para imprimir +print("Soy Python. Encantado de conocerte") + +# No hay necesidad de declarar las variables antes de asignarlas. +una_variable = 5 # La convención es usar guiones_bajos_con_minúsculas +una_variable #=> 5 + +# Acceder a variables no asignadas previamente es una excepción. +# Ve Control de Flujo para aprender más sobre el manejo de excepciones. +otra_variable # Levanta un error de nombre + +# Listas almacena secuencias +lista = [] +# Puedes empezar con una lista prellenada +otra_lista = [4, 5, 6] + +# Añadir cosas al final de una lista con 'append' +lista.append(1) #lista ahora es [1] +lista.append(2) #lista ahora es [1, 2] +lista.append(4) #lista ahora es [1, 2, 4] +lista.append(3) #lista ahora es [1, 2, 4, 3] +# Remueve del final de la lista con 'pop' +lista.pop() #=> 3 y lista ahora es [1, 2, 4] +# Pongámoslo de vuelta +lista.append(3) # Nuevamente lista ahora es [1, 2, 4, 3]. + +# Accede a una lista como lo harías con cualquier arreglo +lista[0] #=> 1 +# Mira el último elemento +lista[-1] #=> 3 + +# Mirar fuera de los límites es un error 'IndexError' +lista[4] # Levanta la excepción IndexError + +# Puedes mirar por rango con la sintáxis de trozo. +# (Es un rango cerrado/abierto para ustedes los matemáticos.) +lista[1:3] #=> [2, 4] +# Omite el inicio +lista[2:] #=> [4, 3] +# Omite el final +lista[:3] #=> [1, 2, 4] +# Selecciona cada dos elementos +lista[::2] # =>[1, 4] +# Invierte la lista +lista[::-1] # => [3, 4, 2, 1] +# Usa cualquier combinación de estos para crear trozos avanzados +# lista[inicio:final:pasos] + +# Remueve elementos arbitrarios de una lista con 'del' +del lista[2] # lista ahora es [1, 2, 3] + +# Puedes sumar listas +lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan + +# Concatenar listas con 'extend' +lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] + +# Chequea la existencia en una lista con 'in' +1 in lista #=> True + +# Examina el largo de una lista con 'len' +len(lista) #=> 6 + + +# Tuplas son como listas pero son inmutables. +tupla = (1, 2, 3) +tupla[0] #=> 1 +tupla[0] = 3 # Levanta un error TypeError + +# También puedes hacer todas esas cosas que haces con listas +len(tupla) #=> 3 +tupla + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tupla[:2] #=> (1, 2) +2 in tupla #=> True + +# Puedes desempacar tuplas (o listas) en variables +a, b, c = (1, 2, 3) # a ahora es 1, b ahora es 2 y c ahora es 3 +# Tuplas son creadas por defecto si omites los paréntesis +d, e, f = 4, 5, 6 +# Ahora mira que fácil es intercambiar dos valores +e, d = d, e # d ahora es 5 y e ahora es 4 + + +# Diccionarios almacenan mapeos +dicc_vacio = {} +# Aquí está un diccionario prellenado +dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} + +# Busca valores con [] +dicc_lleno["uno"] #=> 1 + +# Obtén todas las llaves como una lista con 'keys()'. Necesitamos envolver la llamada en 'list()' porque obtenemos un iterable. Hablaremos de eso luego. +list(dicc_lleno.keys()) #=> ["tres", "dos", "uno"] +# Nota - El orden de las llaves del diccionario no está garantizada. +# Tus resultados podrían no ser los mismos del ejemplo. + +# Obtén todos los valores como una lista. Nuevamente necesitamos envolverlas en una lista para sacarlas del iterable. +list(dicc_lleno.values()) #=> [3, 2, 1] +# Nota - Lo mismo que con las llaves, no se garantiza el orden. + +# Chequea la existencia de una llave en el diccionario con 'in' +"uno" in dicc_lleno #=> True +1 in dicc_lleno #=> False + +# Buscar una llave inexistente deriva en KeyError +dicc_lleno["cuatro"] # KeyError + +# Usa el método 'get' para evitar la excepción KeyError +dicc_lleno.get("uno") #=> 1 +dicc_lleno.get("cuatro") #=> None +# El método 'get' soporta un argumento por defecto cuando el valor no existe. +dicc_lleno.get("uno", 4) #=> 1 +dicc_lleno.get("cuatro", 4) #=> 4 + +# El método 'setdefault' inserta en un diccionario solo si la llave no está presente +dicc_lleno.setdefault("cinco", 5) #dicc_lleno["cinco"] es puesto con valor 5 +dicc_lleno.setdefault("cinco", 6) #dicc_lleno["cinco"] todavía es 5 + + +# Remueve llaves de un diccionario con 'del' +del dicc_lleno['uno'] # Remueve la llave 'uno' de dicc_lleno + +# Sets (conjuntos) almacenan ... bueno, conjuntos +conjunto_vacio = set() +# Inicializar un conjunto con montón de valores. Yeah, se ve un poco como un diccionario. Lo siento. +un_conjunto = {1,2,2,3,4} # un_conjunto ahora es {1, 2, 3, 4} + +# Añade más valores a un conjunto +conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5} + +# Haz intersección de conjuntos con & +otro_conjunto = {3, 4, 5, 6} +conjunto_lleno & otro_conjunto #=> {3, 4, 5} + +# Haz unión de conjuntos con | +conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} + +# Haz diferencia de conjuntos con - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Chequea la existencia en un conjunto con 'in' +2 in conjunto_lleno #=> True +10 in conjunto_lleno #=> False + + +#################################################### +## 3. Control de Flujo +#################################################### + +# Let's just make a variable +some_var = 5 + +# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! +# imprime "una_variable es menor que 10" +if una_variable > 10: + print("una_variable es completamente mas grande que 10.") +elif una_variable < 10: # Este condición 'elif' es opcional. + print("una_variable es mas chica que 10.") +else: # Esto también es opcional. + print("una_variable es de hecho 10.") + +""" +For itera sobre listas +imprime: + perro es un mamifero + gato es un mamifero + raton es un mamifero +""" +for animal in ["perro", "gato", "raton"]: + # Puedes usar % para interpolar strings formateados + print("{} es un mamifero".format(animal)) + +""" +`range(número)` retorna una lista de números +desde cero hasta el número dado +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +While itera hasta que una condición no se cumple. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # versión corta de x = x + 1 + +# Maneja excepciones con un bloque try/except +try: + # Usa raise para levantar un error + raise IndexError("Este es un error de indice") +except IndexError as e: + pass # Pass no hace nada. Usualmente harias alguna recuperacion aqui. + +# Python oferce una abstracción fundamental llamada Iterable. +# Un iterable es un objeto que puede ser tratado como una sequencia. +# El objeto es retornado por la función 'range' es un iterable. + +dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} +nuestro_iterable = dicc_lleno.keys() +print(nuestro_iterable) #=> range(1,10). Este es un objeto que implementa nuestra interfaz Iterable + +Podemos recorrerla. +for i in nuestro_iterable: + print(i) # Imprime uno, dos, tres + +# Aunque no podemos selecionar un elemento por su índice. +nuestro_iterable[1] # Genera un TypeError + +# Un iterable es un objeto que sabe como crear un iterador. +nuestro_iterator = iter(nuestro_iterable) + +# Nuestro iterador es un objeto que puede recordar el estado mientras lo recorremos. +# Obtenemos el siguiente objeto llamando la función __next__. +nuestro_iterator.__next__() #=> "uno" + +# Mantiene el estado mientras llamamos __next__. +nuestro_iterator.__next__() #=> "dos" +nuestro_iterator.__next__() #=> "tres" + +# Después que el iterador ha retornado todos sus datos, da una excepción StopIterator. +nuestro_iterator.__next__() # Genera StopIteration + +# Puedes obtener todos los elementos de un iterador llamando a list() en el. +list(dicc_lleno.keys()) #=> Retorna ["uno", "dos", "tres"] + + + +#################################################### +## 4. Funciones +#################################################### + +# Usa 'def' para crear nuevas funciones +def add(x, y): + print("x es {} y y es {}".format(x, y)) + return x + y # Retorna valores con una la declaración return + +# Llamando funciones con parámetros +add(5, 6) #=> imprime "x es 5 y y es 6" y retorna 11 + +# Otra forma de llamar funciones es con argumentos de palabras claves +add(y=6, x=5) # Argumentos de palabra clave pueden ir en cualquier orden. + + +# Puedes definir funciones que tomen un número variable de argumentos +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Puedes definir funciones que toman un número variable de argumentos +# de palabras claves +def keyword_args(**kwargs): + return kwargs + +# Llamémosla para ver que sucede +keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"} + + +# You can do both at once, if you like# Puedes hacer ambas a la vez si quieres +def todos_los_argumentos(*args, **kwargs): + print args + print kwargs +""" +todos_los_argumentos(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# ¡Cuando llames funciones, puedes hacer lo opuesto a varargs/kwargs! +# Usa * para expandir tuplas y usa ** para expandir argumentos de palabras claves. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +todos_los_argumentos(*args) # es equivalente a foo(1, 2, 3, 4) +todos_los_argumentos(**kwargs) # es equivalente a foo(a=3, b=4) +todos_los_argumentos(*args, **kwargs) # es equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Python tiene funciones de primera clase +def crear_suma(x): + def suma(y): + return x + y + return suma + +sumar_10 = crear_suma(10) +sumar_10(3) #=> 13 + +# También hay funciones anónimas +(lambda x: x > 2)(3) #=> True + +# Hay funciones integradas de orden superior +map(sumar_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Podemos usar listas por comprensión para mapeos y filtros agradables +[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 +#################################################### + + +# Heredamos de object para obtener una clase. +class Humano(object): + + # Un atributo de clase es compartido por todas las instancias de esta clase + especie = "H. sapiens" + + # Constructor basico + def __init__(self, nombre): + # Asigna el argumento al atributo nombre de la instancia + self.nombre = nombre + + # Un metodo de instancia. Todos los metodos toman self como primer argumento + def decir(self, msg): + return "%s: %s" % (self.nombre, msg) + + # Un metodo de clase es compartido a través de todas las instancias + # Son llamados con la clase como primer argumento + @classmethod + def get_especie(cls): + return cls.especie + + # Un metodo estatico es llamado sin la clase o instancia como referencia + @staticmethod + def roncar(): + return "*roncar*" + + +# Instancia una clase +i = Humano(nombre="Ian") +print i.decir("hi") # imprime "Ian: hi" + +j = Humano("Joel") +print j.decir("hello") #imprime "Joel: hello" + +# Llama nuestro método de clase +i.get_especie() #=> "H. sapiens" + +# Cambia los atributos compartidos +Humano.especie = "H. neanderthalensis" +i.get_especie() #=> "H. neanderthalensis" +j.get_especie() #=> "H. neanderthalensis" + +# Llama al método estático +Humano.roncar() #=> "*roncar*" + + +#################################################### +## 6. Módulos +#################################################### + +# Puedes importar módulos +import math +print(math.sqrt(16)) #=> 4 + +# Puedes obtener funciones específicas desde un módulo +from math import ceil, floor +print(ceil(3.7)) #=> 4.0 +print(floor(3.7))#=> 3.0 + +# Puedes importar todas las funciones de un módulo +# Precaución: Esto no es recomendable +from math import * + +# Puedes acortar los nombres de los módulos +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Los módulos de Python son sólo archivos ordinarios de Python. +# Puedes escribir tus propios módulos e importarlos. El nombre del módulo +# es el mismo del nombre del archivo. + +# Puedes encontrar que funciones y atributos definen un módulo. +import math +dir(math) + + +#################################################### +## 7. Avanzado +#################################################### + +# Los generadores te ayudan a hacer un código perezoso (lazy) +def duplicar_numeros(iterable): + for i in iterable: + yield i + i + +# Un generador cera valores sobre la marcha. +# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración. +# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'. +# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse. +_rango = range(1, 900000000) +# Duplicará todos los números hasta que un resultado >= se encuentre. +for i in duplicar_numeros(_rango): + print(i) + if i >= 30: + break + + +# Decoradores +# en este ejemplo 'pedir' envuelve a 'decir' +# Pedir llamará a 'decir'. Si decir_por_favor es True entonces cambiará el mensaje a retornar +from functools import wraps + + +def pedir(_decir): + @wraps(_decir) + def wrapper(*args, **kwargs): + mensaje, decir_por_favor = _decir(*args, **kwargs) + if decir_por_favor: + return "{} {}".format(mensaje, "¡Por favor! Soy pobre :(") + return mensaje + + return wrapper + + +@pedir +def say(decir_por_favor=False): + mensaje = "¿Puedes comprarme una cerveza?" + return mensaje, decir_por_favor + + +print(decir()) # ¿Puedes comprarme una cerveza? +print(decir(decir_por_favor=True)) # ¿Puedes comprarme una cerveza? ¡Por favor! Soy pobre :() +``` + +## ¿Listo para más? + +### Gratis y en línea + +* [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/) +* [Python Module of the Week](http://pymotw.com/3/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Encuadernados + +* [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 93dc62e0a32c3915f4242248dcb698b72083dd41 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Mon, 19 May 2014 15:31:09 +0800 Subject: erlang: add content about concurrency --- erlang.html.markdown | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/erlang.html.markdown b/erlang.html.markdown index 065219ba..64b62f05 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -241,6 +241,45 @@ catcher(N) -> % exception, it is converted into a tuple that describes the error. catcher(N) -> catch generate_exception(N). +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 4. Concurrency +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Erlang relies on the actor model for concurrency. All we need to write +% concurrent programs in erlang are three primitives: spawning processes, +% sending messages and receiving messages. + +% To start a new process we use the `spawn` function, which takes a function +% as argument. + +F = fun() -> 2 + 2 end. % #Fun +spawn(F). % <0.44.0> + +% `spawn` returns a pid (process identifier), you can use this pid to send +% messages to the process. To do message passing we use the `!` operator. +% For all of this to be useful we need to be able to receive messages. This is +% achieved with the `receive` mechanism: + +-module(caculateGeometry). +-compile(export_all). +caculateAera() -> + receive + {rectangle, W, H} -> + W * H; + {circle, R} -> + 3.14 * R * R; + _ -> + io:format("We can only caculate area of rectangles or circles.") + end. + +% Compile the module and create a process that evaluates `caculateAera` in the shell +c(caculateGeometry). +CaculateAera = spawn(caculateGeometry, caculateAera, []). +CaculateAera ! {circle, 2}. % 12.56000000000000049738 + +% The shell is also a process, you can use `self` to get the current pid +self(). % <0.41.0> + ``` ## References -- cgit v1.2.3 From 8c64a457a917d22544d1ce27a99d9cfe952e628c Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Mon, 19 May 2014 16:40:03 +0800 Subject: erlang: Chinese translation --- zh-cn/erlang-cn.html.markdown | 261 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 zh-cn/erlang-cn.html.markdown diff --git a/zh-cn/erlang-cn.html.markdown b/zh-cn/erlang-cn.html.markdown new file mode 100644 index 00000000..8d0f42a4 --- /dev/null +++ b/zh-cn/erlang-cn.html.markdown @@ -0,0 +1,261 @@ +--- +language: erlang +lang: zh-cn +contributors: + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] +translators: + - ["Jakukyo Friel", "http://weakish.github.io"] +filename: erlang-cn.erl +--- + +```erlang +% 百分比符号标明注释的开始。 + +%% 两个符号通常用于注释函数。 + +%%% 三个符号通常用于注释模块。 + +% Erlang 里使用三种标点符号: +% 逗号 (`,`) 分隔函数调用中的参数、数据构建和模式。 +% 句号 (`.`) (后跟空格)分隔函数和 shell 中的表达式。 +% 分号 (`;`) 分隔语句。以下环境中使用语句: +% 函数定义和`case`、`if`、`try..catch`、`receive`表达式。 + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 1. 变量和模式匹配 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +Num = 42. % 变量必须以大写字母开头。 + +% Erlang 的变量只能赋值一次。如果给变量赋不同的值,会导致错误: +Num = 43. % ** exception error: no match of right hand side value 43 + +% 大多数语言中`=`表示赋值语句,在Erlang中,则表示模式匹配。 +% `Lhs = Rhs`实际上意味着: +% 演算右边(Rhs), 将结果与左边的模式匹配。 +Num = 7 * 6. + +% 浮点数 +Pi = 3.14159. + +% Atoms 用于表示非数字的常量。 +% Atom 以小写字母开始,包含字母、数字、`_`和`@`。 +Hello = hello. +OtherNode = example@node. + +% Atom 中如果包含特殊字符,可以用单引号括起。 +AtomWithSpace = 'some atom with space'. + +% Erlang 的元组类似 C 的 struct. +Point = {point, 10, 45}. + +% 使用模式匹配操作符`=`获取元组的值。 +{point, X, Y} = Point. % X = 10, Y = 45 + +% 我们可以使用`_`存放我们不感兴趣的变量。 +% `_`被称为匿名变量。和其他变量不同, +% 同一个模式中的多个`_`变量不必绑定到相同的值。 +Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}. +{_, {_, {_, Who}, _}, _} = Person. % Who = joe + +% 列表使用方括号,元素间使用逗号分隔。 +% 列表的元素可以是任意类型。 +% 列表的第一个元素称为列表的 head,其余元素称为列表的 tail。 +ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}]. + +% 若`T`是一个列表,那么`[H|T]`同样是一个列表,head为`H`,tail为`T`. +% `|`分隔列表的 head 和 tail. +% `[]`是空列表。 +% 我们可以使用模式匹配操作来抽取列表中的元素。 +% 如果我们有一个非空的列表`L`,那么`[X|Y] = L`则 +% 抽取 L 的 head 至 X,tail 至 Y (X、Y需为未定义的变量)。 +[FirstThing|OtherThingsToBuy] = ThingsToBuy. +% FirstThing = {apples, 10} +% OtherThingsToBuy = {pears, 6}, {milk, 3} + +% Erlang 中的字符串其实是由整数组成的数组。字符串使用双引号。 +Name = "Hello". +[72, 101, 108, 108, 111] = "Hello". + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 2. 循序编程 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Module 是 Erlang 代码的基本单位。我们编写的所有函数都储存在 module 中。 +% Module 存储在后缀为 `.erl` 的文件中。 +% Module 必须事先编译。编译好的 module 以 `.beam` 结尾。 +-module(geometry). +-export([area/1]). % module 对外暴露的函数列表 + +% `area`函数包含两个分句,分句间以分号相隔。 +% 最后一个分句以句号加换行结尾。 +% 每个分句由头、体两部门组成。 +% 头部包含函数名称和用括号括起的模式, +% 体部包含一系列表达式,如果头部的模式和调用时的参数匹配,这些表达式会被演算。 +% 模式匹配依照定义时的顺序依次进行。 +area({rectangle, Width, Ht}) -> Width * Ht; +area({circle, R}) -> 3.14159 * R * R. + +% 编译文件为 geometry.erl. +c(geometry). % {ok,geometry} + +% 调用函数时必须使用 module 名和函数名。 +geometry:area({rectangle, 10, 5}). % 50 +geometry:area({circle, 1.4}). % 6.15752 + +% 在 Erlang 中,同一模块中,参数数目不同,名字相同的函数是完全不同的函数。 +-module(lib_misc). +-export([sum/1]). % 对外暴露的`sum`函数接受一个参数:由整数组成的列表。 +sum(L) -> sum(L, 0). +sum([], N) -> N; +sum([H|T], N) -> sum(T, H+N). + +% fun 是匿名函数。它们没有名字,不过可以赋值给变量。 +Double = fun(X) -> 2*X end. % `Double` 指向匿名函数 #Fun +Double(2). % 4 + +% fun 可以作为函数的参数和返回值。 +Mult = fun(Times) -> ( fun(X) -> X * Times end ) end. +Triple = Mult(3). +Triple(5). % 15 + +% 列表解析是创建列表的表达式(不使用fun、map 或 filter)。 +% `[F(X) || X <- L]` 表示 "由 `F(X)` 组成的列表,其中 `X` 取自列表 `L`。 +L = [1,2,3,4,5]. +[2*X || X <- L]. % [2,4,6,8,10] +% 列表解析可以使用生成器,也可以使用过滤器,过滤器用于筛选列表的一部分。 +EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] + +% Guard 是用于增强模式匹配的结构。 +% Guard 可用于简单的测试和比较。 +% Guard 可用于函数定义的头部,以`when`关键字开头,或者其他可以使用表达式的地方。 +max(X, Y) when X > Y -> X; +max(X, Y) -> Y. + +% guard 可以由一系列 guard 表达式组成,这些表达式以逗号分隔。 +% `GuardExpr1, GuardExpr2, ..., GuardExprN` 为真,当且仅当每个 guard 表达式均为真。 +is_cat(A) when is_atom(A), A =:= cat -> true; +is_cat(A) -> false. +is_dog(A) when is_atom(A), A =:= dog -> true; +is_dog(A) -> false. + +% guard 序列 `G1; G2; ...; Gn` 为真,当且仅当其中任意一个 guard 表达式为真。 +% one of the guards `G1, G2, ...` evaluates to true. +is_pet(A) when is_dog(A); is_cat(A) -> true; +is_pet(A) -> false. + +% Record 使得可以将元组中的元素绑定到特定的名称。 +% Record 定义可以包含在 Erlang 源代码中,也可以放在后缀为`.hrl`的文件中。 +% Erlang 源代码可以包含这些文件。 +-record(todo, { + status = reminder, % Default value + who = joe, + text +}). + +% 在定义某个 record 之前,我们需要在 shell 中导入 record 的定义。 +% 我们可以使用 shell 函数`rr` (read records 的简称)。 +rr("records.hrl"). % [todo] + +% 创建和更新 record。 +X = #todo{}. +% #todo{status = reminder, who = joe, text = undefined} +X1 = #todo{status = urgent, text = "Fix errata in book"}. +% #todo{status = urgent, who = joe, text = "Fix errata in book"} +X2 = X1#todo{status = done}. +% #todo{status = done,who = joe,text = "Fix errata in book"} + +% `case` 表达式。 +% `filter` 返回由列表`L`中所有满足`P(x)`为真的元素`X`组成的列表。 +filter(P, [H|T]) -> + case P(H) of + true -> [H|filter(P, T)]; + false -> filter(P, T) + end; +filter(P, []) -> []. +filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4] + +% `if` 表达式。 +max(X, Y) -> + if + X > Y -> X; + X < Y -> Y; + true -> nil; + end. + +% 警告: `if` 表达式里至少有一个 guard 为真,否则会触发异常。 + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 3. 异常 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% 当遇到内部错误或显式调用时,会触发异常。 +% 显式调用包括 `throw(Exception)`, `exit(Exception)` 或 +% `erlang:error(Exception)`. +generate_exception(1) -> a; +generate_exception(2) -> throw(a); +generate_exception(3) -> exit(a); +generate_exception(4) -> {'EXIT', a}; +generate_exception(5) -> erlang:error(a). + +% Erlang 有两种捕获异常的方法。其一是将调用包裹在`try...catch`表达式中。 +catcher(N) -> + try generate_exception(N) of + Val -> {N, normal, Val} + catch + throw:X -> {N, caught, thrown, X}; + exit:X -> {N, caught, exited, X}; + error:X -> {N, caught, error, X} + end. + +% 另一种方式是将调用包裹在`catch`表达式中。 +% 此时异常会被转化为一个描述错误的元组。 +catcher(N) -> catch generate_exception(N). + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 4. 并发 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Erlang 依赖于 actor并发模型。在 Erlang 编写并发程序的三要素: +% 创建进程,发送消息,接收消息 + +% 启动一个新的进程使用`spawn`函数,接收一个函数作为参数 + +F = fun() -> 2 + 2 end. % #Fun +spawn(F). % <0.44.0> + +% `spawn` 函数返回一个pid(进程标识符),你可以使用pid向进程发送消息。 +% 使用 `!` 操作符发送消息。 +% 我们需要在进程内接收消息,要用到 `receive` 机制。 + +-module(caculateGeometry). +-compile(export_all). +caculateAera() -> + receive + {rectangle, W, H} -> + W * H; + {circle, R} -> + 3.14 * R * R; + _ -> + io:format("We can only caculate area of rectangles or circles.") + end. + +% 编译这个模块,在 shell 中创建一个进程,并执行 `caculateArea` 函数。 +c(caculateGeometry). +CaculateAera = spawn(caculateGeometry, caculateAera, []). +CaculateAera ! {circle, 2}. % 12.56000000000000049738 + +% shell也是一个进程(process), 你可以使用`self`获取当前 pid + +self(). % <0.41.0> + +``` + +## References + +* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/) +* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang) +* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/) +* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) -- cgit v1.2.3 From eae9850750d0703e38878bbe50822c0b511a0e32 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Mon, 19 May 2014 17:05:44 +0800 Subject: erlang: refine Chinese translation. --- zh-cn/erlang-cn.html.markdown | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/zh-cn/erlang-cn.html.markdown b/zh-cn/erlang-cn.html.markdown index 8d0f42a4..32e84278 100644 --- a/zh-cn/erlang-cn.html.markdown +++ b/zh-cn/erlang-cn.html.markdown @@ -141,13 +141,11 @@ is_dog(A) when is_atom(A), A =:= dog -> true; is_dog(A) -> false. % guard 序列 `G1; G2; ...; Gn` 为真,当且仅当其中任意一个 guard 表达式为真。 -% one of the guards `G1, G2, ...` evaluates to true. is_pet(A) when is_dog(A); is_cat(A) -> true; is_pet(A) -> false. -% Record 使得可以将元组中的元素绑定到特定的名称。 -% Record 定义可以包含在 Erlang 源代码中,也可以放在后缀为`.hrl`的文件中。 -% Erlang 源代码可以包含这些文件。 +% Record 可以将元组中的元素绑定到特定的名称。 +% Record 定义可以包含在 Erlang 源代码中,也可以放在后缀为`.hrl`的文件中(Erlang 源代码中 include 这些文件)。 -record(todo, { status = reminder, % Default value who = joe, @@ -192,7 +190,7 @@ max(X, Y) -> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 当遇到内部错误或显式调用时,会触发异常。 -% 显式调用包括 `throw(Exception)`, `exit(Exception)` 或 +% 显式调用包括 `throw(Exception)`, `exit(Exception)` 和 % `erlang:error(Exception)`. generate_exception(1) -> a; generate_exception(2) -> throw(a); -- cgit v1.2.3 From 5f3a6c01b8b0890efaa3ba73a0a5a515bcbfdf52 Mon Sep 17 00:00:00 2001 From: hirohope Date: Mon, 19 May 2014 09:21:17 -0400 Subject: fixed file name with es suffix --- es-es/python3-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/python3-es.html.markdown b/es-es/python3-es.html.markdown index 71c38670..1c69481a 100644 --- a/es-es/python3-es.html.markdown +++ b/es-es/python3-es.html.markdown @@ -5,7 +5,7 @@ contributors: translators: - ["Camilo Garrido", "http://twitter.com/hirohope"] lang: es-es -filename: learnpython3.py +filename: learnpython3-es.py --- Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno -- cgit v1.2.3 From 0d6b7513c79bee6daf131d4437bf1319559fb6f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Veiga?= Date: Tue, 20 May 2014 07:51:34 +0200 Subject: replaced <- with send, corrected message sending --- elixir.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 0892deb7..b27b2ee8 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -358,7 +358,7 @@ f = fn -> 2 * 2 end #=> #Function spawn(f) #=> #PID<0.40.0> # `spawn` returns a pid (process identifier), you can use this pid to send -# messages to the process. To do message passing we use the `<-` operator. +# messages to the process. To do message passing we use the `send` operator. # For all of this to be useful we need to be able to receive messages. This is # achived with the `receive` mechanism: defmodule Geometry do @@ -378,11 +378,11 @@ end pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> # Send a message to `pid` that will match a pattern in the receive statement -pid <- {:rectangle, 2, 3} +send pid, {:rectangle, 2, 3} #=> Area = 6 # {:rectangle,2,3} -pid <- {:circle, 2} +send pid, {:circle, 2} #=> Area = 12.56000000000000049738 # {:circle,2} -- cgit v1.2.3 From 31c74615e6a492db39e1586c3d4aaa7c4ada5e56 Mon Sep 17 00:00:00 2001 From: e99n09 Date: Fri, 23 May 2014 15:37:15 -0400 Subject: Significant new content I moved some things around. I preserved isomorphismes' "no programming knowledge first" approach; I really like this. In the "programming-heavy" part of the tutorial, I emphasized from the very beginning that every "single" thing in R, like 4 or "foo", is really just a vector of length 1. I added in some whirlwind tours of data.table and ggplot2. --- r.html.markdown | 468 +++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 293 insertions(+), 175 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index ea94ae42..dfc945c1 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -6,34 +6,42 @@ contributors: filename: learnr.r --- -R is a statistical computing language. It has lots of libraries for uploading and cleaning data sets, running statistical procedures, and making graphs. You can also run `R`commands within a LaTeX document. +R is a statistical computing language. It has lots of libraries for uploading and cleaning data sets, running statistical procedures, and making graphs. You can also run `R` commands within a LaTeX document. ```python # Comments start with number symbols. -# You can't make a multi-line comment per se, +# You can't make multi-line comments, # but you can stack multiple comments like so. -# in Windows, hit COMMAND-ENTER to execute a line +# in Windows or Mac, hit COMMAND-ENTER to execute a line -################################################################### + +############################################################################# # Stuff you can do without understanding anything about programming -################################################################### +############################################################################# + +# In this section, we show off some of the cool stuff you can do in +# R without understanding anything about programming. Do not worry +# about understanding everything the code does. Just enjoy! -data() # Browse pre-loaded data sets -data(rivers) # Lengths of Major North American Rivers -ls() # Notice that "rivers" appears in the workspace -head(rivers) # peek at the dataset +data() # browse pre-loaded data sets +data(rivers) # get this one: "Lengths of Major North American Rivers" +ls() # notice that "rivers" now appears in the workspace +head(rivers) # peek at the data set # 735 320 325 392 524 450 + length(rivers) # how many rivers were measured? # 141 -summary(rivers) +summary(rivers) # what are some summary statistics? # Min. 1st Qu. Median Mean 3rd Qu. Max. # 135.0 310.0 425.0 591.2 680.0 3710.0 -stem(rivers) #stem-and-leaf plot (like a histogram) -# + +# make a stem-and-leaf plot (a histogram-like data visualization) +stem(rivers) + # The decimal point is 2 digit(s) to the right of the | # # 0 | 4 @@ -56,8 +64,8 @@ stem(rivers) #stem-and-leaf plot (like a histogram) # 34 | # 36 | 1 - -stem(log(rivers)) #Notice that the data are neither normal nor log-normal! Take that, Bell Curve fundamentalists. +stem(log(rivers)) # Notice that the data are neither normal nor log-normal! +# Take that, Bell curve fundamentalists. # The decimal point is 1 digit(s) to the left of the | # @@ -80,17 +88,19 @@ stem(log(rivers)) #Notice that the data are neither normal nor log-normal! Take # 80 | # 82 | 2 +# make a histogram: +hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters +hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later -hist(rivers, col="#333333", border="white", breaks=25) #play around with these parameters -hist(log(rivers), col="#333333", border="white", breaks=25) #you'll do more plotting later - -#Here's another neat data set that comes pre-loaded. R has tons of these. data() +# Here's another neat data set that comes pre-loaded. R has tons of these. data(discoveries) -plot(discoveries, col="#333333", lwd=3, xlab="Year", main="Number of important discoveries per year") -plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", main="Number of important discoveries per year") +plot(discoveries, col="#333333", lwd=3, xlab="Year", + main="Number of important discoveries per year") +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", + main="Number of important discoveries per year") - -#rather than leaving the default ordering (by year) we could also sort to see what's typical +# Rather than leaving the default ordering (by year), +# we could also sort to see what's typical: sort(discoveries) # [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 # [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 @@ -117,231 +127,249 @@ stem(discoveries, scale=2) max(discoveries) # 12 - summary(discoveries) # Min. 1st Qu. Median Mean 3rd Qu. Max. # 0.0 2.0 3.0 3.1 4.0 12.0 - - - -#Basic statistical operations don't require any programming knowledge either - -#roll a die a few times +# Roll a die a few times round(runif(7, min=.5, max=6.5)) # 1 4 6 1 4 6 4 +# Your numbers will differ from mine unless we set the same random.seed(31337) -#your numbers will differ from mine unless we set the same random.seed(31337) - - -#draw from a standard Gaussian 9 times +# Draw from a standard Gaussian 9 times rnorm(9) # [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 # [7] -0.59975593 0.57629164 1.08455362 - - - - - - -######################### -# Basic programming stuff -######################### - -# NUMBERS - -# "numeric" means double-precision floating-point numbers -5 # 5 -class(5) # "numeric" -5e4 # 50000 #handy when dealing with large,small,or variable orders of magnitude -6.02e23 # Avogadro's number -1.6e-35 # Planck length - -# long-storage integers are written with L -5L # 5 -class(5L) # "integer" - -# Try ?class for more information on the class() function -# In fact, you can look up the documentation on `xyz` with ?xyz -# or see the source for `xyz` by evaluating xyz - -# Arithmetic -10 + 66 # 76 -53.2 - 4 # 49.2 -2 * 2.0 # 4 -3L / 4 # 0.75 -3 %% 2 # 1 - -# Weird number types -class(NaN) # "numeric" +################################################## +# Data types and basic arithmetic +################################################## + +# Now for the programming-oriented part of the tutorial. +# In this section you will meet the important data types of R: +# integers, numerics, characters, logicals, and factors. +# There are others, but these are the bare minimum you need to +# get started. + +# INTEGERS +# Long-storage integers are written with L +5L # 5 +class(5L) # "integer" +# (Try ?class for more information on the class() function.) +# In R, every single value, like 5L, is considered a vector of length 1 +length(5L) # 1 +# You can have an integer vector with length > 1 too: +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" + +# NUMERICS +# A "numeric" is a double-precision floating-point number +5 # 5 +class(5) # "numeric" +# Again, everything in R is a vector; +# you can make a numeric vector with more than one element +c(3,3,3,2,2,1) # 3 3 3 2 2 1 +# You can use scientific notation too +5e4 # 50000 +6.02e23 # Avogadro's number +1.6e-35 # Planck length +# You can also have infinitely large or small numbers class(Inf) # "numeric" -class(-Inf) # "numeric" #used in for example integrate( dnorm(x), 3, Inf ) -- which obviates Z-score tables - -# but beware, NaN isn't the only weird type... -class(NA) # see below -class(NULL) # NULL - - -# SIMPLE LISTS -c(6, 8, 7, 5, 3, 0, 9) # 6 8 7 5 3 0 9 -c('alef', 'bet', 'gimmel', 'dalet', 'he') # "alef" "bet" "gimmel" "dalet" "he" -c('Z', 'o', 'r', 'o') == "Zoro" # FALSE FALSE FALSE FALSE - -#some more nice built-ins -5:15 # 5 6 7 8 9 10 11 12 13 14 15 - -seq(from=0, to=31337, by=1337) -# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 -# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 - -letters -# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" -# [20] "t" "u" "v" "w" "x" "y" "z" - -month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" - - -# Access the n'th element of a list with list.name[n] or sometimes list.name[[n]] -letters[18] # "r" -LETTERS[13] # "M" -month.name[9] # "September" -c(6, 8, 7, 5, 3, 0, 9)[3] # 7 - - +class(-Inf) # "numeric" +# You might use "Inf", for example, in integrate( dnorm(x), 3, Inf); +# this obviates Z-score tables. + +# BASIC ARITHMETIC +# You can do arithmetic with numbers +# Doing arithmetic on a mix of integers and numerics gives you another numeric +10L + 66L # 76 # integer plus integer gives integer +53.2 - 4 # 49.2 # numeric minus numeric gives numeric +2.0 * 2L # 4 # numeric times integer gives numeric +3L / 4 # 0.75 # integer over integer gives numeric +3 %% 2 # 1 # the remainder of two numerics is another numeric +# Illegal arithmetic yeilds you a "not-a-number": +0 / 0 # NaN +class(NaN) # "numeric" +# You can do arithmetic on two vectors with length greater than 1, +# so long as the larger vector's length is an integer multiple of the smaller +c(1,2,3) + c(1,2,3) # 2 4 6 # CHARACTERS - # There's no difference between strings and characters in R - -"Horatio" # "Horatio" +"Horatio" # "Horatio" class("Horatio") # "character" -substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " -gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." - - +class('H') # "character" +# Those were both character vectors of length 1 +# Here is a longer one: +c('alef', 'bet', 'gimmel', 'dalet', 'he') +# => +# "alef" "bet" "gimmel" "dalet" "he" +length(c("Call","me","Ishmael")) # 3 +# You can do regex operations on character vectors: +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." +# R has several built-in character vectors: +letters +# => +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" # LOGICALS - -# booleans +# In R, a "logical" is a boolean class(TRUE) # "logical" class(FALSE) # "logical" -# Behavior is normal +# Their behavior is normal TRUE == TRUE # TRUE TRUE == FALSE # FALSE FALSE != FALSE # FALSE FALSE != TRUE # TRUE # Missing data (NA) is logical, too class(NA) # "logical" - - +# Here we get a logical vector with many elements: +c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE # FACTORS - # The factor class is for categorical data -# which can be ordered (like childrens' grade levels) -# or unordered (like gender) -levels(factor(c("female", "male", "male", "female", "NA", "female"))) # "female" "male" "NA" - +# Factors can be ordered (like childrens' grade levels) or unordered (like gender) factor(c("female", "female", "male", "NA", "female")) # female female male NA female # Levels: female male NA +# The "levels" are the values the categorical data can take +levels(factor(c("male", "male", "female", "NA", "female"))) # "female" "male" "NA" +# If a factor has length 1, its levels will have length 1, too +length(factor("male")) # 1 +length(levels(factor("male"))) # 1 +# Factors are commonly seen in data frames, a data structure we will cover later +# in this tutorial: +data(infert) # "Infertility after Spontaneous and Induced Abortion" +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + +# WEIRD TYPES +# A quick summary of some of the weirder types in R +class(Inf) # "numeric" +class(-Inf) # "numeric" +class(NaN) # "numeric" +class(NA) # "logical" +class(NULL) # NULL -data(infert) #Infertility after Spontaneous and Induced Abortion -levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" +# TYPE COERCION +# Type-coercion is when you force a value to take on a different type +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +# If you put elements of different classes into a vector, weird coercions happen: +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" +as.numeric("Bilbo") +# => +# [1] NA +# Warning message: +# NAs introduced by coercion +# Also note: those were just the basic data types +# There are many more data types, such as for dates, time series, etc. -# VARIABLES -# Lots of way to assign stuff +################################################## +# Variables, loops, if/else +################################################## + +# A variable is like a box you store a value in for later use. +# We call this "assigning" the value to the variable. +# Having variables lets us write loops, functions, and if/else statements + +# VARIABLES +# Lots of way to assign stuff: x = 5 # this is possible y <- "1" # this is preferred TRUE -> z # this works but is weird -# We can use coerce variables to different classes -as.numeric(y) # 1 -as.character(x) # "5" - # LOOPS - # We've got for loops for (i in 1:4) { print(i) } - # We've got while loops a <- 10 while (a > 4) { cat(a, "...", sep = "") a <- a - 1 } - # Keep in mind that for and while loops run slowly in R # Operations on entire vectors (i.e. a whole row, a whole column) # or apply()-type functions (we'll discuss later) are preferred # IF/ELSE - # Again, pretty standard if (4 > 3) { - print("Huzzah! It worked!") + print("4 is greater than 3") } else { - print("Noooo! This is blatantly illogical!") + print("4 is not greater than 3") } # => -# [1] "Huzzah! It worked!" +# [1] "4 is greater than 3" # FUNCTIONS - # Defined like so: jiggle <- function(x) { x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise return(x) } - # Called like any other R function: jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 -######################### -# Fun with data: vectors, matrices, data frames, and arrays -######################### + + +########################################################################### +# Data structures: Vectors, matrices, data frames, and arrays +########################################################################### # ONE-DIMENSIONAL -# You can vectorize anything, so long as all components have the same type +# Let's start from the very beginning, and with something you already know: vectors. +# As explained above, every single element in R is already a vector +# Make sure the elements of long vectors all have the same type vec <- c(8, 9, 10, 11) vec # 8 9 10 11 -# The class of a vector is the class of its components -class(vec) # "numeric" -# If you vectorize items of different classes, weird coercions happen -c(TRUE, 4) # 1 4 -c("dog", TRUE, 4) # "dog" "TRUE" "4" - -# We ask for specific components like so (R starts counting from 1) -vec[1] # 8 +# We ask for specific elements by subsetting with square brackets +# (Note that R starts counting from 1) +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 # We can also search for the indices of specific components, which(vec %% 2 == 0) # 1 3 -# or grab just the first or last entry in the vector +# grab just the first or last entry in the vector, head(vec, 1) # 8 tail(vec, 1) # 11 +# or figure out if a certain value is in the vector +any(vec == 10) # TRUE # If an index "goes over" you'll get NA: vec[6] # NA # You can find the length of your vector with length() length(vec) # 4 - # You can perform operations on entire vectors or subsets of vectors vec * 4 # 16 20 24 28 vec[2:3] * 5 # 25 30 +any(vec[2:3] == 8) # FALSE # and there are many built-in functions to summarize vectors mean(vec) # 9.5 var(vec) # 1.666667 -sd(vec) # 1.290994 +sd(vec) # 1.290994 max(vec) # 11 min(vec) # 8 sum(vec) # 38 +# Some more nice built-ins: +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +seq(from=0, to=31337, by=1337) +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 # TWO-DIMENSIONAL (ALL ONE CLASS) @@ -361,6 +389,7 @@ mat[1,] # 1 4 3 * mat[,1] # 3 6 9 # Ask for a specific cell mat[3,2] # 6 + # Transpose the whole matrix t(mat) # => @@ -368,6 +397,14 @@ t(mat) # [1,] 1 2 3 # [2,] 4 5 6 +# Matrix multiplication +mat %*% t(mat) +# => +# [,1] [,2] [,3] +# [1,] 17 22 27 +# [2,] 22 29 36 +# [3,] 27 36 45 + # cbind() sticks vectors together column-wise to make a matrix mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) mat2 @@ -395,24 +432,85 @@ mat3 # TWO-DIMENSIONAL (DIFFERENT CLASSES) # For columns of different classes, use the data frame -dat <- data.frame(c(5,2,1,4), c("dog", "cat", "bird", "dog")) -names(dat) <- c("number", "species") # name the columns -class(dat) # "data.frame" -dat +# This data structure is so useful for statistical programming, +# a version of it was added to Python in the package "pandas". + +students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), + c(3,2,2,1,0,-1), + c("H", "G", "G", "R", "S", "G")) +names(students) <- c("name", "year", "house") # name the columns +class(students) # "data.frame" +students # => -# number species -# 1 5 dog -# 2 2 cat -# 3 1 bird -# 4 4 dog -class(dat$number) # "numeric" -class(dat[,2]) # "factor" +# name year house +# 1 Cedric 3 H +# 2 Fred 2 G +# 3 George 2 G +# 4 Cho 1 R +# 5 Draco 0 S +# 6 Ginny -1 G +class(students$year) # "numeric" +class(students[,3]) # "factor" +# find the dimensions +nrow(students) # 6 +ncol(students) # 3 +dim(students) # 6 3 # The data.frame() function converts character vectors to factor vectors +# by default; turn this off by setting stringsAsFactors = FALSE when +# you create the data.frame +?data.frame # There are many twisty ways to subset data frames, all subtly unalike -dat$number # 5 2 1 4 -dat[,1] # 5 2 1 4 -dat[,"number"] # 5 2 1 4 +students$year # 3 2 2 1 0 -1 +students[,2] # 3 2 2 1 0 -1 +students[,"year"] # 3 2 2 1 0 -1 + +# A popular replacement for the data.frame structure is the data.table +# If you're working with huge or panel data, or need to merge a few data +# sets, data.table can be a good choice. Here's a whirlwind tour: +install.packages("data.table") +require(data.table) +students <- as.data.table(students) +students # note the slightly different print-out +# => +# name year house +# 1: Cedric 3 H +# 2: Fred 2 G +# 3: George 2 G +# 4: Cho 1 R +# 5: Draco 0 S +# 6: Ginny -1 G +students[name=="Ginny"] +# => +# name year house +# 1: Ginny -1 G +students[year==2] +# => +# name year house +# 1: Fred 2 G +# 2: George 2 G +founders <- data.table(house=c("G","H","R","S"), + founder=c("Godric","Helga","Rowena","Salazar")) +founders +# => +# house founder +# 1: G Godric +# 2: H Helga +# 3: R Rowena +# 4: S Salazar +setkey(students, house) +setkey(founders, house) +students <- founders[students] # merge the two data sets +setnames(students, c("house","houseFounderName","studentName","year")) +students[,order(c("name","year","house","houseFounderName")), with=F] +# => +# studentName year house houseFounderName +# 1: Fred 2 G Godric +# 2: George 2 G Godric +# 3: Ginny -1 G Godric +# 4: Cedric 3 H Helga +# 5: Cho 1 R Rowena +# 6: Draco 0 S Salazar # MULTI-DIMENSIONAL (ALL OF ONE CLASS) @@ -446,15 +544,23 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) list1 <- list(time = 1:40) list1$price = c(rnorm(40,.5*list1$time,4)) # random list1 - # You can get items in the list like so -list1$time -# You can subset list items like vectors +list1$time # one way +list1[["time"]] # another way +list1[[1]] # yet another way +# => +# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 +# [34] 34 35 36 37 38 39 40 +# You can subset list items like any other vector list1$price[4] -######################### +# Lists are not the most efficient data structure to work with in R; +# unless you have a very good reason, you should stick to data.frames +# Lists are often returned by functions that perform linear regressions + +################################################## # The apply() family of functions -######################### +################################################## # Remember mat? mat @@ -467,7 +573,7 @@ mat # over rows (MAR = 1) or columns (MAR = 2) # That is, R does FUN to each row (or column) of X, much faster than a # for or while loop would do -apply(mat, MAR = 2, myFunc) +apply(mat, MAR = 2, jiggle) # => # [,1] [,2] # [1,] 3 15 @@ -478,16 +584,18 @@ apply(mat, MAR = 2, myFunc) # Don't feel too intimidated; everyone agrees they are rather confusing # The plyr package aims to replace (and improve upon!) the *apply() family. - install.packages("plyr") require(plyr) ?plyr + + ######################### # Loading data ######################### # "pets.csv" is a file on the internet +# (but it could just as easily be be a file on your own computer) pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") pets head(pets, 2) # first two rows @@ -499,10 +607,13 @@ write.csv(pets, "pets2.csv") # to make a new .csv file # Try ?read.csv and ?write.csv for more information + + ######################### # Plots ######################### +# BUILT-IN PLOTTING FUNCTIONS # Scatterplots! plot(list1$time, list1$price, main = "fake data") # Regressions! @@ -512,18 +623,25 @@ linearModel # outputs result of regression abline(linearModel, col = "red") # Get a variety of nice diagnostics plot(linearModel) - # Histograms! hist(rpois(n = 10000, lambda = 5), col = "thistle") - # Barplots! barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) +# GGPLOT2 +# But these are not even the prettiest of R's plots # Try the ggplot2 package for more and better graphics - install.packages("ggplot2") require(ggplot2) ?ggplot2 +pp <- ggplot(students, aes(x=house)) +pp + geom_histogram() +ll <- as.data.table(list1) +pp <- ggplot(ll, aes(x=time,price)) +pp + geom_point() +# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/) + + ``` -- cgit v1.2.3 From fbbbdd241452d336abbbdc5476eac6ceefc558d7 Mon Sep 17 00:00:00 2001 From: KIM Taegyoon Date: Sat, 24 May 2014 13:44:26 +0900 Subject: added Paren --- paren.html.markdown | 193 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 paren.html.markdown diff --git a/paren.html.markdown b/paren.html.markdown new file mode 100644 index 00000000..778598ce --- /dev/null +++ b/paren.html.markdown @@ -0,0 +1,193 @@ +--- + +language: Paren +filename: learnparen.paren +contributors: + - ["KIM Taegyoon", "https://github.com/kimtg"] +--- + +[Paren](https://bitbucket.org/ktg/paren) is a dialect of Lisp. It is designed to be an embedded language. + +Some examples are from http://learnxinyminutes.com/docs/racket/ . + +```lisp +;;; Comments +# comments + +;; Single line comments start with a semicolon or a sharp sign + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Primitive Datatypes and Operators +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Numbers +123 ; int +3.14 ; double +6.02e+23 ; double +(int 3.14) ; => 3 : int +(double 123) ; => 123 : double + +;; Function application is written (f x y z ...) +;; where f is a function and x, y, z, ... are operands +;; If you want to create a literal list of data, use (quote) to stop it from +;; being evaluated +(quote (+ 1 2)) ; => (+ 1 2) +;; Now, some arithmetic operations +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(^ 2 3) ; => 8 +(/ 5 2) ; => 2 +(% 5 2) ; => 1 +(/ 5.0 2) ; => 2.5 + +;;; Booleans +true ; for true +false ; for false +(! true) ; => false +(&& true false (prn "doesn't get here")) ; => false +(|| false true (prn "doesn't get here")) ; => true + +;;; Characters are ints. +(char-at "A" 0) ; => 65 +(chr 65) ; => "A" + +;;; Strings are fixed-length array of characters. +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; backslash is an escaping character +"Foo\tbar\r\n" ; includes C escapes: \t \r \n + +;; Strings can be added too! +(strcat "Hello " "world!") ; => "Hello world!" + +;; A string can be treated like a list of characters +(char-at "Apple" 0) ; => 65 + +;; Printing is pretty easy +(pr "I'm" "Paren. ") (prn "Nice to meet you!") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variables +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; You can create or set a variable using (set) +;; a variable name can use any character except: ();#" +(set some-var 5) ; => 5 +some-var ; => 5 + +;; Accessing a previously unassigned variable is an exception +; x ; => Unknown variable: x : nil + +;; Local binding: Use lambda calculus! `a' and `b' are bound to `1' and `2' only within the (fn ...) +((fn (a b) (+ a b)) 1 2) ; => 3 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Collections +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Lists + +;; Lists are vector-like data structures. (Random access is O(1).) +(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3) +;; `list' is a convenience variadic constructor for lists +(list 1 2 3) ; => (1 2 3) +;; and a quote can also be used for a literal list value +(quote (+ 1 2)) ; => (+ 1 2) + +;; Can still use `cons' to add an item to the beginning of a list +(cons 0 (list 1 2 3)) ; => (0 1 2 3) + +;; Lists are a very basic type, so there is a *lot* of functionality for +;; them, a few examples: +(map inc (list 1 2 3)) ; => (2 3 4) +(filter (fn (x) (== 0 (% x 2))) (list 1 2 3 4)) ; => (2 4) +(length (list 1 2 3 4)) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Functions +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `fn' to create functions. +;; A function always returns the value of its last expression +(fn () "Hello World") ; => (fn () Hello World) : fn + +;; Use parentheses to call all functions, including a lambda expression +((fn () "Hello World")) ; => "Hello World" + +;; Assign a function to a var +(set hello-world (fn () "Hello World")) +(hello-world) ; => "Hello World" + +;; You can shorten this using the function definition syntatcic sugae: +(defn hello-world2 () "Hello World") + +;; The () in the above is the list of arguments for the function +(set hello + (fn (name) + (strcat "Hello " name))) +(hello "Steve") ; => "Hello Steve" + +;; ... or equivalently, using a sugared definition: +(defn hello2 (name) + (strcat "Hello " name)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Equality +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; for numbers use `==' +(== 3 3.0) ; => true +(== 2 1) ; => false + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Control Flow +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Conditionals + +(if true ; test expression + "this is true" ; then expression + "this is false") ; else expression +; => "this is true" + +;;; Loops + +;; for loop is for number +;; (for SYMBOL START END STEP EXPR ..) +(for i 0 10 2 (pr i "")) ; => prints 0 2 4 6 8 10 +(for i 0.0 10 2.5 (pr i "")) ; => prints 0 2.5 5 7.5 10 + +;; while loop +((fn (i) + (while (< i 10) + (pr i) + (++ i))) 0) ; => prints 0123456789 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutation +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `set' to assign a new value to a variable or a place +(set n 5) ; => 5 +(set n (inc n)) ; => 6 +n ; => 6 +(set a (list 1 2)) ; => (1 2) +(set (nth 0 a) 3) ; => 3 +a ; => (3 2) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros let you extend the syntax of the language. +;; Paren macros are easy. +;; In fact, (defn) is a macro. +(defmacro setfn (name ...) (set name (fn ...))) +(defmacro defn (name ...) (def name (fn ...))) + +;; Let's add an infix notation +(defmacro infix (a op ...) (op a ...)) +(infix 1 + 2 (infix 3 * 4)) ; => 15 + +;; Macros are not hygienic, you can clobber existing variables! +;; They are code transformations. +``` -- cgit v1.2.3 From 217d0b076c6b374f34b9af8ec8a362c07867d41d Mon Sep 17 00:00:00 2001 From: KIM Taegyoon Date: Sat, 24 May 2014 18:19:57 +0900 Subject: added racket-kr --- ko-kr/racket-kr.html.markdown | 640 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 640 insertions(+) create mode 100644 ko-kr/racket-kr.html.markdown diff --git a/ko-kr/racket-kr.html.markdown b/ko-kr/racket-kr.html.markdown new file mode 100644 index 00000000..f6056d4d --- /dev/null +++ b/ko-kr/racket-kr.html.markdown @@ -0,0 +1,640 @@ +--- + +language: racket +filename: learnracket.rkt +contributors: + - ["th3rac25", "https://github.com/voila"] + - ["Eli Barzilay", "https://github.com/elibarzilay"] + - ["Gustavo Schmidt", "https://github.com/gustavoschmidt"] + - ["Duong H. Nguyen", "https://github.com/cmpitg"] +translators: + - ["KIM Taegyoon", "https://github.com/kimtg"] +lang: ko-kr +--- + +Racket 은 Lisp/Scheme 계열의 일반 목적의, 다중 패러다임 프로그래밍 언어이다. + +```racket +#lang racket ; 우리가 사용하는 언어를 정의한다. + +;;; 주석 + +;; 한 줄 주석은 세미콜론으로 시작한다. + +#| 블록 주석 + 은 여러 줄에 걸칠 수 있으며... + #| + 중첩될 수 있다! + |# +|# + +;; S-expression 주석은 아래 식을 버리므로, +;; 디버깅할 때 식을 주석화할 때 유용하다. +#; (이 식은 버려짐) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. 근본 자료형과 연산자 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 숫자 +9999999999999999999999 ; 정수 +#b111 ; 이진수 => 7 +#o111 ; 팔진수 => 73 +#x111 ; 16진수 => 273 +3.14 ; 실수 +6.02e+23 +1/2 ; 분수 +1+2i ; 복소수 + +;; 함수 적용은 이렇게 쓴다: (f x y z ...) +;; 여기에서 f는 함수이고 x, y, z는 피연산자이다. +;; 글자 그대로의 데이터 리스트를 만들고 싶다면 평가를 막기 위해 '를 쓰시오. +'(+ 1 2) ; => (+ 1 2) +;; 이제, 산술 연산 몇 개 +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(quotient 5 2) ; => 2 +(remainder 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(exact->inexact 1/3) ; => 0.3333333333333333 +(+ 1+2i 2-3i) ; => 3-1i + +;;; 불린 +#t ; 참 +#f ; 거짓 -- #f가 아닌 것은 참 +(not #t) ; => #f +(and 0 #f (error "doesn't get here")) ; => #f +(or #f 0 (error "doesn't get here")) ; => 0 + +;;; 문자 +#\A ; => #\A +#\λ ; => #\λ +#\u03BB ; => #\λ + +;;; 문자열은 고정 길이의 문자 배열이다. +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; 백슬래시는 탈출 문자이다. +"Foo\tbar\41\x21\u0021\a\r\n" ; C 탈출 문자, 유니코드 포함 +"λx:(μα.α→α).xx" ; 유니코드 문자 포함 가능 + +;; 문자열은 붙여질 수 있다! +(string-append "Hello " "world!") ; => "Hello world!" + +;; 문자열은 문자의 리스트처럼 취급될 수 있다. +(string-ref "Apple" 0) ; => #\A + +;; format은 문자열을 형식화하기 위해 사용된다: +(format "~a can be ~a" "strings" "formatted") + +;; 인쇄는 쉽다. +(printf "I'm Racket. Nice to meet you!\n") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. 변수 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; define으로 변수를 만든다. +;; 변수명으로 다음 문자를 사용할 수 없다: ()[]{}",'`;#|\ +(define some-var 5) +some-var ; => 5 + +;; 유니코드 문자도 사용 가능하다. +(define ⊆ subset?) +(⊆ (set 3 2) (set 1 2 3)) ; => #t + +;; 앞에서 정의되지 않은 변수에 접근하면 예외가 발생한다. +; x ; => x: undefined ... + +;; 지역 변수: `me'는 (let ...) 안에서만 "Bob"이다. +(let ([me "Bob"]) + "Alice" + me) ; => "Bob" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. 구조체(Struct)와 모음(Collection) +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 구조체 +(struct dog (name breed age)) +(define my-pet + (dog "lassie" "collie" 5)) +my-pet ; => # +(dog? my-pet) ; => #t +(dog-name my-pet) ; => "lassie" + +;;; 쌍 (불변) +;; `cons'는 쌍을 만들고, `car'와 `cdr'는 첫번째와 +;; 두번째 원소를 추출한다. +(cons 1 2) ; => '(1 . 2) +(car (cons 1 2)) ; => 1 +(cdr (cons 1 2)) ; => 2 + +;;; 리스트 + +;; 리스트는 연결-리스트 데이터 구조이며, `cons' 쌍으로 만들어지며 +;; `null' (또는 '()) 로 리스트의 끝을 표시한다. +(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) +;; `list'는 편리한 가변인자 리스트 생성자이다. +(list 1 2 3) ; => '(1 2 3) +;; 글자 그대로의 리스트 값에는 인용부호를 쓴다. +'(1 2 3) ; => '(1 2 3) + +;; 리스트의 앞에 항목을 추가하기 위하여 `cons'를 사용한다. +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; 리스트들을 붙이기 위해 `append'를 사용한다. +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; 리스트는 매우 기본적인 자료형이기 때문에, 리스트에 대해 적용되는 많은 기능들이 있다. +;; 예를 들어: +(map add1 '(1 2 3)) ; => '(2 3 4) +(map + '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(filter even? '(1 2 3 4)) ; => '(2 4) +(count even? '(1 2 3 4)) ; => 2 +(take '(1 2 3 4) 2) ; => '(1 2) +(drop '(1 2 3 4) 2) ; => '(3 4) + +;;; 벡터 + +;; 벡터는 고정 길이의 배열이다. +#(1 2 3) ; => '#(1 2 3) + +;; `vector-append'를 사용하여 벡터들을 붙인다. +(vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; 집합 + +;; 리스트로부터 집합 만들기 +(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) + +;; 원소를 추가하려면 `set-add'를 사용한다. +;; (함수적: 확장된 집합을 반환하며, 원래의 입력을 변경하지 않는다.) +(set-add (set 1 2 3) 4) ; => (set 1 2 3 4) + +;; 원소를 삭제하려면 `set-remove' +(set-remove (set 1 2 3) 1) ; => (set 2 3) + +;; 존재 여부를 조사하려면 `set-member?' +(set-member? (set 1 2 3) 1) ; => #t +(set-member? (set 1 2 3) 4) ; => #f + +;;; 해시 + +;; 불변의 해시 테이블을 만든다. (가변 예제는 아래에) +(define m (hash 'a 1 'b 2 'c 3)) + +;; 값 꺼내기 +(hash-ref m 'a) ; => 1 + +;; 없는 값을 꺼내는 것은 예외를 발생시킨다. +; (hash-ref m 'd) => no value found + +;; 키가 없을 때 반환할 기본값을 지정할 수 있다. +(hash-ref m 'd 0) ; => 0 + +;; `hash-set'을 사용하여 불변의 해시 테이블을 확장 +;; (원래 것을 변경하지 않고 확장된 해시를 반환한다.) +(define m2 (hash-set m 'd 4)) +m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) + +;; 이 해시들은 불변이라는 점을 기억하시오! +m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' + +;; `hash-remove'로 키를 삭제 (이것도 함수적) +(hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. 함수 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; `lambda'로 함수를 만든다. +;; 함수는 항상 마지막 식을 반환한다. +(lambda () "Hello World") ; => # +;; 유니코드 `λ'도 사용 가능 +(λ () "Hello World") ; => same function + +;; 모든 함수를 호출할 때는 괄호를 쓴다, lambda 식도 포함하여. +((lambda () "Hello World")) ; => "Hello World" +((λ () "Hello World")) ; => "Hello World" + +;; 변수에 함수를 할당 +(define hello-world (lambda () "Hello World")) +(hello-world) ; => "Hello World" + +;; 문법적 설탕을 사용하여 함수 정의를 더 짧게할 수 있다: +(define (hello-world2) "Hello World") + +;; 위에서 ()는 함수의 인자 리스트이다. +(define hello + (lambda (name) + (string-append "Hello " name))) +(hello "Steve") ; => "Hello Steve" +;; ... 또는, 설탕 친 정의로: +(define (hello2 name) + (string-append "Hello " name)) + +;; 가변인자 함수에는 `case-lambda'를 사용한다. +(define hello3 + (case-lambda + [() "Hello World"] + [(name) (string-append "Hello " name)])) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" +;; ... 또는 선택적 인자에 기본값 지정 +(define (hello4 [name "World"]) + (string-append "Hello " name)) + +;; 함수는 추가 인자를 리스트에 포장할 수 있다. +(define (count-args . args) + (format "You passed ~a args: ~a" (length args) args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" +;; ... 설탕 안 친 `lambda' 형식으로는: +(define count-args2 + (lambda args + (format "You passed ~a args: ~a" (length args) args))) + +;; 일반 인자와 포장된 인자를 섞을 수 있다. +(define (hello-count name . args) + (format "Hello ~a, you passed ~a extra args" name (length args))) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" +;; ... 설탕 안 친 것: +(define hello-count2 + (lambda (name . args) + (format "Hello ~a, you passed ~a extra args" name (length args)))) + +;; 키워드 인자 +(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) + (format "~a ~a, ~a extra args" g name (length args))) +(hello-k) ; => "Hello World, 0 extra args" +(hello-k 1 2 3) ; => "Hello World, 3 extra args" +(hello-k #:greeting "Hi") ; => "Hi World, 0 extra args" +(hello-k #:name "Finn" #:greeting "Hey") ; => "Hey Finn, 0 extra args" +(hello-k 1 2 3 #:greeting "Hi" #:name "Finn" 4 5 6) + ; => "Hi Finn, 6 extra args" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. 동등성 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 숫자에는 `='를 사용하시오. +(= 3 3.0) ; => #t +(= 2 1) ; => #f + +;; 개체의 동등성에는 `eq?'를 사용하시오. +(eq? 3 3) ; => #t +(eq? 3 3.0) ; => #f +(eq? (list 3) (list 3)) ; => #f + +;; 모음에는 `equal?'을 사용하시오. +(equal? (list 'a 'b) (list 'a 'b)) ; => #t +(equal? (list 'a 'b) (list 'b 'a)) ; => #f + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. 흐름 제어하기 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; 조건 + +(if #t ; 조사 식 + "this is true" ; 그러면 식 + "this is false") ; 아니면 식 +; => "this is true" + +;; 조건에서는 #f가 아니면 참으로 취급된다. +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(Groucho Zeppo) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'yep + +;; `cond'는 연속하여 조사하여 값을 선택한다. +(cond [(> 2 2) (error "wrong!")] + [(< 2 2) (error "wrong again!")] + [else 'ok]) ; => 'ok + +;;; 양식 맞춤 + +(define (fizzbuzz? n) + (match (list (remainder n 3) (remainder n 5)) + [(list 0 0) 'fizzbuzz] + [(list 0 _) 'fizz] + [(list _ 0) 'buzz] + [_ #f])) + +(fizzbuzz? 15) ; => 'fizzbuzz +(fizzbuzz? 37) ; => #f + +;;; 반복 + +;; 반복은 (꼬리-) 재귀로 한다. +(define (loop i) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) +(loop 5) ; => i=5, i=6, ... + +;; 이름 있는 let으로도... +(let loop ((i 0)) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) ; => i=0, i=1, ... + +;; Racket은 매우 유연한 `for' 형식을 가지고 있다: +(for ([i 10]) + (printf "i=~a\n" i)) ; => i=0, i=1, ... +(for ([i (in-range 5 10)]) + (printf "i=~a\n" i)) ; => i=5, i=6, ... + +;;; 다른 Sequence들을 순회하는 반복 +;; `for'는 여러 가지의 sequence를 순회할 수 있다: +;; 리스트, 벡터, 문자열, 집합, 해시 테이블 등... + +(for ([i (in-list '(l i s t))]) + (displayln i)) + +(for ([i (in-vector #(v e c t o r))]) + (displayln i)) + +(for ([i (in-string "string")]) + (displayln i)) + +(for ([i (in-set (set 'x 'y 'z))]) + (displayln i)) + +(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))]) + (printf "key:~a value:~a\n" k v)) + +;;; 더 복잡한 반복 + +;; 여러 sequence에 대한 병렬 순회 (가장 짧은 것 기준으로 중단) +(for ([i 10] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x 1:y 2:z + +;; 중첩 반복 +(for* ([i 2] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x, 0:y, 0:z, 1:x, 1:y, 1:z + +;; 조건 +(for ([i 1000] + #:when (> i 5) + #:unless (odd? i) + #:break (> i 10)) + (printf "i=~a\n" i)) +; => i=6, i=8, i=10 + +;;; 함축 +;; `for' 반복과 비슷하며, 결과만 수집한다. + +(for/list ([i '(1 2 3)]) + (add1 i)) ; => '(2 3 4) + +(for/list ([i '(1 2 3)] #:when (even? i)) + i) ; => '(2) + +(for/list ([i 10] [j '(x y z)]) + (list i j)) ; => '((0 x) (1 y) (2 z)) + +(for/list ([i 1000] #:when (> i 5) #:unless (odd? i) #:break (> i 10)) + i) ; => '(6 8 10) + +(for/hash ([i '(1 2 3)]) + (values i (number->string i))) +; => '#hash((1 . "1") (2 . "2") (3 . "3")) + +;; 반복의 값을 수집하는 여러 가지 방법이 있다: +(for/sum ([i 10]) (* i i)) ; => 285 +(for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000 +(for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t +(for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t +;; 임의의 조합을 사용하려면 `for/fold'를 사용: +(for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 +;; (이것은 명령형 반복문을 대체하기도 한다.) + +;;; 예외 + +;; 예외를 잡으려면 `with-handlers' 형식을 사용 +(with-handlers ([exn:fail? (lambda (exn) 999)]) + (+ 1 "2")) ; => 999 +(with-handlers ([exn:break? (lambda (exn) "no time")]) + (sleep 3) + "phew") ; => "phew", but if you break it => "no time" + +;; 예외나 다른 값을 던지려면 `raise'를 사용 +(with-handlers ([number? ; catch numeric values raised + identity]) ; return them as plain values + (+ 1 (raise 2))) ; => 2 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. 변경 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 기존 변수에 새 값을 할당하려면 `set!'을 사용한다. +(define n 5) +(set! n (add1 n)) +n ; => 6 + +;; 명시적인 가변 값을 사용하려면 box 사용 (다른 언어의 포인터나 참조와 비슷함) +(define n* (box 5)) +(set-box! n* (add1 (unbox n*))) +(unbox n*) ; => 6 + +;; 많은 Racket 자료형은 불변이다 (쌍, 리스트 등). 그러나 어떤 것들은 +;; 가변과 불변형이 둘 다 있다. (string, vector, hash table 등) + +;; `vector'나 `make-vector'로 가변 벡터를 생성한다. +(define vec (vector 2 2 3 4)) +(define wall (make-vector 100 'bottle-of-beer)) +;; 칸을 변경하려면 vector-set!을 사용한다. +(vector-set! vec 0 1) +(vector-set! wall 99 'down) +vec ; => #(1 2 3 4) + +;; 비어 있는 가변 해시 테이블을 만들고 조작한다. +(define m3 (make-hash)) +(hash-set! m3 'a 1) +(hash-set! m3 'b 2) +(hash-set! m3 'c 3) +(hash-ref m3 'a) ; => 1 +(hash-ref m3 'd 0) ; => 0 +(hash-remove! m3 'a) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. 모듈 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 모듈은 코드를 여러 파일과 재사용 가능한 라이브러리로 조직하게 한다. +;; 여기서 우리는 서브-모듈을 사용한다. 이 글이 만드는 전체 모듈("lang" 줄 부터 시작)에 포함된 모듈이다. + +(module cake racket/base ; racket/base 기반의 `cake' 모듈 정의 + + (provide print-cake) ; 모듈이 노출(export)시키는 함수 + + (define (print-cake n) + (show " ~a " n #\.) + (show " .-~a-. " n #\|) + (show " | ~a | " n #\space) + (show "---~a---" n #\-)) + + (define (show fmt n ch) ; 내부 함수 + (printf fmt (make-string n ch)) + (newline))) + +;; `require'를 사용하여 모듈에서 모든 `provide'된 이름을 사용한다. +(require 'cake) ; '는 지역 지역 서브-모듈을 위한 것이다. +(print-cake 3) +; (show "~a" 1 #\A) ; => 에러, `show'가 export되지 않았음 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. 클래스와 개체 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 클래스 fish%를 생성한다. (-%는 클래스 정의에 쓰이는 관용구) +(define fish% + (class object% + (init size) ; 초기화 인자 + (super-new) ; 상위 클래스 초기화 + ;; 필드 + (define current-size size) + ;; 공용 메서드 + (define/public (get-size) + current-size) + (define/public (grow amt) + (set! current-size (+ amt current-size))) + (define/public (eat other-fish) + (grow (send other-fish get-size))))) + +;; fish%의 인스턴스를 생성한다. +(define charlie + (new fish% [size 10])) + +;; 개체의 메서드를 호출하기 위해 `send'를 사용한다. +(send charlie get-size) ; => 10 +(send charlie grow 6) +(send charlie get-size) ; => 16 + +;; `fish%'는 보통의 "일급" 값이며, mixin을 줄 수 있다. +(define (add-color c%) + (class c% + (init color) + (super-new) + (define my-color color) + (define/public (get-color) my-color))) +(define colored-fish% (add-color fish%)) +(define charlie2 (new colored-fish% [size 10] [color 'red])) +(send charlie2 get-color) +;; 또는, 이름 없이: +(send (new (add-color fish%) [size 10] [color 'red]) get-color) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 9. 매크로 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 매크로는 언어의 문법을 확장할 수 있게 한다. + +;; while 반복문을 추가하자. +(define-syntax-rule (while condition body ...) + (let loop () + (when condition + body ... + (loop)))) + +(let ([i 0]) + (while (< i 10) + (displayln i) + (set! i (add1 i)))) + +;; 매크로는 위생적이다. 즉, 기존 변수를 침범할 수 없다. +(define-syntax-rule (swap! x y) ; -!는 변경의 관용구 + (let ([tmp x]) + (set! x y) + (set! y tmp))) + +(define tmp 2) +(define other 3) +(swap! tmp other) +(printf "tmp = ~a; other = ~a\n" tmp other) +;; `tmp` 변수는 이름 충돌을 피하기 위해 `tmp_1`로 이름이 변경된다. +;; (let ([tmp_1 tmp]) +;; (set! tmp other) +;; (set! other tmp_1)) + +;; 하지만 그것들은 단지 코드 변형일 뿐이다. 예를 들어: +(define-syntax-rule (bad-while condition body ...) + (when condition + body ... + (bad-while condition body ...))) +;; 이 매크로는 엉터리다: 무한 코드를 생성하며, +;; 이것을 사용하려고 하면 컴파일러가 무한 반복에 빠진다. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 10. 계약(Contract) +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; 계약은 모듈에서 노출된 값에 대해 제약을 부여한다. + +(module bank-account racket + (provide (contract-out + [deposit (-> positive? any)] ; 값은 양수여야 함 + [balance (-> positive?)])) + + (define amount 0) + (define (deposit a) (set! amount (+ amount a))) + (define (balance) amount) + ) + +(require 'bank-account) +(deposit 5) + +(balance) ; => 5 + +;; 양수가 아닌 값을 예치하려고 하는 고객은 비난받는다. +;; (deposit -5) ; => deposit: contract violation +;; expected: positive? +;; given: -5 +;; more details.... + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 11. 입력과 출력 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Racket은 이 "port"라는 개념이 있다. 이것은 다른 언어의 +;; 파일 서술자 (file descriptor)와 매우 비슷하다. + +;; "/tmp/tmp.txt"를 열고 "Hello World"를 기록한다. +;; 그 파일이 이미 있다면 에러를 발생시킨다. +(define out-port (open-output-file "/tmp/tmp.txt")) +(displayln "Hello World" out-port) +(close-output-port out-port) + +;; "/tmp/tmp.txt"에 붙이기 +(define out-port (open-output-file "/tmp/tmp.txt" + #:exists 'append)) +(displayln "Hola mundo" out-port) +(close-output-port out-port) + +;; 파일에서 다시 읽기 +(define in-port (open-input-file "/tmp/tmp.txt")) +(displayln (read-line in-port)) +; => "Hello World" +(displayln (read-line in-port)) +; => "Hola mundo" +(close-input-port in-port) + +;; 다르게, call-with-output-file을 사용하면, 명시적으로 파일을 닫지 않아도 된다. +(call-with-output-file "/tmp/tmp.txt" + #:exists 'update ; 내용을 다시 쓴다. + (λ (out-port) + (displayln "World Hello!" out-port))) + +;; call-with-input-file은 입력에 대해 같은 방식으로 작동한다. +(call-with-input-file "/tmp/tmp.txt" + (λ (in-port) + (displayln (read-line in-port)))) +``` + +## 더 읽을거리 + +더 배우고 싶으면, [Getting Started with Racket](http://docs.racket-lang.org/getting-started/)도 보시오. -- cgit v1.2.3 From 3a44e9de35fb336c860f1ecff2653b65f92fc8a2 Mon Sep 17 00:00:00 2001 From: KIM Taegyoon Date: Sat, 24 May 2014 18:36:25 +0900 Subject: filename fixed --- ko-kr/racket-kr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ko-kr/racket-kr.html.markdown b/ko-kr/racket-kr.html.markdown index f6056d4d..8d830279 100644 --- a/ko-kr/racket-kr.html.markdown +++ b/ko-kr/racket-kr.html.markdown @@ -1,7 +1,7 @@ --- language: racket -filename: learnracket.rkt +filename: learnracket-kr.rkt contributors: - ["th3rac25", "https://github.com/voila"] - ["Eli Barzilay", "https://github.com/elibarzilay"] -- cgit v1.2.3 From a8d8cee0d82a8f8be48f3a80c307223856764a31 Mon Sep 17 00:00:00 2001 From: e99n09 Date: Sat, 24 May 2014 08:54:39 -0400 Subject: Update r.html.markdown Minor changes to comments (fixing typos, etc.). Deleted "weird types" section; broke out "NULL" type into its own type category. Added instructions for dropping rows and columns in data.frame and data.table. How to make summary tables in data.table. --- r.html.markdown | 93 ++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 69 insertions(+), 24 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index dfc945c1..cd09e8da 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -188,7 +188,7 @@ class(-Inf) # "numeric" 10L + 66L # 76 # integer plus integer gives integer 53.2 - 4 # 49.2 # numeric minus numeric gives numeric 2.0 * 2L # 4 # numeric times integer gives numeric -3L / 4 # 0.75 # integer over integer gives numeric +3L / 4 # 0.75 # integer over numeric gives numeric 3 %% 2 # 1 # the remainder of two numerics is another numeric # Illegal arithmetic yeilds you a "not-a-number": 0 / 0 # NaN @@ -241,27 +241,29 @@ factor(c("female", "female", "male", "NA", "female")) # Levels: female male NA # The "levels" are the values the categorical data can take levels(factor(c("male", "male", "female", "NA", "female"))) # "female" "male" "NA" -# If a factor has length 1, its levels will have length 1, too +# If a factor vector has length 1, its levels will have length 1, too length(factor("male")) # 1 length(levels(factor("male"))) # 1 # Factors are commonly seen in data frames, a data structure we will cover later -# in this tutorial: data(infert) # "Infertility after Spontaneous and Induced Abortion" levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" -# WEIRD TYPES -# A quick summary of some of the weirder types in R -class(Inf) # "numeric" -class(-Inf) # "numeric" -class(NaN) # "numeric" -class(NA) # "logical" +# NULL +# "NULL" is a weird one; use it to "blank out" a vector class(NULL) # NULL +parakeet +# => +# [1] "beak" "feathers" "wings" "eyes" +parakeet <- NULL +parakeet +# => +# NULL # TYPE COERCION # Type-coercion is when you force a value to take on a different type as.character(c(6, 8)) # "6" "8" as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE -# If you put elements of different classes into a vector, weird coercions happen: +# If you put elements of different types into a vector, weird coercions happen: c(TRUE, 4) # 1 4 c("dog", TRUE, 4) # "dog" "TRUE" "4" as.numeric("Bilbo") @@ -332,8 +334,6 @@ jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 # ONE-DIMENSIONAL # Let's start from the very beginning, and with something you already know: vectors. -# As explained above, every single element in R is already a vector -# Make sure the elements of long vectors all have the same type vec <- c(8, 9, 10, 11) vec # 8 9 10 11 # We ask for specific elements by subsetting with square brackets @@ -345,9 +345,9 @@ month.name[9] # "September" c(6, 8, 7, 5, 3, 0, 9)[3] # 7 # We can also search for the indices of specific components, which(vec %% 2 == 0) # 1 3 -# grab just the first or last entry in the vector, +# grab just the first or last few entries in the vector, head(vec, 1) # 8 -tail(vec, 1) # 11 +tail(vec, w) # 10 11 # or figure out if a certain value is in the vector any(vec == 10) # TRUE # If an index "goes over" you'll get NA: @@ -358,7 +358,7 @@ length(vec) # 4 vec * 4 # 16 20 24 28 vec[2:3] * 5 # 25 30 any(vec[2:3] == 8) # FALSE -# and there are many built-in functions to summarize vectors +# and R has many built-in functions to summarize vectors mean(vec) # 9.5 var(vec) # 1.666667 sd(vec) # 1.290994 @@ -368,6 +368,7 @@ sum(vec) # 38 # Some more nice built-ins: 5:15 # 5 6 7 8 9 10 11 12 13 14 15 seq(from=0, to=31337, by=1337) +# => # [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 # [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 @@ -427,11 +428,11 @@ mat3 # [,1] [,2] [,3] [,4] # [1,] 1 2 4 5 # [2,] 6 7 0 4 -# Aah, everything of the same class. No coercions. Much better. +# Ah, everything of the same class. No coercions. Much better. # TWO-DIMENSIONAL (DIFFERENT CLASSES) -# For columns of different classes, use the data frame +# For columns of different types, use a data frame # This data structure is so useful for statistical programming, # a version of it was added to Python in the package "pandas". @@ -465,11 +466,11 @@ students$year # 3 2 2 1 0 -1 students[,2] # 3 2 2 1 0 -1 students[,"year"] # 3 2 2 1 0 -1 -# A popular replacement for the data.frame structure is the data.table +# An augmented version of the data.frame structure is the data.table # If you're working with huge or panel data, or need to merge a few data # sets, data.table can be a good choice. Here's a whirlwind tour: -install.packages("data.table") -require(data.table) +install.packages("data.table") # download the package from CRAN +require(data.table) # load it students <- as.data.table(students) students # note the slightly different print-out # => @@ -480,15 +481,17 @@ students # note the slightly different print-out # 4: Cho 1 R # 5: Draco 0 S # 6: Ginny -1 G -students[name=="Ginny"] +students[name=="Ginny"] # get rows with name == "Ginny" # => # name year house # 1: Ginny -1 G -students[year==2] +students[year==2] # get rows with year == 2 # => # name year house # 1: Fred 2 G # 2: George 2 G +# data.table makes merging two data sets easy +# let's make another data.table to merge with students founders <- data.table(house=c("G","H","R","S"), founder=c("Godric","Helga","Rowena","Salazar")) founders @@ -500,7 +503,7 @@ founders # 4: S Salazar setkey(students, house) setkey(founders, house) -students <- founders[students] # merge the two data sets +students <- founders[students] # merge the two data sets by matching "house" setnames(students, c("house","houseFounderName","studentName","year")) students[,order(c("name","year","house","houseFounderName")), with=F] # => @@ -512,9 +515,51 @@ students[,order(c("name","year","house","houseFounderName")), with=F] # 5: Cho 1 R Rowena # 6: Draco 0 S Salazar -# MULTI-DIMENSIONAL (ALL OF ONE CLASS) +# data.table makes summary tables easy +# => +# students[,sum(year),by=house] +# house V1 +# 1: G 3 +# 2: H 3 +# 3: R 1 +# 4: S 0 + +# To drop a column from a data.frame or data.table, +# assign it the NULL value +students$houseFounderName <- NULL +students +# => +# studentName year house +# 1: Fred 2 G +# 2: George 2 G +# 3: Ginny -1 G +# 4: Cedric 3 H +# 5: Cho 1 R +# 6: Draco 0 S + +# Drop a row by subsetting +# Using data.table: +students[studentName != "Draco"] +# => +# house studentName year +# 1: G Fred 2 +# 2: G George 2 +# 3: G Ginny -1 +# 4: H Cedric 3 +# 5: R Cho 1 +# Using data.frame: +students <- as.data.frame(students) +students[students$house != "G",] +# => +# house houseFounderName studentName year +# 4 H Helga Cedric 3 +# 5 R Rowena Cho 1 +# 6 S Salazar Draco 0 + +# MULTI-DIMENSIONAL (ALL ELEMENTS OF ONE TYPE) # Arrays creates n-dimensional tables +# All elements must be of the same type # You can make a two-dimensional table (sort of like a matrix) array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) # => -- cgit v1.2.3 From ae443092709b90594c86552645dffa1a767d12f0 Mon Sep 17 00:00:00 2001 From: e99n09 Date: Sat, 24 May 2014 13:11:07 -0400 Subject: Fix accidentally-commented-out line Un-commented a line that should have been executable. --- r.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/r.html.markdown b/r.html.markdown index cd09e8da..f6a62ae6 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -516,8 +516,8 @@ students[,order(c("name","year","house","houseFounderName")), with=F] # 6: Draco 0 S Salazar # data.table makes summary tables easy +students[,sum(year),by=house] # => -# students[,sum(year),by=house] # house V1 # 1: G 3 # 2: H 3 -- cgit v1.2.3 From 69140eb620d7f185f6b06976f3dc53d3ac3d03ef Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 26 May 2014 17:52:40 +0200 Subject: lisp -> scheme highlighting --- paren.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/paren.html.markdown b/paren.html.markdown index 778598ce..9fffaf93 100644 --- a/paren.html.markdown +++ b/paren.html.markdown @@ -10,7 +10,7 @@ contributors: Some examples are from http://learnxinyminutes.com/docs/racket/ . -```lisp +```scheme ;;; Comments # comments -- cgit v1.2.3 From 8eca57f470c272ca864d85b56ba66c67544d74bb Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 26 May 2014 18:04:02 +0200 Subject: link to racket --- paren.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/paren.html.markdown b/paren.html.markdown index 9fffaf93..cde14853 100644 --- a/paren.html.markdown +++ b/paren.html.markdown @@ -8,7 +8,7 @@ contributors: [Paren](https://bitbucket.org/ktg/paren) is a dialect of Lisp. It is designed to be an embedded language. -Some examples are from http://learnxinyminutes.com/docs/racket/ . +Some examples are from . ```scheme ;;; Comments -- cgit v1.2.3 From 4e6a111b6f08b8a11ccdf2cf236a48d50eefb1f4 Mon Sep 17 00:00:00 2001 From: discomethod Date: Mon, 26 May 2014 18:16:11 +0100 Subject: minor typo --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 81eb467d..4fa8deba 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -307,7 +307,7 @@ on a new line! ""Wow!"", the masses cried"; // try parse will default to type default on failure // in this case: 0 int tryInt; - if (int.TryParse("123", out tryInt)) // Funciton is boolean + if (int.TryParse("123", out tryInt)) // Function is boolean Console.WriteLine(tryInt); // 123 // Convert Integer To String -- cgit v1.2.3 From e8910da685f1195dc597b428dddb05925fb54c23 Mon Sep 17 00:00:00 2001 From: Nattaphoom Ch Date: Wed, 28 May 2014 01:06:24 +0700 Subject: Added missing semicolons and correct some words. --- c.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 0190125b..c89f2b88 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -154,7 +154,7 @@ int main() { int multi_array[2][5] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 0} - } + }; //access elements: int array_int = multi_array[0][2]; // => 3 @@ -215,7 +215,7 @@ int main() { z = (a > b) ? a : b; // => 10 "if a > b return a, else return b." //Increment and decrement operators: - char *s = "iLoveC" + char *s = "iLoveC"; int j = 0; s[j++]; // => "i". Returns the j-th item of s THEN increments value of j. j = 0; @@ -251,7 +251,7 @@ int main() { // While loops exist int ii = 0; while (ii < 10) { //ANY value not zero is true. - printf("%d, ", ii++); // ii++ increments ii AFTER using it's current value. + printf("%d, ", ii++); // ii++ increments ii AFTER using its current value. } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); @@ -259,7 +259,7 @@ int main() { int kk = 0; do { printf("%d, ", kk); - } while (++kk < 10); // ++kk increments kk BEFORE using it's current value. + } while (++kk < 10); // ++kk increments kk BEFORE using its current value. // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); @@ -367,7 +367,7 @@ int main() { // This works because arrays often decay into pointers to their first element. // For example, when an array is passed to a function or is assigned to a pointer, // it decays into (implicitly converted to) a pointer. - // Exceptions: when the array is the argument of the `&` (address-od) operator: + // Exceptions: when the array is the argument of the `&` (address-of) operator: int arr[10]; int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`! // It's of type "pointer to array" (of ten `int`s). @@ -387,7 +387,7 @@ int main() { // You can also dynamically allocate contiguous blocks of memory with the // standard library function malloc, which takes one argument of type size_t // representing the number of bytes to allocate (usually from the heap, although this - // may not be true on e. g. embedded systems - the C standard says nothing about it). + // may not be true on e.g. embedded systems - the C standard says nothing about it). int *my_ptr = malloc(sizeof(*my_ptr) * 20); for (xx = 0; xx < 20; xx++) { *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx @@ -405,7 +405,7 @@ int main() { // Strings are arrays of char, but they are usually represented as a // pointer-to-char (which is a pointer to the first element of the array). // It's good practice to use `const char *' when referring to a string literal, - // since string literals shall not be modified (i. e. "foo"[0] = 'a' is ILLEGAL.) + // since string literals shall not be modified (i.e. "foo"[0] = 'a' is ILLEGAL.) const char *my_str = "This is my very own string literal"; printf("%c\n", *my_str); // => 'T' -- cgit v1.2.3 From 101a75fcbc0b12b6ad7957d6fa721f8828635965 Mon Sep 17 00:00:00 2001 From: Antonio Lima Date: Thu, 29 May 2014 16:51:24 +0200 Subject: Minor typo --- r.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/r.html.markdown b/r.html.markdown index f6a62ae6..b59fc29c 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -347,7 +347,7 @@ c(6, 8, 7, 5, 3, 0, 9)[3] # 7 which(vec %% 2 == 0) # 1 3 # grab just the first or last few entries in the vector, head(vec, 1) # 8 -tail(vec, w) # 10 11 +tail(vec, 2) # 10 11 # or figure out if a certain value is in the vector any(vec == 10) # TRUE # If an index "goes over" you'll get NA: -- cgit v1.2.3 From b0eb92dd5560ebe6f893e2b6088629f1c38d528d Mon Sep 17 00:00:00 2001 From: niuzhist Date: Sat, 31 May 2014 01:15:30 -0700 Subject: JSON: Chinese translation --- zh-cn/json-cn.html.markdown | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 zh-cn/json-cn.html.markdown diff --git a/zh-cn/json-cn.html.markdown b/zh-cn/json-cn.html.markdown new file mode 100644 index 00000000..75966595 --- /dev/null +++ b/zh-cn/json-cn.html.markdown @@ -0,0 +1,51 @@ +--- +language: json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] +translators: + - ["Zach Zhang", "https://github.com/checkcheckzz"] +filename: learnjson-cn.json +lang: zh-cn +--- + +因为JSON是一个极其简单的数据交换形式,这个最有可能将会是曾经最简单 +的Learn X in Y Minutes。 + +最纯正形式的JSON没有实际的注解,但是大多数解析器将会 +接受C-风格(//, /\* \*/)的注解。为了这个目的,但是, +一切都将会是100%有效的JSON。幸亏,它是不言自明的。 + +```json +{ + "numbers": 0, + "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", + "has bools?": true, + "nothingness": null, + + "big number": 1.2e+100, + + "objects": { + "comment": "Most of your structure will come from objects.", + + "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], + + "another object": { + "comment": "These things can be nested, very useful." + } + }, + + "silliness": [ + { + "sources of potassium": ["bananas"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "that was short": "And, you're done. You know know everything JSON has to offer." +} +``` -- cgit v1.2.3 From 070df0635c70dd214fee43b522c2d55523c182f4 Mon Sep 17 00:00:00 2001 From: niuzhist Date: Sat, 31 May 2014 14:13:23 -0700 Subject: XML: Chinese translation --- xml.html.markdown | 10 ++-- zh-cn/xml-cn.html.markdown | 132 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 137 insertions(+), 5 deletions(-) create mode 100644 zh-cn/xml-cn.html.markdown diff --git a/xml.html.markdown b/xml.html.markdown index c072e0c7..1e1eff86 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -37,7 +37,7 @@ Unlike HTML, XML does not specifies how to display or to format data, just carry + That's what the parser will retrieve from the XML file. + Elements appear between the open and close tags, without parenthesis. --> @@ -64,7 +64,7 @@ Unlike HTML, XML does not specifies how to display or to format data, just carry * Well-Formated Document x Validation A XML document is well-formated if it is syntactically correct. -However, is possible to inject more constraints in the document, +However, it is possible to inject more constraints in the document, using document definitions, such as DTD and XML Schema. A XML document which follows a document definition is called valid, @@ -100,7 +100,7 @@ With this tool, you can check the XML data outside the application logic. diff --git a/zh-cn/xml-cn.html.markdown b/zh-cn/xml-cn.html.markdown new file mode 100644 index 00000000..0476a0a8 --- /dev/null +++ b/zh-cn/xml-cn.html.markdown @@ -0,0 +1,132 @@ +--- +language: xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Zach Zhang", "https://github.com/checkcheckzz"] +filename: learnxml-cn.xml +lang: zh-cn +--- + +XML是一种标记语言,被设计用来存储数据和传输数据。 + +不像HTML, XML不指定怎样显示或格式化数据,只是携带它。 + + +* XML 语法 + +```xml + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + + + + +computer.gif + + +``` + +* 良好格式的文件 x 验证 + +一个XML文件是良好格式的如果它是语法正确的。 +但是, 使用文件定义,比如DTD和XML概要,在文件中插入更多的限制是可能的。 + +一个遵守一个文件定义的XML文件被叫做有效的,对于那个文件来说。 + +有了这个工具,你能够在应用逻辑之外检查XML数据。 + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + + + +``` + + + -- cgit v1.2.3 From c93bb219f50b22105e51082824bdf0c98b3fc2b3 Mon Sep 17 00:00:00 2001 From: niuzhist Date: Sat, 31 May 2014 15:18:05 -0700 Subject: remove white space at the end of both xml files --- xml.html.markdown | 7 +------ zh-cn/xml-cn.html.markdown | 7 +------ 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/xml.html.markdown b/xml.html.markdown index 1e1eff86..94fc93f4 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -123,9 +123,4 @@ With this tool, you can check the XML data outside the application logic. 30.00 - - -``` - - - +``` \ No newline at end of file diff --git a/zh-cn/xml-cn.html.markdown b/zh-cn/xml-cn.html.markdown index 0476a0a8..bf0b074f 100644 --- a/zh-cn/xml-cn.html.markdown +++ b/zh-cn/xml-cn.html.markdown @@ -124,9 +124,4 @@ XML是一种标记语言,被设计用来存储数据和传输数据。 30.00 - - -``` - - - +``` \ No newline at end of file -- cgit v1.2.3 From e8b6055e103d03b62b2c09b04435ac8f0093d327 Mon Sep 17 00:00:00 2001 From: niuzhist Date: Sat, 31 May 2014 18:26:12 -0700 Subject: yaml: Chinese translation --- yaml.html.markdown | 4 +- zh-cn/yaml-cn.html.markdown | 136 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 zh-cn/yaml-cn.html.markdown diff --git a/yaml.html.markdown b/yaml.html.markdown index c5d15895..76e430e6 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -33,7 +33,7 @@ however: "A string, enclosed in quotes." "Keys can be quoted too.": "Useful if you want to put a ':' in your key." # Multiple-line strings can be written either as a 'literal block' (using |), -# or a 'folded block' (using '>') +# or a 'folded block' (using '>'). literal_block: | This entire block of text will be the value of the 'literal_block' key, with line breaks being preserved. @@ -66,7 +66,7 @@ a_nested_map: # Maps don't have to have string keys. 0.25: a float key -# Keys can also be multi-line objects, using ? to indicate the start of a key +# Keys can also be multi-line objects, using ? to indicate the start of a key. ? | This is a key that has multiple lines diff --git a/zh-cn/yaml-cn.html.markdown b/zh-cn/yaml-cn.html.markdown new file mode 100644 index 00000000..8370b224 --- /dev/null +++ b/zh-cn/yaml-cn.html.markdown @@ -0,0 +1,136 @@ +--- +language: yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Zach Zhang", "https://github.com/checkcheckzz"] +filename: learnyaml-cn.yaml +lang: zh-cn +--- + +YAMLһлԣƳֱӿдɶġ + +JSONϸ񳬼﷨зPythonPythonһ +YAMLƱ + + +```yaml +# YAMLеע⿴ + +################ +# # +################ + +# ǵĸ (ļ) һͼ +# ȼڱһֵ䣬 +key: value +another_key: Another value goes here. +a_number_value: 100 +scientific_notation: 1e+12 +boolean: true +null_value: null +key with spaces: value +# ע⵽ַҪáǣǿԱá +"Keys can be quoted too.": "Useful if you want to put a ':' in your key." + +# ַȿдһ'ֿ'(ʹ |) +# һ'۵'(ʹ '>') +literal_block: | + This entire block of text will be the value of the 'literal_block' key, + with line breaks being preserved. + + The literal continues until de-dented, and the leading indentation is + stripped. + + Any lines that are 'more-indented' keep the rest of their indentation - + these lines will be indented by 4 spaces. +folded_style: > + This entire block of text will be the value of 'folded_style', but this + time, all newlines will be replaced with a single space. + + Blank lines, like above, are converted to a newline character. + + 'More-indented' lines keep their newlines, too - + this text will appear over two lines. + +#################### +# # +#################### + +# Ƕͨɵġ +a_nested_map: + key: value + another_key: Another Value + another_nested_map: + hello: hello + +# ͼֵַ +0.25: a float key + +# ֵҲǶж?ֵĿʼ +? | + This is a key + that has multiple lines +: and this is its value + +# YAMLҲֵǼͣǺܶԽᱧԹ + +# (ȼڱ) +a_sequence: + - Item 1 + - Item 2 + - 0.5 # sequences can contain disparate types + - Item 4 + - key: value + another_key: another_value + - + - This is a sequence + - inside another sequence + +# ΪYAMLJSONijҲдJSONĵͼУ +json_map: {"key": "value"} +json_seq: [3, 2, 1, "takeoff"] + +####################### +# YAMLص # +####################### + +# YAMLһص'ê'򵥵ļظݡ +# ֵֵͬ +anchored_content: &anchor_name This string will appear as the value of two keys. +other_anchor: *anchor_name + +# YAMLбǩʾ͡ +explicit_string: !!str 0.5 +# һЩʵضԵıǩΪPythonĸ͡ +python_complex_number: !!python/complex 1+2j + +#################### +# YAML # +#################### + +# ֲַǽеYAMLı +# ISO ʽںʱҲǿԱġ +datetime: 2001-12-15T02:59:43.1Z +datetime_with_spaces: 2001-12-14 21:59:43.10 -5 +date: 2002-12-14 + +# !!binaryǩһַʵһblobbase64ʾ +gif_file: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAMLһͣ +set: + ? item1 + ? item2 + ? item3 + +# PythonһϽnullֵĵͼļϵȼڣ +set2: + item1: null + item2: null + item3: null +``` -- cgit v1.2.3 From 195735fd176b359f98450891ce00a233ccd585a8 Mon Sep 17 00:00:00 2001 From: niuzhist Date: Sat, 31 May 2014 18:34:05 -0700 Subject: fix encoding issue --- zh-cn/yaml-cn.html.markdown | 56 ++++++++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/zh-cn/yaml-cn.html.markdown b/zh-cn/yaml-cn.html.markdown index 8370b224..bcc41067 100644 --- a/zh-cn/yaml-cn.html.markdown +++ b/zh-cn/yaml-cn.html.markdown @@ -8,21 +8,21 @@ filename: learnyaml-cn.yaml lang: zh-cn --- -YAMLһлԣƳֱӿдɶġ +YAML是一个数据序列化语言,被设计成人类直接可写可读的。 -JSONϸ񳬼﷨зPythonPythonһ -YAMLƱ +它是JSON的严格超集,增加了语法显著换行符和缩进,就像Python。但和Python不一样, +YAML根本不容许文字制表符。 ```yaml -# YAMLеע⿴ +# YAML中的注解看起来像这样。 ################ -# # +# 标量类型 # ################ -# ǵĸ (ļ) һͼ -# ȼڱһֵ䣬 +# 我们的根对象 (它们在整个文件里延续) 将会是一个地图, +# 它等价于在别的语言里的一个字典,哈西表或对象。 key: value another_key: Another value goes here. a_number_value: 100 @@ -30,11 +30,11 @@ scientific_notation: 1e+12 boolean: true null_value: null key with spaces: value -# ע⵽ַҪáǣǿԱá +# 注意到字符串不需要被引用。但是,它们可以被引用。 "Keys can be quoted too.": "Useful if you want to put a ':' in your key." -# ַȿдһ'ֿ'(ʹ |) -# һ'۵'(ʹ '>') +# 多行字符串既可以写成像一个'文字块'(使用 |), +# 或像一个'折叠块'(使用 '>')。 literal_block: | This entire block of text will be the value of the 'literal_block' key, with line breaks being preserved. @@ -54,28 +54,28 @@ folded_style: > this text will appear over two lines. #################### -# # +# 集合类型 # #################### -# Ƕͨɵġ +# 嵌套是通过缩进完成的。 a_nested_map: key: value another_key: Another Value another_nested_map: hello: hello -# ͼֵַ +# 地图不用有字符串键值。 0.25: a float key -# ֵҲǶж?ֵĿʼ +# 键值也可以是多行对象,用?表明键值的开始。 ? | This is a key that has multiple lines : and this is its value -# YAMLҲֵǼͣǺܶԽᱧԹ +# YAML也容许键值是集合类型,但是很多语言将会抱怨。 -# (ȼڱ) +# 序列 (等价于表或数组) 看起来像这样: a_sequence: - Item 1 - Item 2 @@ -87,48 +87,48 @@ a_sequence: - This is a sequence - inside another sequence -# ΪYAMLJSONijҲдJSONĵͼУ +# 因为YAML是JSON的超集,你也可以写JSON风格的地图和序列: json_map: {"key": "value"} json_seq: [3, 2, 1, "takeoff"] ####################### -# YAMLص # +# 其余的YAML特点 # ####################### -# YAMLһص'ê'򵥵ļظݡ -# ֵֵͬ +# YAML还有一个方便的特点叫'锚',它让你简单地在整个文件里重复内容。 +# 两个键值将会有相同的值: anchored_content: &anchor_name This string will appear as the value of two keys. other_anchor: *anchor_name -# YAMLбǩʾ͡ +# YAML还有标签,你可以用它显示地声明类型。 explicit_string: !!str 0.5 -# һЩʵضԵıǩΪPythonĸ͡ +# 一些解析器实现特定语言的标签,就像这个为了Python的复数类型。 python_complex_number: !!python/complex 1+2j #################### -# YAML # +# 其余的YAML类型 # #################### -# ֲַǽеYAMLı -# ISO ʽںʱҲǿԱġ +# 字符串和数字不是仅有的YAML可以理解的标量。 +# ISO 格式的日期和日期时间文字也是可以被解析的。 datetime: 2001-12-15T02:59:43.1Z datetime_with_spaces: 2001-12-14 21:59:43.10 -5 date: 2002-12-14 -# !!binaryǩһַʵһblobbase64ʾ +# 这个!!binary标签表明一个字符串实际上是一个二进制blob的base64编码表示。 gif_file: !!binary | R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= -# YAMLһͣ +# YAML还有一个集合类型,它看起来像这样: set: ? item1 ? item2 ? item3 -# PythonһϽnullֵĵͼļϵȼڣ +# 像Python一样,集合仅是有null数值的地图;上面的集合等价于: set2: item1: null item2: null -- cgit v1.2.3 From 0b541e789fd2b3c54e0eb43d3102cfd3daea96d8 Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Sun, 1 Jun 2014 15:59:34 +0200 Subject: Start of initial translation: Go -> de-de. --- de-de/go-de.html.markdown | 306 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 306 insertions(+) create mode 100644 de-de/go-de.html.markdown diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown new file mode 100644 index 00000000..ab8769e5 --- /dev/null +++ b/de-de/go-de.html.markdown @@ -0,0 +1,306 @@ +--- +language: Go +filename: learngo-de.go +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 +der realen Welt zu lösen. + +Sie hat vertraute Elemente von imperativen Sprachen mit statisher 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. + +```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 +// einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek +// deklariert. +package main + +// Ein "import" wird verwendet um Packte zu deklarieren, die in dieser +// Quelldatei Anwendung finden. +import ( + "fmt" // Ein Packet in der Go standard Bibliothek + "net/http" // Ja, ein Webserver. + "strconv" // Zeichenkettenmanipulation +) + +// Es folgt die Definition einer Funktions, in diesem Fall von "main". Auch hier +// ist der Name wieder besonders. "main" markiert den Eintrittspunkt des +// 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. + fmt.Println("Hello world!") + + // Aufruf einer weiteren Funktion definiert innerhalb dieses Packets. + beyondHello() +} + +// Functions have parameters in parentheses. +// If there are no parameters, empty parentheses are still required. +func beyondHello() { + var x int // Variable declaration. Variables must be declared before use. + x = 3 // Variable assignment. + // "Short" declarations use := to infer the type, declare, and assign. + y := 4 + sum, prod := learnMultiple(x, y) // function returns two values + fmt.Println("sum:", sum, "prod:", prod) // simple output + learnTypes() // < y minutes, learn more! +} + +// Functions can have parameters and (multiple!) return values. +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // return two values +} + +// Some built-in types and literals. +func learnTypes() { + // Short declaration usually gives you what you want. + s := "Learn Go!" // string type + + s2 := `A "raw" string literal +can include line breaks.` // same string type + + // non-ASCII literal. Go source is UTF-8. + g := 'Σ' // rune type, an alias for uint32, holds a unicode code point + + f := 3.14195 // float64, an IEEE-754 64-bit floating point number + c := 3 + 4i // complex128, represented internally with two float64s + + // Var syntax with an initializers. + var u uint = 7 // unsigned, but implementation dependent size as with int + var pi float32 = 22. / 7 + + // Conversion syntax with a short declaration. + n := byte('\n') // byte is an alias for uint8 + + // Arrays have size fixed at compile time. + var a4 [4]int // an array of 4 ints, initialized to all 0 + a3 := [...]int{3, 1, 5} // an array of 3 ints, initialized as shown + + // Slices have dynamic size. Arrays and slices each have advantages + // but use cases for slices are much more common. + s3 := []int{4, 5, 9} // compare to a3. no ellipsis here + s4 := make([]int, 4) // allocates slice of 4 ints, initialized to all 0 + var d2 [][]float64 // declaration only, nothing allocated here + bs := []byte("a slice") // type conversion syntax + + p, q := learnMemory() // declares p, q to be type pointer to int. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + + // Maps are a dynamically growable associative array type, like the + // hash or dictionary types of some other languages. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // Unused variables are an error in Go. + // The underbar lets you "use" a variable but discard its value. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Output of course counts as using a variable. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // back in the flow +} + +// Go is fully garbage collected. It has pointers but no pointer arithmetic. +// You can make a mistake with a nil pointer, but not by incrementing a pointer. +func learnMemory() (p, q *int) { + // Named return values p and q have type pointer to int. + p = new(int) // built-in function new allocates memory. + // The allocated int is initialized to 0, p is no longer nil. + s := make([]int, 20) // allocate 20 ints as a single block of memory + s[3] = 7 // assign one of them + r := -2 // declare another local variable + return &s[3], &r // & takes the address of an object. +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // If statements require brace brackets, and do not require parens. + if true { + fmt.Println("told ya") + } + // Formatting is standardized by the command line command "go fmt." + if false { + // pout + } else { + // gloat + } + // Use switch in preference to chained if statements. + x := 1 + switch x { + case 0: + case 1: + // cases don't "fall through" + case 2: + // unreached + } + // Like if, for doesn't use parens either. + for x := 0; x < 3; x++ { // ++ is a statement + fmt.Println("iteration", x) + } + // x == 1 here. + + // For is the only loop statement in Go, but it has alternate forms. + for { // infinite loop + break // just kidding + continue // unreached + } + // As with for, := in an if statement means to declare and assign y first, + // then test y > x. + if y := expensiveComputation(); y > x { + x = y + } + // Function literals are closures. + xBig := func() bool { + return x > 100 // references x declared above switch statement. + } + fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x) + x /= 1e5 // this makes it == 10 + fmt.Println("xBig:", xBig()) // false now + + // When you need it, you'll love it. + goto love +love: + + learnInterfaces() // Good stuff coming up! +} + +// Define Stringer as an interface type with one method, String. +type Stringer interface { + String() string +} + +// Define pair as a struct with two fields, ints named x and y. +type pair struct { + x, y int +} + +// Define a method on type pair. Pair now implements Stringer. +func (p pair) String() string { // p is called the "receiver" + // Sprintf is another public function in package fmt. + // Dot syntax references fields of p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // Brace syntax is a "struct literal." It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. + p := pair{3, 4} + fmt.Println(p.String()) // call String method of p, of type pair. + var i Stringer // declare i of interface type Stringer. + i = p // valid because pair implements Stringer + // Call String method of i, of type Stringer. Output same as above. + fmt.Println(i.String()) + + // Functions in the fmt package call the String method to ask an object + // for a printable representation of itself. + fmt.Println(p) // output same as above. Println calls String method. + fmt.Println(i) // output same as above + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" idiom used to tell if something worked or not. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. + fmt.Println("no one there") + } else { + fmt.Print(x) // x would be the value, if it were in the map. + } + // An error value communicates not just "ok" but more about the problem. + if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value + // prints "strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // We'll revisit interfaces a little later. Meanwhile, + learnConcurrency() +} + +// c is a channel, a concurrency-safe communication object. +func inc(i int, c chan int) { + c <- i + 1 // <- is the "send" operator when a channel appears on the left. +} + +// We'll use inc to increment some numbers concurrently. +func learnConcurrency() { + // Same make function used earlier to make a slice. Make allocates and + // initializes slices, maps, and channels. + c := make(chan int) + // Start three concurrent goroutines. Numbers will be incremented + // concurrently, perhaps in parallel if the machine is capable and + // properly configured. All three send to the same channel. + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) + // Read three results from the channel and print them out. + // There is no telling in what order the results will arrive! + fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. + + cs := make(chan string) // another channel, this one handles strings. + cc := make(chan chan string) // a channel of string channels. + go func() { c <- 84 }() // start a new goroutine just to send a value + go func() { cs <- "wordy" }() // again, for cs this time + // Select has syntax like a switch statement but each case involves + // a channel operation. It selects a case at random out of the cases + // that are ready to communicate. + select { + case i := <-c: // the value received can be assigned to a variable + fmt.Printf("it's a %T", i) + case <-cs: // or the value received can be discarded + fmt.Println("it's a string") + case <-cc: // empty channel, not ready for communication. + fmt.Println("didn't happen.") + } + // At this point a value was taken from either c or cs. One of the two + // goroutines started above has completed, the other will remain blocked. + + learnWebProgramming() // Go does it. You want to do it too. +} + +// A single function from package http starts a web server. +func learnWebProgramming() { + // ListenAndServe first parameter is TCP address to listen at. + // Second parameter is an interface, specifically http.Handler. + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // don't ignore errors +} + +// Make pair an http.Handler by implementing its only method, ServeHTTP. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Serve data with a method of http.ResponseWriter + w.Write([]byte("You learned Go in Y minutes!")) +} +``` + +## Further Reading + +The root of all things Go is the [official Go web site](http://golang.org/). +There you can follow the tutorial, play interactively, and read lots. + +The language definition itself is highly recommended. It's easy to read +and amazingly short (as language definitions go these days.) + +On the reading list for students of Go is the [source code to the standard +library](http://golang.org/src/pkg/). Comprehensively documented, it +demonstrates the best of readable and understandable Go, Go style, and Go +idioms. Or you can click on a function name in [the +documentation](http://golang.org/pkg/) and the source code comes up! + -- cgit v1.2.3 From ccdffbe0ca8d18c240df879e1236ef240799db2a Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Sun, 1 Jun 2014 16:09:06 +0200 Subject: Translation of next 2 functions. --- de-de/go-de.html.markdown | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index ab8769e5..b59378a1 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -39,7 +39,7 @@ import ( // Es folgt die Definition einer Funktions, in diesem Fall von "main". Auch hier // ist der Name wieder besonders. "main" markiert den Eintrittspunkt des -// Programms. Vergessen sie nicht die geschweiften Klammern! +// 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. @@ -49,14 +49,17 @@ func main() { beyondHello() } -// Functions have parameters in parentheses. -// If there are no parameters, empty parentheses are still required. +// Funktionen können Parameter akzeptieren, diese werden in Klammern deklariert, +// die aber auch bei keinen Parametern erforderlich sind. func beyondHello() { - var x int // Variable declaration. Variables must be declared before use. - x = 3 // Variable assignment. - // "Short" declarations use := to infer the type, declare, and assign. + var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. + x = 3 // Zuweisung eines Werts. + // Kurze Deklaration: Benutzen Sie ":=" um die Typisierung automatisch zu + // folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen. y := 4 - sum, prod := learnMultiple(x, y) // function returns two values + + // Eine Funktion mit mehreren Rückgabewerten. + sum, prod := learnMultiple(x, y) fmt.Println("sum:", sum, "prod:", prod) // simple output learnTypes() // < y minutes, learn more! } -- cgit v1.2.3 From f3387dc621edbd3ce309969fbdd437ae91f4395b Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Sun, 1 Jun 2014 16:25:30 +0200 Subject: Translated function: learnTypes() --- de-de/go-de.html.markdown | 73 ++++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index b59378a1..5edcb958 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -60,62 +60,63 @@ func beyondHello() { // Eine Funktion mit mehreren Rückgabewerten. sum, prod := learnMultiple(x, y) - fmt.Println("sum:", sum, "prod:", prod) // simple output - learnTypes() // < y minutes, learn more! + + fmt.Println("sum:", sum, "prod:", prod) // Simple Ausgabe + learnTypes() // In < y Minuten lernen Sie mehr! } -// Functions can have parameters and (multiple!) return values. +// Funktionen können mehrere Parameter und (mehrere!) Rückgabewerte haben. func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // return two values + return x + y, x * y // Wiedergabe zweier Werte } -// Some built-in types and literals. +// Überblick ueber einige eingebaute Typen und Literale. func learnTypes() { - // Short declaration usually gives you what you want. - s := "Learn Go!" // string type + // Kurze Deklarationen sind die Norm. + s := "Lernen Sie Go!" // Zeichenketten-Typ - s2 := `A "raw" string literal -can include line breaks.` // same string type + s2 := `Eine "raw" Zeichenkette kann +Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ - // non-ASCII literal. Go source is UTF-8. - g := 'Σ' // rune type, an alias for uint32, holds a unicode code point + // nicht-ASCII Literal. Go Quelltext ist UTF-8 kompatibel. + g := 'Σ' // Ein Runen-Typ, alias uint32, gebraucht für unicode code points. - f := 3.14195 // float64, an IEEE-754 64-bit floating point number - c := 3 + 4i // complex128, represented internally with two float64s + f := 3.14195 // float64, eine IEEE-754 64-bit Dezimalzahl + c := 3 + 4i // complex128, besteht intern aus zwei float64-er - // Var syntax with an initializers. - var u uint = 7 // unsigned, but implementation dependent size as with int + // "var"-Syntax mit Initalwert + var u uint = 7 // Vorzeichenlos, aber die Größe ist implementationsabhängig var pi float32 = 22. / 7 - // Conversion syntax with a short declaration. - n := byte('\n') // byte is an alias for uint8 + // Umwandlungs-Syntax mit kurzer Deklaration + n := byte('\n') // byte ist ein Alias für uint8 - // Arrays have size fixed at compile time. - var a4 [4]int // an array of 4 ints, initialized to all 0 - a3 := [...]int{3, 1, 5} // an array of 3 ints, initialized as shown + // Arrays haben bei Kompile-Zeit festgelegte Größen + var a4 [4]int // Ein Array mit 4 ints, alle mit Initialwert 0 + a3 := [...]int{3, 1, 5} // Ein Array mit 4 ints, Initialwerte wie angezeigt - // Slices have dynamic size. Arrays and slices each have advantages - // but use cases for slices are much more common. - s3 := []int{4, 5, 9} // compare to a3. no ellipsis here - s4 := make([]int, 4) // allocates slice of 4 ints, initialized to all 0 - var d2 [][]float64 // declaration only, nothing allocated here - bs := []byte("a slice") // type conversion syntax + // "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre + // Vorzüge, aber slices werden viel häufiger verwendet + s3 := []int{4, 5, 9} // Vergleichen Sie mit a3, hier: keine Ellipse + s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Initialwert 0 + var d2 [][]float64 // Nur eine Deklaration, keine Speicherzuweisung + bs := []byte("eine slice") // Umwandlungs-Syntax - p, q := learnMemory() // declares p, q to be type pointer to int. - fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + p, q := learnMemory() // Deklariert p & q als Zeiger zu einer int. + fmt.Println(*p, *q) // Die gibt die zwei Werte aus. "*" für den Zugriff - // Maps are a dynamically growable associative array type, like the - // hash or dictionary types of some other languages. - m := map[string]int{"three": 3, "four": 4} - m["one"] = 1 + // "Maps" sind dynamische Datenstrukturen mit variabler Größe. Sie sind wie + // "hashs" oder "dictionaries" aus anderen Sprachen. + m := map[string]int{"drei": 3, "vier": 4} + m["eins"] = 1 - // Unused variables are an error in Go. - // The underbar lets you "use" a variable but discard its value. + // Ungebrauchte Variablen sind Fehler in Go + // Der Unterstrich wird verwendet um einen Wert zu verwerfen. _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs - // Output of course counts as using a variable. + // Die Ausgabe zählt natürlich auch als Gebrauch fmt.Println(s, c, a4, s3, d2, m) - learnFlowControl() // back in the flow + learnFlowControl() // Auf zum Kontrollfluss! } // Go is fully garbage collected. It has pointers but no pointer arithmetic. -- cgit v1.2.3 From 23b6e66f8b261d0439cadd7af87c8010f3231437 Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Sun, 1 Jun 2014 16:31:07 +0200 Subject: Translated function: learnMemory() --- de-de/go-de.html.markdown | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 5edcb958..6c285e89 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -119,16 +119,17 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ learnFlowControl() // Auf zum Kontrollfluss! } -// Go is fully garbage collected. It has pointers but no pointer arithmetic. -// You can make a mistake with a nil pointer, but not by incrementing a pointer. +// Go ist komplett "garbage collected". Sie unterstützt Zeiger (pointers) aber +// keine Zeiger-Rechnungen. Fehler können sich durch "nil" einschleichen, jedoch +// nicht durch erhöhen eines Zeigers. func learnMemory() (p, q *int) { - // Named return values p and q have type pointer to int. - p = new(int) // built-in function new allocates memory. - // The allocated int is initialized to 0, p is no longer nil. - s := make([]int, 20) // allocate 20 ints as a single block of memory - s[3] = 7 // assign one of them - r := -2 // declare another local variable - return &s[3], &r // & takes the address of an object. + // Die bennanten Rückgabewerte p & q sind vom Typ *int + p = new(int) // Eingebaute Funktion "new" weist neuen Speicherplatz zu + // Der zugewiesene Speicher ist mit 0 initialisiert, p ist nicht länger nil + s := make([]int, 20) // So weist man 20 ints nebeneinander (im Speicher) zu + s[3] = 7 // Einer von ihnen wird ein Wert zugewiesen + r := -2 // Deklaration einer weiteren lokalen Variable + return &s[3], &r // & gibt die Addresse einer Variable } func expensiveComputation() int { -- cgit v1.2.3 From 67e28c96b914a81ff355ad215b27cfec4d48a142 Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Sun, 1 Jun 2014 16:41:17 +0200 Subject: Translated function: learnControlFlow() --- de-de/go-de.html.markdown | 53 +++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 6c285e89..d4bc06cc 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -137,54 +137,57 @@ func expensiveComputation() int { } func learnFlowControl() { - // If statements require brace brackets, and do not require parens. + // Bedingte Anweisungen verlangen nach geschweiften Klammern, normale + // Klammern um die Bedingung werden aber nicht gebraucht. if true { - fmt.Println("told ya") + fmt.Println("hab's dir ja gesagt!") } - // Formatting is standardized by the command line command "go fmt." + // Die Formattierung ist durch den Befehl "go fmt" standardisiert if false { - // pout + // nicht hier } else { - // gloat + // sonder hier! spielt die Musik } - // Use switch in preference to chained if statements. + + // Benutzen Sie ein "switch" Statement anstatt eine Anreihung von if-s x := 1 switch x { case 0: case 1: - // cases don't "fall through" + // Einzelne Fälle fallen nicht zum nächsten durch! case 2: - // unreached + // wird nicht ausgeführt } - // Like if, for doesn't use parens either. - for x := 0; x < 3; x++ { // ++ is a statement - fmt.Println("iteration", x) + // Wie bei "if", braucht "for" auch keine Klammern um die Bedingung + for x := 0; x < 3; x++ { // ++ ist ein Statement + fmt.Println(x, "-te Iteration") } - // x == 1 here. + // Ab hier gilt wieder: x == 1 - // For is the only loop statement in Go, but it has alternate forms. - for { // infinite loop - break // just kidding - continue // unreached + // For ist die einzige Schleifenform in Go, sie hat aber mehrere Formen: + for { // Endloschleife + break // nur ein Spaß + continue // wird nie ausgeführt } - // As with for, := in an if statement means to declare and assign y first, - // then test y > x. + + // 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 } - // Function literals are closures. + // Funktionsliterale sind "closures" xBig := func() bool { - return x > 100 // references x declared above switch statement. + return x > 100 // Verweist auf x, deklariert vor dem switch } - fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x) - x /= 1e5 // this makes it == 10 - fmt.Println("xBig:", xBig()) // false now + fmt.Println("xBig:", xBig()) // true (im moment gilt: x == 1e6) + x /= 1e5 // dies macht x == 10 + fmt.Println("xBig:", xBig()) // jetzt: false - // When you need it, you'll love it. + // Wenn Sie's brauchen, werden Sie's lieben! goto love love: - learnInterfaces() // Good stuff coming up! + learnInterfaces() // Jetzt zum interessanten Teil! } // Define Stringer as an interface type with one method, String. -- cgit v1.2.3 From 5a174230a3f191fa45938be49bde9c3be8c92ca8 Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Sun, 1 Jun 2014 16:48:58 +0200 Subject: Translated function: learnInterfaces() --- de-de/go-de.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index d4bc06cc..d94ce3d2 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -190,37 +190,37 @@ love: learnInterfaces() // Jetzt zum interessanten Teil! } -// Define Stringer as an interface type with one method, String. +// Definiere "Stringer" als ein Interface mit einer Methode: String type Stringer interface { String() string } -// Define pair as a struct with two fields, ints named x and y. +// Definiere ein Paar als struct mit zwei Feldern, Integers mit Namen x & y. type pair struct { x, y int } -// Define a method on type pair. Pair now implements Stringer. -func (p pair) String() string { // p is called the "receiver" - // Sprintf is another public function in package fmt. - // Dot syntax references fields of p. +// Definiere eine Methode von "pair". Dieser Typ erfüllt jetzt das Stringer interface. +func (p pair) String() string { // p ist der Empfänger + // Sprintf ist eine weitere öffentliche Funktion von fmt. + // Der Syntax mit Punkt greift auf die Felder zu. return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { - // Brace syntax is a "struct literal." It evaluates to an initialized - // struct. The := syntax declares and initializes p to this struct. + // Der Klammer-Syntax ist ein "struct literal". Es ist ein vollkommen + // initialisiertes struct. Der := Syntax deklariert und initialisiert p. p := pair{3, 4} - fmt.Println(p.String()) // call String method of p, of type pair. - var i Stringer // declare i of interface type Stringer. - i = p // valid because pair implements Stringer - // Call String method of i, of type Stringer. Output same as above. + fmt.Println(p.String()) // Aufruf der String() Methode von p. + var i Stringer // Deklariere i vom Typ: Stringer + i = p // Ok, weil p auch vom Typ Stringer ist. + // Aufruf der String Methode von i, gleiche Ausgabe wie zuvor. fmt.Println(i.String()) - // Functions in the fmt package call the String method to ask an object - // for a printable representation of itself. - fmt.Println(p) // output same as above. Println calls String method. - fmt.Println(i) // output same as above + // Funktionen des fmt-Packets 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 learnErrorHandling() } -- cgit v1.2.3 From 2b1e58f22cb7a932c478d1ee2bfe8fd5afa812d3 Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Sun, 1 Jun 2014 16:52:53 +0200 Subject: Translated function: learnErrorHandling() --- de-de/go-de.html.markdown | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index d94ce3d2..d3f35c1f 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -226,19 +226,21 @@ func learnInterfaces() { } func learnErrorHandling() { - // ", ok" idiom used to tell if something worked or not. - m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. - fmt.Println("no one there") + // Das ", ok" Idiom wird häufig verwendet um zu überprüfen ob etwas schief + // gegangen ist. + m := map[int]string{3: "drei", 4: "vier"} + if x, ok := m[1]; !ok { // ok wird false sein, da 1 nicht in der map ist. + fmt.Println("keine eins gefunden") } else { - fmt.Print(x) // x would be the value, if it were in the map. + fmt.Print(x) // x wäre der Wert, wenn er in der map wäre. } - // An error value communicates not just "ok" but more about the problem. - if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value - // prints "strconv.ParseInt: parsing "non-int": invalid syntax" + // Ein Fehler-Wert (error value) gibt mehr Informationen über den Grund für + // das Problem an. + if _, err := strconv.Atoi("nicht-int"); err != nil { // _ verwirft den Wert + // Gibt: "strconv.ParseInt: parsing "nicht-int": invalid syntax" aus fmt.Println(err) } - // We'll revisit interfaces a little later. Meanwhile, + // Wir kommen bald nochmal auf Interfaces zurück. Aber inzwischen: learnConcurrency() } -- cgit v1.2.3 From 4f61f9b851fa3640d6336c7735abb3f928e4bb50 Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Sun, 1 Jun 2014 17:08:20 +0200 Subject: Translated function: learnConcurrency() --- de-de/go-de.html.markdown | 60 ++++++++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index d3f35c1f..d701a46e 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -244,45 +244,47 @@ func learnErrorHandling() { learnConcurrency() } -// c is a channel, a concurrency-safe communication object. +// c ist ein Kannal, ein sicheres Kommunikationsmedium. func inc(i int, c chan int) { - c <- i + 1 // <- is the "send" operator when a channel appears on the left. + c <- i + 1 // <- ist der "send" Operator, wenn ein Kannal auf der Linken ist } -// We'll use inc to increment some numbers concurrently. +// Wir verwenden "inc" um Zahlen parallel zu erhöhen. func learnConcurrency() { - // Same make function used earlier to make a slice. Make allocates and - // initializes slices, maps, and channels. + // Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für + // maps, slices und Kannäle. c := make(chan int) - // Start three concurrent goroutines. Numbers will be incremented - // concurrently, perhaps in parallel if the machine is capable and - // properly configured. All three send to the same channel. - go inc(0, c) // go is a statement that starts a new goroutine. + // Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently) + // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kannal. + go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine go inc(10, c) go inc(-805, c) - // Read three results from the channel and print them out. - // There is no telling in what order the results will arrive! - fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. - - cs := make(chan string) // another channel, this one handles strings. - cc := make(chan chan string) // a channel of string channels. - go func() { c <- 84 }() // start a new goroutine just to send a value - go func() { cs <- "wordy" }() // again, for cs this time - // Select has syntax like a switch statement but each case involves - // a channel operation. It selects a case at random out of the cases - // that are ready to communicate. + // Auslesen und dann Ausgeben der drei berechneten Werte. + // Man kann nicht im voraus feststellen in welcher Reihenfolge die Werte + // ankommen. + fmt.Println(<-c, <-c, <-c) // mit dem Kannal rechts ist <- der Empfangs-Operator + + cs := make(chan string) // ein weiterer Kannal, diesmal für strings + cc := make(chan chan string) // ein Kannal für string Kannäle + + // Start einer neuen Goroutine, nur um einen Wert zu senden + go func() { c <- 84 }() + go func() { cs <- "wortreich" }() // schon wider, 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. select { - case i := <-c: // the value received can be assigned to a variable - fmt.Printf("it's a %T", i) - case <-cs: // or the value received can be discarded - fmt.Println("it's a string") - case <-cc: // empty channel, not ready for communication. - fmt.Println("didn't happen.") + 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 + fmt.Println("wird nicht passieren.") } - // At this point a value was taken from either c or cs. One of the two - // goroutines started above has completed, the other will remain blocked. + // Hier wird eine der beiden Goroutines fertig sein, die andere nicht. + // Sie wird warten bis der Wert den sie sendet von dem Kannal gelesen wird. - learnWebProgramming() // Go does it. You want to do it too. + learnWebProgramming() // Go kann es und Sie hoffentlich auch bald. } // A single function from package http starts a web server. -- cgit v1.2.3 From b351f1896fccda1e1a3ff324f862ff5f988f3575 Mon Sep 17 00:00:00 2001 From: Joseph Adams Date: Sun, 1 Jun 2014 17:19:55 +0200 Subject: Added rest of translation. --- de-de/go-de.html.markdown | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index d701a46e..8c2f58dd 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -287,32 +287,32 @@ func learnConcurrency() { learnWebProgramming() // Go kann es und Sie hoffentlich auch bald. } -// A single function from package http starts a web server. +// Eine einzige Funktion aus dem http-Packet kann einen Webserver starten. func learnWebProgramming() { - // ListenAndServe first parameter is TCP address to listen at. - // Second parameter is an interface, specifically http.Handler. + // 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) // don't ignore errors + fmt.Println(err) // Fehler sollte man nicht ignorieren! } -// Make pair an http.Handler by implementing its only method, ServeHTTP. +// 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) { - // Serve data with a method of http.ResponseWriter - w.Write([]byte("You learned Go in Y minutes!")) + // Senden von Daten mit einer Methode des http.ResponseWriter + w.Write([]byte("Sie habe Go in Y Minuten gelernt!")) } ``` -## Further Reading - -The root of all things Go is the [official Go web site](http://golang.org/). -There you can follow the tutorial, play interactively, and read lots. - -The language definition itself is highly recommended. It's easy to read -and amazingly short (as language definitions go these days.) - -On the reading list for students of Go is the [source code to the standard -library](http://golang.org/src/pkg/). Comprehensively documented, it -demonstrates the best of readable and understandable Go, Go style, and Go -idioms. Or you can click on a function name in [the -documentation](http://golang.org/pkg/) and the source code comes up! +## Weitere Resourcen +Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/). +Dort können sie der Tutorial folgen, interaktiv Quelltext ausprobieren und viel +Dokumentation lesen. + +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/). -- cgit v1.2.3 From 24cffa75360ac915f61369ebaf0db34d6b7fc0e1 Mon Sep 17 00:00:00 2001 From: niuzhist Date: Sun, 1 Jun 2014 09:39:22 -0700 Subject: [yaml/cn]: add last translation --- yaml.html.markdown | 2 +- zh-cn/yaml-cn.html.markdown | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/yaml.html.markdown b/yaml.html.markdown index 76e430e6..6e3e2c94 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -79,7 +79,7 @@ a_nested_map: a_sequence: - Item 1 - Item 2 - - 0.5 # sequences can contain disparate types + - 0.5 # sequences can contain disparate types. - Item 4 - key: value another_key: another_value diff --git a/zh-cn/yaml-cn.html.markdown b/zh-cn/yaml-cn.html.markdown index bcc41067..fc510eb5 100644 --- a/zh-cn/yaml-cn.html.markdown +++ b/zh-cn/yaml-cn.html.markdown @@ -79,7 +79,7 @@ a_nested_map: a_sequence: - Item 1 - Item 2 - - 0.5 # sequences can contain disparate types + - 0.5 # 序列可以包含不同类型。 - Item 4 - key: value another_key: another_value -- cgit v1.2.3 From befd5b66aaa5f67c51e623352b8d9de6630c1855 Mon Sep 17 00:00:00 2001 From: ins429 Date: Sun, 1 Jun 2014 16:25:55 -0700 Subject: [go/ko-kr] add missing translations --- ko-kr/go-kr.html.markdown | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown index e6ebe097..e4eaee56 100644 --- a/ko-kr/go-kr.html.markdown +++ b/ko-kr/go-kr.html.markdown @@ -5,8 +5,12 @@ language: Go filename: learngo-kr.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"] translators: - ["Jongmin Kim", "http://github.com/atomaths"] + - ["Peter Lee", "http://github.com/ins429"] lang: ko-kr --- @@ -184,9 +188,20 @@ func learnFlowControl() { goto love love: + learnDefer() // defer에 대해 learnInterfaces() // 곧이어서 좋은 기능에 대한 설명이 나올 거다. } +func learnDefer() (ok bool) { + // deferred statements are executed just before the function returns. + // 연기된(deferred) 구문은 함수가 리턴하기 직전에 실행된다. + defer fmt.Println("deferred statements execute in reverse (LIFO) order.") // 연기된 구문은 LIFO순으로 실행된다. + defer fmt.Println("\nThis line is being printed first because") // 이 줄이 먼저 실행된다. + // defer는 주로 파일을 닫는데 사용된다. + // 파일을 닫는함수를 파일을 여는함수에 가까이 둘수 있다. + return true +} + // String 이라는 메서드 하나를 가진 Stringer 라는 인터페이스 타입을 정의하자. type Stringer interface { String() string @@ -220,6 +235,21 @@ func learnInterfaces() { fmt.Println(p) // 결과는 위와 같다. Println은 String 메서드를 호출한다. fmt.Println(i) // 결과는 위와 같다. + learnVariadicParams("great", "learning", "here!") +} + +// 함수는 가변 인수(variadic) 파라미터를 가질수 있다. +func learnVariadicParams(myStrings ...interface{}) { + // 가변 인수를 차례로 반복한다. + // 여기서 언더바(언더스코어, `_`)는 배열의 인덱스 인수를 무시한다. + // The underbar here is ignoring the index argument of the array. + for _, param := range myStrings { + fmt.Println("param:", param) + } + + // 가변 인수 값을 가변인수 파라미터로 보내기. + fmt.Println("params:", fmt.Sprintln(myStrings...)) + learnErrorHandling() } @@ -312,3 +342,5 @@ Go 소스코드에 대해 좀더 알아보고 싶다면 [Go 표준 라이브러 분석해보기 바란다. 이해하기 쉽게 문서화되어 있고, Go 스타일 그리고 Go에서의 관례 배우기에 가장 좋은 방법일 것이다. 또는 [문서](http://golang.org/pkg/) 안에서 함수 이름 하나를 클릭해보면 소스코드를 브라우저에서 살펴볼 수도 있다. + +Go를 배울수 있는 또하나의 좋은 방법은 [Go by example](https://gobyexample.com/). -- cgit v1.2.3 From 5d5fbc79a9cf72adbd1ade419f69a3e55f74c268 Mon Sep 17 00:00:00 2001 From: Joao Farias Date: Mon, 2 Jun 2014 16:44:13 -0300 Subject: Translating C to PT-BR --- pt-br/c-pt.html.markdown | 649 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 649 insertions(+) create mode 100644 pt-br/c-pt.html.markdown diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown new file mode 100644 index 00000000..451df4f3 --- /dev/null +++ b/pt-br/c-pt.html.markdown @@ -0,0 +1,649 @@ +--- +language: c +filename: learnc.c +contributors: + - ["Adam Bard", "http://adambard.com/"] + - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] +translators: + - ["João Farias", "https://github.com/JoaoGFarias"] +lang: pt-br +filename: c-pt.el +--- + +Ah, C. Ainda é **a** linguagem de computação de alta performance. + +C é a liguangem de mais baixo nível que a maioria dos programadores +irão usar, e isso dá a ela uma grande velocidade bruta. Apenas fique +antento que este manual de gerenciamento de memória e C vai levanter-te +tão longe quanto você precisa. + +```c +// Comentários de uma linha iniciam-se com // - apenas disponível a partir do C99 + +/* +Comentários de multiplas linhas se parecem com este. +Funcionam no C89 também. +*/ + +// Constantes: #define +#definie DAY_IN_YEAR 365 + +//enumarações também são modos de definir constantes. +enum day {DOM = 1, SEG, TER, QUA, QUI, SEX, SAB}; +// SEG recebe 2 automaticamente, TER recebe 3, etc. + +// Cabeçalhos são inclusos com #include +#include +#include +#include + +// (Nomes dos arquivos entre são cabeçalhos para bibliotecas padrão de C.) +// Para cabeçalhos próprios, use aspas ao invés de colchetes: +#include "minha_biblioteca.h" + +// Declare assinaturas das funções no início do arquivo .h ou no topo +// do seu arquivo .c. +void funcao_1(char c); +int funcao_2(void); + +// Deve-se declarar um 'protótipo de função' antes do main() quando as ocorrências +// dessas funções estão após sua função main() +int soma_dois_ints(int x1, int x2); // protótipo de função + +// O ponto de entrada do teu programa é uma função +// chamada main, com tipo de retorno inteiro +int main() { + // Usa-se printf para escrever na tela, + // para "saída formatada" + // %d é um inteiro, \n é uma nova linha + printf("%d\n", 0); // => Imprime 0 + // Todos as declarações devem acabar com + // ponto e vírgula + + /////////////////////////////////////// + // Tipos + /////////////////////////////////////// + + // ints normalmente tem 4 bytes + int x_int = 0; + + // shorts normalmente tem 2 bytes + short x_short = 0; + + // chars sempre tem um byte + char x_char = 0; + char y_char = 'y'; // Literais de caracter são cercados por ' + + // longs tem entre 4 e 8 bytes; longs long tem garantia + // de ter pelo menos 64 bits + long x_long = 0; + long long x_long_long = 0; + + // floats são normalmente números de ponto flutuante + // com 32 bits + float x_float = 0.0; + + // doubles são normalmente números de ponto flutuante + // com 64 bits + double x_double = 0.0; + + // Tipos inteiros podem ser sem sinal. + unsigned short ux_short; + unsigned int ux_int; + unsigned long long ux_long_long; + + // caracteres dentro de aspas simples são inteiros + // no conjunto de caracteres da máquina. + '0' // => 48 na tabela ASCII. + 'A' // => 65 na tabela ASCII. + + // sizeof(T) devolve o tamanho de uma variável do tipo T em bytes + // sizeof(obj) devolve o tamanho de uma expressão (variável, literal, etc.). + printf("%zu\n", sizeof(int)); // => 4 (na maioria das máquinas com palavras de 4 bytes) + + // Se o argumento do operador `sizeof` é uma expressão, então seus argumentos + // não são avaliados (exceto em VLAs (veja abaixo)). + // O valor devolve, neste caso, é uma constante de tempo de compilação. + int a = 1; + // size_t é um inteiro sem sinal com pelo menos 2 bytes que representa + // o tamanho de um objeto. + size_t size = sizeof(a++); // a++ não é avaliada. + printf("sizeof(a++) = %zu where a = %d\n", size, a); + // imprime "sizeof(a++) = 4 onde a = 1" (quando em uma arquitetura de 32 bits) + + // Arrays precisam ser inicializados com um tamanho concreto + char meu_char_array[20]; // Este array ocupa 1 * 20 = 20 bytes + int meu_int_array[20]; // Este array ocupa 4 * 20 = 80 bytes + // (assumindo palavras de 4 bytes) + + // Você pode inicializar um array com 0 desta forma: + char meu_array[20] = {0}; + + // Indexar um array é semelhante a outras linguages + // Melhor dizendo, outras linguagens são semelhantes a C + meu_array[0]; // => 0 + + // Array são mutáveis; são apenas memória! + meu_array[1] = 2; + printf("%d\n", meu_array[1]); // => 2 + + // No C99 (e como uma features opcional em C11), arrays de tamanho variável + // VLA (do inglês), podem ser declarados também. O tamanho destes arrays + // não precisam ser uma constante de tempo de compilação: + printf("Entre o tamanho do array: "); // Pergunta ao usuário pelo tamanho + char buf[0x100]; + fgets(buf, sizeof buf, stdin); + + // strtoul transforma a string em um inteiro sem sinal + size_t size = strtoul(buf, NULL, 10); + int var_length_array[size]; // declara o VLA + printf("sizeof array = %zu\n", sizeof var_length_array); + + //Uma possível saída para esse programa seria: + // > Entre o tamanho do array:: 10 + // > sizeof array = 40 + + // String são apenas arrays de caracteres terminados por um + // byte NUL (0x00), representado em string pelo caracter especial '\0'. + // (Não precisamos incluir o byte NUL em literais de string; o compilador + // o insere ao final do array para nós.) + char uma_string[20] = "Isto é uma string"; + // Observe que 'é' não está na tabela ASCII + // A string vai ser salva, mas a saída vai ser estranha + // Porém, comentários podem conter acentos + printf("%s\n", uma_string); // %s formata a string + + printf("%d\n", uma_string[16]); // => 0 + // i.e., byte #17 é 0 (assim como 18, 19, e 20) + + // Se temos caracteres entre aspas simples, temos um caracter literal. + // Seu tipo é `int`, *não* `char` (por razões históricas). + int cha = 'a'; // ok + char chb = 'a'; // ok também (conversão implícita de int para char) + + // Arrays multi-dimensionais: + int multi_array[2][5] = { + {1, 2, 3, 4, 5}, + {6, 7, 8, 9, 0} + }; + // Acesso a elementos: + int array_int = multi_array[0][2]; // => 3 + + /////////////////////////////////////// + // Operadores + /////////////////////////////////////// + + // Atalho para multiplas declarações: + int i1 = 1, i2 = 2; + float f1 = 1.0, f2 = 2.0; + + int a, b, c; + a = b = c = 0; + + // Aritimética é óbvia + i1 + i2; // => 3 + i2 - i1; // => 1 + i2 * i1; // => 2 + i1 / i2; // => 0 (0.5, porém, é truncado para 0) + + f1 / f2; // => 0.5, mais ou menos epsilon + // Números e cálculos de ponto flutuante não são exatos + + // Modulo também existe + 11 % 3; // => 2 + + // Operadores de comparação provavelmente são familiares, + // porém não há tipo booleano em C. Usa-se ints no lugar. + // (Ou _Bool or bool em C99.) + // 0 é falso e qualquer outra coisa é verdadeiro + // (Os operadores de comparação devolvem 0 ou 1.) + // Comparison operators are probably familiar, but + 3 == 2; // => 0 (falso) + 3 != 2; // => 1 (verdadeiro) + 3 > 2; // => 1 + 3 < 2; // => 0 + 2 <= 2; // => 1 + 2 >= 2; // => 1 + + // C não é Python - comparações não se encadeam. + int a = 1; + // Errado: + int entre_0_e_2 = 0 < a < 2; + // Correto: + int entre_0_e_2 = 0 < a && a < 2; + + // Lógica funciona sobre ints + !3; // => 0 (Não lógico) + !0; // => 1 + 1 && 1; // => 1 (E lógico) + 0 && 1; // => 0 + 0 || 1; // => 1 (Ou lógico) + 0 || 0; // => 0 + + //Expressão condicional ( ? : ) + int a = 5; + int b = 10; + int z; + z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b." + + //Operadores de incremento e decremento: + char *s = "iLoveC"; + int j = 0; + s[j++]; // => "i". Retorna o j-ésimo item de s E DEPOIS incrementa o valor de j. + j = 0; + s[++j]; // => "L". Incrementa o valor de j. E DEPOIS retorna o j-ésimo item de s. + // o mesmo com j-- e --j + + // Operadores bit a bit! + ~0x0F; // => 0xF0 (negação bit a bit, "complemento de 1") + 0x0F & 0xF0; // => 0x00 (bit a bit E) + 0x0F | 0xF0; // => 0xFF (bit a bit OU) + 0x04 ^ 0x0F; // => 0x0B (bit a bit OU EXCLUSIVO) + 0x01 << 1; // => 0x02 (bit a bit shift para esquerda (por 1)) + 0x02 >> 1; // => 0x01 (bit a bit shift para direita (por 1)) + + // Cuidado quando fizer shift em inteiro com sinal - o seguinte é indefinido: + // - Fazer shift sobre um bit de sinal de um inteiro com sinal (int a = 1 << 32) + // - Fazer shift a esquerda sobre um número negativo (int a = -1 << 2) + // - Fazer shift maior que a largura do tipo de LHS: + // int a = 1 << 32; // Indefinido se int é de tamanho 32 bits + + /////////////////////////////////////// + // Estruturas de Controle + /////////////////////////////////////// + + if (0) { + printf("Nunca rodará\n"); + } else if (0) { + printf("Também nunca rodará\n"); + } else { + printf("Eu serei impresso\n"); + } + + // Loops while existem + int ii = 0; + while (ii < 10) { //QUALQUER valor diferente de 0 é verdadeiro + printf("%d, ", ii++); // ii++ incrementa o valor de ii APÓS usá-lo + } // => imprime "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + int kk = 0; + do { + printf("%d, ", kk); + } while (++kk < 10); // ++kk incrementa o valor de kk ANTES de usá-lo + // => imprime "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + // Loops for também + int jj; + for (jj=0; jj < 10; jj++) { + printf("%d, ", jj); + } // => imprime "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + // *****NOTAS*****: + // Loops e Funções PRECISAM ter um corpo. Se nenhum corpo é necessário: + int i; + for (i = 0; i <= 5; i++) { + ; // Use ponto e vírgula para agir como um corpo (declaração nula) + } + + // Criando branchs com escolhas múltiplas: switch() + switch (alguma_expressao_integral) { + case 0: // labels precisam ser expressões integrais **constantes** + faca_algo(); + break; // Sem break, o controle continua após a label + case 1: + faca_outra_coisa(); + break; + default: + // Se `alguma_expressao_integral` não coincidir com nenhuma label + fputs("erro!\n", stderr); + exit(-1); + break; + } + + + /////////////////////////////////////// + // Cast de tipos + /////////////////////////////////////// + + // Todo valor em C tem um tipo, mas você pode fazer um cast de um valor em outro tipo + // se você quiser (com algumas restrições). + + int x_hex = 0x01; // Você pode colocar valores hexadecimais em variáveis + + // Cast entre tipos tentará preservar seus valores numéricos + printf("%d\n", x_hex); // => Imprime 1 + printf("%d\n", (short) x_hex); // => Imprime 1 + printf("%d\n", (char) x_hex); // => Imprime 1 + + // Tipos irão ter overflow sem aviso + printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 se char tem 8 bits) + + // Para determinar o valor máximo de um `char`, de um `signed char` e de + // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX + // e UCHAR_MAX de + + // Tipos inteiros podem sofrer cast para pontos-flutuantes e vice-versa. + printf("%f\n", (float)100); // %f formata um float + printf("%lf\n", (double)100); // %lf formata um double + printf("%d\n", (char)100.0); + + /////////////////////////////////////// + // Ponteiros + /////////////////////////////////////// + + // Um ponteiro é uma variável declarada para armazenar um endereço de memória. + // Seu declaração irá também dizer o tipo de dados para o qual ela aponta. Você + // Pode usar o endereço de memória de suas variáveis, então, brincar com eles. + + int x = 0; + printf("%p\n", (void *)&x); // Use & para usar o endereço de uma variável + // (%p formata um objeto ponteiro do tipo void *) + // => Imprime algum endereço de memória; + + // Ponteiros começam com * na sua declaração + int *px, nao_eh_um_ponteiro; // px é um ponteiro para um int + px = &x; // armazena o endereço de x em px + printf("%p\n", (void *)px); // => Imprime algum endereço de memória + printf("%zu, %zu\n", sizeof(px), sizeof(nao_eh_um_ponteiro)); + // => Imprime "8, 4" em um sistema típico de 64 bits + + // Para pegar um valor no endereço apontado por um ponteiro, + // coloque * na frente para de-referenciá-lo. + // Nota: sim, é confuso usar '*' _tanto_ para declaração de ponteiro + // como para de-referenciá-lo. + printf("%d\n", *px); // => Imprime 0, o valor de x + + // Você também pode mudar o valor que o ponteiro está apontando. + // Teremo que cercar a de-referência entre parenteses, pois + // ++ tem uma precedência maior que *. + (*px)++; // Incrementa o valor que px está apontando por 1 + printf("%d\n", *px); // => Imprime 1 + printf("%d\n", x); // => Imprime 1 + + // Arrays são um boa maneira de alocar um bloco contínuo de memória + int x_array[20]; // Declara um array de tamanho 20 (não pode-se mudar o tamanho + int xx; + for (xx = 0; xx < 20; xx++) { + x_array[xx] = 20 - xx; + } //Inicializa x_array com 20, 19, 18,... 2, 1 + + // Declara um ponteiro do tipo int e inicialize ele para apontar para x_array + int* x_ptr = x_array; + // x_ptr agora aponta para o primeiro elemento do array (o inteiro 20). + // Isto funciona porque arrays são apenas ponteiros para seu primeiros elementos. + // Por exemplo, quando um array é passado para uma função ou é atribuído a um + // ponteiro, ele transforma-se (convertido implicitamente) em um ponteiro. + // Exceções: quando o array é o argumento de um operador `&` (endereço-de): + // Exceptions: when the array is the argument of the `&` (address-of) operator: + int arr[10]; + int (*ptr_to_arr)[10] = &arr; // &arr não é do tipo `int *`! + // É do tipo "ponteiro para array" (de `int`s). + // ou quando o array é uma string literal usada para inicializar um array de char: + char arr[] = "foobarbazquirk"; + // ou quando é um argumento dos operadores `sizeof` ou `alignof`: + int arr[10]; + int *ptr = arr; // equivalente a int *ptr = &arr[0]; + printf("%zu, %zu\n", sizeof arr, sizeof ptr); // provavelmente imprime "40, 4" ou "40, 8" + + // Ponteiros podem ser incrementados ou decrementados baseado no seu tipo + // (isto é chamado aritimética de ponteiros + printf("%d\n", *(x_ptr + 1)); // => Imprime 19 + printf("%d\n", x_array[1]); // => Imprime 19 + + // Você também pode alocar dinamicamente blocos de memória com a função + // da biblioteca padrão malloc, a qual recebe um argumento do tipo size_t + // representando o número de bytes a ser alocado (geralmente da heap, apesar de + // isto poder não ser verdadeiro em, e.g., sistemas embarcados - o C padrão diz + // nada sobre isso). + int *my_ptr = malloc(sizeof(*my_ptr) * 20); + for (xx = 0; xx < 20; xx++) { + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx + } //Inicializa a memória com 20, 19, 18, 17... 2, 1 (como ints) + + // Dereferenciar memória que você não alocou cria + // "resultados imprevisíveis" - o programa é dito ter um "comportamento indefinido" + printf("%d\n", *(my_ptr + 21)); // => Imprime quem-sabe-o-que? Talvez até quebre o programa. + + // Quando termina-se de usar um bloco de memória alocado, você pode liberá-lo, + // ou ninguém mais será capaz de usá-lo até o fim da execução + // (Isto cham-se "memory leak"): + free(my_ptr); + + // Strings são arrays de char, mas elas geralmente são representadas + // como um ponteiro para char (com o apontador para o primeiro elemento do array). + // É boa prática usar `const char *' quando de-referenciando uma literal string, + // dado que elas não deverão ser modificadas (i.e. "foo"[0] = 'a' é ILEGAL.) + const char *my_str = "Esta é a minha literal string"; + printf("%c\n", *my_str); // => 'T' + + // Este não é o caso se a string for um array + // (potencialmente inicializado com um literal string) + // que reside em uma memória de escrita, como em: + char foo[] = "foo"; + foo[0] = 'a'; // Isto é legal, foo agora contém "aoo" + + funcao_1(); +} // fim da função main + +/////////////////////////////////////// +// Funções +/////////////////////////////////////// + +//Sintaxe de declaração de funções: +// () + +int soma_dois_int(int x1, int x2) +{ + return x1 + x2; // Use return para retornar um valor +} + +/* +Funções são chamadas por valor. Quando uma função é chamada, os argumentos passados +para a função são cópias dos argumento originais (a não ser arrays). Qualquer coisa +que você faz nos argumentos de uma função não alteram o valor do argumento original +onde a função foi chamada. + +Use ponteiros se você precisa alterar os valores dos argumentos originais + +Exemplo: reversão de string in-place +*/ + +// Uma função void não retorna valor algum +void str_reverse(char *str_in) +{ + char tmp; + int ii = 0; + size_t len = strlen(str_in); // `strlen()` é parte da biblioteca padrão C + for (ii = 0; ii < len / 2; ii++) { + tmp = str_in[ii]; + str_in[ii] = str_in[len - ii - 1]; // iiº char do final + str_in[len - ii - 1] = tmp; + } +} + +/* +char c[] = "Isto é um teste."; +str_reverse(c); +printf("%s\n", c); // => ".etset mu é otsI" +*/ + +// Se estiver referenciando variáveis externas à função, use a palavra-chave extern. +int i = 0; +void testFunc() { + extern int i; //i aqui agora está usando a variável externa +} + +// Faça variáveis externas privadas para o código-fonte com static: +static int i = 0; // Outros arquivos usando testFunc() não podem acessar a variável i +void testFunc() { + extern int i; +} +//**Você pode declarar funções como static para torná-las privadas** + + +/////////////////////////////////////// +// Tipos definidos pelo usuário e structs +/////////////////////////////////////// + +// Typedefs podem ser usadas para criar apelidos para tipos +typedef int meu_tipo; +meu_tipo var_meu_tipo = 0; + +// Structs são apenas coleções de dados, os membros são alocados sequencialmente, +// na ordem que são escritos: +struct retangulo { + int altura; + int largura; +}; + +// Geralmente não é verdade que +// sizeof(struct retangulo) == sizeof(int) + sizeof(int) +// devido ao potencial de preenchimento entre os membros da estrutura +// (isto é por razões de alinhamento). [1] + +void funcao_1() +{ + struct retangulo meu_retan; + + // Acesse os membros da estrutura com . + meu_retan.altura = 10; + meu_retan.largura = 20; + + // Você pode declarar ponteiros para structs + struct retangulo *meu_retan_ptr = &meu_retan; + + // Use de-referenciamento para setar os membros da + // struct apontada... + (*meu_retan_ptr).altura = 30; + + // ... ou ainda melhor: prefira usar o atalho -> para melhorar legibilidade + meu_retan_ptr->largura = 10; // O mesmo que (*meu_retan_ptr).largura = 10; +} + +//Você pode aplicar um typedef para uma struct por conveniência +typedef struct retangulo retan; + +int area(retan r) +{ + return r.largura * r.altura; +} + +// Se você tiver structus grande, você pode passá-las "por ponteiro" +// para evitar cópia de toda a struct: +int area(const retan *r) +{ + return r->largura * r->altura; +} + +/////////////////////////////////////// +// Ponteiros para funções +/////////////////////////////////////// +/* +Em tempo de execução, funções são localizadas em endereços de memória +conhecidos. Ponteiros para funções são como qualquer outro ponteiro +(apenas guardam endereços de memória), mas podem ser usados para invocar funções +diretamente e passá-las para por toda parte. +Entretanto, a sintaxe de definição por ser um pouco confusa. + +Exemplo: use str_reverso através de um ponteiro +*/ +void str_reverso_através_ponteiro(char *str_entrada) { + // Define uma variável de ponteiro para função, nomeada f. + void (*f)(char *); //Assinatura deve ser exatamente igual à função alvo. + f = &str_reverso; //Atribue o endereço da função em si (determinado em tempo de execução. + // f = str_reverso; Também funciona - função tornam-se ponteiros, assim como arrays + (*f)(str_entrada); // Chamando a função através do ponteiro + // f(str_entrada); // Esta é uma sintaxe alternativa, mas equivalente. +} + +/* +Desde que as assinaturas das funções sejam compatíveis, você pode atribuir qualquer +função ao mesmo ponteiro. Ponteiros para funções são geralmente um typedef por +simplicidade e legibilidade, como segue: +*/ + +typedef void (*minha_função_type)(char *); + +// Declarando o ponteiro: +// ... +// minha_função_type f; + +//Caracteres especiais: +'\a' // Alerta (sino) +'\n' // Nova linha +'\t' // Tab (justifica texto a esquerda) +'\v' // Tab vertical +'\f' // Nova linha (formfeed) +'\r' // Retorno de carroça +'\b' // Backspace +'\0' // Caracter nulo. Geralmente colocado ao final de string em C. + // oi\n\0. \0 é usado por convenção para marcar o fim da string. +'\\' // Barra invertida +'\?' // Interrogação +'\'' // Aspas simples +'\"' // Aspas duplas +'\xhh' // Número hexadecimal. Exemplo: '\xb' = tab vertical +'\ooo' // Número octal. Exemplo: '\013' = tab vertical + +// formatando impressão: +"%d" // inteiro +"%3d" // inteiro com pelo menos 3 dígitos (justifica texto a direita) +"%s" // string +"%f" // ponto-flutuante +"%ld" // long +"%3.2f" // ponto-flutuante com pelo menos 3 dígitos a esquerda e 2 a direita +"%7.4s" // (também pode-se fazer com strings) +"%c" // char +"%p" // ponteiro +"%x" // hexadecimal +"%o" // octal +"%%" // imprime % + +/////////////////////////////////////// +// Ordem de avaliação +/////////////////////////////////////// + +//-----------------------------------------------------------// +// Operadores | Associatividade // +//-----------------------------------------------------------// +// () [] -> . | esquerda para direita // +// ! ~ ++ -- + = *(type)sizeof | direita para esqureda // +// * / % | esquerda para direita // +// + - | esquerda para direita // +// << >> | esquerda para direita // +// < <= > >= | esquerda para direita // +// == != | esquerda para direita // +// & | esquerda para direita // +// ^ | esquerda para direita // +// | | esquerda para direita // +// && | esquerda para direita // +// || | esquerda para direita // +// ?: | direita para esqureda // +// = += -= *= /= %= &= ^= |= <<= >>= | direita para esqureda // +// , | esquerda para direita // +//-----------------------------------------------------------// + +``` + +## Leitura adicional + +É recomendado ter uma cópia de [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language). +Este é *o* livro sobre C, escrito pelos criadores da linguage. Mas cuidado - ele é antigo e contém alguns erros (bem, +ideias que não são consideradas boas hoje) ou práticas mudadas. + +Outra boa referência é [Learn C the hard way](http://c.learncodethehardway.org/book/). + +Se você tem uma pergunta, leia [compl.lang.c Frequently Asked Questions](http://c-faq.com). + +É importante usar espaços e indentação adequadamente e ser consistente com seu estilo de código em geral. +Código legível é melhor que código 'esperto' e rápido. Para adotar um estilo de código bom e são, veja +[Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle). + +Além disso, Google é teu amigo. +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member -- cgit v1.2.3 From 49eed60496327a9a98155db57d58deb7d2c86fae Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 3 Jun 2014 11:40:06 -0500 Subject: Add git push -u command to git tutorial. --- git.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index 4b5e466e..65e57f05 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -327,6 +327,11 @@ Push and merge changes from a branch to a remote & branch. # git push # git push => implicitly defaults to => git push origin master $ git push origin master + +# To link up current local branch with a remote branch, add -u flag: +$ git push -u origin master +# Now, anytime you want to push from that same local branch, use shortcut: +$ git push ``` ### rebase (caution) -- cgit v1.2.3 From 0d984535bde0bad8e0e76857bdb504bc63bdcca9 Mon Sep 17 00:00:00 2001 From: Grant Timmerman Date: Wed, 4 Jun 2014 00:50:17 -0700 Subject: Added swift docs --- swift.html.markdown | 224 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 224 insertions(+) create mode 100644 swift.html.markdown diff --git a/swift.html.markdown b/swift.html.markdown new file mode 100644 index 00000000..c7615a82 --- /dev/null +++ b/swift.html.markdown @@ -0,0 +1,224 @@ +--- +language: swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] +filename: learnswift.swift +--- + +Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta. + +See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. + +# Overview +- [Basics](#basics) +- [Arrays and Dictionaries](#array) +- [Control Flow](#control) +- [Functions](#func) +- [Closures](#closures) +- [Classes](#classes) +- [Enums](#enums) +- [Other](#other) +- [Links](#links) + +## Basics + +```js +println("Hello, world") +var myVariable = 42 +let myConstant = 3.1415926 +let explicitDouble: Double = 70 +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(myConstant)" // String interpolation +var optionalString: String? = "optional" // Can be nil +optionalString = nil +``` + +## Arrays and Dictionaries + +```js +// Array +var shoppingList = ["catfish", "water", "lemons"] +shoppingList[1] = "bottle of water" +let emptyArray = String[]() + +// Dictionary +var occupations = [ + "Malcolm": "Captain", + "kaylee": "Mechanic" +] +occupations["Jayne"] = "Public Relations" +let emptyDictionary = Dictionary() +``` + +## Control Flow + +```js +// for loop (array) +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + println("One!") + } else { + println("Not one!") + } +} + +// for loop (dictionary) +for (key, value) in dict { + println("\(key): \(value)") +} + +// for loop (range) +for i in -1...1 { // [-1, 0, 1] + println(i) +} +// use .. to exclude the last number + +// while loop +var i = 1 +while i < 1000 { + i *= 2 +} + +// do-while loop +do { + println("hello") +} while 1 == 2 + +// Switch +let vegetable = "red pepper" +switch vegetable { +case "celery": + let vegetableComment = "Add some raisins and make ants on a log." +case "cucumber", "watercress": + let vegetableComment = "That would make a good tea sandwich." +case let x where x.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(x)?" +default: // required (in order to cover all possible input) + let vegetableComment = "Everything tastes good in soup." +} +``` + +## Functions + +Functions are a first-class type, meaning they can be nested in functions and can be passed around + +```js +// Function +func greet(name: String, day: String) -> String { + return "Hello \(name), today is \(day)." +} +greet("Bob", "Tuesday") + +// Function that returns multiple items in a tuple +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} + +// Args +func setup(numbers: Int...) {} + +// Passing and returning functions +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) +``` + +## Closures + +Functions are special case closures ({}) + +```js +// Closure example. +// `->` separates the arguments and return type +// `in` separates the closure header from the closure body +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result + }) + +// When the type is known, like above, we can do this +var numbers = [1, 2, 6] +numbers = numbers.map({ number in 3 * number }) +print(numbers) // [3, 6, 18] +``` + +## Classes + +All methods and properties of a class are public. If you just need to store data +in a structured object, you should use a `struct` + +```js +// A simple class `Square` extends `Shape +class Rect: Shape { + var sideLength: Int = 1 + + // Custom getter and setter property + var perimeter: Int { + get { + return 4 * sideLength + } + set { + sideLength = newValue / 4 + } + } + + init(sideLength: Int) { + super.init() + self.sideLength = sideLength + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} +var mySquare = new Square(sideLength: 5) +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// If you don't need a custom getter and setter, but still want to run code +// before an after getting or setting a property, you can use `willSet` and `didSet` +``` + +## Enums + +Enums can optionally be of a specific type or on their own. They can contain methods like classes. + +```js +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} +``` + +## Other + +- **`protocol`**: Similar to Java interfaces. +- **`extension`s**: Add extra functionality to an already created type +- **Generics**: Similar to Java. Use the `where` keyword to specify the requirements of the generics. + +## Links + +- [Homepage](https://developer.apple.com/swift/) +- [Guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) +- [Book](https://itunes.apple.com/us/book/the-swift-programming-language/id881256329?mt=11) -- cgit v1.2.3 From 76f4c1b3b6d99d05197224dfec905a46dbd80713 Mon Sep 17 00:00:00 2001 From: Grant Timmerman Date: Wed, 4 Jun 2014 13:22:01 -0700 Subject: Formatted the document according to the guidelines --- swift.html.markdown | 94 ++++++++++++++++++++++++++--------------------------- 1 file changed, 47 insertions(+), 47 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index c7615a82..6ab0cc20 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -9,20 +9,11 @@ Swift is a programming language for iOS and OS X development created by Apple. D See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. -# Overview -- [Basics](#basics) -- [Arrays and Dictionaries](#array) -- [Control Flow](#control) -- [Functions](#func) -- [Closures](#closures) -- [Classes](#classes) -- [Enums](#enums) -- [Other](#other) -- [Links](#links) - -## Basics - ```js +// +// Basics +// + println("Hello, world") var myVariable = 42 let myConstant = 3.1415926 @@ -31,11 +22,12 @@ let label = "some text " + String(myVariable) // Casting let piText = "Pi = \(myConstant)" // String interpolation var optionalString: String? = "optional" // Can be nil optionalString = nil -``` -## Arrays and Dictionaries -```js +// +// Arrays and Dictionaries +// + // Array var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" @@ -48,11 +40,12 @@ var occupations = [ ] occupations["Jayne"] = "Public Relations" let emptyDictionary = Dictionary() -``` -## Control Flow -```js +// +// Control Flow +// + // for loop (array) let myArray = [1, 1, 2, 3, 5] for value in myArray { @@ -97,13 +90,15 @@ case let x where x.hasSuffix("pepper"): default: // required (in order to cover all possible input) let vegetableComment = "Everything tastes good in soup." } -``` -## Functions -Functions are a first-class type, meaning they can be nested in functions and can be passed around +// +// Functions +// + +// Functions are a first-class type, meaning they can be nested +// in functions and can be passed around -```js // Function func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." @@ -127,13 +122,14 @@ func makeIncrementer() -> (Int -> Int) { } var increment = makeIncrementer() increment(7) -``` -## Closures -Functions are special case closures ({}) +// +// Closures +// + +// Functions are special case closures ({}) -```js // Closure example. // `->` separates the arguments and return type // `in` separates the closure header from the closure body @@ -147,14 +143,16 @@ numbers.map({ var numbers = [1, 2, 6] numbers = numbers.map({ number in 3 * number }) print(numbers) // [3, 6, 18] -``` -## Classes -All methods and properties of a class are public. If you just need to store data -in a structured object, you should use a `struct` +// +// Classes +// + +// All methods and properties of a class are public. +// If you just need to store data in a +// structured object, you should use a `struct` -```js // A simple class `Square` extends `Shape class Rect: Shape { var sideLength: Int = 1 @@ -189,15 +187,18 @@ print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 -// If you don't need a custom getter and setter, but still want to run code -// before an after getting or setting a property, you can use `willSet` and `didSet` -``` +// If you don't need a custom getter and setter, +// but still want to run code before an after getting or setting +// a property, you can use `willSet` and `didSet` -## Enums -Enums can optionally be of a specific type or on their own. They can contain methods like classes. +// +// Enums +// + +// Enums can optionally be of a specific type or on their own. +// They can contain methods like classes. -```js enum Suit { case Spades, Hearts, Diamonds, Clubs func getIcon() -> String { @@ -209,16 +210,15 @@ enum Suit { } } } -``` -## Other -- **`protocol`**: Similar to Java interfaces. -- **`extension`s**: Add extra functionality to an already created type -- **Generics**: Similar to Java. Use the `where` keyword to specify the requirements of the generics. +// +// Other +// -## Links +// `protocol`: Similar to Java interfaces. +// `extension`s: Add extra functionality to an already created type +// Generics: Similar to Java. Use the `where` keyword to specify the +// requirements of the generics. -- [Homepage](https://developer.apple.com/swift/) -- [Guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) -- [Book](https://itunes.apple.com/us/book/the-swift-programming-language/id881256329?mt=11) +``` \ No newline at end of file -- cgit v1.2.3 From b5e3cb4206277b204cfdf57734be57df61d920a4 Mon Sep 17 00:00:00 2001 From: miguel araujo Date: Thu, 5 Jun 2014 10:20:18 -0300 Subject: Translating coffeescript to pt-br --- pt-br/coffeescript-pt.html.markdown | 106 ++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 pt-br/coffeescript-pt.html.markdown diff --git a/pt-br/coffeescript-pt.html.markdown b/pt-br/coffeescript-pt.html.markdown new file mode 100644 index 00000000..8b1094b1 --- /dev/null +++ b/pt-br/coffeescript-pt.html.markdown @@ -0,0 +1,106 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +filename: learncoffeescript-pt.coffee +--- + +CoffeeScript é uma pequena linguagem que compila um-para-um para o JavaScript +equivalente, e não há interpretação em tempo de execução. Como um dos sucessores +de JavaScript, CoffeeScript tenta o seu melhor para exibir uma saída legível, +bem-impressa e bom funcionamento dos códigos JavaScript em todo o tempo de +execução JavaScript. + +Veja também [site do CoffeeScript](http://coffeescript.org/), que tem um tutorial +completo sobre CoffeeScript. + +``` coffeescript +#CoffeeScript é uma linguagem moderna +#Segue as tendências de muitas linguagens modernas +#Assim, os comentários são iguais a Ruby e Python, eles usam símbolos numéricos. + +### +Os comentários em bloco são como estes, e eles traduzem diretamente para '/ *'s e +'* /'s para o código JavaScript que resulta... + +Você deveria entender mais de semântica de JavaScript antes de continuar... +### + +# Tarefa: +numero = 42 #=> número var = 42; +oposto = true #=> var oposto = true; + +# Condições: +numero = -42 if oposto #=> if (oposto) {número = -42;} + +# Funções: +quadrado = (x) -> x * x #=> var quadrado = function (x) {return x * x;} + +preencher = (recipiente, líquido = "coffee") -> + "Preenchendo o #{recipiente} with #{líquido}..." +#=>var preencher; +# +#preencher = function(recipiente, líquido) { +# if (líquido == null) { +# líquido = "coffee"; +# } +# return "Preenchendo o " + recipiente + " with " + líquido + "..."; +#}; + +# Alcances: +list = [1 .. 5] #=> lista var = [1, 2, 3, 4, 5]; + +# Objetos: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +#} + +# Splats: +corrida = (vencedor, corredores...) -> + print vencedor, corredores +#=>corrida = function() { +# var corredores, vencedor; +# vencedor = arguments[0], corredores = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(vencedor, corredores); +#}; + +# Existências: +alert "Eu sabia!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Eu sabia!"); } + +# Compressão de Matrizes: +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +comidas = ['brócolis', 'espinafre', 'chocolate'] +eat alimento for alimento in comidas when alimento isnt 'chocolate' +#=>comidas = ['brócolis', 'espinafre', 'chocolate']; +# +#for (_k = 0, _len2 = comidas.length; _k < _len2; _k++) { +# alimento = comidas[_k]; +# if (alimento !== 'chocolate') { +# eat(alimento); +# } + +## Recursos adicionais + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) \ No newline at end of file -- cgit v1.2.3 From 1f1c7b616cf07ab1dee784ca8abb2a82d92f5f32 Mon Sep 17 00:00:00 2001 From: Xavier Yao Date: Thu, 5 Jun 2014 22:48:49 +0800 Subject: zh-cn translatation for Swift --- zh-cn/swift-cn.html.markdown | 226 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 zh-cn/swift-cn.html.markdown diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown new file mode 100644 index 00000000..e9dcb858 --- /dev/null +++ b/zh-cn/swift-cn.html.markdown @@ -0,0 +1,226 @@ +--- +language: swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] +translators: + - ["Xavier Yao", "http://github.com/xavieryao"] +filename: learnswift-cn.swift +--- + +Swift 是Apple 开发的用于iOS 和OS X 开发的编程语言。Swift 于2014年Apple WWDC (全球开发者大会)中被引入,用以与Objective-C 共存,同时对错误代码更具弹性。Swift 由Xcode 6 beta 中包含的LLVM编译器编译。 + +参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) ——一个完整的Swift 教程 + +```js +// +// 基础 +// + +println("Hello, world") +var myVariable = 42 +let myConstant = 3.1415926 +let explicitDouble: Double = 70 +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(myConstant)" // String interpolation +var optionalString: String? = "optional" // Can be nil +optionalString = nil + + +// +// 数组与字典(关联数组) +// + +// 数组 +var shoppingList = ["catfish", "water", "lemons"] +shoppingList[1] = "bottle of water" +let emptyArray = String[]() + +// 字典 +var occupations = [ + "Malcolm": "Captain", + "kaylee": "Mechanic" +] +occupations["Jayne"] = "Public Relations" +let emptyDictionary = Dictionary() + + +// +// 控制流 +// + +// 用于数组的for 循环 +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + println("One!") + } else { + println("Not one!") + } +} + +// 用于字典的for 循环 +for (key, value) in dict { + println("\(key): \(value)") +} + +// 用于区间的for 循环 +for i in -1...1 { // [-1, 0, 1] + println(i) +} +// 使用 .. 表示的区间不包含最后一个元素 [-1,0,1) + +// while 循环 +var i = 1 +while i < 1000 { + i *= 2 +} + +// do-while 循环 +do { + println("hello") +} while 1 == 2 + +// Switch +let vegetable = "red pepper" +switch vegetable { +case "celery": + let vegetableComment = "Add some raisins and make ants on a log." +case "cucumber", "watercress": + let vegetableComment = "That would make a good tea sandwich." +case let x where x.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(x)?" +default: // 必须 (为了覆盖所有可能的输入) + let vegetableComment = "Everything tastes good in soup." +} + + +// +// 函数 +// + +// 函数是一等类型,这意味着可以在函数中构建函数 +// 并且可以被传递 + +// 函数 +func greet(name: String, day: String) -> String { + return "Hello \(name), today is \(day)." +} +greet("Bob", "Tuesday") + +// 使用多元数组返回多返回值的函数 +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} + +// 不定参数 +func setup(numbers: Int...) {} + +// 传递、返回函数 +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + + +// +// 闭包 +// + +// 函数是特殊的闭包({}) + +// 闭包示例. +// `->` 分隔参数和返回类型 +// `in` 分隔闭包头和闭包体 +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result + }) + +// 当类型已知时,可以这样做: +var numbers = [1, 2, 6] +numbers = numbers.map({ number in 3 * number }) +print(numbers) // [3, 6, 18] + + +// +// 类 +// + +// 类的全部方法和属性都是public 的 +// 如果你在一个数据结构中只需储存数据, +// 应使用 `struct` + +// 集成自`Shape` 类的简单的类`Square +class Rect: Shape { + var sideLength: Int = 1 + + // Custom getter and setter property + var perimeter: Int { + get { + return 4 * sideLength + } + set { + sideLength = newValue / 4 + } + } + + init(sideLength: Int) { + super.init() + self.sideLength = sideLength + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} +var mySquare = new Square(sideLength: 5) +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// 如果你不需要自定义getter 和setter, +// 但仍希望在获取或设置一个属性之前或之后运行 +// 一些代码,你可以使用`willSet` 和 `didSet` + + +// +// 枚举类型 +// + +// 枚举类型可以是某种指定的类型,抑或自成一种类型 +// 像类一样,枚举类型可以包含方法 + +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + + +// +// 其它 +// + +// `协议(protocol)`: 与Java 的接口(Interface) 类似. +// `扩展(extension)`: 为现有类型添加额外特性 +// 泛型: 与Java 相似。使用`where` 关键字指定 +// 泛型的要求. + +``` \ No newline at end of file -- cgit v1.2.3 From e07f88cb4db7e1eac0668707d4c06ab68a967253 Mon Sep 17 00:00:00 2001 From: Xavier Yao Date: Thu, 5 Jun 2014 22:49:42 +0800 Subject: Tiny symbol missing fixed. --- swift.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 6ab0cc20..f24b1592 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -153,7 +153,7 @@ print(numbers) // [3, 6, 18] // If you just need to store data in a // structured object, you should use a `struct` -// A simple class `Square` extends `Shape +// A simple class `Square` extends `Shape` class Rect: Shape { var sideLength: Int = 1 @@ -188,7 +188,7 @@ mySquare.shrink() print(mySquare.sideLength) // 4 // If you don't need a custom getter and setter, -// but still want to run code before an after getting or setting +// but still want to run code before and after getting or setting // a property, you can use `willSet` and `didSet` -- cgit v1.2.3 From e0e17156ee45822ea198ffdd11ff4d9f176f5b05 Mon Sep 17 00:00:00 2001 From: ysagal Date: Thu, 5 Jun 2014 12:20:54 -0400 Subject: Tiny typo fix --- julia.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 15b4be90..e9d3a162 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -500,7 +500,7 @@ typeof(DataType) # => DataType # Users can define types # They are like records or structs in other languages. -# New types are defined used the `type` keyword. +# New types are defined using the `type` keyword. # type Name # field::OptionalType -- cgit v1.2.3 From d9e5677d1a820021bd486040a8beeb9942f46603 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Thu, 5 Jun 2014 22:45:41 +0200 Subject: Add lang: tag for swift/zh-cn - fixes #640 --- zh-cn/swift-cn.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index e9dcb858..c87f9d10 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -1,10 +1,11 @@ --- language: swift +filename: learnswift-cn.swift contributors: - ["Grant Timmerman", "http://github.com/grant"] translators: - ["Xavier Yao", "http://github.com/xavieryao"] -filename: learnswift-cn.swift +lang: zh-cn --- Swift 是Apple 开发的用于iOS 和OS X 开发的编程语言。Swift 于2014年Apple WWDC (全球开发者大会)中被引入,用以与Objective-C 共存,同时对错误代码更具弹性。Swift 由Xcode 6 beta 中包含的LLVM编译器编译。 @@ -223,4 +224,4 @@ enum Suit { // 泛型: 与Java 相似。使用`where` 关键字指定 // 泛型的要求. -``` \ No newline at end of file +``` -- cgit v1.2.3 From 506ffb7a683d136c550278efa184a51af0e5b5e7 Mon Sep 17 00:00:00 2001 From: William Clifford Date: Sat, 7 Jun 2014 07:45:57 -0700 Subject: Update elixir.html.markdown minor spelling fix: `s/catched/caught/` --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index b27b2ee8..946c0a1b 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -201,7 +201,7 @@ cond do end # `try/catch` is used to catch values that are thrown, it also supports an -# `after` clause that is invoked whether or not a value is catched. +# `after` clause that is invoked whether or not a value is caught. try do throw(:hello) catch -- cgit v1.2.3 From 8348e27660026f70f57ca95dbd4b175adada0410 Mon Sep 17 00:00:00 2001 From: Marco Scannadinari Date: Sun, 8 Jun 2014 22:00:14 +0100 Subject: Add extra detail --- json.html.markdown | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/json.html.markdown b/json.html.markdown index f86f0ae9..28906116 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -3,6 +3,7 @@ language: json filename: learnjson.json contributors: - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] --- As JSON is an extremely simple data-interchange format, this is most likely going @@ -14,6 +15,9 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. ```json { + "key": "value", + + "keys": "must always be enclosed in quotes (' or \")" "numbers": 0, "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", "has bools?": true, @@ -42,6 +46,11 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. [0, 0, 0, 1] ] ], + + "alternative style": { + "comment": "check this out!" + , "comma position": "doesn't matter - as long as its before the value, then its valid" + , "see for rationale": "https://gist.github.com/isaacs/357981" "that was short": "And, you're done. You know know everything JSON has to offer." } -- cgit v1.2.3 From fac959a398c7242086c23a9c565f2f56150e8e0c Mon Sep 17 00:00:00 2001 From: Timothy Malcham Date: Tue, 10 Jun 2014 10:06:08 -0700 Subject: Shortens line lengths of comments in Perl guide --- perl.html.markdown | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index da2e0cdf..aac95939 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -28,7 +28,8 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f my $animal = "camel"; my $answer = 42; -# Scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required. +# Scalar values can be strings, integers or floating point numbers, and +# Perl will automatically convert between them as required. ## Arrays # An array represents a list of values: @@ -49,9 +50,11 @@ my %fruit_color = ( apple => "red", banana => "yellow", ); -# Scalars, arrays and hashes are documented more fully in perldata. (perldoc perldata). +# Scalars, arrays and hashes are documented more fully in perldata. +# (perldoc perldata). -# More complex data types can be constructed using references, which allow you to build lists and hashes within lists and hashes. +# More complex data types can be constructed using references, which allow you +# to build lists and hashes within lists and hashes. #### Conditional and looping constructs @@ -92,7 +95,9 @@ foreach (@array) { #### Regular expressions -# Perl's regular expression support is both broad and deep, and is the subject of lengthy documentation in perlrequick, perlretut, and elsewhere. However, in short: +# Perl's regular expression support is both broad and deep, and is the subject +# of lengthy documentation in perlrequick, perlretut, and elsewhere. +# However, in short: # Simple matching if (/foo/) { ... } # true if $_ contains "foo" @@ -112,8 +117,9 @@ open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; -# You can read from an open filehandle using the "<>" operator. In scalar context it reads a single line from -# the filehandle, and in list context it reads the whole file in, assigning each line to an element of the list: +# You can read from an open filehandle using the "<>" operator. In scalar +# context it reads a single line from the filehandle, and in list context it +# reads the whole file in, assigning each line to an element of the list: my $line = <$in>; my @lines = <$in>; -- cgit v1.2.3 From 659bc7566f1791800a06995a610306cdc8430e71 Mon Sep 17 00:00:00 2001 From: Nati Date: Tue, 10 Jun 2014 16:54:32 -0700 Subject: Changed "complimenting" to "complementing". --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 76017c17..c59a90c3 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -7,7 +7,7 @@ filename: javascript.js --- JavaScript was created by Netscape's Brendan Eich in 1995. It was originally -intended as a simpler scripting language for websites, complimenting the use of +intended as a simpler scripting language for websites, complementing the use of Java for more complex web applications, but its tight integration with Web pages and built-in support in browsers has caused it to become far more common than Java in web frontends. -- cgit v1.2.3 From a5f41dd164ec69da6a748a50fa6c9af1b0ba6db6 Mon Sep 17 00:00:00 2001 From: Marco Scannadinari Date: Wed, 11 Jun 2014 09:55:56 +0100 Subject: Fix missing commas and closing braces --- json.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/json.html.markdown b/json.html.markdown index 28906116..6891e04e 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -17,7 +17,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. { "key": "value", - "keys": "must always be enclosed in quotes (' or \")" + "keys": "must always be enclosed in quotes (' or \")", "numbers": 0, "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", "has bools?": true, @@ -51,6 +51,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. "comment": "check this out!" , "comma position": "doesn't matter - as long as its before the value, then its valid" , "see for rationale": "https://gist.github.com/isaacs/357981" + }, "that was short": "And, you're done. You know know everything JSON has to offer." } -- cgit v1.2.3 From 2420e593a4e5c0450b8a2f485be874715c645372 Mon Sep 17 00:00:00 2001 From: Osvaldo Mendoza Date: Wed, 11 Jun 2014 17:36:16 -0400 Subject: Update markdown.html.markdown typo --- markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index 606840d3..9a863bac 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -59,7 +59,7 @@ Github, we also have: --> -This is a paragraph. I'm tryping in a paragraph isn't this fun? +This is a paragraph. I'm typing in a paragraph isn't this fun? Now I'm in paragraph 2. I'm still in paragraph 2 too! -- cgit v1.2.3 From a88daf14358c9d699adc9a2e2808cce65e6b202e Mon Sep 17 00:00:00 2001 From: Jack Hooper Date: Thu, 12 Jun 2014 13:49:22 +1000 Subject: [json/en] - fixed typo Changed "You know know everything..." to "You now know everything..." --- json.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/json.html.markdown b/json.html.markdown index f86f0ae9..0e1a7d24 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -43,6 +43,6 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. ] ], - "that was short": "And, you're done. You know know everything JSON has to offer." + "that was short": "And, you're done. You now know everything JSON has to offer." } ``` -- cgit v1.2.3 From ce2e9b93fb80d546fa83cc364aac770a5ae17a0e Mon Sep 17 00:00:00 2001 From: bobozhengsir Date: Fri, 13 Jun 2014 20:01:16 +0800 Subject: Update scala-cn.html.markdown miss a comma at line 372 --- zh-cn/scala-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 24f73bb5..28af8ddc 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -369,7 +369,7 @@ import scala.collection.immutable._ import scala.collection.immutable.{List, Map} // 使用 '=>' 来重命名一个 import -import scala.collection.immutable{ List => ImmutableList } +import scala.collection.immutable.{ List => ImmutableList } // import 除了一些类的其它所有的类。下面的例子除去了 Map 类和 Set 类: import scala.collection.immutable.{Map => _, Set => _, _} -- cgit v1.2.3 From de369eaa29e6cd1b979014a2a23742297d8e9edf Mon Sep 17 00:00:00 2001 From: Marco Scannadinari Date: Fri, 13 Jun 2014 19:20:21 +0100 Subject: Remove escaped quotes and external gist link --- json.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/json.html.markdown b/json.html.markdown index 6891e04e..6d06ffe4 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -17,7 +17,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. { "key": "value", - "keys": "must always be enclosed in quotes (' or \")", + "keys": "must always be enclosed in quotes (either double or single)", "numbers": 0, "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", "has bools?": true, @@ -50,7 +50,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. "alternative style": { "comment": "check this out!" , "comma position": "doesn't matter - as long as its before the value, then its valid" - , "see for rationale": "https://gist.github.com/isaacs/357981" + , "another comment": "how nice" }, "that was short": "And, you're done. You know know everything JSON has to offer." -- cgit v1.2.3 From b6f889c9e6761430c72d1b967980d61f494280c5 Mon Sep 17 00:00:00 2001 From: niuzhist Date: Fri, 13 Jun 2014 19:10:37 -0700 Subject: [json/cn]: fix the original typo --- zh-cn/json-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/json-cn.html.markdown b/zh-cn/json-cn.html.markdown index 75966595..3a8db2cf 100644 --- a/zh-cn/json-cn.html.markdown +++ b/zh-cn/json-cn.html.markdown @@ -46,6 +46,6 @@ lang: zh-cn ] ], - "that was short": "And, you're done. You know know everything JSON has to offer." + "that was short": "And, you're done. You now know everything JSON has to offer." } ``` -- cgit v1.2.3 From 7bc3a435c6716931addb11251bd40fc13d77ce1a Mon Sep 17 00:00:00 2001 From: miguel araujo Date: Sat, 14 Jun 2014 01:28:20 -0300 Subject: Translating GIT and JSON to pt-br. Added link to further information --- git.html.markdown | 2 + pt-br/git-pt.html.markdown | 402 ++++++++++++++++++++++++++++++++++++++++++++ pt-br/json-pt.html.markdown | 52 ++++++ 3 files changed, 456 insertions(+) create mode 100644 pt-br/git-pt.html.markdown create mode 100644 pt-br/json-pt.html.markdown diff --git a/git.html.markdown b/git.html.markdown index 65e57f05..618d1906 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -395,3 +395,5 @@ $ 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 - the simple guide](http://rogerdudler.github.io/git-guide/index.html) \ No newline at end of file diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown new file mode 100644 index 00000000..6d2a55cd --- /dev/null +++ b/pt-br/git-pt.html.markdown @@ -0,0 +1,402 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +filename: learngit-pt.txt +--- + +Git é um sistema de controle de versão distribuído e de gerenciamento de código-fonte. + +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. + +## Versionando Conceitos + +### 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. + +### Versionamento Centralizado VS Versionamento 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. + +[Informação Adicional](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### Porque usar o Git? + +* Possibilidade de trabalhar offline +* Colaborar com os outros é fácil! +* Ramificação é fácil +* Mesclagem é fácil +* Git é rápido +* Git é flexível. + +## 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 repositório git é composto do diretório git. e árvore de trabalho. + +### 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) + +### Árvore de trabalho (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. + +### Índice (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. + +### Comete (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! + +### Ramo (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. + +### Cabeça (HEAD) e cabeça (head) (componente 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. + +### Recursos Conceituais + +* [Git para Cientistas da Computação](http://eagain.net/articles/git-for-computer-scientists/) +* [Git para Designers](http://hoth.entp.com/output/git_for_designers.html) + +## Comandos + +### 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". + +```bash +$ git init +``` + +### config + +Para configurar as definições. Quer seja para o repositório, o próprio sistema, ou +configurações globais. + +```bash +# Impressão e definir algumas variáveis ​​de configuração básica (global) +$ git config --global user.email +$ git config --global user.name + +$ 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) + +### 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. + +```bash +# Rapidamente verificar os comandos disponíveis +$ git help + +# Confira todos os comandos disponíveis +$ git help -a + +# Ajuda específica de comando - manual do usuário +# git help +$ git help add +$ git help commit +$ 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. + +```bash +# Irá exibir o ramo, os arquivos não monitorados, as alterações e outras diferenças +$ git status + +# Para saber outras "tid bits" 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! + +```bash +# Adicionar um arquivo no seu diretório de trabalho atual +$ git add HelloWorld.java + +# Adicionar um arquivo em um diretório aninhado +$ git add /path/to/file/HelloWorld.c + +# Suporte a expressões regulares! +$ git add ./*.java +``` + +### branch + +Gerenciar seus ramos. Você pode visualizar, editar, criar, apagar ramos usando este comando. + +```bash +# Lista ramos e controles remotos existentes +$ git branch -a + +# Criar um novo ramo +$ git branch myNewBranch + +# Apagar um ramo +$ git branch -d myBranch + +# Renomear um ramo +# git branch -m +$ git branch -m myBranchName myNewBranchName + +# Editar a descrição de um ramo +$ git branch myBranchName --edit-description +``` + +### checkout + +Atualiza todos os arquivos na árvore de trabalho para corresponder à versão no +índice, ou árvore especificada. + +```bash +# Finalizar um repo - padrão de ramo mestre +$ git checkout +# Checa um ramo especificado +$ git checkout branchName +# Criar um novo ramo e mudar para ela, como: " 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. + +```bash +# Clone 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. + +```bash +# commit com uma mensagem +$ 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. + +```bash +# Mostrar diferença entre o seu diretório de trabalho e o índice. +$ git diff + +# Mostrar diferenças entre o índice e o commit mais recente. +$ git diff --cached + +# Mostrar diferenças entre o seu diretório de trabalho e o commit mais recente. +$ git diff HEAD +``` + +### grep + +Permite procurar rapidamente um 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 +$ git config --global grep.lineNumber true + +# Fazer resultados de pesquisa mais legível, incluindo agrupamento +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Procure 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 \) +``` + +Google é seu amigo; para mais exemplos +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Mostrar commits para o repositório. + +```bash +# Mostrar todos os commits +$ git log + +# Mostrar um número X de commits +$ git log -n 10 + +# Mostrar somente commits mesclados +$ git log --merges +``` + +### merge + +"Merge" em mudanças de commits externos no branch atual. + +```bash +# Mesclar o ramo especificado para o atual. +$ git merge branchName + +# Gera sempre uma mesclagem commit ao mesclar +$ git merge --no-ff branchName +``` + +### mv + +Renomear ou mover um arquivo + +```bash +# Renomear 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 +$ git mv -f myFile existingFile +``` + +### pull + +Puxa de um repositório e se funde com outro ramo. + +```bash +# Atualize seu repo local, através da fusão de novas mudanças +# A partir da "origem" remoto e ramo "master (mestre)". +# git pull +# git pull => implícito por padrã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 " +$ git pull origin master --rebase +``` + +### push + +Empurre e mesclar as alterações de uma ramificação para uma remota e ramo. + +```bash +# Pressione e mesclar as alterações de um repo local para um +# Chamado remoto "origem" e ramo de "mestre". +# git push +# git push => implícito por padrã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) + +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 *. + +```bash +# Rebase experimentBranch para mestre +# git rebase +$ git rebase master experimentBranch +``` + +[Leitura Adicional.](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (CAUTELA) + +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. + +```bash +# Repor a área de teste, para coincidir com o último commit (deixa diretório inalterado) +$ git reset + +# Repor a área de teste, para coincidir com o último commit, e substituir diretório trabalhado +$ 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. +$ 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). +$ git reset --hard 31f2bb1 +``` + +### rm + +O oposto do git add, git rm remove arquivos da atual árvore de trabalho. + +```bash +# remove HelloWorld.c +$ git rm HelloWorld.c + +# Remove um arquivo de um diretório aninhado +$ git rm /pather/to/the/file/HelloWorld.c +``` + +# # Mais informações + +* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) + +* [git-scm - Video Tutorials](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) + +* [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 diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown new file mode 100644 index 00000000..da8ba78d --- /dev/null +++ b/pt-br/json-pt.html.markdown @@ -0,0 +1,52 @@ +--- +language: json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +filename: learnjson-pt.json +--- + +Como JSON é um formato de intercâmbio de dados, este será, muito provavelmente, o +"Learn X in Y minutes" mais simples existente. + +JSON na sua forma mais pura não tem comentários em reais, mas a maioria dos analisadores +aceitarão comentários no estilo C (//, /\* \*/). Para os fins do presente, no entanto, +tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. + + +```json +{ + "números": 0, + "strings": "Olá, mundo. Todo o padrão UNICODE é permitido, junto com \"escapando\".", + "possui booleano?": true, + "nada": null, + + "número grande": 1.2e+100, + + "objetos": { + "comentário": "A maior parte da sua estrutura virá de objetos.", + + "array": [0, 1, 2, 3, "Arrays podem ter qualquer coisa em si.", 5], + + "outro objeto": { + "ccomentário": "Estas coisas podem ser aninhadas, muito úteis." + } + }, + + "tolice": [ + { + "fonte de potássio": ["bananas"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer.". +} +``` -- cgit v1.2.3 From 664389fb7c17a8c7271b32270f51b38a85f75bdd Mon Sep 17 00:00:00 2001 From: chtiprog Date: Tue, 10 Jun 2014 17:52:36 +0200 Subject: Added french version of Scala --- fr-fr/scala.html.markdown | 456 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 456 insertions(+) create mode 100644 fr-fr/scala.html.markdown diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown new file mode 100644 index 00000000..56ecfb0b --- /dev/null +++ b/fr-fr/scala.html.markdown @@ -0,0 +1,456 @@ +--- +language: Scala +filename: learnscala.scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] +translators: + - ["Anne-Catherine Dehier", "https://github.com/spellart"] +filename: learn.scala +lang: fr-fr +--- + +### Scala - le langage évolutif + +```scala + +/* + Pour vous préparer : + + 1) Téléchargez Scala - http://www.scala-lang.org/downloads + 2) dézippez/décompressez dans votre endroit préféré + et ajoutez le chemin du sous-répertoire bin au chemin du système + 3) Commencez un REPL de Scala en tapant juste scala. Vous devriez voir le prompteur : + + scala> + + C'est ce qu'on appelle un REPL. Vous pouvez y exécuter des commandes. + Allons-y : +*/ + +println(10) // imprime l'integer 10 + +println("Boo!") // imprime avec retour à la ligne la chaîne de caractère Boo! + + +// Quelques basiques + +// Imprimer et forcer une nouvelle ligne à la prochaine impression +println("Hello world!") +// Imprimer sans forcer une nouvelle ligne à la prochaine impression +print("Hello world") + +// Pour déclarer des valeurs on utile var ou val +// Les déclarations val sont immuables, tandis que les var sont muables. +// L'immuabilité est une bonne chose. + +val x = 10 // x vaut maintenant 10 +x = 20 // erreur: réaffectation à val +var x = 10 +x = 20 // x vaut maintenant 20 + +// Les commentaires d'une ligne commencent par deux slashs + +/* +Les commentaires multilignes ressemblent à ça. +*/ + +// les valeurs booléennes +true +false + +// Les opérateurs booléens +!true // false +!false // true +true == false // false +10 > 5 // true + +// Les maths sont comme d'habitude +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 + + +// REPL donne le type et la valeur du résultat quand vous évaluez une commande + +1 + 7 + +/* Les lignes ci-dessous donne les résultats : + + scala> 1 + 7 + res29: Int = 8 + + Ça signifie que le résultat de l'évaluation 1 + 7 est un objet de + type Int avec une valeur de 8 + + 1+7 donnera le même résultat +*/ + + +// Tout est un objet, même une fonction. Tapez ceci dans le REPL : + +7 // donne res30: Int = 7 (res30 est seulement un nom de var généré pour le résultat) + + +// La ligne suivante est une fonction qui prend un Int et retourne son carré +(x:Int) => x * x + + +// On peut assigner cette fonction à un identifieur comme ceci : +val sq = (x:Int) => x * x + +/* La ligne suivante nous dit : + + sq: Int => Int = + + Ce qui signifie que cette fois-ci nous avons donné un nom explicite à la valeur + sq est une fonction qui prend un Int et retourne un Int. + + + sq peut-être exécuté comme ci-dessous : +*/ + +sq(10) // donne comme résultat : res33: Int = 100. + + +// les deux-points définissent explicitement le type de valeur, +// dans ce cas une fonction qui prend un Int et retourne un Int. +val add10: Int => Int = _ + 10 + +// Scala autorise des méthodes et des fonctions pour retourner, +// ou prendre comme paramètres, des autres fonctions ou méthodes + + +List(1, 2, 3) map add10 // List(11, 12, 13) - add10 est appliqué à chaque éléments + + +// Les fonctions anonymes peuvent être utilisées à la place des fonctions nommées : +List(1, 2, 3) map (x => x + 10) + + + + +// Le tiret du bas peut être utilisé si il n'y a qu'un paramètre à la fonction anonyme. +// Il se borne à une variable +List(1, 2, 3) map (_ + 10) + + + +// Si le bloc et la fonction anonyme prennent tous les deux un seul argument, +// vous pouvez omettre le tiret du bas +List("Dom", "Bob", "Natalia") foreach println + + + +// Les structures de données + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Jette une exception + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Jette une exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Jetez un oeil sur la documentation de map ici - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + */ + + +// Tuples + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(a, 2, "three") + +// Pourquoi avoir ça ? +val divideInts = (x:Int, y:Int) => (x / y, x % y) + + +divideInts(10,3) // La fonction divideInts donne le résultat et le reste de la division + +// Pour accéder à un élément d'un tuple, utilisez _._n +// où n est l'index de base 1 de l'élément +val d = divideInts(10,3) + +d._1 + +d._2 + + + +// Des combinaisons + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + + + +// La fonction filter prends un prédicat (une fonction de A -> Booléen) et +// sélectionne tous les éléments qui satisfont ce prédicat +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)) + + + +// Scala a une méthode foreach définie pour certaines collections +// qui prend un type d'argument retournant Unit (une méthode void) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + + + + +// For compréhensions + +for { n <- s } yield sq(n) + +val nSquared2 = for { n <- s } yield sq(n) + +for { n <- nSquared2 if n < 10 } yield n + +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + + + +/* Ci-dessus ce ne sont pas des boucles for. La sémantique des boucles for est "répète", + alors qu'une for-compréhension définit une relation entre deux ensembles de données. */ + + + +// Boucles et itération + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// NB: Scala est vraiment tolérant par rapport aux points et aux parenthèses en étudiant +// les roles séparément. Ça aide pour écrire des DSL ou des API qui se lisent comme en anglais + + +(5 to 1 by -1) foreach ( println ) + +// Une boucle while +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // Oui, encore. Qu'est-ce qui s'est passé ? Pourquoi ? + + + + + + +i // Montre la valeur de i. Notez que while est une boucle au sens classique. + // Il exécute séquentiellement pendant que la variable de boucle change. + // While est très rapide, plus rapide que les boucles Java, + // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus + // facile pour comprendre et faire le parallèle + +// La boucle do while +do { + println("x is still less then 10"); + x += 1 +} while (x < 10) + + +// La récursivité est un moyen idiomatique de faire une chose récurrente en Scala. +// Les fonctions récursives ont besoin d'un type de retour explicite, +// le compilateur ne peut pas le déduire. +// Ici c'est Unit. +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} + + + +// Conditionnelles + +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" + +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + + + +// Les caractéristiques orientées objets + +// Classname is Dog +class Dog { + // Une méthode appelée bark qui retourne une chaîne de caractère + def bark: String = { + // le corps de la méthode + "Woof, woof!" + } +} + + +// Les classes peuvent contenir presque n'importe quel autre constructeur, incluant d'autres classes, +// des fonctions, des méthodes, des objets, des classes case, des traits, etc ... + + + +// Les classes case + +case class Person(name:String, phoneNumber:String) + +Person("George", "1234") == Person("Kate", "1236") + + + + +// Correspondances de motifs + +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..." } + +me match { case Person("George", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + +val kate = Person("Kate", "1234") + +kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + + + +// Expressions régulières + +val email = "(.*)@(.*)".r // On fait un Regex en invoquant r sur la chaîne de caractère + +val email(user, domain) = "henry@zkpr.com" + +"mrbean@pyahoo.com" match { + case email(name, domain) => "I know your name, " + name +} + + + +// Les chaînes de caractères + +"Les chaînes de caractères Scala sont entourées de doubles guillements" // +'a' // Un caractère de Scala +'Les simples guillemets n'existent pas en Scala // Erreur +"Les chaînes de caractères possèdent les méthodes usuelles de Java".length +"Il y a aussi quelques méthodes extra de Scala.".reverse + +// Voir également : scala.collection.immutable.StringOps + +println("ABCDEF".length) +println("ABCDEF".substring(2, 6)) +println("ABCDEF".replace("C", "3")) + +val n = 45 +println(s"We have $n apples") + +val a = Array(11, 9, 6) +println(s"My second daughter is ${a(2-1)} years old") + +// Certains caractères ont besoin d'être "échappés", +// ex un double guillement à l'intérieur d'une chaîne de caractère : +val a = "They stood outside the \"Rose and Crown\"" + +// Les triples doubles guillemets permettent d'écrire des chaînes de caractères +// sur plusieurs lignes et peuvent contenir des guillements + +val html = """
+

Press belo', Joe

+ | +
""" + + + +// Structure et organisation d'une application + +// Importer des chaînes de caratères +import scala.collection.immutable.List + +// Importer tous les sous-paquets +import scala.collection.immutable._ + +// Importer des classes multiples en une seule instruction +import scala.collection.immutable.{List, Map} + +// Renommer un import en utilisant '=>' +import scala.collection.immutable.{ List => ImmutableList } + +// Importer toutes les classes, à l'exception de quelques unes. +// Les suivantes excluant Map et Set : +import scala.collection.immutable.{Map => _, Set => _, _} + +// Le point d'entrée du programme est défini dans un fichier scala +// utilisant un objet, avec une simple méthode, main : +object Application { + def main(args: Array[String]): Unit = { + // stuff goes here. + } +} + +// Les fichiers peuvent contenir des classes multiples et des objets. +// On les compile avec scalac + + + + +// Entrée et Sortie + +// Pour lire un fichier lignes par lignes +import scala.io.Source +for(line <- Source.fromFile("myfile.txt").getLines()) + println(line) + +// On utilise Java's PrintWriter pour écrire un fichier + + +``` + +## Autres ressources + +[Scala for the impatient](http://horstmann.com/scala/) + +[Twitter Scala school](http://twitter.github.io/scala_school/) + +[The scala documentation](http://docs.scala-lang.org/) + +[Try Scala in your browser](http://scalatutorials.com/tour/) + +Rejoindre le[Scala user group](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From f011c1af0e84570e567d07e48904b579b8b58a1f Mon Sep 17 00:00:00 2001 From: chtiprog Date: Tue, 10 Jun 2014 23:12:07 +0200 Subject: Updated french version of scala --- fr-fr/scala.html.markdown | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown index 56ecfb0b..dfcdf7cc 100644 --- a/fr-fr/scala.html.markdown +++ b/fr-fr/scala.html.markdown @@ -148,12 +148,12 @@ List("Dom", "Bob", "Natalia") foreach println val a = Array(1, 2, 3, 5, 8, 13) a(0) a(3) -a(21) // Jette une exception +a(21) // Lance une exception val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") m("fork") m("spoon") -m("bottle") // Jette une exception +m("bottle") // Lance une exception val safeM = m.withDefaultValue("no lo se") safeM("bottle") @@ -183,7 +183,7 @@ val divideInts = (x:Int, y:Int) => (x / y, x % y) divideInts(10,3) // La fonction divideInts donne le résultat et le reste de la division -// Pour accéder à un élément d'un tuple, utilisez _._n +// Pour accéder à un élément d'un tuple, utilisez _._n // où n est l'index de base 1 de l'élément val d = divideInts(10,3) @@ -233,7 +233,7 @@ for { n <- nSquared2 if n < 10 } yield n for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared - + /* Ci-dessus ce ne sont pas des boucles for. La sémantique des boucles for est "répète", alors qu'une for-compréhension définit une relation entre deux ensembles de données. */ @@ -265,9 +265,9 @@ while (i < 10) { println("i " + i); i+=1 } // Oui, encore. Qu'est-ce qui s'es i // Montre la valeur de i. Notez que while est une boucle au sens classique. - // Il exécute séquentiellement pendant que la variable de boucle change. - // While est très rapide, plus rapide que les boucles Java, - // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus + // Il exécute séquentiellement pendant que la variable de boucle change. + // While est très rapide, plus rapide que les boucles Java, + // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus // facile pour comprendre et faire le parallèle // La boucle do while @@ -278,8 +278,8 @@ do { // La récursivité est un moyen idiomatique de faire une chose récurrente en Scala. -// Les fonctions récursives ont besoin d'un type de retour explicite, -// le compilateur ne peut pas le déduire. +// Les fonctions récursives ont besoin d'un type de retour explicite, +// le compilateur ne peut pas le déduire. // Ici c'est Unit. def showNumbersInRange(a:Int, b:Int):Unit = { print(a) @@ -355,7 +355,7 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Expressions régulières -val email = "(.*)@(.*)".r // On fait un Regex en invoquant r sur la chaîne de caractère +val email = "(.*)@(.*)".r // On fait un Regex en invoquant r sur la chaîne de caractère val email(user, domain) = "henry@zkpr.com" @@ -370,8 +370,8 @@ val email(user, domain) = "henry@zkpr.com" "Les chaînes de caractères Scala sont entourées de doubles guillements" // 'a' // Un caractère de Scala 'Les simples guillemets n'existent pas en Scala // Erreur -"Les chaînes de caractères possèdent les méthodes usuelles de Java".length -"Il y a aussi quelques méthodes extra de Scala.".reverse +"Les chaînes de caractères possèdent les méthodes usuelles de Java".length +"Il y a aussi quelques méthodes extra de Scala.".reverse // Voir également : scala.collection.immutable.StringOps @@ -385,7 +385,7 @@ println(s"We have $n apples") val a = Array(11, 9, 6) println(s"My second daughter is ${a(2-1)} years old") -// Certains caractères ont besoin d'être "échappés", +// Certains caractères ont besoin d'être "échappés", // ex un double guillement à l'intérieur d'une chaîne de caractère : val a = "They stood outside the \"Rose and Crown\"" @@ -410,14 +410,14 @@ import scala.collection.immutable._ // Importer des classes multiples en une seule instruction import scala.collection.immutable.{List, Map} -// Renommer un import en utilisant '=>' +// Renommer un import en utilisant '=>' import scala.collection.immutable.{ List => ImmutableList } -// Importer toutes les classes, à l'exception de quelques unes. +// Importer toutes les classes, à l'exception de quelques unes. // Les suivantes excluant Map et Set : import scala.collection.immutable.{Map => _, Set => _, _} -// Le point d'entrée du programme est défini dans un fichier scala +// Le point d'entrée du programme est défini dans un fichier scala // utilisant un objet, avec une simple méthode, main : object Application { def main(args: Array[String]): Unit = { @@ -425,7 +425,7 @@ object Application { } } -// Les fichiers peuvent contenir des classes multiples et des objets. +// Les fichiers peuvent contenir des classes multiples et des objets. // On les compile avec scalac -- cgit v1.2.3 From 57cc424b54736287f911777f8b9615882647374d Mon Sep 17 00:00:00 2001 From: chtiprog Date: Sat, 14 Jun 2014 13:04:18 +0200 Subject: Corrections after pull request of the french translation of Scala --- fr-fr/scala.html.markdown | 96 ++++++++++++++++++++++++----------------------- 1 file changed, 49 insertions(+), 47 deletions(-) diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown index dfcdf7cc..2e18d219 100644 --- a/fr-fr/scala.html.markdown +++ b/fr-fr/scala.html.markdown @@ -18,19 +18,20 @@ lang: fr-fr Pour vous préparer : 1) Téléchargez Scala - http://www.scala-lang.org/downloads - 2) dézippez/décompressez dans votre endroit préféré + 2) Dézippez/décompressez dans votre endroit préféré et ajoutez le chemin du sous-répertoire bin au chemin du système 3) Commencez un REPL de Scala en tapant juste scala. Vous devriez voir le prompteur : scala> - C'est ce qu'on appelle un REPL. Vous pouvez y exécuter des commandes. + C'est ce qu'on appelle un REPL (Read-Eval-Print-Loop), c'est une interface de programmation interactive. + Vous pouvez y exécuter des commandes. Allons-y : */ -println(10) // imprime l'integer 10 +println(10) // affiche l'integer 10 -println("Boo!") // imprime avec retour à la ligne la chaîne de caractère Boo! +println("Boo!") // affiche avec retour à la ligne la chaîne de caractère Boo! // Quelques basiques @@ -40,14 +41,14 @@ println("Hello world!") // Imprimer sans forcer une nouvelle ligne à la prochaine impression print("Hello world") -// Pour déclarer des valeurs on utile var ou val +// Pour déclarer des valeurs on utilise var ou val // Les déclarations val sont immuables, tandis que les var sont muables. // L'immuabilité est une bonne chose. val x = 10 // x vaut maintenant 10 -x = 20 // erreur: réaffectation à val +x = 20 // erreur : réaffectation à val var x = 10 -x = 20 // x vaut maintenant 20 +x = 20 // x vaut maintenant 20 // Les commentaires d'une ligne commencent par deux slashs @@ -65,18 +66,18 @@ false true == false // false 10 > 5 // true -// Les maths sont comme d'habitude +// Les opérateurs mathématiques sont habituels 1 + 1 // 2 2 - 1 // 1 5 * 3 // 15 6 / 2 // 3 -// REPL donne le type et la valeur du résultat quand vous évaluez une commande +// Le REPL donne le type et la valeur du résultat quand vous évaluez une commande 1 + 7 -/* Les lignes ci-dessous donne les résultats : +/* Les lignes ci-dessous donnent les résultats : scala> 1 + 7 res29: Int = 8 @@ -90,7 +91,7 @@ true == false // false // Tout est un objet, même une fonction. Tapez ceci dans le REPL : -7 // donne res30: Int = 7 (res30 est seulement un nom de var généré pour le résultat) +7 // donne res30: Int = 7 (res30 est seulement un nom de variable généré pour le résultat) // La ligne suivante est une fonction qui prend un Int et retourne son carré @@ -104,22 +105,22 @@ val sq = (x:Int) => x * x sq: Int => Int = - Ce qui signifie que cette fois-ci nous avons donné un nom explicite à la valeur + Ce qui signifie que cette fois-ci nous avons donné un nom explicite à la valeur. sq est une fonction qui prend un Int et retourne un Int. - sq peut-être exécuté comme ci-dessous : + sq peut être exécutée comme ci-dessous : */ -sq(10) // donne comme résultat : res33: Int = 100. +sq(10) // donne comme résultat : res33: Int = 100. -// les deux-points définissent explicitement le type de valeur, +// les deux-points définissent explicitement le type de la valeur, // dans ce cas une fonction qui prend un Int et retourne un Int. val add10: Int => Int = _ + 10 -// Scala autorise des méthodes et des fonctions pour retourner, -// ou prendre comme paramètres, des autres fonctions ou méthodes +// Scala autorise des méthodes et des fonctions à retourner +// ou prendre comme paramètres des autres fonctions ou méthodes List(1, 2, 3) map add10 // List(11, 12, 13) - add10 est appliqué à chaque éléments @@ -131,8 +132,8 @@ List(1, 2, 3) map (x => x + 10) -// Le tiret du bas peut être utilisé si il n'y a qu'un paramètre à la fonction anonyme. -// Il se borne à une variable +// Le tiret du bas peut être utilisé si la fonction anonyme ne prend qu'un paramètre. +// Il se comporte comme une variable List(1, 2, 3) map (_ + 10) @@ -177,7 +178,7 @@ s(1) (a, 2, "three") -// Pourquoi avoir ça ? +// Exemple d'utilisation val divideInts = (x:Int, y:Int) => (x / y, x % y) @@ -205,7 +206,7 @@ sSquared.reduce (_+_) -// La fonction filter prends un prédicat (une fonction de A -> Booléen) et +// La fonction filter prend un prédicat (une fonction de type A -> Booléen) et // sélectionne tous les éléments qui satisfont ce prédicat List(1, 2, 3) filter (_ > 2) // List(3) List( @@ -216,14 +217,14 @@ List( // Scala a une méthode foreach définie pour certaines collections -// qui prend un type d'argument retournant Unit (une méthode void) +// qui prend en argument une fonction renvoyant Unit (une méthode void) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println -// For compréhensions +// Compréhensions de listes for { n <- s } yield sq(n) @@ -235,8 +236,9 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared -/* Ci-dessus ce ne sont pas des boucles for. La sémantique des boucles for est "répète", - alors qu'une for-compréhension définit une relation entre deux ensembles de données. */ +/* Les exemples précédents ne sont pas des boucles for. La sémantique des boucles for + est "répète", alors qu'une for-compréhension définit une relation + entre deux ensembles de données. */ @@ -247,8 +249,8 @@ val r = 1 to 5 r.foreach( println ) r foreach println -// NB: Scala est vraiment tolérant par rapport aux points et aux parenthèses en étudiant -// les roles séparément. Ça aide pour écrire des DSL ou des API qui se lisent comme en anglais +// NB: Scala est vraiment tolérant par rapport aux points et aux parenthèses en étudiant les roles séparément. +// Ça aide pour écrire des DSL ou des API qui se lisent comme en anglais. (5 to 1 by -1) foreach ( println ) @@ -277,7 +279,7 @@ do { } while (x < 10) -// La récursivité est un moyen idiomatique de faire une chose récurrente en Scala. +// La récursivité est un moyen idiomatique de faire une chose répétitive en Scala. // Les fonctions récursives ont besoin d'un type de retour explicite, // le compilateur ne peut pas le déduire. // Ici c'est Unit. @@ -289,7 +291,7 @@ def showNumbersInRange(a:Int, b:Int):Unit = { -// Conditionnelles +// Structures de contrôle val x = 10 @@ -306,9 +308,9 @@ while (i < 10) { println("i " + i); i+=1 } -// Les caractéristiques orientées objets +// Les caractéristiques "Orienté Objet" -// Classname is Dog +// Création d'une classe Dog class Dog { // Une méthode appelée bark qui retourne une chaîne de caractère def bark: String = { @@ -318,7 +320,7 @@ class Dog { } -// Les classes peuvent contenir presque n'importe quel autre constructeur, incluant d'autres classes, +// Les classes peuvent contenir presque n'importe quelle autre construction, incluant d'autres classes, // des fonctions, des méthodes, des objets, des classes case, des traits, etc ... @@ -355,7 +357,7 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Expressions régulières -val email = "(.*)@(.*)".r // On fait un Regex en invoquant r sur la chaîne de caractère +val email = "(.*)@(.*)".r // On fait une Regex en invoquant r sur la chaîne de caractère val email(user, domain) = "henry@zkpr.com" @@ -367,13 +369,13 @@ val email(user, domain) = "henry@zkpr.com" // Les chaînes de caractères -"Les chaînes de caractères Scala sont entourées de doubles guillements" // +"Les chaînes de caractères Scala sont entourées de doubles guillements" 'a' // Un caractère de Scala 'Les simples guillemets n'existent pas en Scala // Erreur "Les chaînes de caractères possèdent les méthodes usuelles de Java".length "Il y a aussi quelques méthodes extra de Scala.".reverse -// Voir également : scala.collection.immutable.StringOps +// Voir également : scala.collection.immutable.StringOps println("ABCDEF".length) println("ABCDEF".substring(2, 6)) @@ -386,11 +388,11 @@ val a = Array(11, 9, 6) println(s"My second daughter is ${a(2-1)} years old") // Certains caractères ont besoin d'être "échappés", -// ex un double guillement à l'intérieur d'une chaîne de caractère : +// ex un guillemet à l'intérieur d'une chaîne de caractères : val a = "They stood outside the \"Rose and Crown\"" -// Les triples doubles guillemets permettent d'écrire des chaînes de caractères -// sur plusieurs lignes et peuvent contenir des guillements +// Les triples guillemets permettent d'écrire des chaînes de caractères +// sur plusieurs lignes et peuvent contenir des guillemets val html = """

Press belo', Joe

@@ -407,25 +409,25 @@ import scala.collection.immutable.List // Importer tous les sous-paquets import scala.collection.immutable._ -// Importer des classes multiples en une seule instruction +// Importer plusieurs classes en une seule instruction import scala.collection.immutable.{List, Map} // Renommer un import en utilisant '=>' import scala.collection.immutable.{ List => ImmutableList } -// Importer toutes les classes, à l'exception de quelques unes. -// Les suivantes excluant Map et Set : +// Importer toutes les classes, à l'exception de certaines. +// La ligne suivante exclut Map et Set : import scala.collection.immutable.{Map => _, Set => _, _} // Le point d'entrée du programme est défini dans un fichier scala -// utilisant un objet, avec une simple méthode, main : +// utilisant un objet, avec une simple méthode main : object Application { def main(args: Array[String]): Unit = { - // stuff goes here. + // Votre code ici. } } -// Les fichiers peuvent contenir des classes multiples et des objets. +// Les fichiers peuvent contenir plusieurs classes et plusieurs objets. // On les compile avec scalac @@ -433,12 +435,12 @@ object Application { // Entrée et Sortie -// Pour lire un fichier lignes par lignes +// Pour lire un fichier ligne par ligne import scala.io.Source for(line <- Source.fromFile("myfile.txt").getLines()) println(line) -// On utilise Java's PrintWriter pour écrire un fichier +// On utilise le PrintWriter de Java pour écrire un fichier ``` @@ -453,4 +455,4 @@ for(line <- Source.fromFile("myfile.txt").getLines()) [Try Scala in your browser](http://scalatutorials.com/tour/) -Rejoindre le[Scala user group](https://groups.google.com/forum/#!forum/scala-user) +Rejoindre le [Scala user group](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From ad9186f4f8389cb4cb23744a80bcf7bf47735869 Mon Sep 17 00:00:00 2001 From: chtiprog Date: Sat, 14 Jun 2014 19:26:14 +0200 Subject: Updated links and fix typo --- fr-fr/scala.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown index 2e18d219..46f602ff 100644 --- a/fr-fr/scala.html.markdown +++ b/fr-fr/scala.html.markdown @@ -17,14 +17,14 @@ lang: fr-fr /* Pour vous préparer : - 1) Téléchargez Scala - http://www.scala-lang.org/downloads + 1) (Téléchargez Scala)[http://www.scala-lang.org/downloads] 2) Dézippez/décompressez dans votre endroit préféré et ajoutez le chemin du sous-répertoire bin au chemin du système 3) Commencez un REPL de Scala en tapant juste scala. Vous devriez voir le prompteur : scala> - C'est ce qu'on appelle un REPL (Read-Eval-Print-Loop), c'est une interface de programmation interactive. + C'est ce qu'on appelle un REPL (Read-Eval-Print-Loop), c'est une interface de programmation interactive. Vous pouvez y exécuter des commandes. Allons-y : */ @@ -237,7 +237,7 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared /* Les exemples précédents ne sont pas des boucles for. La sémantique des boucles for - est "répète", alors qu'une for-compréhension définit une relation + est "répète", alors qu'une for-compréhension définit une relation entre deux ensembles de données. */ @@ -249,7 +249,7 @@ val r = 1 to 5 r.foreach( println ) r foreach println -// NB: Scala est vraiment tolérant par rapport aux points et aux parenthèses en étudiant les roles séparément. +// NB: Scala est vraiment tolérant par rapport aux points et aux parenthèses en étudiant les roles séparément. // Ça aide pour écrire des DSL ou des API qui se lisent comme en anglais. @@ -270,7 +270,7 @@ i // Montre la valeur de i. Notez que while est une boucle au sens classique. // Il exécute séquentiellement pendant que la variable de boucle change. // While est très rapide, plus rapide que les boucles Java, // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus - // facile pour comprendre et faire le parallèle + // facile pour comprendre et faire la parallélisation // La boucle do while do { -- cgit v1.2.3 From 7c306cead86cbcfe56c0f5b112066260389b28ea Mon Sep 17 00:00:00 2001 From: chtiprog Date: Sat, 14 Jun 2014 19:37:45 +0200 Subject: Removing comparison with java performance for while loops --- fr-fr/scala.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown index 46f602ff..da562138 100644 --- a/fr-fr/scala.html.markdown +++ b/fr-fr/scala.html.markdown @@ -268,9 +268,9 @@ while (i < 10) { println("i " + i); i+=1 } // Oui, encore. Qu'est-ce qui s'es i // Montre la valeur de i. Notez que while est une boucle au sens classique. // Il exécute séquentiellement pendant que la variable de boucle change. - // While est très rapide, plus rapide que les boucles Java, + // While est très rapide, // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus - // facile pour comprendre et faire la parallélisation + // facile pour comprendre et pour faire la parallélisation // La boucle do while do { -- cgit v1.2.3 From 9f2929605470ba40b5dfe717554972f18f497826 Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Mon, 16 Jun 2014 14:47:43 -0400 Subject: Update python3.html.markdown fixed python 3 english sets error and editted .add comment because .add only accepts one argument --- python3.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index 77811535..778076f8 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -238,7 +238,10 @@ 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} -# Add more items to a set +#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 & -- cgit v1.2.3 From 3d87e263508280977000d94d52a6a9ab5314c6ca Mon Sep 17 00:00:00 2001 From: miguel araujo Date: Thu, 19 Jun 2014 11:33:59 -0300 Subject: JSON updated --- pt-br/json-pt.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index da8ba78d..fc63b126 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -2,6 +2,7 @@ language: json contributors: - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] translators: - ["Miguel Araújo", "https://github.com/miguelarauj1o"] lang: pt-br @@ -18,6 +19,9 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. ```json { + "chave": "valor", + + "chaves": "deve ser sempre entre aspas (junto ou separado)", "números": 0, "strings": "Olá, mundo. Todo o padrão UNICODE é permitido, junto com \"escapando\".", "possui booleano?": true, @@ -47,6 +51,12 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. ] ], + "estilo alternativo": { + "comentário": "verificar isso!" + , "posição da vírgula": "não importa - enquanto é antes do valor, então é válido" + , "outro comentário": "que bom" + }, + "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer.". } ``` -- cgit v1.2.3 From 03c03f7d19c4bc5af5525543f43dc83a507a25a7 Mon Sep 17 00:00:00 2001 From: Jichao Ouyang Date: Sat, 21 Jun 2014 00:01:09 +0800 Subject: [julia/zh-cn] Chinese translation for Julia --- zh-cn/julia-cn.html.markdown | 729 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 729 insertions(+) create mode 100644 zh-cn/julia-cn.html.markdown diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown new file mode 100644 index 00000000..b7239786 --- /dev/null +++ b/zh-cn/julia-cn.html.markdown @@ -0,0 +1,729 @@ +--- +language: julia +filename: learn-julia-zh.jl +contributors: + - ["Jichao Ouyang", "http://oyanglul.us"] +translators: + - ["Jichao Ouyang"] +lang: zh-cn +--- + +```julia +# 单行注释只需要一个井号 +#= 多行注释 + 只需要以 '#=' 开始 '=#' 结束 + 还可以嵌套. +=# + +#################################################### +## 1. 原始类型与操作符 +#################################################### + +# Julia 中一切皆是表达式。 + +# 这是一些基本数字类型. +3 # => 3 (Int64) +3.2 # => 3.2 (Float64) +2 + 1im # => 2 + 1im (Complex{Int64}) +2//3 # => 2//3 (Rational{Int64}) + +# 支持所有的普通中缀操作符。 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 +5 / 2 # => 2.5 # 用 Int 除 Int 永远返回 Float +div(5, 2) # => 2 # 使用 div 截断小数点 +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # 次方, 不是二进制 xor +12 % 10 # => 2 + +# 用括号提高优先级 +(1 + 3) * 2 # => 8 + +# 二进制操作符 +~2 # => -3 # 非 +3 & 5 # => 1 # 与 +2 | 4 # => 6 # 或 +2 $ 4 # => 6 # 异或 +2 >>> 1 # => 1 # 逻辑右移 +2 >> 1 # => 1 # 算术右移 +2 << 1 # => 4 # 逻辑/算术 右移 + +# 可以用函数 bits 查看二进制数。 +bits(12345) +# => "0000000000000000000000000000000000000000000000000011000000111001" +bits(12345.0) +# => "0100000011001000000111001000000000000000000000000000000000000000" + +# 布尔值是原始类型 +true +false + +# 布尔操作符 +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +1 < 10 # => true +1 > 10 # => false +2 <= 2 # => true +2 >= 2 # => true +# 比较可以串联 +1 < 2 < 3 # => true +2 < 3 < 2 # => false + +# 字符串可以由 " 创建 +"This is a string." + +# 字符字面量可用 ' 创建 +'a' + +# 可以像取数组取值一样用 index 取出对应字符 +"This is a string"[1] # => 'T' # Julia 的 index 从 1 开始 :( +# 但是对 UTF-8 无效, +# 因此建议使用遍历器 (map, for loops, 等). + +# $ 可用于字符插值: +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" +# 可以将任何 Julia 表达式放入括号。 + +# 另一种格式化字符串的方式是 printf 宏. +@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 + +# 打印字符串很容易 +println("I'm Julia. Nice to meet you!") + +#################################################### +## 2. 变量与集合 +#################################################### + +# 给变量赋值就是声明变量 +some_var = 5 # => 5 +some_var # => 5 + +# 访问未声明变量会抛出异常 +try + some_other_var # => ERROR: some_other_var not defined +catch e + println(e) +end + +# 变量名需要以字母开头. +# 之后任何字母,数字,下划线,叹号都是合法的。 +SomeOtherVar123! = 6 # => 6 + +# 甚至可以用 unicode 字符 +☃ = 8 # => 8 +# 用数学符号非常方便 +2 * π # => 6.283185307179586 + +# 注意 Julia 的命名规约: +# +# * 变量名为小写,单词之间以下划线连接('\_')。 +# +# * 类型名以大写字母开头,单词以 CamelCase 方式连接。 +# +# * 函数与宏的名字小写,无下划线。 +# +# * 会改变输入的函数名末位为 !。 +# 这类函数有时被称为 mutating functions 或 in-place functions. + +# 数组存储一列值,index 从 1 开始。 +a = Int64[] # => 0-element Int64 Array + +# 一维数组可以以逗号分隔值的方式声明。 +b = [4, 5, 6] # => 包含 3 个 Int64 类型元素的数组: [4, 5, 6] +b[1] # => 4 +b[end] # => 6 + +# 二维数组以分号分隔维度。 +matrix = [1 2; 3 4] # => 2x2 Int64 数组: [1 2; 3 4] + +# 使用 push! 和 append! 往数组末尾添加元素 +push!(a,1) # => [1] +push!(a,2) # => [1,2] +push!(a,4) # => [1,2,4] +push!(a,3) # => [1,2,4,3] +append!(a,b) # => [1,2,4,3,4,5,6] + +# 用 pop 弹出末尾元素 +pop!(b) # => 6 and b is now [4,5] + +# 可以再放回去 +push!(b,6) # b 又变成了 [4,5,6]. + +a[1] # => 1 # 永远记住 Julia 的 index 从 1 开始! + +# 用 end 可以直接取到最后索引. 可用作任何索引表达式 +a[end] # => 6 + +# 还支持 shift 和 unshift +shift!(a) # => 返回 1,而 a 现在时 [2,4,3,4,5,6] +unshift!(a,7) # => [7,2,4,3,4,5,6] + +# 以叹号结尾的函数名表示它会改变参数的值 +arr = [5,4,6] # => 包含三个 Int64 元素的数组: [5,4,6] +sort(arr) # => [4,5,6]; arr 还是 [5,4,6] +sort!(arr) # => [4,5,6]; arr 现在是 [4,5,6] + +# 越界会抛出 BoundsError 异常 +try + a[0] # => ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 +catch e + println(e) +end + +# 错误会指出发生的行号,包括标准库 +# 如果你有 Julia 源代码,你可以找到这些地方 + +# 可以用 range 初始化数组 +a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] + +# 可以切割数组 +a[1:3] # => [1, 2, 3] +a[2:end] # => [2, 3, 4, 5] + +# 用 splice! 切割原数组 +arr = [3,4,5] +splice!(arr,2) # => 4 ; arr 变成了 [3,5] + +# 用 append! 连接数组 +b = [1,2,3] +append!(a,b) # a 变成了 [1, 2, 3, 4, 5, 1, 2, 3] + +# 检查元素是否在数组中 +in(1, a) # => true + +# 用 length 获得数组长度 +length(a) # => 8 + +# Tuples 是 immutable 的 +tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. +tup[1] # => 1 +try: + tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +catch e + println(e) +end + +# 大多数组的函数同样支持 tuples +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true + +# 可以将 tuples 元素分别赋给变量 +a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 + +# 不用括号也可以 +d, e, f = 4, 5, 6 # => (4,5,6) + +# 单元素 tuple 不等于其元素值 +(1,) == 1 # => false +(1) == 1 # => true + +# 交换值 +e, d = d, e # => (5,4) # d is now 5 and e is now 4 + + +# 字典Dictionaries store mappings +empty_dict = Dict() # => Dict{Any,Any}() + +# 也可以用字面量创建字典 +filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +# => Dict{ASCIIString,Int64} + +# 用 [] 获得键值 +filled_dict["one"] # => 1 + +# 获得所有键 +keys(filled_dict) +# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# 注意,键的顺序不是插入时的顺序 + +# 获得所有值 +values(filled_dict) +# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# 注意,值的顺序也一样 + +# 用 in 检查键值是否已存在,用 haskey 检查键是否存在 +in(("one", 1), filled_dict) # => true +in(("two", 3), filled_dict) # => false +haskey(filled_dict, "one") # => true +haskey(filled_dict, 1) # => false + +# 获取不存在的键的值会抛出异常 +try + filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 +catch e + println(e) +end + +# 使用 get 可以提供默认值来避免异常 +# get(dictionary,key,default_value) +get(filled_dict,"one",4) # => 1 +get(filled_dict,"four",4) # => 4 + +# 用 Sets 表示无序不可重复的值的集合 +empty_set = Set() # => Set{Any}() +# 初始化一个 Set 并定义其值 +filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) + +# 添加值 +push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) + +# 检查是否存在某值 +in(2, filled_set) # => true +in(10, filled_set) # => false + +# 交集,并集,差集 +other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) +intersect(filled_set, other_set) # => Set{Int64}(3,4,5) +union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) +setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) + + +#################################################### +## 3. 控制流 +#################################################### + +# 声明一个变量 +some_var = 5 + +# 这是一个 if 语句,缩进不是必要的 +if some_var > 10 + println("some_var is totally bigger than 10.") +elseif some_var < 10 # elseif 是可选的. + println("some_var is smaller than 10.") +else # else 也是可选的. + println("some_var is indeed 10.") +end +# => prints "some var is smaller than 10" + + +# For 循环遍历 +# Iterable 类型包括 Range, Array, Set, Dict, 以及 String. +for animal=["dog", "cat", "mouse"] + println("$animal is a mammal") + # 可用 $ 将 variables 或 expression 转换为字符串into strings +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# You can use 'in' instead of '='. +for animal in ["dog", "cat", "mouse"] + println("$animal is a mammal") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$(a[1]) is a $(a[2])") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$k is a $v") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# While 循环 +x = 0 +while x < 4 + println(x) + x += 1 # x = x + 1 +end +# prints: +# 0 +# 1 +# 2 +# 3 + +# 用 try/catch 处理异常 +try + error("help") +catch e + println("caught it $e") +end +# => caught it ErrorException("help") + + +#################################################### +## 4. 函数 +#################################################### + +# 用关键字 'function' 可创建一个新函数 +#function name(arglist) +# body... +#end +function add(x, y) + println("x is $x and y is $y") + + # 最后一行语句的值为返回 + x + y +end + +add(5, 6) # => 在 "x is 5 and y is 6" 后会打印 11 + +# 还可以定义接收可变长参数的函数 +function varargs(args...) + return args + # 关键字 return 可在函数内部任何地方返回 +end +# => varargs (generic function with 1 method) + +varargs(1,2,3) # => (1,2,3) + +# 省略号 ... 被称为 splat. +# 刚刚用在了函数定义中 +# 还可以用在函数的调用 +# Array 或者 Tuple 的内容会变成参数列表 +Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # 获得一个 Array 的 Set +Set([1,2,3]...) # => Set{Int64}(1,2,3) # 相当于 Set(1,2,3) + +x = (1,2,3) # => (1,2,3) +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # 一个 Tuple 的 Set +Set(x...) # => Set{Int64}(2,3,1) + + +# 可定义可选参数的函数 +function defaults(a,b,x=5,y=6) + return "$a $b and $x $y" +end + +defaults('h','g') # => "h g and 5 6" +defaults('h','g','j') # => "h g and j 6" +defaults('h','g','j','k') # => "h g and j k" +try + defaults('h') # => ERROR: no method defaults(Char,) + defaults() # => ERROR: no methods defaults() +catch e + println(e) +end + +# 还可以定义键值对的参数 +function keyword_args(;k1=4,name2="hello") # note the ; + return ["k1"=>k1,"name2"=>name2] +end + +keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] +keyword_args() # => ["name2"=>"hello","k1"=>4] + +# 可以组合各种类型的参数在同一个函数的参数列表中 +function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") + println("normal arg: $normal_arg") + println("optional arg: $optional_positional_arg") + println("keyword arg: $keyword_arg") +end + +all_the_args(1, 3, keyword_arg=4) +# prints: +# normal arg: 1 +# optional arg: 3 +# keyword arg: 4 + +# Julia 有一等函数 +function create_adder(x) + adder = function (y) + return x + y + end + return adder +end + +# 这是用 "stabby lambda syntax" 创建的匿名函数 +(x -> x > 2)(3) # => true + +# 这个函数和上面的 create_adder 一模一样 +function create_adder(x) + y -> x + y +end + +# 你也可以给内部函数起个名字 +function create_adder(x) + function adder(y) + x + y + end + adder +end + +add_10 = create_adder(10) +add_10(3) # => 13 + + +# 内置的高阶函数有 +map(add_10, [1,2,3]) # => [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# 还可以使用 list comprehensions 替代 map +[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] + +#################################################### +## 5. 类型 +#################################################### + +# Julia 有类型系统 +# 所有的值都有类型;但变量本身没有类型 +# 你可以用 `typeof` 函数获得值的类型 +typeof(5) # => Int64 + +# 类型是一等值 +typeof(Int64) # => DataType +typeof(DataType) # => DataType +# DataType 是代表类型的类型,也代表他自己的类型 + +# 类型可用作文档化,优化,以及调度 +# 并不是静态检查类型 + +# 用户还可以自定义类型 +# 跟其他语言的 records 或 structs 一样 +# 用 `type` 关键字定义新的类型 + +# type Name +# field::OptionalType +# ... +# end +type Tiger + taillength::Float64 + coatcolor # 不附带类型标注的相当于 `::Any` +end + +# 构造函数参数是类型的属性 +tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") + +# 用新类型作为构造函数还会创建一个类型 +sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") + +# struct 类似的类型被称为具体类型 +# 他们可被实例化但不能有子类型 +# 另一种类型是抽象类型 + +# abstract Name +abstract Cat # just a name and point in the type hierarchy + +# 抽象类型不能被实例化,但是可以有子类型 +# 例如,Number 就是抽象类型 +subtypes(Number) # => 6-element Array{Any,1}: + # Complex{Float16} + # Complex{Float32} + # Complex{Float64} + # Complex{T<:Real} + # ImaginaryUnit + # Real +subtypes(Cat) # => 0-element Array{Any,1} + +# 所有的类型都有父类型; 可以用函数 `super` 得到父类型. +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Number +super(Any) # => Any +# 所有这些类型,除了 Int64, 都是抽象类型. + +# <: 是类型集成操作符 +type Lion <: Cat # Lion 是 Cat 的子类型 + mane_color + roar::String +end + +# 可以继续为你的类型定义构造函数 +# 只需要定义一个同名的函数 +# 并调用已有的构造函数设置一个固定参数 +Lion(roar::String) = Lion("green",roar) +# 这是一个外部构造函数,因为他再类型定义之外 + +type Panther <: Cat # Panther 也是 Cat 的子类型 + eye_color + Panther() = new("green") + # Panthers 只有这个构造函数,没有默认构造函数 +end +# 使用内置构造函数,如 Panther,可以让你控制 +# 如何构造类型的值 +# 应该尽可能使用外部构造函数而不是内部构造函数 + +#################################################### +## 6. 多分派 +#################################################### + +# 在Julia中, 所有的具名函数都是类属函数 +# 这意味着他们都是有很大小方法组成的 +# 每个 Lion 的构造函数都是类属函数 Lion 的方法 + +# 我们来看一个非构造函数的例子 + +# Lion, Panther, Tiger 的 meow 定义为 +function meow(animal::Lion) + animal.roar # 使用点符号访问属性 +end + +function meow(animal::Panther) + "grrr" +end + +function meow(animal::Tiger) + "rawwwr" +end + +# 试试 meow 函数 +meow(tigger) # => "rawwr" +meow(Lion("brown","ROAAR")) # => "ROAAR" +meow(Panther()) # => "grrr" + +# 再看看层次结构 +issubtype(Tiger,Cat) # => false +issubtype(Lion,Cat) # => true +issubtype(Panther,Cat) # => true + +# 定义一个接收 Cats 的函数 +function pet_cat(cat::Cat) + println("The cat says $(meow(cat))") +end + +pet_cat(Lion("42")) # => prints "The cat says 42" +try + pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) +catch e + println(e) +end + +# 在面向对象语言中,通常都是单分派 +# 这意味着分派方法是通过第一个参数的类型决定的 +# 在Julia中, 所有参数类型都会被考虑到 + +# 让我们定义有多个参数的函数,好看看区别 +function fight(t::Tiger,c::Cat) + println("The $(t.coatcolor) tiger wins!") +end +# => fight (generic function with 1 method) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! + +# 让我们修改一下传入具体为 Lion 类型时的行为 +fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") +# => fight (generic function with 2 methods) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! + +# 把 Tiger 去掉 +fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +# => fight (generic function with 3 methods) + +fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr +try + fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) +catch +end + +# 在试试让 Cat 在前面 +fight(c::Cat,l::Lion) = println("The cat beats the Lion") +# => Warning: New definition +# fight(Cat,Lion) at none:1 +# is ambiguous with +# fight(Lion,Cat) at none:2. +# Make sure +# fight(Lion,Lion) +# is defined first. +#fight (generic function with 4 methods) + +# 警告说明了无法判断使用哪个 fight 方法 +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr +# 结果在老版本 Julia 中可能会不一样 + +fight(l::Lion,l2::Lion) = println("The lions come to a tie") +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie + + +# Under the hood +# 你还可以看看 llvm 以及生成的汇编代码 + +square_area(l) = l * l # square_area (generic function with 1 method) + +square_area(5) #25 + +# 给 square_area 一个整形时发生什么 +code_native(square_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 # Prologue + # push RBP + # mov RBP, RSP + # Source line: 1 + # movsxd RAX, EDI # Fetch l from memory? + # imul RAX, RAX # Square l and store the result in RAX + # pop RBP # Restore old base pointer + # ret # Result will still be in RAX + +code_native(square_area, (Float32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) + # pop RBP + # ret + +code_native(square_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) + # pop RBP + # ret + # +# 注意 只要参数中又浮点类型,Julia 就使用浮点指令 +# 让我们计算一下圆的面积 +circle_area(r) = pi * r * r # circle_area (generic function with 1 method) +circle_area(5) # 78.53981633974483 + +code_native(circle_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory + # movabs RAX, 4593140240 # Load pi + # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r + # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r + # pop RBP + # ret + # + +code_native(circle_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # movabs RAX, 4593140496 + # Source line: 1 + # vmulsd XMM1, XMM0, QWORD PTR [RAX] + # vmulsd XMM0, XMM1, XMM0 + # pop RBP + # ret + # +``` -- cgit v1.2.3 From 760fee2ba8b8e6f235cc91c10686980341b6ff66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torbj=C3=B8rn=20Mar=C3=B8?= Date: Sat, 21 Jun 2014 12:10:34 +0200 Subject: Fixed missing + sign in lambda section --- whip.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/whip.html.markdown b/whip.html.markdown index 3429ec24..dc5a0b39 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -153,8 +153,8 @@ undefined ; user to indicate a value that hasn't been set ; Lambdas in Whip are declared with the `lambda` or `->` function. ; And functions are really just lambdas with names. -(def my_function (-> (x y) (+ (x y) 10))) -; | | | | +(def my_function (-> (x y) (+ (+ x y) 10))) +; | | | | ; | | | returned value(with scope containing argument vars) ; | | arguments ; | lambda declaration function -- cgit v1.2.3 From e5d8895c8e837ac8fd0b7272195d0d99afbf589b Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Sun, 22 Jun 2014 06:20:12 -0700 Subject: Should have more detail about named return values. There was not a section about named return values, and it feels like it is a valuable and important enough thing to learn early on. If nothing else, when looking at someone else's code this may be a point of confusion. --- go.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/go.html.markdown b/go.html.markdown index bb6b04eb..2e68a25c 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -116,6 +116,16 @@ can include line breaks.` // Same string type. learnFlowControl() // Back in the flow. } +// It is possible, unlike in many other languages for functions on go +// to have named return values. +// We just have to assign a name to the type being returned in the function +// declaration line. This allows us to easily return from multiple points +// in a function as well as to only use the return keyword, without anything further. +func learnNamedReturns(x, y int) (z int) { + z = x * y + return // z is implicit here, because we named it earlier. +} + // Go is fully garbage collected. It has pointers but no pointer arithmetic. // You can make a mistake with a nil pointer, but not by incrementing a pointer. func learnMemory() (p, q *int) { -- cgit v1.2.3 From ff49deb88608785f913aa0129bab21807b397cd9 Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Sun, 22 Jun 2014 06:21:21 -0700 Subject: Fixed `on` to `in` in comment. --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 2e68a25c..0f022541 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -116,7 +116,7 @@ can include line breaks.` // Same string type. learnFlowControl() // Back in the flow. } -// It is possible, unlike in many other languages for functions on go +// It is possible, unlike in many other languages for functions in go // to have named return values. // We just have to assign a name to the type being returned in the function // declaration line. This allows us to easily return from multiple points -- cgit v1.2.3 From 94484047091a18d4b2440650382b9ecbd7840044 Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Sun, 22 Jun 2014 20:49:29 -0700 Subject: Slight language change per pull req. comment --- go.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 0f022541..0a0e6c53 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -118,9 +118,9 @@ can include line breaks.` // Same string type. // It is possible, unlike in many other languages for functions in go // to have named return values. -// We just have to assign a name to the type being returned in the function -// declaration line. This allows us to easily return from multiple points -// in a function as well as to only use the return keyword, without anything further. +// Giving a name to type being returned allows us to easily return from +// multiple points in a function as well as to only use the return keyword, +// without anything further. func learnNamedReturns(x, y int) (z int) { z = x * y return // z is implicit here, because we named it earlier. -- cgit v1.2.3 From e881ba74f302cc5cac7f21cd1e7da163ca774d78 Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Mon, 23 Jun 2014 07:31:39 -0700 Subject: Hopefully slight language improvement over orig. --- go.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 0a0e6c53..c70f96bd 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -118,9 +118,9 @@ can include line breaks.` // Same string type. // It is possible, unlike in many other languages for functions in go // to have named return values. -// Giving a name to type being returned allows us to easily return from -// multiple points in a function as well as to only use the return keyword, -// without anything further. +// Assigning a name to the type being returned in the function declaration line +// allows us to easily return from multiple points in a function as well as to +// only use the return keyword, without anything further. func learnNamedReturns(x, y int) (z int) { z = x * y return // z is implicit here, because we named it earlier. -- cgit v1.2.3 From 104b9add58ff808ac26dad9b315e00f6e9ac9bd2 Mon Sep 17 00:00:00 2001 From: Nick Ward Date: Sat, 28 Jun 2014 11:53:25 +1000 Subject: Fix spelling and other small issues --- c.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index c89f2b88..22f251f2 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -23,7 +23,7 @@ Multi-line comments look like this. They work in C89 as well. // Constants: #define #define DAYS_IN_YEAR 365 -//enumeration constants are also ways to declare constants. +// Enumeration constants are also ways to declare constants. enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; // MON gets 2 automatically, TUE gets 3, etc. @@ -96,7 +96,7 @@ int main() { // is not evaluated (except VLAs (see below)). // The value it yields in this case is a compile-time constant. int a = 1; - // size_t is an unsiged integer type of at least 2 bytes used to represent + // size_t is an unsigned integer type of at least 2 bytes used to represent // the size of an object. size_t size = sizeof(a++); // a++ is not evaluated printf("sizeof(a++) = %zu where a = %d\n", size, a); @@ -135,9 +135,9 @@ int main() { // > Enter the array size: 10 // > sizeof array = 40 - // Strings are just arrays of chars terminated by a NUL (0x00) byte, + // Strings are just arrays of chars terminated by a NULL (0x00) byte, // represented in strings as the special character '\0'. - // (We don't have to include the NUL byte in string literals; the compiler + // (We don't have to include the NULL byte in string literals; the compiler // inserts it at the end of the array for us.) char a_string[20] = "This is a string"; printf("%s\n", a_string); // %s formats a string @@ -182,7 +182,7 @@ int main() { 11 % 3; // => 2 // Comparison operators are probably familiar, but - // there is no boolean type in c. We use ints instead. + // there is no Boolean type in c. We use ints instead. // (Or _Bool or bool in C99.) // 0 is false, anything else is true. (The comparison // operators always yield 0 or 1.) @@ -281,7 +281,7 @@ int main() { // branching with multiple choices: switch() switch (some_integral_expression) { - case 0: // labels need to be integral *constant* epxressions + case 0: // labels need to be integral *constant* expressions do_stuff(); break; // if you don't break, control flow falls over labels case 1: @@ -312,7 +312,7 @@ int main() { // Types will overflow without warning printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long) - // For determining the max value of a `char`, a `signed char` and an `unisigned char`, + // For determining the max value of a `char`, a `signed char` and an `unsigned char`, // respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from // Integral types can be cast to floating-point types, and vice-versa. @@ -342,13 +342,13 @@ int main() { // => Prints "8, 4" on a typical 64-bit system // To retrieve the value at the address a pointer is pointing to, - // put * in front to de-reference it. + // put * in front to dereference it. // Note: yes, it may be confusing that '*' is used for _both_ declaring a // pointer and dereferencing it. printf("%d\n", *px); // => Prints 0, the value of x // You can also change the value the pointer is pointing to. - // We'll have to wrap the de-reference in parenthesis because + // We'll have to wrap the dereference in parenthesis because // ++ has a higher precedence than *. (*px)++; // Increment the value px is pointing to by 1 printf("%d\n", *px); // => Prints 1 @@ -532,7 +532,7 @@ int area(const rect *r) // Function pointers /////////////////////////////////////// /* -At runtime, functions are located at known memory addresses. Function pointers are +At run time, functions are located at known memory addresses. Function pointers are much like any other pointer (they just store a memory address), but can be used to invoke functions directly, and to pass handlers (or callback functions) around. However, definition syntax may be initially confusing. @@ -542,7 +542,7 @@ Example: use str_reverse from a pointer void str_reverse_through_pointer(char *str_in) { // Define a function pointer variable, named f. void (*f)(char *); // Signature should exactly match the target function. - f = &str_reverse; // Assign the address for the actual function (determined at runtime) + f = &str_reverse; // Assign the address for the actual function (determined at run time) // f = str_reverse; would work as well - functions decay into pointers, similar to arrays (*f)(str_in); // Just calling the function through the pointer // f(str_in); // That's an alternative but equally valid syntax for calling it. @@ -564,10 +564,10 @@ typedef void (*my_fnp_type)(char *); '\n' // newline character '\t' // tab character (left justifies text) '\v' // vertical tab -'\f' // new page (formfeed) +'\f' // new page (form feed) '\r' // carriage return '\b' // backspace character -'\0' // null character. Usually put at end of strings in C lang. +'\0' // NULL character. Usually put at end of strings in C. // hello\n\0. \0 used by convention to mark end of string. '\\' // backslash '\?' // question mark @@ -586,7 +586,7 @@ typedef void (*my_fnp_type)(char *); "%7.4s" // (can do with strings too) "%c" // char "%p" // pointer -"%x" // hexidecimal +"%x" // hexadecimal "%o" // octal "%%" // prints % @@ -628,7 +628,7 @@ If you have a question, read the [compl.lang.c Frequently Asked Questions](http: It's very important to use proper spacing, indentation and to be consistent with your coding style in general. Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the -[Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle). +[Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle). Other than that, Google is your friend. -- cgit v1.2.3 From 2a8e20ca27c59347df58197f821b1eee2e913128 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sat, 28 Jun 2014 22:59:14 +0200 Subject: Basic Perl 6 LearnXinYminutes --- perl6.html.markdown | 121 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 perl6.html.markdown diff --git a/perl6.html.markdown b/perl6.html.markdown new file mode 100644 index 00000000..4ba76d6c --- /dev/null +++ b/perl6.html.markdown @@ -0,0 +1,121 @@ +--- +name: perl6 +category: language +language: perl6 +filename: learnperl6.pl +contributors: + - ["Nami-Doc", "http://github.com/Nami-Doc"] +--- + +Perl 6 is a highly capable, feature-rich programming language made for the upcoming hundred years. + +Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM and [the MoarVM](http://moarvm.com). + +```perl6 +# Single line comment start with a pound + +#`( + Multiline comments use #` and a quoting construct. (), [], {}, 「」, etc, will work. +) + +### Variables + +# In Perl 6, you declare a lexical variable using `my` + +# Perl 6 has 4 variable types : + +## - Scalars. They represent a single value. They start with a `$` + +my $str = 'String'; +my $str2 = "String"; # double quotes allow for interpolation + +# variable names can contain but not end with simple quotes and dashes, and can contain (and end with) underscores + +my $weird'variable-name_ = 5; + +## - Arrays. They represent multiple values. They start with `@` + +my @array = 1, 2, 3; +my @array = 'a', 'b', 'c'; +# equivalent to : +my @array = ; # similar to perl5's qw, or Ruby's %w + +say @array[2]; # Arrays are 0-indexed + +## - Hashes + +my %hash = 1 => 2, + 3 => 4; +my %hash = autoquoted => "key", + "some other" => "value", # trailing commas are okay + ; +my %hash = # you can also create a hash from an even-numbered array + +say %hash{'key1'}; # You can use {} to get the value from a key +say %hash; # if it's a string, you can actually use <> + +## - Subs (subroutines, or functions in most other languages). Stored in variable, they use `&` +sub say-hello { say "Hello, world" } + +# since you can omit parenthesis to call a function with no arguments, you need to use `&` also to capture `say-hello` +my &s = &say-hello; +my &other-s = sub { say "anonymous function !" } + +# `->`, lambda with arguments, and string interpolation +my &lambda = -> $argument { "The argument passed to this lambda is $argument" } + +### Control Flow Structures + +# You don't need to put parenthesis around the condition, but that also means you always have to use brackets (`{ }`) for their body : + +## Conditionals + +if True { + say "It's true !"; +} + +unless False { + say "It's not false !"; +} + +# if (true) say; # Won't work + +# `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching : +given "foo bar" { # given just puts its argument into `$_`, and `when` uses it. + when /foo/ { # smart matching a string with a regex returns true if it matches + say "Yay !"; + } + when $_.chars > 50 { # smart matching anything with True gives True, so you can also put "normal" conditionals + say "Quite a long string !"; + } +} + +## Looping constructs + +### - `loop` is an infinite loop if you don't pass it arguments, but can also be a c-style `for` : +loop { + say "This is an infinite loop !"; + last; # last breaks out of the loop, like the `break` keyword in other languages +} + +loop (my $i = 0; $i < 5; $i++) { + next if $i == 3; # `next` skips to the next iteration, like `continue` in other languages. + # Notice that you can also use postfix conditionals, loops, etc. + say "This is a C-style for loop !"; +} + +### - `for` - Foreaches an array +for @array -> $variable { + say "I've found $variable !"; +} + +# default variable is $_ +for array { + say "I've got $_"; +} + +# Note - the "lambda" `->` syntax isn't reserved to for : +if long-computation() -> $result { + say "The result is $result"; +} +``` -- cgit v1.2.3 From 8b6920a70a6f52657bf59a20a4120af98e4187fe Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Sun, 29 Jun 2014 08:12:58 -0700 Subject: Learn function decorators with Go Added snippet about using closures as function decorators in Go. Also removed a few extra whitespaces. --- go.html.markdown | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index c70f96bd..a9a7de72 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -116,10 +116,10 @@ can include line breaks.` // Same string type. learnFlowControl() // Back in the flow. } -// It is possible, unlike in many other languages for functions in go +// It is possible, unlike in many other languages for functions in go // to have named return values. // Assigning a name to the type being returned in the function declaration line -// allows us to easily return from multiple points in a function as well as to +// allows us to easily return from multiple points in a function as well as to // only use the return keyword, without anything further. func learnNamedReturns(x, y int) (z int) { z = x * y @@ -196,6 +196,21 @@ love: learnInterfaces() // Good stuff coming up! } +// Decorators are common in other languages. Same can be done in Go +// with function literals that accept arguments. +func learnFunctionFactory(mystring string) func(before, after string) string { + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // new string + } +} + +// Next two are equivalent, with second being more practical +fmt.Println(learnFunctionFactory("summer")("A beautiful", "day!")) + +d := learnFunctionFactory("summer") +fmt.Println(d("A beautiful", "day!")) +fmt.Println(d("A lazy", "afternoon!")) + func learnDefer() (ok bool) { // Deferred statements are executed just before the function returns. defer fmt.Println("deferred statements execute in reverse (LIFO) order.") -- cgit v1.2.3 From 4b9c50733d9a2b20ce09b8a42c36df47a0ea10c7 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sun, 29 Jun 2014 21:41:57 +0200 Subject: Moar operators --- perl6.html.markdown | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 2 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 4ba76d6c..7a8c7525 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -78,11 +78,12 @@ unless False { say "It's not false !"; } + # if (true) say; # Won't work # `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching : -given "foo bar" { # given just puts its argument into `$_`, and `when` uses it. - when /foo/ { # smart matching a string with a regex returns true if it matches +given "foo bar" { # given just puts its argument into `$_`, and `when` uses it using the "smart matching" operator. + when /foo/ { # you'll read about the smart-matching operator below say "Yay !"; } when $_.chars > 50 { # smart matching anything with True gives True, so you can also put "normal" conditionals @@ -118,4 +119,85 @@ for array { if long-computation() -> $result { say "The result is $result"; } + + + +# Operators + +## 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) + +## The categories are : +### - "prefix" : before (like `!` in `!True`). +### "postfix" : after (like `++` in `$a++`). +### "infix" : in between (like `*` in `4 * 3`). +### "circumfix" : around (like `[`-`]` in `[1, 2]`). +### "post-circumfix" : around, after another term (like `{`-`}` in `%hash{'key'}`) + +## The precedence list can be found here : http://perlcabal.org/syn/S03.html#Operator_precedence +## But first, we need a little explanation about associativity : + +### Binary operators: +$a ! $b ! $c; # with a left-associative `!`, this is `($a ! $b) ! $c` +$a ! $b ! $c; # with a right-associative `!`, this is `$a ! ($b ! $c)` +$a ! $b ! $c; # with a non-associative `!`, this is illegal +$a ! $b ! $c; # with a chain-associative `!`, this is `($a ! $b) and ($b ! $c)` +$a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` + +### Unary operators: +!$a! # with left-associative `!`, this is `(!$a)!` +!$a! # with right-associative `!`, this is `!($a!)` +!$a! # with non-associative `!`, this is illegal + +## Alright, you're set to go ! + +## * Equality Checking + +### - `==` is numeric comparison +3 == 4; # False +3 != 4; # True + +### - `eq` is string comparison +'a' eq 'b'; +'a' ne 'b'; # not equal +'a' !eq 'b'; # same as above + +### - `eqv` is canonical equivalence +(1, 2) eqv (1, 3); + +### - `~~` is smart matching +### for a complete combinations list, use this table : http://perlcabal.org/syn/S03.html#Smart_matching +'a' ~~ /a/; # true if matches regexp +'key' ~~ %hash; # true if key exists in hash +$arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an argument, returns True +1 ~~ Int; # "is of type" + +### - `===` is value identity and uses `.WHICH` on the objects to compare them +### - `=:=` is container identity and uses `VAR()` on the objects to compare them + +### You also, of course, have `<`, `<=`, `>`, `>=`. +### Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`. +3 > 4; + +## * Sort comparison +### They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1). +1 <=> 4; # sort comparison for numerics +'a' leg 'b'; # sort comparison for string +$obj eqv $obj2; # sort comparison using eqv semantics + +## * Generic ordering +3 before 4; # True +'b' after 'a'; # True + +## * Range constructors +3 .. 7; # 3 to 7, both included +### `^` on either side them exclusive on that side : +3 ^..^ 7; # 3 to 7, not included (basically `4 .. 6`) + +# * And, Or + +## Short-circuit (and tight) +$a && $b && $c; # returns the first argument that evaluates to False, or the last argument +$a || $b; ``` -- cgit v1.2.3 From 83283c0d4ca5f797e505f511b418c3a2f6472d8c Mon Sep 17 00:00:00 2001 From: P1start Date: Mon, 30 Jun 2014 16:41:13 +1200 Subject: [rust/en] Add an English Rust tutorial Fixes #480. --- rust.html.markdown | 245 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 245 insertions(+) create mode 100644 rust.html.markdown diff --git a/rust.html.markdown b/rust.html.markdown new file mode 100644 index 00000000..532362d1 --- /dev/null +++ b/rust.html.markdown @@ -0,0 +1,245 @@ +--- +language: rust +contributors: + - ["P1start", "http://p1start.github.io/"] +filename: learnrust.rs +--- + +Rust is an in-development programming language developed by Mozilla Research. +It is relatively unique among systems languages in that it can assert memory +safety *at compile time*. Rust’s first alpha release occurred in January +2012, and development moves so quickly that at the moment the use of stable +releases is discouraged, and instead one should use nightly builds. + +Although Rust is a relatively low-level language, Rust has some functional +concepts that are generally found in higher-level languages. This makes +Rust not only fast, but also easy and efficient to code in. + +```rust +// This is a comment. Single-line look like this... +/* ...and multi-line comment look like this */ + +/////////////// +// 1. Basics // +/////////////// + +// Functions +fn add2(x: int, y: int) -> int { + // Implicit return (no semicolon) + x + y +} + +// Main function +fn main() { + // Numbers // + + // Immutable bindings + let x: int = 1; + + // Integer/float suffixes + let y: int = 13i; + let f: f64 = 1.3f64; + + // Type inference + let implicit_x = 1i; + let implicit_f = 1.3f64; + + // Maths + let sum = x + y + 13i; + + // Mutable variable + let mut mutable = 1; + mutable += 2; + + // Strings // + + // String literals + let x: &'static str = "hello world!"; + + // Printing + println!("{} {}", f, x); // 1.3 hello world + + // A `String` + let s: String = "hello world".to_string(); + + // A string slice - a view into another string + let s_slice: &str = s.as_slice(); + + ////////////// + // 2. Types // + ////////////// + + // Struct + struct Point { + x: int, + y: int, + } + + let origin: Point = Point { x: 0, y: 0 }; + + // Tuple struct + struct Point2(int, int); + + let origin2 = Point2(0, 0); + + // Basic C-like enum + enum Direction { + Left, + Right, + Up, + Down, + } + + let up = Up; + + // Enum with fields + enum OptionalInt { + AnInt(int), + Nothing, + } + + let two: OptionalInt = AnInt(2); + let nothing: OptionalInt = Nothing; + + // Generics // + + struct Foo { bar: T } + + // This is defined in the standard library as `Option` + enum Optional { + SomeVal(T), + NoVal, + } + + // Methods // + + impl Foo { + // Methods take an explicit `self` parameter + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1i }; + println!("{}", a_foo.get_bar()); // 1 + + // Traits (interfaces) // + + trait Frobnicate { + fn frobnicate(self) -> Option; + } + + impl Frobnicate for Foo { + fn frobnicate(self) -> Option { + Some(self.bar) + } + } + + println!("{}", a_foo.frobnicate()); // Some(1) + + ///////////////////////// + // 3. Pattern matching // + ///////////////////////// + + let foo = AnInt(1); + match foo { + AnInt(n) => println!("it’s an int: {}", n), + Nothing => println!("it’s nothing!"), + } + + // Advanced pattern matching + struct FooBar { x: int, y: OptionalInt } + let bar = FooBar { x: 15, y: AnInt(32) }; + + match bar { + FooBar { x: 0, y: AnInt(0) } => + println!("The numbers are zero!"), + FooBar { x: n, y: AnInt(m) } if n == m => + println!("The numbers are the same"), + FooBar { x: n, y: AnInt(m) } => + println!("Different numbers: {} {}", n, m), + FooBar { x: _, y: Nothing } => + println!("The second number is Nothing!"), + } + + ///////////////////// + // 4. Control flow // + ///////////////////// + + // `for` loops/iteration + let array = [1i, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + for i in range(0u, 10) { + print!("{} ", i); + } + println!(""); + // prints `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1i == 1 { + println!("Maths is working!"); + } else { + println!("Oh no..."); + } + + // `if` as expression + let value = if true { + "good" + else { + "bad" + }; + + // `while` loop + while 1i == 1 { + println!("The universe is operating normally."); + } + + // Infinite loop + loop { + println!("Hello!"); + } + + ///////////////////////////////// + // 5. Memory safety & pointers // + ///////////////////////////////// + + // Owned pointer - only one thing can ‘own’ this pointer at a time + let mut mine: Box = box 3; + *mine = 5; // dereference + let mut now_its_mine = mine; + *now_its_mine += 2; + println!("{}", now_its_mine); // 7 + // println!("{}", mine); // this would error + + // Reference - an immutable pointer that refers to other data + let mut var = 4i; + var = 3; + let ref_var: &int = &var; + println!("{}", var); // Unlike `box`, `var` can still be used + println!("{}", *ref_var); + // var = 5; // this would error + // *ref_var = 6; // this would too + + // Mutable reference + let mut var2 = 4i; + let ref_var2: &mut int = &mut var2; + *ref_var2 += 2; + println!("{}", *ref_var2); // 6 + // var2 = 2; // this would error +} +``` + +## Further reading + +There’s a lot more to Rust—this is just the basics of Rust so you can +understand the most important things. To learn more about Rust, read the +[Rust tutorial](http://doc.rust-lang.org/tutorial.html) and check out the +[/r/rust](http://reddit.com/r/rust) subreddit. The folks on the #rust channel +on irc.mozilla.org are also always keen to help newcomers. + +You can also try out features of Rust with an online compiler at the official +[Rust playpen](http://play.rust-lang.org) or on the main +[Rust website](http://rust-lang.org). -- cgit v1.2.3 From 9874c063d32e1b9affffac7cca457ffe977c5d71 Mon Sep 17 00:00:00 2001 From: P1start Date: Tue, 1 Jul 2014 15:24:08 +1200 Subject: add &str explanation; add section on vectors --- rust.html.markdown | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 532362d1..0b9a5e58 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -59,12 +59,32 @@ fn main() { // Printing println!("{} {}", f, x); // 1.3 hello world - // A `String` + // A `String` - a heap-allocated string let s: String = "hello world".to_string(); - // A string slice - a view into another string + // A string slice - an immutable view into another string + // This is basically an immutable pointer to a string - it doesn’t + // actually contain the characters of a string, just a pointer to + // something that does (in this case, `s`) let s_slice: &str = s.as_slice(); + println!("{} {}", s, s_slice); // hello world hello world + + // Vectors/arrays // + + // A fixed-size array + let four_ints: [int, ..4] = [1, 2, 3, 4]; + + // A dynamically-sized vector + let mut vector: Vec = vec![1, 2, 3, 4]; + vector.push(5); + + // A slice - an immutable view into a vector or array + // This is much like a string slice, but for vectors + let slice: &[int] = vector.as_slice(); + + println!("{} {}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + ////////////// // 2. Types // ////////////// @@ -188,7 +208,7 @@ fn main() { // `if` as expression let value = if true { "good" - else { + } else { "bad" }; -- cgit v1.2.3 From 74c0a49e6d79e80b1f0a511afe3eece0cde6f43c Mon Sep 17 00:00:00 2001 From: Vincent Voyer Date: Wed, 2 Jul 2014 14:37:15 +0200 Subject: fix(go func factory): fix func factory example previous code did not run because outside main() code was done --- go.html.markdown | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index a9a7de72..980fdc66 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -192,16 +192,26 @@ func learnFlowControl() { goto love love: + learnFunctionFactory() // func returning func is fun(3)(3) learnDefer() // A quick detour to an important keyword. learnInterfaces() // Good stuff coming up! } +func learnFunctionFactory() { + // Next two are equivalent, with second being more practical + fmt.Println(sentenceFactory("summer")("A beautiful", "day!")) + + d := sentenceFactory("summer") + fmt.Println(d("A beautiful", "day!")) + fmt.Println(d("A lazy", "afternoon!")) +} + // Decorators are common in other languages. Same can be done in Go // with function literals that accept arguments. -func learnFunctionFactory(mystring string) func(before, after string) string { - return func(before, after string) string { - return fmt.Sprintf("%s %s %s", before, mystring, after) // new string - } +func sentenceFactory(mystring string) func(before, after string) string { + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // new string + } } // Next two are equivalent, with second being more practical -- cgit v1.2.3 From f2e3d99476c0b549e468e3090d0938322e8142d4 Mon Sep 17 00:00:00 2001 From: Vincent Voyer Date: Wed, 2 Jul 2014 14:55:33 +0200 Subject: feat(webserver request): add a http.Get example 1. script now exits 2. we initiate a request to the started server to prove the serverHTTP works what do you think? --- go.html.markdown | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index a9a7de72..61d7db84 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -329,17 +329,31 @@ func learnConcurrency() { // A single function from package http starts a web server. func learnWebProgramming() { + // First parameter of ListenAndServe is TCP address to listen to. // Second parameter is an interface, specifically http.Handler. - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // don't ignore errors + go func() { + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // don't ignore errors + }() + + requestServer(); } + // Make pair an http.Handler by implementing its only method, ServeHTTP. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Serve data with a method of http.ResponseWriter. w.Write([]byte("You learned Go in 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("\nWebserver said: `%s`", string(body)) +} ``` ## Further Reading -- cgit v1.2.3 From 4c3409670319e4a450a5e0f8e4b9669e73792326 Mon Sep 17 00:00:00 2001 From: Pete Hamilton Date: Sat, 5 Jul 2014 12:03:09 +0100 Subject: Remove duplication of function factory example --- go.html.markdown | 7 ------- 1 file changed, 7 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 03227676..4ea6861b 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -214,13 +214,6 @@ func sentenceFactory(mystring string) func(before, after string) string { } } -// Next two are equivalent, with second being more practical -fmt.Println(learnFunctionFactory("summer")("A beautiful", "day!")) - -d := learnFunctionFactory("summer") -fmt.Println(d("A beautiful", "day!")) -fmt.Println(d("A lazy", "afternoon!")) - func learnDefer() (ok bool) { // Deferred statements are executed just before the function returns. defer fmt.Println("deferred statements execute in reverse (LIFO) order.") -- cgit v1.2.3 From 73195400ba731c43365078023db792ab23bca1d6 Mon Sep 17 00:00:00 2001 From: Duncan Beaton Date: Sun, 6 Jul 2014 20:10:15 +0100 Subject: Fix 'Immutability' typo --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 2666746e..432933c2 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -37,7 +37,7 @@ println("Hello world!") print("Hello world") // Declaring values is done using either var or val -// val declarations are immutable, whereas var's are mutable. Immutablility is +// val declarations are immutable, whereas var's are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -- cgit v1.2.3 From 1f4bcf8a7a23cd2ea687e3a197f65508b4d1b919 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 12:58:17 +0800 Subject: Create markdown-cn.html.markdown initiate --- zh-cn/markdown-cn.html.markdown | 246 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 246 insertions(+) create mode 100644 zh-cn/markdown-cn.html.markdown diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown new file mode 100644 index 00000000..9a863bac --- /dev/null +++ b/zh-cn/markdown-cn.html.markdown @@ -0,0 +1,246 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +filename: markdown.md +--- + +Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). + +Give me as much feedback as you want! / Feel free to fork and pull request! + + +``` + + + + + + +# This is an

+## This is an

+### This is an

+#### This is an

+##### This is an

+###### This is an
+ + +This is an h1 +============= + +This is an h2 +------------- + + + + +*This text is in italics.* +_And so is this text._ + +**This text is in bold.** +__And so is this text.__ + +***This text is in both.*** +**_As is this!_** +*__And this!__* + + + +~~This text is rendered with strikethrough.~~ + + + +This is a paragraph. I'm typing in a paragraph isn't this fun? + +Now I'm in paragraph 2. +I'm still in paragraph 2 too! + + +I'm in paragraph three! + + + +I end with two spaces (highlight me to see them). + +There's a
above me! + + + +> This is a block quote. You can either +> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. +> It doesn't make a difference so long as they start with a `>`. + +> You can also use more than one level +>> of indentation? +> How neat is that? + + + + +* Item +* Item +* Another item + +or + ++ Item ++ Item ++ One more item + +or + +- Item +- Item +- One last item + + + +1. Item one +2. Item two +3. Item three + + + +1. Item one +1. Item two +1. Item three + + + + +1. Item one +2. Item two +3. Item three + * Sub-item + * Sub-item +4. Item four + + + + + This is code + So is this + + + + my_array.each do |item| + puts item + end + + + +John didn't even know what the `go_to()` function did! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + +<-- The above text doesn't require indenting, plus Github will use syntax +highlighting of the language you specify after the ``` --> + + + + +*** +--- +- - - +**************** + + + + +[Click me!](http://test.com/) + + + +[Click me!](http://test.com/ "Link to Test.com") + + + +[Go to music](/music/). + + + +[Click this link][link1] for more info about it! +[Also check out this link][foobar] if you want to. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Alright!" + + + + + +[This][] is a link. + +[this]: http://thisisalink.com/ + + + + + + +![This is hover-text (alt text) for my image](http://imgur.com/myimage.jpg "An optional title") + + + +![This is the hover-text.][myimage] + +[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" + + + + + is equivalent to +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +I want to type *this text surrounded by asterisks* but I don't want it to be +in italics, so I do this: \*this text surrounded by asterisks\*. + + + + +| Col1 | Col2 | Col3 | +| :----------- | :------: | ------------: | +| Left-aligned | Centered | Right-aligned | +| blah | blah | blah | + + + +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ugh this is so ugly | make it | stop + + + +``` + +For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 1e18c52f615c05343de77edf0ce364b9c3437764 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 13:00:39 +0800 Subject: Updated the file head --- zh-cn/markdown-cn.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 9a863bac..68f2e909 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -2,7 +2,10 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Fangzhou Chen", "http://binarythink.net"] filename: markdown.md +lang: zh-cn --- Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). -- cgit v1.2.3 From 62e5ab350acd1803dea8f52ffd5b437c04cf7f84 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 13:01:14 +0800 Subject: Update markdown-cn.html.markdown --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 68f2e909..1e463287 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -3,7 +3,7 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - - ["Fangzhou Chen", "http://binarythink.net"] + - ["Fangzhou Chen"] filename: markdown.md lang: zh-cn --- -- cgit v1.2.3 From 821464185ac044a0812584ac794049947d25b736 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 13:24:22 +0800 Subject: 2nd para --- zh-cn/markdown-cn.html.markdown | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 1e463287..f27722ba 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -8,17 +8,16 @@ filename: markdown.md lang: zh-cn --- -Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). +Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的语法结构,并可以便利地转换成HTML(以及其他很多)格式。 -Give me as much feedback as you want! / Feel free to fork and pull request! +欢迎您多多反馈以及分支和请求合并。 ``` - + - - - - -# This is an

-## This is an

-### This is an

-#### This is an

-##### This is an

-###### This is an
- - -This is an h1 + + + + +# 这是一个

+## 这是一个

+### 这是一个

+#### 这是一个

+##### 这是一个

+###### 这是一个
+ + +这是一个 h1 ============= -This is an h2 +这是一个 h2 ------------- - - + + -*This text is in italics.* -_And so is this text._ +*此文本为斜体。* +_此文本也是。_ -**This text is in bold.** -__And so is this text.__ +**此文本为粗体。** +__此文本也是__ -***This text is in both.*** -**_As is this!_** -*__And this!__* +***此文本是斜体加粗体。*** +**_或者这样。_** +*__这个也是!__* - + -~~This text is rendered with strikethrough.~~ +~~此文本为删除线效果。~~ - + -This is a paragraph. I'm typing in a paragraph isn't this fun? +这是第一段落. 这句话在同一个段落里,好玩么? -Now I'm in paragraph 2. -I'm still in paragraph 2 too! +现在我是第二段落。 +这句话也在第二段落! +这句话在第三段落! -I'm in paragraph three! + - +此段落结尾有两个空格(选中以显示)。 -I end with two spaces (highlight me to see them). +上文有一个
! -There's a
above me! + - +> 这是一个段落引用. 你可以 +> 手动断开你的句子,然后在每句句子前面添加 “>” 字符。或者让你的句子变得很长,以至于他们自动得断开。 +> 只要你的文字以“>” 字符开头,两种方式无异。 -> This is a block quote. You can either -> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. -> It doesn't make a difference so long as they start with a `>`. +> 你也对文本进行 +>> 多层引用 +> 这多机智啊! -> You can also use more than one level ->> of indentation? -> How neat is that? + + - - +* 项目 +* 项目 +* 另一个项目 -* Item -* Item -* Another item +或者 -or ++ 项目 ++ 项目 ++ 另一个项目 -+ Item -+ Item -+ One more item +或者 -or +- 项目 +- 项目 +- 最后一个项目 -- Item -- Item -- One last item + - +1. 项目一 +2. 项目二 +3. 项目三 -1. Item one -2. Item two -3. Item three + - +1. 项目一 +1. 项目二 +1. 项目三 + -1. Item one -1. Item two -1. Item three - + - +1. 项目一 +2. 项目二 +3. 项目三 + * 子项目 + * 子项目 +4. 项目四 -1. Item one -2. Item two -3. Item three - * Sub-item - * Sub-item -4. Item four - - - + + This is code So is this - + my_array.each do |item| puts item end - + John didn't even know what the `go_to()` function did! -- cgit v1.2.3 From e98b62883cd0ef08d72a9da5384df7f5402cb180 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 16:55:29 +0800 Subject: Finally Done --- zh-cn/markdown-cn.html.markdown | 115 ++++++++++++++++++++-------------------- 1 file changed, 58 insertions(+), 57 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 4f4b4c51..5de5f75b 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -19,10 +19,13 @@ Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的 并不会被Markdown解析器所影响。不过如果你在Markdown文件内创建了HTML元素, 你将无法在HTML元素的内容中使用Markdown语法。--> - + - + + # 这是一个

## 这是一个

### 这是一个

@@ -54,7 +57,7 @@ __此文本也是__ ~~此文本为删除线效果。~~ - + 这是第一段落. 这句话在同一个段落里,好玩么? @@ -70,7 +73,7 @@ __此文本也是__ 上文有一个
! - + > 这是一个段落引用. 你可以 > 手动断开你的句子,然后在每句句子前面添加 “>” 字符。或者让你的句子变得很长,以至于他们自动得断开。 @@ -105,7 +108,8 @@ __此文本也是__ 2. 项目二 3. 项目三 - + 1. 项目一 1. 项目二 @@ -122,7 +126,8 @@ __此文本也是__ 4. 项目四 - + This is code So is this @@ -135,105 +140,101 @@ __此文本也是__ -John didn't even know what the `go_to()` function did! +John 甚至不知道 `go_to()` 方程是干嘛的! - + -\`\`\`ruby +\`\`\`ruby def foobar puts "Hello world!" end -\`\`\` +\`\`\` -<-- The above text doesn't require indenting, plus Github will use syntax -highlighting of the language you specify after the ``` --> + - - + + *** --- - - - **************** - - + + -[Click me!](http://test.com/) +[点我点我!](http://test.com/) - + -[Click me!](http://test.com/ "Link to Test.com") +[点我点我!](http://test.com/ "连接到Test.com") - + -[Go to music](/music/). +[去 music](/music/). - + -[Click this link][link1] for more info about it! -[Also check out this link][foobar] if you want to. +[点此链接][link1]以获取更多信息! +[看一看这个链接][foobar] 如果你愿意的话. [link1]: http://test.com/ "Cool!" [foobar]: http://foobar.biz/ "Alright!" - + - + [This][] is a link. [this]: http://thisisalink.com/ - + - - + + -![This is hover-text (alt text) for my image](http://imgur.com/myimage.jpg "An optional title") +![这是我图像的悬停文本(alt text)](http://imgur.com/myimage.jpg "可选命名") - + -![This is the hover-text.][myimage] +![这是我的悬停文本.][myimage] -[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" +[myimage]: relative/urls/cool/image.jpg "在此输入标题" - - + + - is equivalent to -[http://testwebsite.com/](http://testwebsite.com/) + 与 +[http://testwebsite.com/](http://testwebsite.com/) 等同 - + - + -I want to type *this text surrounded by asterisks* but I don't want it to be -in italics, so I do this: \*this text surrounded by asterisks\*. +我希望 *将这段文字置于星号之间* 但是我不希望它被 +斜体化, 所以我就: \*这段置文字于星号之间\*。 - - + + -| Col1 | Col2 | Col3 | -| :----------- | :------: | ------------: | -| Left-aligned | Centered | Right-aligned | -| blah | blah | blah | +| 第一列 | 第二列 | 第三列 | +| :---------- | :------: | ---------: | +| 左对齐 | 居个中 | 右对齐 | +| 某某某 | 某某某 | 某某某 | - + -Col 1 | Col2 | Col3 +第一列 | 第二列 | 第三列 :-- | :-: | --: -Ugh this is so ugly | make it | stop +这太丑了 | 药不能 | 停 - + ``` -For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). +更多信息, 请见John Gruber 关于语法的官方帖子[此处](http://daringfireball.net/projects/markdown/syntax)以及 Adam Pritchard 的摘要笔记 [此处](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From fd010c57e08336d108d979ecad9a82ef30980ed3 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 17:01:22 +0800 Subject: Proofread and checked style --- zh-cn/markdown-cn.html.markdown | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 5de5f75b..f82ebcea 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -1,25 +1,25 @@ --- -language: markdown +language: Markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Fangzhou Chen"] -filename: markdown.md +filename: Markdown.md lang: zh-cn --- -Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的语法结构,并可以便利地转换成HTML(以及其他很多)格式。 +Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的语法结构,并可以便利地转换成 HTML(以及其他很多)格式。 欢迎您多多反馈以及分支和请求合并。 ``` - + - @@ -41,7 +41,7 @@ Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的 ------------- - + *此文本为斜体。* _此文本也是。_ @@ -53,7 +53,7 @@ __此文本也是__ **_或者这样。_** *__这个也是!__* - + ~~此文本为删除线效果。~~ @@ -66,7 +66,7 @@ __此文本也是__ 这句话在第三段落! - 此段落结尾有两个空格(选中以显示)。 @@ -108,7 +108,7 @@ __此文本也是__ 2. 项目二 3. 项目三 - 1. 项目一 @@ -126,7 +126,7 @@ __此文本也是__ 4. 项目四 - This is code @@ -150,7 +150,7 @@ def foobar end \`\`\` - + @@ -161,7 +161,7 @@ end **************** - [点我点我!](http://test.com/) @@ -220,10 +220,10 @@ end 斜体化, 所以我就: \*这段置文字于星号之间\*。 - + | 第一列 | 第二列 | 第三列 | -| :---------- | :------: | ---------: | +| :---------- | :------: | ----------: | | 左对齐 | 居个中 | 右对齐 | | 某某某 | 某某某 | 某某某 | @@ -237,4 +237,4 @@ end ``` -更多信息, 请见John Gruber 关于语法的官方帖子[此处](http://daringfireball.net/projects/markdown/syntax)以及 Adam Pritchard 的摘要笔记 [此处](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). +更多信息, 请见John Gruber 关于语法的官方帖子[此处](http://daringfireball.net/projects/Markdown/syntax)以及 Adam Pritchard 的摘要笔记 [此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 3b55d56287ca64e3f8504a6de01d45a305aef90f Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 17:03:38 +0800 Subject: typo correction --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index f82ebcea..95aef8e2 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -41,7 +41,7 @@ Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的 ------------- - + *此文本为斜体。* _此文本也是。_ -- cgit v1.2.3 From ed8da6c3a70e93958d71e0d4ae79f1ae7f1ab114 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 17:06:11 +0800 Subject: Footnote corrected --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 95aef8e2..d0d84d31 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -237,4 +237,4 @@ end ``` -更多信息, 请见John Gruber 关于语法的官方帖子[此处](http://daringfireball.net/projects/Markdown/syntax)以及 Adam Pritchard 的摘要笔记 [此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet). +更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet)。 参见 Adam Pritchard 的摘要笔记。 -- cgit v1.2.3 From 731026a038c7f9322ade73d3b4fee3c22cb84640 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 17:13:48 +0800 Subject: Update markdown-cn.html.markdown --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index d0d84d31..96b0244c 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -237,4 +237,4 @@ end ``` -更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet)。 参见 Adam Pritchard 的摘要笔记。 +更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet) 参见 Adam Pritchard 的摘要笔记。 -- cgit v1.2.3 From 7401ef2411e19d073685a09a668c9aa3a31081f6 Mon Sep 17 00:00:00 2001 From: Adhithya R Date: Mon, 7 Jul 2014 16:38:17 +0530 Subject: MethodSignature -> MethodSignatures Possible typo. Text mentions method names being the same but they weren't. Corrected. --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 4fa8deba..136f6c50 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -367,7 +367,7 @@ on a new line! ""Wow!"", the masses cried"; } // Methods can have the same name, as long as the signature is unique - public static void MethodSignature(string maxCount) + public static void MethodSignatures(string maxCount) { } -- cgit v1.2.3 From 026bca201dab15d3ad9beebda382ec9dc0576f8b Mon Sep 17 00:00:00 2001 From: Rafal Chmiel Date: Mon, 7 Jul 2014 20:14:53 +0100 Subject: [ruby-ecosystem/en] Add links to resources --- ruby-ecosystem.html.markdown | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index d186f712..4b31f8e1 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -3,6 +3,7 @@ category: tool tool: ruby ecosystem contributors: - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] --- @@ -61,29 +62,29 @@ not need to know Java to use it. Very mature/compatible: -* MRI - Written in C, this is the reference implementation of ruby. By +* [MRI](https://github.com/ruby/ruby) - Written in C, this is the reference implementation of ruby. By definition it is 100% compatible (with itself). All other rubies maintain compatibility with MRI (see [RubySpec](#rubyspec) below). -* JRuby - Written in Java and ruby, this robust implementation is quite fast. +* [JRuby](http://jruby.org/) - Written in Java and ruby, this robust implementation is quite fast. Most importantly, JRuby's strength is JVM/Java interop, leveraging existing JVM tools, projects, and languages. -* Rubinius - Written primarily in ruby itself with a C++ bytecode VM. Also +* [Rubinius](http://rubini.us/) - Written primarily in ruby itself with a C++ bytecode VM. Also mature and fast. Because it is implemented in ruby itself, it exposes many VM features into rubyland. Medium mature/compatible: -* Maglev - Built on top of Gemstone, a Smalltalk VM. Smalltalk has some +* [Maglev](http://maglev.github.io/) - Built on top of Gemstone, a Smalltalk VM. Smalltalk has some impressive tooling, and this project tries to bring that into ruby development. -* RubyMotion - Brings ruby to iOS development. +* [RubyMotion](http://www.rubymotion.com/) - Brings ruby to iOS development. Less mature/compatible: -* Topaz - Written in RPython (using the PyPy toolchain), Topaz is fairly young +* [Topaz](http://topazruby.com/) - Written in RPython (using the PyPy toolchain), Topaz is fairly young and not yet compatible. It shows promise to be a high-performance ruby implementation. -* IronRuby - Written in C# targeting the .NET platform, work on IronRuby seems +* [IronRuby](http://ironruby.net/) - Written in C# targeting the .NET platform, work on IronRuby seems to have stopped since Microsoft pulled their support. Ruby implementations may have their own release version numbers, but they always @@ -125,10 +126,10 @@ Testing is a large part of ruby culture. Ruby comes with its own Unit-style testing framework called minitest (Or TestUnit for ruby version 1.8.x). There are many testing libraries with different goals. -* TestUnit - Ruby 1.8's built-in "Unit-style" testing framework -* minitest - Ruby 1.9/2.0's built-in testing framework -* RSpec - A testing framework that focuses on expressivity -* Cucumber - A BDD testing framework that parses Gherkin formatted tests +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Ruby 1.8's built-in "Unit-style" testing framework +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Ruby 1.9/2.0's built-in testing framework +* [RSpec](http://rspec.info/) - A testing framework that focuses on expressivity +* [Cucumber](http://cukes.info/) - A BDD testing framework that parses Gherkin formatted tests ## Be Nice -- cgit v1.2.3 From 764e93156f8b4d9a3c9edb0cadc895c67ecee319 Mon Sep 17 00:00:00 2001 From: Rafal Chmiel Date: Mon, 7 Jul 2014 20:25:45 +0100 Subject: [ruby-ecosystem/en] 'ruby' -> 'Ruby' + fix typo --- ruby-ecosystem.html.markdown | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 4b31f8e1..2463d4b8 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -7,15 +7,15 @@ contributors: --- -People using ruby generally have a way to install different ruby versions, +People using Ruby generally have a way to install different Ruby versions, manage their packages (or gems), and manage their gem dependencies. ## Ruby Managers -Some platforms have ruby pre-installed or available as a package. Most rubyists +Some platforms have Ruby pre-installed or available as a package. Most rubyists do not use these, or if they do, they only use them to bootstrap another ruby -installer or implementation. Instead rubyists tend to install a ruby manager to -install and switch between many versions of ruby and their projects' ruby +installer or implementation. Instead rubyists tend to install a Ruby manager to +install and switch between many versions of Ruby and their projects' ruby environments. The following are the popular ruby/environment managers: @@ -33,11 +33,11 @@ The following are the popular ruby/environment managers: Ruby was created by Yukihiro "Matz" Matsumoto, who remains somewhat of a [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), although -that is changing recently. As a result, the reference implementation of ruby is -called MRI (Matz' Reference Implementation), and when you hear a ruby version, +that is changing recently. As a result, the reference implementation of Ruby is +called MRI (Matz' Reference Implementation), and when you hear a Ruby version, it is referring to the release version of MRI. -The three major version of ruby in use are: +The three major version of Ruby in use are: * 2.0.0 - Released in February 2013. Most major libraries and frameworks support 2.0.0. @@ -53,11 +53,11 @@ the community has moved to at least 1.9.2 or 1.9.3. ## Ruby Implementations -The ruby ecosystem enjoys many different implementations of ruby, each with +The Ruby ecosystem enjoys many different implementations of ruby, each with unique strengths and states of compatability. To be clear, the different implementations are written in different languages, but *they are all ruby*. Each implementation has special hooks and extra features, but they all run -normal ruby files well. For instance, JRuby is written in Java, but you do +normal Ruby files well. For instance, JRuby is written in Java, but you do not need to know Java to use it. Very mature/compatible: @@ -68,8 +68,8 @@ maintain compatibility with MRI (see [RubySpec](#rubyspec) below). * [JRuby](http://jruby.org/) - Written in Java and ruby, this robust implementation is quite fast. Most importantly, JRuby's strength is JVM/Java interop, leveraging existing JVM tools, projects, and languages. -* [Rubinius](http://rubini.us/) - Written primarily in ruby itself with a C++ bytecode VM. Also - mature and fast. Because it is implemented in ruby itself, it exposes many VM +* [Rubinius](http://rubini.us/) - Written primarily in Ruby itself with a C++ bytecode VM. Also + mature and fast. Because it is implemented in Ruby itself, it exposes many VM features into rubyland. Medium mature/compatible: @@ -77,7 +77,7 @@ Medium mature/compatible: * [Maglev](http://maglev.github.io/) - Built on top of Gemstone, a Smalltalk VM. Smalltalk has some impressive tooling, and this project tries to bring that into ruby development. -* [RubyMotion](http://www.rubymotion.com/) - Brings ruby to iOS development. +* [RubyMotion](http://www.rubymotion.com/) - Brings Ruby to iOS development. Less mature/compatible: @@ -94,9 +94,9 @@ which MRI version to target. ## RubySpec -Most ruby implementations rely heavily on [RubySpec](http://rubyspec.org/). Ruby +Most Ruby implementations rely heavily on [RubySpec](http://rubyspec.org/). Ruby has no official specification, so the community has written executable specs in -ruby to test their implementations' compatability with MRI. +Ruby to test their implementations' compatibility with MRI. ## RubyGems @@ -122,8 +122,8 @@ dependency graph to resolve. # Testing -Testing is a large part of ruby culture. Ruby comes with its own Unit-style -testing framework called minitest (Or TestUnit for ruby version 1.8.x). There +Testing is a large part of Ruby culture. Ruby comes with its own Unit-style +testing framework called minitest (Or TestUnit for Ruby version 1.8.x). There are many testing libraries with different goals. * [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Ruby 1.8's built-in "Unit-style" testing framework @@ -133,6 +133,6 @@ are many testing libraries with different goals. ## Be Nice -The ruby community takes pride in being an open, diverse, welcoming community. +The Ruby community takes pride in being an open, diverse, welcoming community. Matz himself is extremely friendly, and the generosity of rubyists on the whole is amazing. -- cgit v1.2.3 From 73128555323a3339e2502abfb6a1bc9829fcd10d Mon Sep 17 00:00:00 2001 From: Rafal Chmiel Date: Mon, 7 Jul 2014 21:07:29 +0100 Subject: [ruby-ecosystem/en] 'ruby' -> 'Ruby' (cont.) --- ruby-ecosystem.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 2463d4b8..56b293b7 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -13,12 +13,12 @@ manage their packages (or gems), and manage their gem dependencies. ## Ruby Managers Some platforms have Ruby pre-installed or available as a package. Most rubyists -do not use these, or if they do, they only use them to bootstrap another ruby +do not use these, or if they do, they only use them to bootstrap another Ruby installer or implementation. Instead rubyists tend to install a Ruby manager to -install and switch between many versions of Ruby and their projects' ruby +install and switch between many versions of Ruby and their projects' Ruby environments. -The following are the popular ruby/environment managers: +The following are the popular Ruby environment managers: * [RVM](https://rvm.io/) - Installs and switches between rubies. RVM also has the concept of gemsets to isolate projects' environments completely. @@ -53,19 +53,19 @@ the community has moved to at least 1.9.2 or 1.9.3. ## Ruby Implementations -The Ruby ecosystem enjoys many different implementations of ruby, each with +The Ruby ecosystem enjoys many different implementations of Ruby, each with unique strengths and states of compatability. To be clear, the different -implementations are written in different languages, but *they are all ruby*. +implementations are written in different languages, but *they are all Ruby*. Each implementation has special hooks and extra features, but they all run normal Ruby files well. For instance, JRuby is written in Java, but you do not need to know Java to use it. Very mature/compatible: -* [MRI](https://github.com/ruby/ruby) - Written in C, this is the reference implementation of ruby. By +* [MRI](https://github.com/ruby/ruby) - Written in C, this is the reference implementation of Ruby. By definition it is 100% compatible (with itself). All other rubies maintain compatibility with MRI (see [RubySpec](#rubyspec) below). -* [JRuby](http://jruby.org/) - Written in Java and ruby, this robust implementation is quite fast. +* [JRuby](http://jruby.org/) - Written in Java and Ruby, this robust implementation is quite fast. Most importantly, JRuby's strength is JVM/Java interop, leveraging existing JVM tools, projects, and languages. * [Rubinius](http://rubini.us/) - Written primarily in Ruby itself with a C++ bytecode VM. Also @@ -75,7 +75,7 @@ features into rubyland. Medium mature/compatible: * [Maglev](http://maglev.github.io/) - Built on top of Gemstone, a Smalltalk VM. Smalltalk has some - impressive tooling, and this project tries to bring that into ruby + impressive tooling, and this project tries to bring that into Ruby development. * [RubyMotion](http://www.rubymotion.com/) - Brings Ruby to iOS development. -- cgit v1.2.3 From aa89d993ed63e3ab0691828481fb2b0b0416e9a0 Mon Sep 17 00:00:00 2001 From: Rafal Chmiel Date: Mon, 7 Jul 2014 21:50:27 +0100 Subject: [ruby-ecosystem/en] 'ruby' -> 'Ruby' (cont. cont.) --- ruby-ecosystem.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 56b293b7..8b292edd 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -82,7 +82,7 @@ development. Less mature/compatible: * [Topaz](http://topazruby.com/) - Written in RPython (using the PyPy toolchain), Topaz is fairly young - and not yet compatible. It shows promise to be a high-performance ruby + and not yet compatible. It shows promise to be a high-performance Ruby implementation. * [IronRuby](http://ironruby.net/) - Written in C# targeting the .NET platform, work on IronRuby seems to have stopped since Microsoft pulled their support. @@ -100,8 +100,8 @@ Ruby to test their implementations' compatibility with MRI. ## RubyGems -[RubyGems](http://rubygems.org/) is a community-run package manager for ruby. -RubyGems ships with ruby, so there is no need to download it separately. +[RubyGems](http://rubygems.org/) is a community-run package manager for Ruby. +RubyGems ships with Ruby, so there is no need to download it separately. Ruby packages are called "gems," and they can be hosted by the community at RubyGems.org. Each gem contains its source code and some metadata, including -- cgit v1.2.3 From 55e1c2adafcf0f2590633064aaf83af5ff1964af Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Wed, 9 Jul 2014 20:56:01 -0700 Subject: Go inline function literals as arguments to other functions or function literals. --- go.html.markdown | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/go.html.markdown b/go.html.markdown index a9a7de72..e496117e 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -188,6 +188,15 @@ func learnFlowControl() { x = 1.3e3 // This makes x == 1300 fmt.Println("xBig:", xBig()) // false now. + // What's more is function literals may be defined and called inline, + // acting as an argument to function, as long as: + // a) function literal is called immediately (), + // b) result type matches expected type of argument. + fmt.Println("Add + double two numbers: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Called with args (10, 2) + // When you need it, you'll love it. goto love love: -- cgit v1.2.3 From 174f0baa14421834e181f37bd969d7f015a02adc Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Thu, 10 Jul 2014 09:22:47 -0700 Subject: Small change to inline literal functions comments. --- go.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index e496117e..a5ea5859 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -195,7 +195,8 @@ func learnFlowControl() { fmt.Println("Add + double two numbers: ", func(a, b int) int { return (a + b) * 2 - }(10, 2)) // Called with args (10, 2) + }(10, 2)) // Called with args 10 and 2 + // Add + double two numbers: 24 // When you need it, you'll love it. goto love -- cgit v1.2.3 From 7cddab2925260946c61eac60cc62764017a8e8af Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Thu, 10 Jul 2014 09:25:48 -0700 Subject: Forgot to add `=>` to comment line. --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index a5ea5859..88e2c8da 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -196,7 +196,7 @@ func learnFlowControl() { func(a, b int) int { return (a + b) * 2 }(10, 2)) // Called with args 10 and 2 - // Add + double two numbers: 24 + // => Add + double two numbers: 24 // When you need it, you'll love it. goto love -- cgit v1.2.3 From 7db96aafe39ff4dab601a73a871c02a9841cf6b0 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Thu, 10 Jul 2014 22:23:56 +0200 Subject: switcheroo operators --- perl6.html.markdown | 67 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 39 insertions(+), 28 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 7a8c7525..f86c3d64 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -130,25 +130,12 @@ if long-computation() -> $result { ## The categories are : ### - "prefix" : before (like `!` in `!True`). -### "postfix" : after (like `++` in `$a++`). -### "infix" : in between (like `*` in `4 * 3`). -### "circumfix" : around (like `[`-`]` in `[1, 2]`). -### "post-circumfix" : around, after another term (like `{`-`}` in `%hash{'key'}`) +### - "postfix" : after (like `++` in `$a++`). +### - "infix" : in between (like `*` in `4 * 3`). +### - "circumfix" : around (like `[`-`]` in `[1, 2]`). +### - "post-circumfix" : around, after another term (like `{`-`}` in `%hash{'key'}`) -## The precedence list can be found here : http://perlcabal.org/syn/S03.html#Operator_precedence -## But first, we need a little explanation about associativity : - -### Binary operators: -$a ! $b ! $c; # with a left-associative `!`, this is `($a ! $b) ! $c` -$a ! $b ! $c; # with a right-associative `!`, this is `$a ! ($b ! $c)` -$a ! $b ! $c; # with a non-associative `!`, this is illegal -$a ! $b ! $c; # with a chain-associative `!`, this is `($a ! $b) and ($b ! $c)` -$a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` - -### Unary operators: -!$a! # with left-associative `!`, this is `(!$a)!` -!$a! # with right-associative `!`, this is `!($a!)` -!$a! # with non-associative `!`, this is illegal +## The associativity and precedence list are explained below. ## Alright, you're set to go ! @@ -180,24 +167,48 @@ $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an ar ### Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`. 3 > 4; -## * Sort comparison -### They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1). -1 <=> 4; # sort comparison for numerics -'a' leg 'b'; # sort comparison for string -$obj eqv $obj2; # sort comparison using eqv semantics - -## * Generic ordering -3 before 4; # True -'b' after 'a'; # True - ## * Range constructors 3 .. 7; # 3 to 7, both included ### `^` on either side them exclusive on that side : 3 ^..^ 7; # 3 to 7, not included (basically `4 .. 6`) # * And, Or +3 && 4; # True. Calls `.Bool` on `3` +0 || False; # False. Calls `.Bool` on `0` ## Short-circuit (and tight) $a && $b && $c; # returns the first argument that evaluates to False, or the last argument $a || $b; + +# More operators thingies ! + +## Everybody loves operators ! Let's get more of them + +## The precedence list can be found here : http://perlcabal.org/syn/S03.html#Operator_precedence +## But first, we need a little explanation about associativity : + +### Binary operators: +$a ! $b ! $c; # with a left-associative `!`, this is `($a ! $b) ! $c` +$a ! $b ! $c; # with a right-associative `!`, this is `$a ! ($b ! $c)` +$a ! $b ! $c; # with a non-associative `!`, this is illegal +$a ! $b ! $c; # with a chain-associative `!`, this is `($a ! $b) and ($b ! $c)` +$a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` + +### Unary operators: +!$a! # with left-associative `!`, this is `(!$a)!` +!$a! # with right-associative `!`, this is `!($a!)` +!$a! # with non-associative `!`, this is illegal + +## And to end the list of operators ... + +## * Sort comparison +### They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1). +1 <=> 4; # sort comparison for numerics +'a' leg 'b'; # sort comparison for string +$obj eqv $obj2; # sort comparison using eqv semantics + +## * Generic ordering +3 before 4; # True +'b' after 'a'; # True + ``` -- cgit v1.2.3 From bdbff25c5850e41552e5fc517c99fe3933dc591c Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Sun, 13 Jul 2014 14:08:12 -0400 Subject: [python3/en] added int div, modulo, and scoping Added integer or truncation division, the modulo operator which were missing from operators section. Added function scoping in the functions section. --- python3.html.markdown | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index 778076f8..eca49862 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -2,6 +2,7 @@ language: python3 contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://sbasart.com"] filename: learnpython3.py --- @@ -37,9 +38,16 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Except division which returns floats by default 35 / 5 # => 7.0 +# Truncation or Integer division +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 + # When you use a float, results are floats 3 * 2.0 # => 6.0 +# Modulo operation +7 % 3 # => 1 + # Enforce precedence with parentheses (1 + 3) * 2 # => 8 @@ -406,6 +414,24 @@ 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) + +setX(43) +setGlobalX(6) + + # Python has first class functions def create_adder(x): def adder(y): -- cgit v1.2.3 From d6fa11cb750bf791d7f53fe95ed14a50e2cac60a Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sun, 13 Jul 2014 20:42:29 +0200 Subject: Some class love --- perl6.html.markdown | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index f86c3d64..fb052590 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -38,7 +38,7 @@ my $weird'variable-name_ = 5; my @array = 1, 2, 3; my @array = 'a', 'b', 'c'; # equivalent to : -my @array =
; # similar to perl5's qw, or Ruby's %w +my @array = ; # array of string, delimited by space. similar to perl5's qw, or Ruby's %w say @array[2]; # Arrays are 0-indexed @@ -57,6 +57,12 @@ say %hash; # if it's a string, you can actually use <> ## - Subs (subroutines, or functions in most other languages). Stored in variable, they use `&` sub say-hello { say "Hello, world" } +sub say-hello-to(Str $name) { # you can provide the type of an argument + # and it'll be checked at compile-time + + say "Hello, $name !"; +} + # since you can omit parenthesis to call a function with no arguments, you need to use `&` also to capture `say-hello` my &s = &say-hello; my &other-s = sub { say "anonymous function !" } @@ -64,6 +70,25 @@ my &other-s = sub { say "anonymous function !" } # `->`, lambda with arguments, and string interpolation my &lambda = -> $argument { "The argument passed to this lambda is $argument" } +### Containers +# In Perl 6, values are actually stored in "containers". +# the assignment operator asks the container on the left to store the value on its right +# When passed around, containers are marked as immutable. Which means that, in a function, +# you'll get an error if you try to mutate one of your argument. +# If you really need to, you can ask for a mutable container using `is rw` : +sub mutate($n is rw) { + $n++; + say "\$n is now $n !"; +} + +# If what you want is a copy instead, use `is copy`. + +# A sub itself returns a container, which means it can be marked as rw : +my $x = 42; +sub mod() is rw { $x } +mod() = 52; # in this case, the parentheses are mandatory +say $x; #=> 52 + ### Control Flow Structures # You don't need to put parenthesis around the condition, but that also means you always have to use brackets (`{ }`) for their body : @@ -180,6 +205,37 @@ $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an ar $a && $b && $c; # returns the first argument that evaluates to False, or the last argument $a || $b; +# Perl 6 has a quite comprehensive class system +## You declare a class with the keyword `class`, fields with `has`, methods with `method` +## `$.` declares a public field, `$!` declares a private field +## (a public field also has `$!`, which is its private interface) + +class A { + has $.field; + has Int $!private-field = 10; + + method get-value { + $.field + $!private-field + $n; + } + + method set-value($n) { + # $.field = $n; # This fails, because a public field is actually an immutable container + # (even from inside the class) + # You either need to use `is rw` on the `has` + # (which will make it mutable, even from outside the class) + # or you need to use the `$!` version : + + $!field = $n; # This works, because `$!` is always mutable + } +}; + +# Create a new instance of A with $.field set to 5 : +# note : you can't set private-field from here (more later on) +my $a = A.new(field => 5); +$a.get-value; #=> 18 +#$a.field = 5; # This fails, because the `has $.field` is lacking the `is rw` + + # More operators thingies ! ## Everybody loves operators ! Let's get more of them -- cgit v1.2.3 From 42c93bf407d91cdb549ef5053c3db7f4a58bcd7e Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Sun, 13 Jul 2014 14:45:14 -0400 Subject: [python3/en] added int div, modulo, and scoping Added integer or truncation division, the modulo operator which were missing from operators section. Added function scoping in the functions section. --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index eca49862..8d9b8e77 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -426,7 +426,7 @@ def setGlobalX(num): global x print (x) # => 5 x = num # global var x is now set to 6 - print (x) + print (x) # => 6 setX(43) setGlobalX(6) -- cgit v1.2.3 From 2a9a4f39babe369395de580d0bd7f405a0283803 Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Sun, 13 Jul 2014 14:51:34 -0400 Subject: [python/en] added int div, modulo, and scoping Added integer or truncation division, the modulo operator which were missing from operators section. Added function scoping in the functions section. --- python.html.markdown | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 210c9619..d1b88b25 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -45,6 +45,13 @@ to Python 2.x. Look for another tour of Python 3 soon! 2.0 # This is a float 11.0 / 4.0 # => 2.75 ahhh...much better +# Truncation or Integer division +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 + +# Modulo operation +7 % 3 # => 1 + # Enforce precedence with parentheses (1 + 3) * 2 # => 8 @@ -380,6 +387,22 @@ 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): -- cgit v1.2.3 From 0dcc5640b6e1a9bba857114e1257a29aa9829ce9 Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Sun, 13 Jul 2014 14:52:31 -0400 Subject: [python/en] added int div, modulo, and scoping Added integer or truncation division, the modulo operator which were missing from operators section. Added function scoping in the functions section. --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index d1b88b25..aa077e57 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -47,7 +47,7 @@ to Python 2.x. Look for another tour of Python 3 soon! # Truncation or Integer division 5 // 3 # => 1 -5.0 // 3.0 # => 1.0 +5.0 // 3.0 # => 1.0 # works on floats too # Modulo operation 7 % 3 # => 1 -- cgit v1.2.3 From f08663db5cd965924e0fb4f344dea5c7ada9057e Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Sun, 13 Jul 2014 16:00:28 -0400 Subject: Update python3.html.markdown --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index 8d9b8e77..7657295d 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -2,7 +2,7 @@ language: python3 contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://sbasart.com"] + - ["Steven Basart", "http://github.com/xksteven"] filename: learnpython3.py --- -- cgit v1.2.3 From f97d9c5aba4b50911c0580cccbd3950be5192c01 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sun, 13 Jul 2014 22:28:41 +0200 Subject: Moar classes. Roles. And stuff. And dispatch todo : muti dispatch --- perl6.html.markdown | 171 +++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 143 insertions(+), 28 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index fb052590..057c74f8 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -70,6 +70,52 @@ my &other-s = sub { say "anonymous function !" } # `->`, lambda with arguments, and string interpolation my &lambda = -> $argument { "The argument passed to this lambda is $argument" } +# add 3 to each value of an array using map : +map({ $_ + 3 }, @array); # $_ is the implicit argument (the same as for `given` and `for`) + +# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`) : +# a block doesn't have a function context (though it can have arguments), which means that if you +# return from it, you're going to return from the parent function, compare: +sub is-in(@array, $elem) { + map({ return True if $_ == $elem }, @array); # this will `return` out of `is-in` +} +sub truthy-array(@array) { + # this will produce an array of `True` and `False` : + # (you can also say `anon sub` for "anonymous subroutine") + map(sub { if $_ { return True } else { return False } }, @array); +} + +# `-> {}` and `{}` are pretty much the same thing, except taht the former can take arguments, +# and that the latter can be mistaken as a hash by the compiler + +# You can also use the "whatever star" to create an anonymous function : +map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` +map(*+*+3, @array); # also works. Same as `-> $a, $b -> { $a + $b + 3 }` + +# but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`), +# you can also use the implicit argument syntax, `$^` : +map({ $^a + $^b + 3 }, @array); # same as the above + +# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $ b / $a }` + +## Multiple Dispatch +# Perl 6 can decide which variant of a `sub` to call based on the type of the arguments, +# or on arbitrary preconditions, using `where` : + +# with types +multi sub sayit(Int $n) { # note the `multi` keyword here + say "Number: $n"; +} +multi sayit(Str $s) } # the `sub` is implicit + say "String: $s"; +} +sayit("foo"); # prints "String: foo" +sayit(True); # fails at *compile time* with "calling 'sayit' will never work with arguments of types ..." + +# with arbitrary precondition : +multi is-big(Int $n where * > 10) { True } +multi is-big(Int $) { False } + ### Containers # In Perl 6, values are actually stored in "containers". # the assignment operator asks the container on the left to store the value on its right @@ -95,6 +141,7 @@ say $x; #=> 52 ## Conditionals +# - `if` if True { say "It's true !"; } @@ -103,10 +150,12 @@ unless False { say "It's not false !"; } - # if (true) say; # Won't work -# `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching : +# - Ternary conditional +my $a = $condition ?? $value-if-true !! $value-if-false; # `??` and `!!` are like `?` and `:` in other languages' + +# - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching : given "foo bar" { # given just puts its argument into `$_`, and `when` uses it using the "smart matching" operator. when /foo/ { # you'll read about the smart-matching operator below say "Yay !"; @@ -118,7 +167,7 @@ given "foo bar" { # given just puts its argument into `$_`, and `when` uses it u ## Looping constructs -### - `loop` is an infinite loop if you don't pass it arguments, but can also be a c-style `for` : +# - `loop` is an infinite loop if you don't pass it arguments, but can also be a c-style `for` : loop { say "This is an infinite loop !"; last; # last breaks out of the loop, like the `break` keyword in other languages @@ -130,7 +179,7 @@ loop (my $i = 0; $i < 5; $i++) { say "This is a C-style for loop !"; } -### - `for` - Foreaches an array +# - `for` - Foreaches an array for @array -> $variable { say "I've found $variable !"; } @@ -147,69 +196,74 @@ if long-computation() -> $result { -# Operators +### Operators ## 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) ## The categories are : -### - "prefix" : before (like `!` in `!True`). -### - "postfix" : after (like `++` in `$a++`). -### - "infix" : in between (like `*` in `4 * 3`). -### - "circumfix" : around (like `[`-`]` in `[1, 2]`). -### - "post-circumfix" : around, after another term (like `{`-`}` in `%hash{'key'}`) +# - "prefix" : before (like `!` in `!True`). +# - "postfix" : after (like `++` in `$a++`). +# - "infix" : in between (like `*` in `4 * 3`). +# - "circumfix" : around (like `[`-`]` in `[1, 2]`). +# - "post-circumfix" : around, after another term (like `{`-`}` in `%hash{'key'}`) ## The associativity and precedence list are explained below. -## Alright, you're set to go ! +# Alright, you're set to go ! ## * Equality Checking -### - `==` is numeric comparison +# - `==` is numeric comparison 3 == 4; # False 3 != 4; # True -### - `eq` is string comparison +# - `eq` is string comparison 'a' eq 'b'; 'a' ne 'b'; # not equal 'a' !eq 'b'; # same as above -### - `eqv` is canonical equivalence +# - `eqv` is canonical equivalence (1, 2) eqv (1, 3); -### - `~~` is smart matching -### for a complete combinations list, use this table : http://perlcabal.org/syn/S03.html#Smart_matching +# - `~~` is smart matching +# for a complete combinations list, use this table : http://perlcabal.org/syn/S03.html#Smart_matching 'a' ~~ /a/; # true if matches regexp 'key' ~~ %hash; # true if key exists in hash $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an argument, returns True 1 ~~ Int; # "is of type" -### - `===` is value identity and uses `.WHICH` on the objects to compare them -### - `=:=` is container identity and uses `VAR()` on the objects to compare them +# - `===` is value identity and uses `.WHICH` on the objects to compare them +# - `=:=` is container identity and uses `VAR()` on the objects to compare them -### You also, of course, have `<`, `<=`, `>`, `>=`. -### Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`. +# You also, of course, have `<`, `<=`, `>`, `>=`. +# Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`. 3 > 4; ## * Range constructors 3 .. 7; # 3 to 7, both included -### `^` on either side them exclusive on that side : +# `^` on either side them exclusive on that side : 3 ^..^ 7; # 3 to 7, not included (basically `4 .. 6`) -# * And, Or +## * And, Or 3 && 4; # True. Calls `.Bool` on `3` 0 || False; # False. Calls `.Bool` on `0` -## Short-circuit (and tight) +## Short-circuit (and tight) versions of the above $a && $b && $c; # returns the first argument that evaluates to False, or the last argument $a || $b; -# Perl 6 has a quite comprehensive class system +### Object Model + +## Perl 6 has a quite comprehensive object model ## You declare a class with the keyword `class`, fields with `has`, methods with `method` ## `$.` declares a public field, `$!` declares a private field ## (a public field also has `$!`, which is its private interface) +# (Perl 6's object model ("P6Model") is very flexible, and allows you to dynamically add methods, +# change semantics, etc -- This will not be covered here, and you should refer to the Synopsis) + class A { has $.field; has Int $!private-field = 10; @@ -227,6 +281,10 @@ class A { $!field = $n; # This works, because `$!` is always mutable } + + method !private-method { + say "This method is private to the class !"; + } }; # Create a new instance of A with $.field set to 5 : @@ -235,22 +293,79 @@ my $a = A.new(field => 5); $a.get-value; #=> 18 #$a.field = 5; # This fails, because the `has $.field` is lacking the `is rw` +## Perl 6 also has inheritance (along with multiple inheritance ... Considered a misfeature by many) + +class A { + has $.val; + + submethod not-inherited { + say "This method won't be available on B."; + say "This is most useful for BUILD, which we'll see later"; + } + + method bar { $.val * 5 } +} +class B is A { # inheritance uses `is` + method foo { + say $.val; + } + + method bar { $.val * 10 } # this shadows A's `bar` +} + +my B $b .= new(val => 5); # When you use `my T $var`, `$var` starts off with `T` itself in it, so you can call `new` on it + # (`.=` is just the compound operator composed of the dot-call and of the assignment operator) + # + # Also note that `BUILD` (the method called inside `new`) will set parent properties too, + # so you can pass `val => 5` +# $b.not-inherited; # This won't work, for reasons explained above +$b.foo; # prints 5 +$b.bar; #=> 50, since it calls B's `bar` + +## Roles are supported too (also called Mixins in other languages) +role PrintableVal { + has $!counter = 0; + method print { + say $.val; + } +} + +# you "use" a mixin with "does" : +class Item does PrintableVal { + has $.val; + + # When `does`-ed, a `role` literally "mixes in" the class : + # the methods and fields are put together, which means a class can access + # the private fields/methods of its roles (but not the inverse !) : + method access { + say $!counter++; + } + + # However, this : + # method print {} + # is an error, since the compiler wouldn't know which `print` to use : + # contrarily to inheritance, methods mixed in can't be shadowed - they're put at the same "level" + + # NOTE : You can use a role as a class (with `is ROLE`). In this case, methods will be shadowed, + # since the compiler will consider `ROLE` to be a class +} + -# More operators thingies ! +### More operators thingies ! ## Everybody loves operators ! Let's get more of them ## The precedence list can be found here : http://perlcabal.org/syn/S03.html#Operator_precedence ## But first, we need a little explanation about associativity : -### Binary operators: +# - Binary operators: $a ! $b ! $c; # with a left-associative `!`, this is `($a ! $b) ! $c` $a ! $b ! $c; # with a right-associative `!`, this is `$a ! ($b ! $c)` $a ! $b ! $c; # with a non-associative `!`, this is illegal $a ! $b ! $c; # with a chain-associative `!`, this is `($a ! $b) and ($b ! $c)` $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` -### Unary operators: +# - Unary operators: !$a! # with left-associative `!`, this is `(!$a)!` !$a! # with right-associative `!`, this is `!($a!)` !$a! # with non-associative `!`, this is illegal @@ -258,7 +373,7 @@ $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` ## And to end the list of operators ... ## * Sort comparison -### They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1). +# They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1). 1 <=> 4; # sort comparison for numerics 'a' leg 'b'; # sort comparison for string $obj eqv $obj2; # sort comparison using eqv semantics -- cgit v1.2.3 From 0654a19b44b290828211372e8148338c4c1d1c23 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Tue, 15 Jul 2014 13:30:27 +0930 Subject: [python3/en] Clean up confusion between % and .format() --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 7657295d..43d62e77 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -292,7 +292,7 @@ prints: mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: - # You can use % to interpolate formatted strings + # You can use format() to interpolate formatted strings print("{} is a mammal".format(animal)) """ @@ -471,7 +471,7 @@ class Human(object): # An instance method. All methods take "self" as the first argument def say(self, msg): - return "{name}: {message}" % (name=self.name, message=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 -- cgit v1.2.3 From c022e2e857ceca9914f0b6ff8d4d2f9e60a729cd Mon Sep 17 00:00:00 2001 From: Hey Alexej Date: Wed, 16 Jul 2014 05:28:50 +0700 Subject: fix import of io/ioutil, run gofmt generated/downloaded file doesn't work with "go run". it's missing ioutil. ran gofmt which uses tabs (width=8) for formatting. longest line is 85 characters now. removed whitespace. --- go.html.markdown | 449 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 225 insertions(+), 224 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 0ecc6120..a1be08af 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -9,6 +9,7 @@ contributors: - ["Jesse Johnson", "https://github.com/holocronweaver"] - ["Quint Guvernator", "https://github.com/qguv"] - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] --- Go was created out of the need to get work done. It's not the latest trend @@ -33,87 +34,88 @@ package main // Import declaration declares library packages referenced in this file. import ( - "fmt" // A package in the Go standard library. - "net/http" // Yes, a web server! - "strconv" // String conversions. - m "math" // Math library with local alias m. + "fmt" // A package in the Go standard library. + "io/ioutil" // Implements some I/O utility functions. + m "math" // Math library with local alias m. + "net/http" // Yes, a web server! + "strconv" // String conversions. ) // A function definition. Main is special. It is the entry point for the // executable program. Love it or hate it, Go uses brace brackets. func main() { - // Println outputs a line to stdout. - // Qualify it with the package name, fmt. - fmt.Println("Hello world!") + // Println outputs a line to stdout. + // Qualify it with the package name, fmt. + fmt.Println("Hello world!") - // Call another function within this package. - beyondHello() + // Call another function within this package. + beyondHello() } // Functions have parameters in parentheses. // If there are no parameters, empty parentheses are still required. func beyondHello() { - var x int // Variable declaration. Variables must be declared before use. - x = 3 // Variable assignment. - // "Short" declarations use := to infer the type, declare, and assign. - y := 4 - sum, prod := learnMultiple(x, y) // Function returns two values. - fmt.Println("sum:", sum, "prod:", prod) // Simple output. - learnTypes() // < y minutes, learn more! + var x int // Variable declaration. Variables must be declared before use. + x = 3 // Variable assignment. + // "Short" declarations use := to infer the type, declare, and assign. + y := 4 + sum, prod := learnMultiple(x, y) // Function returns two values. + fmt.Println("sum:", sum, "prod:", prod) // Simple output. + learnTypes() // < y minutes, learn more! } // Functions can have parameters and (multiple!) return values. func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // Return two values. + return x + y, x * y // Return two values. } // Some built-in types and literals. func learnTypes() { - // Short declaration usually gives you what you want. - s := "Learn Go!" // string type. + // Short declaration usually gives you what you want. + s := "Learn Go!" // string type. - s2 := `A "raw" string literal + s2 := `A "raw" string literal can include line breaks.` // Same string type. - // Non-ASCII literal. Go source is UTF-8. - g := 'Σ' // rune type, an alias for uint32, holds a unicode code point. + // Non-ASCII literal. Go source is UTF-8. + g := 'Σ' // rune type, an alias for uint32, holds a unicode code point. - f := 3.14195 // float64, an IEEE-754 64-bit floating point number. - c := 3 + 4i // complex128, represented internally with two float64's. + f := 3.14195 // float64, an IEEE-754 64-bit floating point number. + c := 3 + 4i // complex128, represented internally with two float64's. - // Var syntax with an initializers. - var u uint = 7 // Unsigned, but implementation dependent size as with int. - var pi float32 = 22. / 7 + // Var syntax with an initializers. + var u uint = 7 // Unsigned, but implementation dependent size as with int. + var pi float32 = 22. / 7 - // Conversion syntax with a short declaration. - n := byte('\n') // byte is an alias for uint8. + // Conversion syntax with a short declaration. + n := byte('\n') // byte is an alias for uint8. - // Arrays have size fixed at compile time. - var a4 [4]int // An array of 4 ints, initialized to all 0. - a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown. + // Arrays have size fixed at compile time. + var a4 [4]int // An array of 4 ints, initialized to all 0. + a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown. - // Slices have dynamic size. Arrays and slices each have advantages - // but use cases for slices are much more common. - s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. - s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0. - var d2 [][]float64 // Declaration only, nothing allocated here. - bs := []byte("a slice") // Type conversion syntax. + // Slices have dynamic size. Arrays and slices each have advantages + // but use cases for slices are much more common. + s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. + s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0. + var d2 [][]float64 // Declaration only, nothing allocated here. + bs := []byte("a slice") // Type conversion syntax. - p, q := learnMemory() // Declares p, q to be type pointer to int. - fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + p, q := learnMemory() // Declares p, q to be type pointer to int. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. - // Maps are a dynamically growable associative array type, like the - // hash or dictionary types of some other languages. - m := map[string]int{"three": 3, "four": 4} - m["one"] = 1 + // Maps are a dynamically growable associative array type, like the + // hash or dictionary types of some other languages. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 - // Unused variables are an error in Go. - // The underbar lets you "use" a variable but discard its value. - _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs - // Output of course counts as using a variable. - fmt.Println(s, c, a4, s3, d2, m) + // Unused variables are an error in Go. + // The underbar lets you "use" a variable but discard its value. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Output of course counts as using a variable. + fmt.Println(s, c, a4, s3, d2, m) - learnFlowControl() // Back in the flow. + learnFlowControl() // Back in the flow. } // It is possible, unlike in many other languages for functions in go @@ -122,250 +124,249 @@ can include line breaks.` // Same string type. // allows us to easily return from multiple points in a function as well as to // only use the return keyword, without anything further. func learnNamedReturns(x, y int) (z int) { - z = x * y - return // z is implicit here, because we named it earlier. + z = x * y + return // z is implicit here, because we named it earlier. } // Go is fully garbage collected. It has pointers but no pointer arithmetic. // You can make a mistake with a nil pointer, but not by incrementing a pointer. func learnMemory() (p, q *int) { - // Named return values p and q have type pointer to int. - p = new(int) // Built-in function new allocates memory. - // The allocated int is initialized to 0, p is no longer nil. - s := make([]int, 20) // Allocate 20 ints as a single block of memory. - s[3] = 7 // Assign one of them. - r := -2 // Declare another local variable. - return &s[3], &r // & takes the address of an object. + // Named return values p and q have type pointer to int. + p = new(int) // Built-in function new allocates memory. + // The allocated int is initialized to 0, p is no longer nil. + s := make([]int, 20) // Allocate 20 ints as a single block of memory. + s[3] = 7 // Assign one of them. + r := -2 // Declare another local variable. + return &s[3], &r // & takes the address of an object. } func expensiveComputation() float64 { - return m.Exp(10) + return m.Exp(10) } func learnFlowControl() { - // If statements require brace brackets, and do not require parens. - if true { - fmt.Println("told ya") - } - // Formatting is standardized by the command line command "go fmt." - if false { - // Pout. - } else { - // Gloat. - } - // Use switch in preference to chained if statements. - x := 42.0 - switch x { - case 0: - case 1: - case 42: - // Cases don't "fall through". - case 43: - // Unreached. - } - // Like if, for doesn't use parens either. - // Variables declared in for and if are local to their scope. - for x := 0; x < 3; x++ { // ++ is a statement. - fmt.Println("iteration", x) - } - // x == 42 here. - - // For is the only loop statement in Go, but it has alternate forms. - for { // Infinite loop. - break // Just kidding. - continue // Unreached. - } - // As with for, := in an if statement means to declare and assign y first, - // then test y > x. - if y := expensiveComputation(); y > x { - x = y - } - // Function literals are closures. - xBig := func() bool { - return x > 10000 // References x declared above switch statement. - } - fmt.Println("xBig:", xBig()) // true (we last assigned e^10 to x). - x = 1.3e3 // This makes x == 1300 - fmt.Println("xBig:", xBig()) // false now. - - // What's more is function literals may be defined and called inline, - // acting as an argument to function, as long as: - // a) function literal is called immediately (), - // b) result type matches expected type of argument. - fmt.Println("Add + double two numbers: ", - func(a, b int) int { - return (a + b) * 2 - }(10, 2)) // Called with args 10 and 2 - // => Add + double two numbers: 24 - - // When you need it, you'll love it. - goto love + // If statements require brace brackets, and do not require parens. + if true { + fmt.Println("told ya") + } + // Formatting is standardized by the command line command "go fmt." + if false { + // Pout. + } else { + // Gloat. + } + // Use switch in preference to chained if statements. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Cases don't "fall through". + case 43: + // Unreached. + } + // Like if, for doesn't use parens either. + // Variables declared in for and if are local to their scope. + for x := 0; x < 3; x++ { // ++ is a statement. + fmt.Println("iteration", x) + } + // x == 42 here. + + // For is the only loop statement in Go, but it has alternate forms. + for { // Infinite loop. + break // Just kidding. + continue // Unreached. + } + // As with for, := in an if statement means to declare and assign + // y first, then test y > x. + if y := expensiveComputation(); y > x { + x = y + } + // Function literals are closures. + xBig := func() bool { + return x > 10000 // References x declared above switch statement. + } + fmt.Println("xBig:", xBig()) // true (we last assigned e^10 to x). + x = 1.3e3 // This makes x == 1300 + fmt.Println("xBig:", xBig()) // false now. + + // What's more is function literals may be defined and called inline, + // acting as an argument to function, as long as: + // a) function literal is called immediately (), + // b) result type matches expected type of argument. + fmt.Println("Add + double two numbers: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Called with args 10 and 2 + // => Add + double two numbers: 24 + + // When you need it, you'll love it. + goto love love: - learnFunctionFactory() // func returning func is fun(3)(3) - learnDefer() // A quick detour to an important keyword. - learnInterfaces() // Good stuff coming up! + learnFunctionFactory() // func returning func is fun(3)(3) + learnDefer() // A quick detour to an important keyword. + learnInterfaces() // Good stuff coming up! } func learnFunctionFactory() { - // Next two are equivalent, with second being more practical - fmt.Println(sentenceFactory("summer")("A beautiful", "day!")) + // Next two are equivalent, with second being more practical + fmt.Println(sentenceFactory("summer")("A beautiful", "day!")) - d := sentenceFactory("summer") - fmt.Println(d("A beautiful", "day!")) - fmt.Println(d("A lazy", "afternoon!")) + d := sentenceFactory("summer") + fmt.Println(d("A beautiful", "day!")) + fmt.Println(d("A lazy", "afternoon!")) } // Decorators are common in other languages. Same can be done in Go // with function literals that accept 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) // new string - } + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // new string + } } func learnDefer() (ok bool) { - // Deferred statements are executed just before the function returns. - defer fmt.Println("deferred statements execute in reverse (LIFO) order.") - defer fmt.Println("\nThis line is being printed first because") - // Defer is commonly used to close a file, so the function closing the file - // stays close to the function opening the file - return true + // Deferred statements are executed just before the function returns. + defer fmt.Println("deferred statements execute in reverse (LIFO) order.") + defer fmt.Println("\nThis line is being printed first because") + // Defer is commonly used to close a file, so the function closing the + // file stays close to the function opening the file. + return true } // Define Stringer as an interface type with one method, String. type Stringer interface { - String() string + String() string } // Define pair as a struct with two fields, ints named x and y. type pair struct { - x, y int + x, y int } // Define a method on type pair. Pair now implements Stringer. func (p pair) String() string { // p is called the "receiver" - // Sprintf is another public function in package fmt. - // Dot syntax references fields of p. - return fmt.Sprintf("(%d, %d)", p.x, p.y) + // Sprintf is another public function in package fmt. + // Dot syntax references fields of p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { - // Brace syntax is a "struct literal." It evaluates to an initialized - // struct. The := syntax declares and initializes p to this struct. - p := pair{3, 4} - fmt.Println(p.String()) // Call String method of p, of type pair. - var i Stringer // Declare i of interface type Stringer. - i = p // Valid because pair implements Stringer - // Call String method of i, of type Stringer. Output same as above. - fmt.Println(i.String()) - - // Functions in the fmt package call the String method to ask an object - // for a printable representation of itself. - fmt.Println(p) // Output same as above. Println calls String method. - fmt.Println(i) // Output same as above. - - learnVariadicParams("great", "learning", "here!") + // Brace syntax is a "struct literal." It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. + p := pair{3, 4} + fmt.Println(p.String()) // Call String method of p, of type pair. + var i Stringer // Declare i of interface type Stringer. + i = p // Valid because pair implements Stringer + // Call String method of i, of type Stringer. Output same as above. + fmt.Println(i.String()) + + // Functions in the fmt package call the String method to ask an object + // for a printable representation of itself. + fmt.Println(p) // Output same as above. Println calls String method. + fmt.Println(i) // Output same as above. + + learnVariadicParams("great", "learning", "here!") } // Functions can have variadic parameters. func learnVariadicParams(myStrings ...interface{}) { - // Iterate each value of the variadic. - // The underbar here is ignoring the index argument of the array. - for _, param := range myStrings { - fmt.Println("param:", param) - } + // Iterate each value of the variadic. + // The underbar here is ignoring the index argument of the array. + for _, param := range myStrings { + fmt.Println("param:", param) + } - // Pass variadic value as a variadic parameter. - fmt.Println("params:", fmt.Sprintln(myStrings...)) + // Pass variadic value as a variadic parameter. + fmt.Println("params:", fmt.Sprintln(myStrings...)) - learnErrorHandling() + learnErrorHandling() } func learnErrorHandling() { - // ", ok" idiom used to tell if something worked or not. - m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. - fmt.Println("no one there") - } else { - fmt.Print(x) // x would be the value, if it were in the map. - } - // An error value communicates not just "ok" but more about the problem. - if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value - // prints 'strconv.ParseInt: parsing "non-int": invalid syntax' - fmt.Println(err) - } - // We'll revisit interfaces a little later. Meanwhile, - learnConcurrency() + // ", ok" idiom used to tell if something worked or not. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. + fmt.Println("no one there") + } else { + fmt.Print(x) // x would be the value, if it were in the map. + } + // An error value communicates not just "ok" but more about the problem. + if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value + // prints 'strconv.ParseInt: parsing "non-int": invalid syntax' + fmt.Println(err) + } + // We'll revisit interfaces a little later. Meanwhile, + learnConcurrency() } // c is a channel, a concurrency-safe communication object. func inc(i int, c chan int) { - c <- i + 1 // <- is the "send" operator when a channel appears on the left. + c <- i + 1 // <- is the "send" operator when a channel appears on the left. } // We'll use inc to increment some numbers concurrently. func learnConcurrency() { - // Same make function used earlier to make a slice. Make allocates and - // initializes slices, maps, and channels. - c := make(chan int) - // Start three concurrent goroutines. Numbers will be incremented - // concurrently, perhaps in parallel if the machine is capable and - // properly configured. All three send to the same channel. - go inc(0, c) // go is a statement that starts a new goroutine. - go inc(10, c) - go inc(-805, c) - // Read three results from the channel and print them out. - // There is no telling in what order the results will arrive! - fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. - - cs := make(chan string) // Another channel, this one handles strings. - ccs := make(chan chan string) // A channel of string channels. - go func() { c <- 84 }() // Start a new goroutine just to send a value. - go func() { cs <- "wordy" }() // Again, for cs this time. - // Select has syntax like a switch statement but each case involves - // a channel operation. It selects a case at random out of the cases - // that are ready to communicate. - select { - case i := <-c: // The value received can be assigned to a variable, - fmt.Printf("it's a %T", i) - case <-cs: // or the value received can be discarded. - fmt.Println("it's a string") - case <-ccs: // Empty channel, not ready for communication. - fmt.Println("didn't happen.") - } - // At this point a value was taken from either c or cs. One of the two - // goroutines started above has completed, the other will remain blocked. - - learnWebProgramming() // Go does it. You want to do it too. + // Same make function used earlier to make a slice. Make allocates and + // initializes slices, maps, and channels. + c := make(chan int) + // Start three concurrent goroutines. Numbers will be incremented + // concurrently, perhaps in parallel if the machine is capable and + // properly configured. All three send to the same channel. + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) + // Read three results from the channel and print them out. + // There is no telling in what order the results will arrive! + fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. + + cs := make(chan string) // Another channel, this one handles strings. + ccs := make(chan chan string) // A channel of string channels. + go func() { c <- 84 }() // Start a new goroutine just to send a value. + go func() { cs <- "wordy" }() // Again, for cs this time. + // Select has syntax like a switch statement but each case involves + // a channel operation. It selects a case at random out of the cases + // that are ready to communicate. + select { + case i := <-c: // The value received can be assigned to a variable, + fmt.Printf("it's a %T", i) + case <-cs: // or the value received can be discarded. + fmt.Println("it's a string") + case <-ccs: // Empty channel, not ready for communication. + fmt.Println("didn't happen.") + } + // At this point a value was taken from either c or cs. One of the two + // goroutines started above has completed, the other will remain blocked. + + learnWebProgramming() // Go does it. You want to do it too. } // A single function from package http starts a web server. func learnWebProgramming() { - // First parameter of ListenAndServe is TCP address to listen to. - // Second parameter is an interface, specifically http.Handler. - go func() { - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // don't ignore errors - }() + // First parameter of ListenAndServe is TCP address to listen to. + // Second parameter is an interface, specifically http.Handler. + go func() { + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // don't ignore errors + }() - requestServer(); + requestServer() } - // Make pair an http.Handler by implementing its only method, ServeHTTP. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Serve data with a method of http.ResponseWriter. - w.Write([]byte("You learned Go in Y minutes!")) + // Serve data with a method of http.ResponseWriter. + w.Write([]byte("You learned Go in 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("\nWebserver said: `%s`", string(body)) + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nWebserver said: `%s`", string(body)) } ``` -- cgit v1.2.3 From 164cf1ce78bcd96fda2a02addc0217ecdf033b5d Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 16 Jul 2014 10:25:03 +0930 Subject: Mention that Python 2.5-style string formatting still works in 3 --- python3.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index 43d62e77..bc0c05bd 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -98,6 +98,10 @@ not False # => True # 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 -- cgit v1.2.3 From 772370c5184822e61fa81da878d3853bb06a33a6 Mon Sep 17 00:00:00 2001 From: Akira Hirose Date: Wed, 16 Jul 2014 14:51:56 +0900 Subject: Japanese version. Just on a middle of way. --- ja-jp/r-jp.html.markdown | 782 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 782 insertions(+) create mode 100644 ja-jp/r-jp.html.markdown diff --git a/ja-jp/r-jp.html.markdown b/ja-jp/r-jp.html.markdown new file mode 100644 index 00000000..26d8403f --- /dev/null +++ b/ja-jp/r-jp.html.markdown @@ -0,0 +1,782 @@ +--- +language: R +contributors: + - ["e99n09", "http://github.com/e99n09"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] +translators: + - ["akirahirose", "https://www.facebook.com/akira.hirose"] +filename: learnr-jp.r +lang: ja-jp +--- + + +R は統計計算用の言語です。 +データの取得やクリーニング、統計処理やグラフ作成をするために使える、たくさんのライブラリがあります。また、LaTeX文書からRコマンドを呼び出すこともできます。 + + +```python +# コメント行は、#で開始します + + +# コメントを複数の行に分けたい場合は、 +# このように、コメント行を複数連続させるとできます + + +# WindowsやMacでは、 COMMAND-ENTERで1行のコマンド実行ができます + + + + + + +############################################################################# +# プログラミングがわからなくとも使えるコマンド類 +############################################################################# + + +# この節では、プログラミングがわからなくとも使える便利なRコマンドを紹介します +# 全てを理解できなくとも、まずはやってみましょう! + + +data() # 既にロードされているデータを閲覧します +data(rivers) # "北米にある大きな川の長さ"データを取得します +ls() # "rivers" がワークスペースに表示されました +head(rivers) # データの先頭部分です +# 735 320 325 392 524 450 + + +length(rivers) # 何本の川がデータにある? +# 141 +summary(rivers) # 統計的に要約するとどうなる? +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 + + +# 茎葉図(ヒストグラムに似た図)を描く +stem(rivers) + + +# The decimal point is 2 digit(s) to the right of the | +# +# 0 | 4 +# 2 | 011223334555566667778888899900001111223333344455555666688888999 +# 4 | 111222333445566779001233344567 +# 6 | 000112233578012234468 +# 8 | 045790018 +# 10 | 04507 +# 12 | 1471 +# 14 | 56 +# 16 | 7 +# 18 | 9 +# 20 | +# 22 | 25 +# 24 | 3 +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | +# 36 | 1 + + +stem(log(rivers)) # このデータは、正規分布でも対数正規分布でもないので注意! +# 特に正規分布原理主義のみなさん + + +# The decimal point is 1 digit(s) to the left of the | +# +# 48 | 1 +# 50 | +# 52 | 15578 +# 54 | 44571222466689 +# 56 | 023334677000124455789 +# 58 | 00122366666999933445777 +# 60 | 122445567800133459 +# 62 | 112666799035 +# 64 | 00011334581257889 +# 66 | 003683579 +# 68 | 0019156 +# 70 | 079357 +# 72 | 89 +# 74 | 84 +# 76 | 56 +# 78 | 4 +# 80 | +# 82 | 2 + + +# ヒストグラム作成 +hist(rivers, col="#333333", border="white", breaks=25) # これらのパラメータをつかいます +hist(log(rivers), col="#333333", border="white", breaks=25) # いろいろな使い方ができます + + +# 別のロード済データでやってみましょう。Rには、いろいろなデータがロードされています。 +data(discoveries) +plot(discoveries, col="#333333", lwd=3, xlab="Year", + main="Number of important discoveries per year") +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", + main="Number of important discoveries per year") + + +# 年次のソートだけではなく、 +# 標準的な並べ替えもできます +sort(discoveries) +# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 +# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 +# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 +# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 + + +stem(discoveries, scale=2) +# +# The decimal point is at the | +# +# 0 | 000000000 +# 1 | 000000000000 +# 2 | 00000000000000000000000000 +# 3 | 00000000000000000000 +# 4 | 000000000000 +# 5 | 0000000 +# 6 | 000000 +# 7 | 0000 +# 8 | 0 +# 9 | 0 +# 10 | 0 +# 11 | +# 12 | 0 + + +max(discoveries) +# 12 +summary(discoveries) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 + + +# サイコロを振ります +round(runif(7, min=.5, max=6.5)) +# 1 4 6 1 4 6 4 +# 私と同じrandom.seed(31337)を使わない限りは、別の値になります + + +# ガウス分布を9回生成します +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + + + + +################################################## +# データ型と基本計算 +################################################## + + +# ここからは、プログラミングをつかうチュートリアルです +# この節ではRで重要なデータ型の、整数型、数字型、文字型、論理型と因子型をつかいます +# 他にもいろいろありますが、まずは最小限必要な、これらから始めましょう + + +# 整数型 +# 整数型の長さは、Lで指定します +5L # 5 +class(5L) # "integer" +# (?class を実行すると、class()関数についてさらなる情報が得られます) +# Rでは、この5Lのような単一の値は、長さ1のベクトルとして扱われます +length(5L) # 1 +# 整数型のベクトルはこのようにつくります +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" + + +# 数字型 +# 倍精度浮動小数点数です +5 # 5 +class(5) # "numeric" +# くどいですが、すべてはベクトルです +# 1つ以上の要素がある数字のベクトルも、作ることができます +c(3,3,3,2,2,1) # 3 3 3 2 2 1 +# 指数表記もできます +5e4 # 50000 +6.02e23 # アボガドロ数 +1.6e-35 # プランク長 +# 無限大、無限小もつかえます +class(Inf) # "numeric" +class(-Inf) # "numeric" +# 例のように、"Inf"を使ってください。integrate( dnorm(x), 3, Inf); +# Z-スコア表が必要なくなります + + +# 基本的な計算 +# 数を計算できます +# 整数と整数以外の数字を両方使った計算をすると、結果は整数以外の数字になります +10L + 66L # 76 # 整数足す整数は整数 +53.2 - 4 # 49.2 # 整数引く数字は数字 +2.0 * 2L # 4 # 数字かける整数は数字 +3L / 4 # 0.75 # 整数割る数字は数字 +3 %% 2 # 1 # 二つの数字を割った余りは数字 +# 不正な計算は "not-a-number"になる +0 / 0 # NaN +class(NaN) # "numeric" +# You can do arithmetic on two vectors with length greater than 1, +# so long as the larger vector's length is an integer multiple of the smaller +c(1,2,3) + c(1,2,3) # 2 4 6 + + +# CHARACTERS +# There's no difference between strings and characters in R +"Horatio" # "Horatio" +class("Horatio") # "character" +class('H') # "character" +# Those were both character vectors of length 1 +# Here is a longer one: +c('alef', 'bet', 'gimmel', 'dalet', 'he') +# => +# "alef" "bet" "gimmel" "dalet" "he" +length(c("Call","me","Ishmael")) # 3 +# You can do regex operations on character vectors: +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." +# R has several built-in character vectors: +letters +# => +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" + + +# LOGICALS +# In R, a "logical" is a boolean +class(TRUE) # "logical" +class(FALSE) # "logical" +# Their behavior is normal +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE +# Missing data (NA) is logical, too +class(NA) # "logical" +# Here we get a logical vector with many elements: +c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE + + +# FACTORS +# The factor class is for categorical data +# Factors can be ordered (like childrens' grade levels) or unordered (like gender) +factor(c("female", "female", "male", "NA", "female")) +# female female male NA female +# Levels: female male NA +# The "levels" are the values the categorical data can take +levels(factor(c("male", "male", "female", "NA", "female"))) # "female" "male" "NA" +# If a factor vector has length 1, its levels will have length 1, too +length(factor("male")) # 1 +length(levels(factor("male"))) # 1 +# Factors are commonly seen in data frames, a data structure we will cover later +data(infert) # "Infertility after Spontaneous and Induced Abortion" +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + + +# NULL +# "NULL" is a weird one; use it to "blank out" a vector +class(NULL) # NULL +parakeet +# => +# [1] "beak" "feathers" "wings" "eyes" +parakeet <- NULL +parakeet +# => +# NULL + + +# TYPE COERCION +# Type-coercion is when you force a value to take on a different type +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +# If you put elements of different types into a vector, weird coercions happen: +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" +as.numeric("Bilbo") +# => +# [1] NA +# Warning message: +# NAs introduced by coercion + + +# Also note: those were just the basic data types +# There are many more data types, such as for dates, time series, etc. + + + + + + +################################################## +# Variables, loops, if/else +################################################## + + +# A variable is like a box you store a value in for later use. +# We call this "assigning" the value to the variable. +# Having variables lets us write loops, functions, and if/else statements + + +# VARIABLES +# Lots of way to assign stuff: +x = 5 # this is possible +y <- "1" # this is preferred +TRUE -> z # this works but is weird + + +# LOOPS +# We've got for loops +for (i in 1:4) { + print(i) +} +# We've got while loops +a <- 10 +while (a > 4) { + cat(a, "...", sep = "") + a <- a - 1 +} +# Keep in mind that for and while loops run slowly in R +# Operations on entire vectors (i.e. a whole row, a whole column) +# or apply()-type functions (we'll discuss later) are preferred + + +# IF/ELSE +# Again, pretty standard +if (4 > 3) { + print("4 is greater than 3") +} else { + print("4 is not greater than 3") +} +# => +# [1] "4 is greater than 3" + + +# FUNCTIONS +# Defined like so: +jiggle <- function(x) { + x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise + return(x) +} +# Called like any other R function: +jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 + + + + + + +########################################################################### +# Data structures: Vectors, matrices, data frames, and arrays +########################################################################### + + +# ONE-DIMENSIONAL + + +# Let's start from the very beginning, and with something you already know: vectors. +vec <- c(8, 9, 10, 11) +vec # 8 9 10 11 +# We ask for specific elements by subsetting with square brackets +# (Note that R starts counting from 1) +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +# We can also search for the indices of specific components, +which(vec %% 2 == 0) # 1 3 +# grab just the first or last few entries in the vector, +head(vec, 1) # 8 +tail(vec, 2) # 10 11 +# or figure out if a certain value is in the vector +any(vec == 10) # TRUE +# If an index "goes over" you'll get NA: +vec[6] # NA +# You can find the length of your vector with length() +length(vec) # 4 +# You can perform operations on entire vectors or subsets of vectors +vec * 4 # 16 20 24 28 +vec[2:3] * 5 # 25 30 +any(vec[2:3] == 8) # FALSE +# and R has many built-in functions to summarize vectors +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 +# Some more nice built-ins: +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +seq(from=0, to=31337, by=1337) +# => +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 + + +# TWO-DIMENSIONAL (ALL ONE CLASS) + + +# You can make a matrix out of entries all of the same type like so: +mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Unlike a vector, the class of a matrix is "matrix", no matter what's in it +class(mat) # => "matrix" +# Ask for the first row +mat[1,] # 1 4 +# Perform operation on the first column +3 * mat[,1] # 3 6 9 +# Ask for a specific cell +mat[3,2] # 6 + + +# Transpose the whole matrix +t(mat) +# => +# [,1] [,2] [,3] +# [1,] 1 2 3 +# [2,] 4 5 6 + + +# Matrix multiplication +mat %*% t(mat) +# => +# [,1] [,2] [,3] +# [1,] 17 22 27 +# [2,] 22 29 36 +# [3,] 27 36 45 + + +# cbind() sticks vectors together column-wise to make a matrix +mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) +mat2 +# => +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" +# [4,] "4" "dog" +class(mat2) # matrix +# Again, note what happened! +# Because matrices must contain entries all of the same class, +# everything got converted to the character class +c(class(mat2[,1]), class(mat2[,2])) + + +# rbind() sticks vectors together row-wise to make a matrix +mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 2 4 5 +# [2,] 6 7 0 4 +# Ah, everything of the same class. No coercions. Much better. + + +# TWO-DIMENSIONAL (DIFFERENT CLASSES) + + +# For columns of different types, use a data frame +# This data structure is so useful for statistical programming, +# a version of it was added to Python in the package "pandas". + + +students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), + c(3,2,2,1,0,-1), + c("H", "G", "G", "R", "S", "G")) +names(students) <- c("name", "year", "house") # name the columns +class(students) # "data.frame" +students +# => +# name year house +# 1 Cedric 3 H +# 2 Fred 2 G +# 3 George 2 G +# 4 Cho 1 R +# 5 Draco 0 S +# 6 Ginny -1 G +class(students$year) # "numeric" +class(students[,3]) # "factor" +# find the dimensions +nrow(students) # 6 +ncol(students) # 3 +dim(students) # 6 3 +# The data.frame() function converts character vectors to factor vectors +# by default; turn this off by setting stringsAsFactors = FALSE when +# you create the data.frame +?data.frame + + +# There are many twisty ways to subset data frames, all subtly unalike +students$year # 3 2 2 1 0 -1 +students[,2] # 3 2 2 1 0 -1 +students[,"year"] # 3 2 2 1 0 -1 + + +# An augmented version of the data.frame structure is the data.table +# If you're working with huge or panel data, or need to merge a few data +# sets, data.table can be a good choice. Here's a whirlwind tour: +install.packages("data.table") # download the package from CRAN +require(data.table) # load it +students <- as.data.table(students) +students # note the slightly different print-out +# => +# name year house +# 1: Cedric 3 H +# 2: Fred 2 G +# 3: George 2 G +# 4: Cho 1 R +# 5: Draco 0 S +# 6: Ginny -1 G +students[name=="Ginny"] # get rows with name == "Ginny" +# => +# name year house +# 1: Ginny -1 G +students[year==2] # get rows with year == 2 +# => +# name year house +# 1: Fred 2 G +# 2: George 2 G +# data.table makes merging two data sets easy +# let's make another data.table to merge with students +founders <- data.table(house=c("G","H","R","S"), + founder=c("Godric","Helga","Rowena","Salazar")) +founders +# => +# house founder +# 1: G Godric +# 2: H Helga +# 3: R Rowena +# 4: S Salazar +setkey(students, house) +setkey(founders, house) +students <- founders[students] # merge the two data sets by matching "house" +setnames(students, c("house","houseFounderName","studentName","year")) +students[,order(c("name","year","house","houseFounderName")), with=F] +# => +# studentName year house houseFounderName +# 1: Fred 2 G Godric +# 2: George 2 G Godric +# 3: Ginny -1 G Godric +# 4: Cedric 3 H Helga +# 5: Cho 1 R Rowena +# 6: Draco 0 S Salazar + + +# data.table makes summary tables easy +students[,sum(year),by=house] +# => +# house V1 +# 1: G 3 +# 2: H 3 +# 3: R 1 +# 4: S 0 + + +# To drop a column from a data.frame or data.table, +# assign it the NULL value +students$houseFounderName <- NULL +students +# => +# studentName year house +# 1: Fred 2 G +# 2: George 2 G +# 3: Ginny -1 G +# 4: Cedric 3 H +# 5: Cho 1 R +# 6: Draco 0 S + + +# Drop a row by subsetting +# Using data.table: +students[studentName != "Draco"] +# => +# house studentName year +# 1: G Fred 2 +# 2: G George 2 +# 3: G Ginny -1 +# 4: H Cedric 3 +# 5: R Cho 1 +# Using data.frame: +students <- as.data.frame(students) +students[students$house != "G",] +# => +# house houseFounderName studentName year +# 4 H Helga Cedric 3 +# 5 R Rowena Cho 1 +# 6 S Salazar Draco 0 + + +# MULTI-DIMENSIONAL (ALL ELEMENTS OF ONE TYPE) + + +# Arrays creates n-dimensional tables +# All elements must be of the same type +# You can make a two-dimensional table (sort of like a matrix) +array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 4 8 3 +# [2,] 2 5 9 6 +# You can use array to make three-dimensional matrices too +array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +# => +# , , 1 +# +# [,1] [,2] +# [1,] 2 8 +# [2,] 300 9 +# [3,] 4 0 +# +# , , 2 +# +# [,1] [,2] +# [1,] 5 66 +# [2,] 60 7 +# [3,] 0 847 + + +# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES) + + +# Finally, R has lists (of vectors) +list1 <- list(time = 1:40) +list1$price = c(rnorm(40,.5*list1$time,4)) # random +list1 +# You can get items in the list like so +list1$time # one way +list1[["time"]] # another way +list1[[1]] # yet another way +# => +# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 +# [34] 34 35 36 37 38 39 40 +# You can subset list items like any other vector +list1$price[4] + + +# Lists are not the most efficient data structure to work with in R; +# unless you have a very good reason, you should stick to data.frames +# Lists are often returned by functions that perform linear regressions + + +################################################## +# The apply() family of functions +################################################## + + +# Remember mat? +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X +# over rows (MAR = 1) or columns (MAR = 2) +# That is, R does FUN to each row (or column) of X, much faster than a +# for or while loop would do +apply(mat, MAR = 2, jiggle) +# => +# [,1] [,2] +# [1,] 3 15 +# [2,] 7 19 +# [3,] 11 23 +# Other functions: ?lapply, ?sapply + + +# Don't feel too intimidated; everyone agrees they are rather confusing + + +# The plyr package aims to replace (and improve upon!) the *apply() family. +install.packages("plyr") +require(plyr) +?plyr + + + + + + +######################### +# Loading data +######################### + + +# "pets.csv" is a file on the internet +# (but it could just as easily be be a file on your own computer) +pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") +pets +head(pets, 2) # first two rows +tail(pets, 1) # last row + + +# To save a data frame or matrix as a .csv file +write.csv(pets, "pets2.csv") # to make a new .csv file +# set working directory with setwd(), look it up with getwd() + + +# Try ?read.csv and ?write.csv for more information + + + + + + +######################### +# Plots +######################### + + +# BUILT-IN PLOTTING FUNCTIONS +# Scatterplots! +plot(list1$time, list1$price, main = "fake data") +# Regressions! +linearModel <- lm(price ~ time, data = list1) +linearModel # outputs result of regression +# Plot regression line on existing plot +abline(linearModel, col = "red") +# Get a variety of nice diagnostics +plot(linearModel) +# Histograms! +hist(rpois(n = 10000, lambda = 5), col = "thistle") +# Barplots! +barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) + + +# GGPLOT2 +# But these are not even the prettiest of R's plots +# Try the ggplot2 package for more and better graphics +install.packages("ggplot2") +require(ggplot2) +?ggplot2 +pp <- ggplot(students, aes(x=house)) +pp + geom_histogram() +ll <- as.data.table(list1) +pp <- ggplot(ll, aes(x=time,price)) +pp + geom_point() +# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/) + + + + + + +``` + + +## How do I get R? + + +* Get R and the R GUI from [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) is another GUI \ No newline at end of file -- cgit v1.2.3 From bb1dc2de97660e3ec83e5a243f8374c33b704660 Mon Sep 17 00:00:00 2001 From: Akira Hirose Date: Wed, 16 Jul 2014 18:53:32 +0900 Subject: still on a middle way --- ja-jp/r-jp.html.markdown | 107 +++++++++++++++++++++++------------------------ 1 file changed, 53 insertions(+), 54 deletions(-) diff --git a/ja-jp/r-jp.html.markdown b/ja-jp/r-jp.html.markdown index 26d8403f..66c451dd 100644 --- a/ja-jp/r-jp.html.markdown +++ b/ja-jp/r-jp.html.markdown @@ -221,26 +221,25 @@ class(-Inf) # "numeric" # 不正な計算は "not-a-number"になる 0 / 0 # NaN class(NaN) # "numeric" -# You can do arithmetic on two vectors with length greater than 1, -# so long as the larger vector's length is an integer multiple of the smaller +# 長さが1より大きなベクター同士で計算ができます +# どちらかが長い場合、短い方は何度も繰り返して使われます c(1,2,3) + c(1,2,3) # 2 4 6 - -# CHARACTERS -# There's no difference between strings and characters in R +# 文字 +# Rでは、文字列と文字に区別がありません "Horatio" # "Horatio" class("Horatio") # "character" class('H') # "character" -# Those were both character vectors of length 1 -# Here is a longer one: +# 上記は両方とも、長さ1のベクターです +# 以下は、より長いものです c('alef', 'bet', 'gimmel', 'dalet', 'he') # => # "alef" "bet" "gimmel" "dalet" "he" length(c("Call","me","Ishmael")) # 3 -# You can do regex operations on character vectors: +# 正規表現処理を文字ベクターに使えます substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." -# R has several built-in character vectors: +# Rはいくつかの文字ベクターを組み込みで持っています letters # => # [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" @@ -248,40 +247,40 @@ letters month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" -# LOGICALS -# In R, a "logical" is a boolean +# 論理 +# Rでは、Booleanは論理(logical)型です class(TRUE) # "logical" class(FALSE) # "logical" -# Their behavior is normal +# 以下は正しい動きです TRUE == TRUE # TRUE TRUE == FALSE # FALSE FALSE != FALSE # FALSE FALSE != TRUE # TRUE -# Missing data (NA) is logical, too +# 無いデータ (NA) も論理型です class(NA) # "logical" -# Here we get a logical vector with many elements: +# 以下のようにすると、複数の要素を持つ、論理型ベクターが返ります c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE -# FACTORS -# The factor class is for categorical data -# Factors can be ordered (like childrens' grade levels) or unordered (like gender) +# ファクター +# ファクタークラスは、カテゴリカルデータようのクラスです +# ファクターは、子供の学年のように順序がつけられるものか、性別のように順序がないものがあります factor(c("female", "female", "male", "NA", "female")) # female female male NA female # Levels: female male NA -# The "levels" are the values the categorical data can take +# "levels" は、カテゴリカルデータがとりうる値を返します levels(factor(c("male", "male", "female", "NA", "female"))) # "female" "male" "NA" -# If a factor vector has length 1, its levels will have length 1, too +# ファクターベクターの長さが1ならば、そのlevelも1です length(factor("male")) # 1 length(levels(factor("male"))) # 1 -# Factors are commonly seen in data frames, a data structure we will cover later +# ファクターは、この後で紹介するデータフレーム(というデータ型)内で、よくみられます data(infert) # "Infertility after Spontaneous and Induced Abortion" levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" # NULL -# "NULL" is a weird one; use it to "blank out" a vector +# "NULL" は変わった型です。ベクターを空にするときに使います class(NULL) # NULL parakeet # => @@ -292,11 +291,11 @@ parakeet # NULL -# TYPE COERCION -# Type-coercion is when you force a value to take on a different type +# 型の強制 +# 型の強制は、ある値を、強制的にある型として利用する事です as.character(c(6, 8)) # "6" "8" as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE -# If you put elements of different types into a vector, weird coercions happen: +# さまざまな要素が入っているベクターに対して型の強制を行うと、おかしなことになります c(TRUE, 4) # 1 4 c("dog", TRUE, 4) # "dog" "TRUE" "4" as.numeric("Bilbo") @@ -306,8 +305,8 @@ as.numeric("Bilbo") # NAs introduced by coercion -# Also note: those were just the basic data types -# There are many more data types, such as for dates, time series, etc. +# 追記: ここで紹介したのは、基本的な型だけです +# 実際には、日付(dates)や時系列(time series)など、いろいろな型があります @@ -315,40 +314,40 @@ as.numeric("Bilbo") ################################################## -# Variables, loops, if/else +# 変数、ループ、もし/ほかに(if/else) ################################################## -# A variable is like a box you store a value in for later use. -# We call this "assigning" the value to the variable. -# Having variables lets us write loops, functions, and if/else statements +# 変数は、ある値を後で使うために入れておく、箱のようなものです +# 箱に入れることを、変数に値を代入する、といいます +# 変数を使うと、ループや関数、if/else 分岐を利用できます -# VARIABLES -# Lots of way to assign stuff: -x = 5 # this is possible -y <- "1" # this is preferred -TRUE -> z # this works but is weird +# 変数 +# 代入する方法はいろいろあります +x = 5 # これはできます +y <- "1" # これがおすすめです +TRUE -> z # これも使えますが、変です -# LOOPS -# We've got for loops +# ループ +# forでループできます for (i in 1:4) { print(i) } -# We've got while loops +# whileでループできます a <- 10 while (a > 4) { cat(a, "...", sep = "") a <- a - 1 } -# Keep in mind that for and while loops run slowly in R -# Operations on entire vectors (i.e. a whole row, a whole column) -# or apply()-type functions (we'll discuss later) are preferred +# Rでは、forやwhileは遅いことを覚えておいてください +# 処理を行う場合は、ベクター丸ごと処理する(つまり、行全体や、列全体)を指定して行うか、 +# 後述する、apply()系の関数を使うのがお勧めです # IF/ELSE -# Again, pretty standard +# ごく普通のif文です if (4 > 3) { print("4 is greater than 3") } else { @@ -358,14 +357,14 @@ if (4 > 3) { # [1] "4 is greater than 3" -# FUNCTIONS -# Defined like so: +# 関数 +# 以下のように定義します jiggle <- function(x) { - x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise + x = x + rnorm(1, sd=.1) #すこしだけ(制御された)ノイズを入れます return(x) } -# Called like any other R function: -jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 +# 他のR関数と同じように呼びます +jiggle(5) # 5±ε. set.seed(2716057)をすると、jiggle(5)==5.005043 @@ -373,26 +372,26 @@ jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 ########################################################################### -# Data structures: Vectors, matrices, data frames, and arrays +# データ構造: ベクター、行列、データフレーム、配列 ########################################################################### -# ONE-DIMENSIONAL +# 1次元 -# Let's start from the very beginning, and with something you already know: vectors. +# まずは基本からです。すでにご存じのベクターからです vec <- c(8, 9, 10, 11) vec # 8 9 10 11 -# We ask for specific elements by subsetting with square brackets -# (Note that R starts counting from 1) +# 特定の要素を、[角括弧]による指定で取り出せます +# (Rでは、最初の要素は1番目と数えます) vec[1] # 8 letters[18] # "r" LETTERS[13] # "M" month.name[9] # "September" c(6, 8, 7, 5, 3, 0, 9)[3] # 7 -# We can also search for the indices of specific components, +# 特定のルールに当てはまる要素を見つけることもできます which(vec %% 2 == 0) # 1 3 -# grab just the first or last few entries in the vector, +# 最初か最後の数個を取り出すこともできます head(vec, 1) # 8 tail(vec, 2) # 10 11 # or figure out if a certain value is in the vector -- cgit v1.2.3 From ba855b16643661fef54842c5eb2d7ec93e29c4f9 Mon Sep 17 00:00:00 2001 From: Umberto Raimondi Date: Wed, 16 Jul 2014 12:20:57 +0200 Subject: Update swift to beta3 Updated to beta3, new array declaration style,".." and a few other modifications. --- swift.html.markdown | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index f24b1592..a47b085a 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -31,7 +31,7 @@ optionalString = nil // Array var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" -let emptyArray = String[]() +let emptyArray = [String]() // Dictionary var occupations = [ @@ -65,7 +65,7 @@ for (key, value) in dict { for i in -1...1 { // [-1, 0, 1] println(i) } -// use .. to exclude the last number +// use ..< to exclude the last number // while loop var i = 1 @@ -127,6 +127,7 @@ increment(7) // // Closures // +var numbers = [1, 2, 6] // Functions are special case closures ({}) @@ -140,8 +141,10 @@ numbers.map({ }) // When the type is known, like above, we can do this -var numbers = [1, 2, 6] numbers = numbers.map({ number in 3 * number }) +//Or even this +//numbers = numbers.map({ $0 * 3 }) + print(numbers) // [3, 6, 18] @@ -221,4 +224,4 @@ enum Suit { // Generics: Similar to Java. Use the `where` keyword to specify the // requirements of the generics. -``` \ No newline at end of file +``` -- cgit v1.2.3 From 6a33cbd3aee825f4cc16c82c15963c66486d1834 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Wed, 16 Jul 2014 20:07:35 +0200 Subject: Try to fix HL --- perl6.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 057c74f8..7029de27 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -14,10 +14,6 @@ Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM and [the MoarVM](htt ```perl6 # Single line comment start with a pound -#`( - Multiline comments use #` and a quoting construct. (), [], {}, 「」, etc, will work. -) - ### Variables # In Perl 6, you declare a lexical variable using `my` @@ -88,9 +84,11 @@ sub truthy-array(@array) { # `-> {}` and `{}` are pretty much the same thing, except taht the former can take arguments, # and that the latter can be mistaken as a hash by the compiler -# You can also use the "whatever star" to create an anonymous function : +# You can also use the "whatever star" to create an anonymous function +# (it'll stop at the furthest operator in the current expression) map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` -map(*+*+3, @array); # also works. Same as `-> $a, $b -> { $a + $b + 3 }` +map(*+*+3, @array); # also works. Same as `-> $a, $b { $a + $b + 3 }` +say ((*+3)/5)(5); # immediatly execute the function Whatever created -- works even in parens ! # but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`), # you can also use the implicit argument syntax, `$^` : @@ -116,6 +114,9 @@ sayit(True); # fails at *compile time* with "calling 'sayit' will never work wit multi is-big(Int $n where * > 10) { True } multi is-big(Int $) { False } +# you can also name these checks, by creating "subsets" : +subset Even of Int where * %% 2; + ### Containers # In Perl 6, values are actually stored in "containers". # the assignment operator asks the container on the left to store the value on its right @@ -195,7 +196,6 @@ if long-computation() -> $result { } - ### Operators ## Since Perl languages are very much operator-based languages -- cgit v1.2.3 From 3d81df43b15debcf3643a1977a83c5051b25803b Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Wed, 16 Jul 2014 20:08:01 +0200 Subject: Switch to perl to see if it fixes comments ... --- perl6.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 7029de27..830b8182 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -11,9 +11,13 @@ Perl 6 is a highly capable, feature-rich programming language made for the upcom Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM and [the MoarVM](http://moarvm.com). -```perl6 +```perl # Single line comment start with a pound +#`( + Multiline comments use #` and a quoting construct. (), [], {}, 「」, etc, will work. +) + ### Variables # In Perl 6, you declare a lexical variable using `my` -- cgit v1.2.3 From 78e3a442e927f858d1a83fdc005b94ffca3ee659 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Wed, 16 Jul 2014 20:08:48 +0200 Subject: Sigh. --- perl6.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 830b8182..30468c56 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -29,9 +29,8 @@ Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM and [the MoarVM](htt my $str = 'String'; my $str2 = "String"; # double quotes allow for interpolation -# variable names can contain but not end with simple quotes and dashes, and can contain (and end with) underscores - -my $weird'variable-name_ = 5; +# variable names can contain but not end with simple quotes and dashes, and can contain (and end with) underscores : +# my $weird'variable-name_ = 5; # works ! ## - Arrays. They represent multiple values. They start with `@` -- cgit v1.2.3 From 22ad9896836e7fc74d50c55533b13fda9ca54a32 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Wed, 16 Jul 2014 23:12:20 +0200 Subject: Move stuff around Probably for the worst ... --- perl6.html.markdown | 156 +++++++++++++++++++++++++++++++++------------------- 1 file changed, 99 insertions(+), 57 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 30468c56..d9dce641 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -37,9 +37,9 @@ my $str2 = "String"; # double quotes allow for interpolation my @array = 1, 2, 3; my @array = 'a', 'b', 'c'; # equivalent to : -my @array = ; # array of string, delimited by space. similar to perl5's qw, or Ruby's %w +my @array = ; # array of words, delimited by space. similar to perl5's qw, or Ruby's %w -say @array[2]; # Arrays are 0-indexed +say @array[2]; # Array indices start at 0 -- This is the third element ## - Hashes @@ -68,57 +68,8 @@ my &other-s = sub { say "anonymous function !" } # `->`, lambda with arguments, and string interpolation my &lambda = -> $argument { "The argument passed to this lambda is $argument" } - -# add 3 to each value of an array using map : -map({ $_ + 3 }, @array); # $_ is the implicit argument (the same as for `given` and `for`) - -# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`) : -# a block doesn't have a function context (though it can have arguments), which means that if you -# return from it, you're going to return from the parent function, compare: -sub is-in(@array, $elem) { - map({ return True if $_ == $elem }, @array); # this will `return` out of `is-in` -} -sub truthy-array(@array) { - # this will produce an array of `True` and `False` : - # (you can also say `anon sub` for "anonymous subroutine") - map(sub { if $_ { return True } else { return False } }, @array); -} - -# `-> {}` and `{}` are pretty much the same thing, except taht the former can take arguments, -# and that the latter can be mistaken as a hash by the compiler - -# You can also use the "whatever star" to create an anonymous function -# (it'll stop at the furthest operator in the current expression) -map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` -map(*+*+3, @array); # also works. Same as `-> $a, $b { $a + $b + 3 }` -say ((*+3)/5)(5); # immediatly execute the function Whatever created -- works even in parens ! - -# but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`), -# you can also use the implicit argument syntax, `$^` : -map({ $^a + $^b + 3 }, @array); # same as the above - -# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $ b / $a }` - -## Multiple Dispatch -# Perl 6 can decide which variant of a `sub` to call based on the type of the arguments, -# or on arbitrary preconditions, using `where` : - -# with types -multi sub sayit(Int $n) { # note the `multi` keyword here - say "Number: $n"; -} -multi sayit(Str $s) } # the `sub` is implicit - say "String: $s"; -} -sayit("foo"); # prints "String: foo" -sayit(True); # fails at *compile time* with "calling 'sayit' will never work with arguments of types ..." - -# with arbitrary precondition : -multi is-big(Int $n where * > 10) { True } -multi is-big(Int $) { False } - -# you can also name these checks, by creating "subsets" : -subset Even of Int where * %% 2; +# We're going to see how powerful Perl 6 subs are just a little down below, after seeing the basics of operators +# and control flow structures ### Containers # In Perl 6, values are actually stored in "containers". @@ -154,7 +105,10 @@ unless False { say "It's not false !"; } -# if (true) say; # Won't work +# You can also use their postfix versions, with the keyword after: +say "Quite truthy" if True; + +# if (true) say; # This doesn't work ! # - Ternary conditional my $a = $condition ?? $value-if-true !! $value-if-false; # `??` and `!!` are like `?` and `:` in other languages' @@ -189,16 +143,15 @@ for @array -> $variable { } # default variable is $_ -for array { +for @array { say "I've got $_"; } -# Note - the "lambda" `->` syntax isn't reserved to for : +# Note - the "lambda" `->` syntax isn't reserved to `for` : if long-computation() -> $result { say "The result is $result"; } - ### Operators ## Since Perl languages are very much operator-based languages @@ -248,6 +201,17 @@ $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an ar 3 .. 7; # 3 to 7, both included # `^` on either side them exclusive on that side : 3 ^..^ 7; # 3 to 7, not included (basically `4 .. 6`) +# this also works as a shortcut for `0..^N` +^10; # 0..^10 + +# This also allows us to demonstrate that Perl 6 has lazy arrays : +my @array = 1..*; # 1 to Infinite ! +say @array[^10]; # you can pass arrays as subscripts and it'll return an array of results + # this will print "1 2 3 4 5 6 7 8 9 10" (and not run out of memory !) + +# Warning, though : if you try this example in the REPL and juste 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 ## * And, Or 3 && 4; # True. Calls `.Bool` on `3` @@ -257,6 +221,84 @@ $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an ar $a && $b && $c; # returns the first argument that evaluates to False, or the last argument $a || $b; +## Sequence operator +# !TODO! +1, 2, 3 ... 10; + +## More on Subs ! +# Perl 6 likes functions. So, in Perl 6, functions are very powerful: + +## Multiple Dispatch +# Perl 6 can decide which variant of a `sub` to call based on the type of the arguments, +# or on arbitrary preconditions, using `where` : + +# with types +multi sub sayit(Int $n) { # note the `multi` keyword here + say "Number: $n"; +} +multi sayit(Str $s) } # the `sub` is implicit + say "String: $s"; +} +sayit("foo"); # prints "String: foo" +sayit(True); # fails at *compile time* with "calling 'sayit' will never work with arguments of types ..." + +# with arbitrary precondition: +multi is-big(Int $n where * > 10) { True } +multi is-big(Int $) { False } + +# you can also name these checks, by creating "subsets": +subset Even of Int where * %% 2; + + +# The last expression of a sub is returned automatically (though you may use the `return` keyword, of course): +sub next-index($n) { + $n + 1; +} +my $new-n = next-index(3); # $new-n is now 4 +# This is true for everything, except for the looping constructs (due to performance reasons): +# there's no purpose in building a list if we're just going to discard all the results. +# If you still want to build one, you can use the `do` prefix: (or the `gather` prefix, which we'll see later) +sub list-of($n) { + do for ^$n { # note the use of the range-to prefix operator `^` (`0..^N`) + $_ # current loop iteration + } +} +my @list3 = list-of(3); #=> (0, 1, 2) + +# We can, for example, add 3 to each value of an array using map : +my @arrayplus3 = map({ $_ + 3 }, @array); # $_ is the implicit argument (the same as for `given` and `for`) + +# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`) : +# a block doesn't have a function context (though it can have arguments), which means that if you +# return from it, you're going to return from the parent function, compare: +sub is-in(@array, $elem) { + # this will `return` out of `is-in` sub + # once the condition evaluated to True, the loop won't be run anymore + map({ return True if $_ == $elem }, @array); +} +sub truthy-array(@array) { + # this will produce an array of `True` and `False` : + # (you can also say `anon sub` for "anonymous subroutine") + map(sub { if $_ { return True } else { return False } }, @array); # returns the correct value, even in a `if` +} + +# `-> {}` and `{}` are pretty much the same thing, except that the former can take arguments, +# and that the latter can be mistaken as a hash by the compiler + +# You can also use the "whatever star" to create an anonymous function +# (it'll stop at the furthest operator in the current expression) +my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` +my @arrayplus3 = map(*+*+3, @array); # also works. Same as `-> $a, $b { $a + $b + 3 }` +say ((*+3)/5)(5); # immediatly execute the function Whatever created -- works even in parens ! + +# but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`), +# you can also use the implicit argument syntax, `$^` : +map({ $^a + $^b + 3 }, @array); # same as the above + +# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $ b / $a }` + + + ### Object Model ## Perl 6 has a quite comprehensive object model -- cgit v1.2.3 From 15353d1938999fe419b4b46295dd4eec92191835 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Thu, 17 Jul 2014 10:46:24 +0200 Subject: Fix c tutorial Fixes #678 Still missing symbols, though --- c.html.markdown | 834 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 417 insertions(+), 417 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 22f251f2..bc9a959a 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -16,15 +16,15 @@ memory management and C will take you as far as you need to go. ```c // Single-line comments start with // - only available in C99 and later. -/* + /* Multi-line comments look like this. They work in C89 as well. -*/ + */ -// Constants: #define + // Constants: #define #define DAYS_IN_YEAR 365 -// Enumeration constants are also ways to declare constants. -enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; + // Enumeration constants are also ways to declare constants. + enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; // MON gets 2 automatically, TUE gets 3, etc. // Import headers with #include @@ -34,11 +34,11 @@ enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; // (File names between are headers from the C standard library.) // For your own headers, use double quotes instead of angle brackets: -#include "my_header.h" +//#include "my_header.h" // Declare function signatures in advance in a .h file, or at the top of // your .c file. -void function_1(char c); +void function_1(); int function_2(void); // Must declare a 'function prototype' before main() when functions occur after @@ -48,374 +48,373 @@ int add_two_ints(int x1, int x2); // function prototype // Your program's entry point is a function called // main with an integer return type. int main() { - // print output using printf, for "print formatted" - // %d is an integer, \n is a newline - printf("%d\n", 0); // => Prints 0 - // All statements must end with a semicolon - - /////////////////////////////////////// - // Types - /////////////////////////////////////// - - // ints are usually 4 bytes - int x_int = 0; - - // shorts are usually 2 bytes - short x_short = 0; - - // chars are guaranteed to be 1 byte - char x_char = 0; - char y_char = 'y'; // Char literals are quoted with '' - - // longs are often 4 to 8 bytes; long longs are guaranteed to be at least - // 64 bits - long x_long = 0; - long long x_long_long = 0; - - // floats are usually 32-bit floating point numbers - float x_float = 0.0; - - // doubles are usually 64-bit floating-point numbers - double x_double = 0.0; - - // Integral types may be unsigned. - unsigned short ux_short; - unsigned int ux_int; - unsigned long long ux_long_long; - - // chars inside single quotes are integers in machine's character set. - '0' // => 48 in the ASCII character set. - 'A' // => 65 in the ASCII character set. - - // sizeof(T) gives you the size of a variable with type T in bytes - // sizeof(obj) yields the size of the expression (variable, literal, etc.). - printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) - - - // If the argument of the `sizeof` operator is an expression, then its argument - // is not evaluated (except VLAs (see below)). - // The value it yields in this case is a compile-time constant. - int a = 1; - // size_t is an unsigned integer type of at least 2 bytes used to represent - // the size of an object. - size_t size = sizeof(a++); // a++ is not evaluated - printf("sizeof(a++) = %zu where a = %d\n", size, a); - // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) - - // Arrays must be initialized with a concrete size. - char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes - int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes - // (assuming 4-byte words) - - - // You can initialize an array to 0 thusly: - char my_array[20] = {0}; - - // Indexing an array is like other languages -- or, - // rather, other languages are like C - my_array[0]; // => 0 - - // Arrays are mutable; it's just memory! - my_array[1] = 2; - printf("%d\n", my_array[1]); // => 2 - - // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) - // can be declared as well. The size of such an array need not be a compile - // time constant: - printf("Enter the array size: "); // ask the user for an array size - char buf[0x100]; - fgets(buf, sizeof buf, stdin); - - // strtoul parses a string to an unsigned integer - size_t size = strtoul(buf, NULL, 10); - int var_length_array[size]; // declare the VLA - printf("sizeof array = %zu\n", sizeof var_length_array); - - // A possible outcome of this program may be: - // > Enter the array size: 10 - // > sizeof array = 40 - - // Strings are just arrays of chars terminated by a NULL (0x00) byte, - // represented in strings as the special character '\0'. - // (We don't have to include the NULL byte in string literals; the compiler - // inserts it at the end of the array for us.) - char a_string[20] = "This is a string"; - printf("%s\n", a_string); // %s formats a string - - printf("%d\n", a_string[16]); // => 0 - // i.e., byte #17 is 0 (as are 18, 19, and 20) - - // If we have characters between single quotes, that's a character literal. - // It's of type `int`, and *not* `char` (for historical reasons). - int cha = 'a'; // fine - char chb = 'a'; // fine too (implicit conversion from int to char) - - //Multi-dimensional arrays: - int multi_array[2][5] = { - {1, 2, 3, 4, 5}, - {6, 7, 8, 9, 0} - }; - //access elements: - int array_int = multi_array[0][2]; // => 3 - - /////////////////////////////////////// - // Operators - /////////////////////////////////////// - - // Shorthands for multiple declarations: - int i1 = 1, i2 = 2; - float f1 = 1.0, f2 = 2.0; - - int a, b, c; - a = b = c = 0; - - // Arithmetic is straightforward - i1 + i2; // => 3 - i2 - i1; // => 1 - i2 * i1; // => 2 - i1 / i2; // => 0 (0.5, but truncated towards 0) - - f1 / f2; // => 0.5, plus or minus epsilon - // Floating-point numbers and calculations are not exact - - // Modulo is there as well - 11 % 3; // => 2 - - // Comparison operators are probably familiar, but - // there is no Boolean type in c. We use ints instead. - // (Or _Bool or bool in C99.) - // 0 is false, anything else is true. (The comparison - // operators always yield 0 or 1.) - 3 == 2; // => 0 (false) - 3 != 2; // => 1 (true) - 3 > 2; // => 1 - 3 < 2; // => 0 - 2 <= 2; // => 1 - 2 >= 2; // => 1 - - // C is not Python - comparisons don't chain. - int a = 1; - // WRONG: - int between_0_and_2 = 0 < a < 2; - // Correct: - int between_0_and_2 = 0 < a && a < 2; - - // Logic works on ints - !3; // => 0 (Logical not) - !0; // => 1 - 1 && 1; // => 1 (Logical and) - 0 && 1; // => 0 - 0 || 1; // => 1 (Logical or) - 0 || 0; // => 0 - - //Conditional expression ( ? : ) - int a = 5; - int b = 10; - int z; - z = (a > b) ? a : b; // => 10 "if a > b return a, else return b." - - //Increment and decrement operators: - char *s = "iLoveC"; - int j = 0; - s[j++]; // => "i". Returns the j-th item of s THEN increments value of j. - j = 0; - s[++j]; // => "L". Increments value of j THEN returns j-th value of s. - // same with j-- and --j - - // Bitwise operators! - ~0x0F; // => 0xF0 (bitwise negation, "1's complement") - 0x0F & 0xF0; // => 0x00 (bitwise AND) - 0x0F | 0xF0; // => 0xFF (bitwise OR) - 0x04 ^ 0x0F; // => 0x0B (bitwise XOR) - 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) - 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) - // - 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 - - /////////////////////////////////////// - // Control Structures - /////////////////////////////////////// - - if (0) { - printf("I am never run\n"); - } else if (0) { - printf("I am also never run\n"); - } else { - printf("I print\n"); - } - - // While loops exist - int ii = 0; - while (ii < 10) { //ANY value not zero is true. - printf("%d, ", ii++); // ii++ increments ii AFTER using its current value. - } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - - printf("\n"); - - int kk = 0; - do { - printf("%d, ", kk); - } while (++kk < 10); // ++kk increments kk BEFORE using its current value. - // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - - printf("\n"); - - // For loops too - int jj; - for (jj=0; jj < 10; jj++) { - printf("%d, ", jj); - } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - - printf("\n"); - - // *****NOTES*****: - // Loops and Functions MUST have a body. If no body is needed: - int i; - for (i = 0; i <= 5; i++) { - ; // use semicolon to act as the body (null statement) - } - - // branching with multiple choices: switch() - switch (some_integral_expression) { - case 0: // labels need to be integral *constant* expressions - do_stuff(); - break; // if you don't break, control flow falls over labels - case 1: - do_something_else(); - break; - default: - // if `some_integral_expression` didn't match any of the labels - fputs("error!\n", stderr); - exit(-1); - break; - } + // print output using printf, for "print formatted" + // %d is an integer, \n is a newline + printf("%d\n", 0); // => Prints 0 + // All statements must end with a semicolon + + /////////////////////////////////////// + // Types + /////////////////////////////////////// + + // ints are usually 4 bytes + int x_int = 0; + + // shorts are usually 2 bytes + short x_short = 0; + + // chars are guaranteed to be 1 byte + char x_char = 0; + char y_char = 'y'; // Char literals are quoted with '' + + // longs are often 4 to 8 bytes; long longs are guaranteed to be at least + // 64 bits + long x_long = 0; + long long x_long_long = 0; + + // floats are usually 32-bit floating point numbers + float x_float = 0.0; + + // doubles are usually 64-bit floating-point numbers + double x_double = 0.0; + + // Integral types may be unsigned. + unsigned short ux_short; + unsigned int ux_int; + unsigned long long ux_long_long; + + // chars inside single quotes are integers in machine's character set. + '0'; // => 48 in the ASCII character set. + 'A'; // => 65 in the ASCII character set. + + // sizeof(T) gives you the size of a variable with type T in bytes + // sizeof(obj) yields the size of the expression (variable, literal, etc.). + printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) + + + // If the argument of the `sizeof` operator is an expression, then its argument + // is not evaluated (except VLAs (see below)). + // The value it yields in this case is a compile-time constant. + int a = 1; + // size_t is an unsigned integer type of at least 2 bytes used to represent + // the size of an object. + size_t size = sizeof(a++); // a++ is not evaluated + printf("sizeof(a++) = %zu where a = %d\n", size, a); + // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) + + // Arrays must be initialized with a concrete size. + char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes + int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes + // (assuming 4-byte words) + + + // You can initialize an array to 0 thusly: + char my_array[20] = {0}; + + // Indexing an array is like other languages -- or, + // rather, other languages are like C + my_array[0]; // => 0 + + // Arrays are mutable; it's just memory! + my_array[1] = 2; + printf("%d\n", my_array[1]); // => 2 + + // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) + // can be declared as well. The size of such an array need not be a compile + // time constant: + printf("Enter the array size: "); // ask the user for an array size + char buf[0x100]; + fgets(buf, sizeof buf, stdin); + + // strtoul parses a string to an unsigned integer + size_t size2 = strtoul(buf, NULL, 10); + int var_length_array[size2]; // declare the VLA + printf("sizeof array = %zu\n", sizeof var_length_array); + + // A possible outcome of this program may be: + // > Enter the array size: 10 + // > sizeof array = 40 + + // Strings are just arrays of chars terminated by a NULL (0x00) byte, + // represented in strings as the special character '\0'. + // (We don't have to include the NULL byte in string literals; the compiler + // inserts it at the end of the array for us.) + char a_string[20] = "This is a string"; + printf("%s\n", a_string); // %s formats a string + + printf("%d\n", a_string[16]); // => 0 + // i.e., byte #17 is 0 (as are 18, 19, and 20) + + // If we have characters between single quotes, that's a character literal. + // It's of type `int`, and *not* `char` (for historical reasons). + int cha = 'a'; // fine + char chb = 'a'; // fine too (implicit conversion from int to char) + + //Multi-dimensional arrays: + int multi_array[2][5] = { + {1, 2, 3, 4, 5}, + {6, 7, 8, 9, 0} + }; + //access elements: + int array_int = multi_array[0][2]; // => 3 + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + + // Shorthands for multiple declarations: + int i1 = 1, i2 = 2; + float f1 = 1.0, f2 = 2.0; + + int b, c; + b = c = 0; + + // Arithmetic is straightforward + i1 + i2; // => 3 + i2 - i1; // => 1 + i2 * i1; // => 2 + i1 / i2; // => 0 (0.5, but truncated towards 0) + + f1 / f2; // => 0.5, plus or minus epsilon + // Floating-point numbers and calculations are not exact + + // Modulo is there as well + 11 % 3; // => 2 + + // Comparison operators are probably familiar, but + // there is no Boolean type in c. We use ints instead. + // (Or _Bool or bool in C99.) + // 0 is false, anything else is true. (The comparison + // operators always yield 0 or 1.) + 3 == 2; // => 0 (false) + 3 != 2; // => 1 (true) + 3 > 2; // => 1 + 3 < 2; // => 0 + 2 <= 2; // => 1 + 2 >= 2; // => 1 + + // C is not Python - comparisons don't chain. + // WRONG: + //int between_0_and_2 = 0 < a < 2; + // Correct: + int between_0_and_2 = 0 < a && a < 2; + + // Logic works on ints + !3; // => 0 (Logical not) + !0; // => 1 + 1 && 1; // => 1 (Logical and) + 0 && 1; // => 0 + 0 || 1; // => 1 (Logical or) + 0 || 0; // => 0 + + //Conditional expression ( ? : ) + int e = 5; + int f = 10; + int z; + z = (a > b) ? a : b; // => 10 "if a > b return a, else return b." + + //Increment and decrement operators: + char *s = "iLoveC"; + int j = 0; + s[j++]; // => "i". Returns the j-th item of s THEN increments value of j. + j = 0; + s[++j]; // => "L". Increments value of j THEN returns j-th value of s. + // same with j-- and --j + + // Bitwise operators! + ~0x0F; // => 0xF0 (bitwise negation, "1's complement") + 0x0F & 0xF0; // => 0x00 (bitwise AND) + 0x0F | 0xF0; // => 0xFF (bitwise OR) + 0x04 ^ 0x0F; // => 0x0B (bitwise XOR) + 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) + 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) + // - 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 + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + + if (0) { + printf("I am never run\n"); + } else if (0) { + printf("I am also never run\n"); + } else { + printf("I print\n"); + } + + // While loops exist + int ii = 0; + while (ii < 10) { //ANY value not zero is true. + printf("%d, ", ii++); // ii++ increments ii AFTER using its current value. + } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + int kk = 0; + do { + printf("%d, ", kk); + } while (++kk < 10); // ++kk increments kk BEFORE using its current value. + // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + // For loops too + int jj; + for (jj=0; jj < 10; jj++) { + printf("%d, ", jj); + } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + // *****NOTES*****: + // Loops and Functions MUST have a body. If no body is needed: + int i; + for (i = 0; i <= 5; i++) { + ; // use semicolon to act as the body (null statement) + } + + // branching with multiple choices: switch() + switch (a) { + case 0: // labels need to be integral *constant* expressions + do_stuff(); + break; // if you don't break, control flow falls over labels + case 1: + do_something_else(); + break; + default: + // if `some_integral_expression` didn't match any of the labels + fputs("error!\n", stderr); + exit(-1); + break; + } - /////////////////////////////////////// - // Typecasting - /////////////////////////////////////// + /////////////////////////////////////// + // Typecasting + /////////////////////////////////////// - // Every value in C has a type, but you can cast one value into another type - // if you want (with some constraints). + // Every value in C has a type, but you can cast one value into another type + // if you want (with some constraints). - int x_hex = 0x01; // You can assign vars with hex literals + int x_hex = 0x01; // You can assign vars with hex literals - // Casting between types will attempt to preserve their numeric values - printf("%d\n", x_hex); // => Prints 1 - printf("%d\n", (short) x_hex); // => Prints 1 - printf("%d\n", (char) x_hex); // => Prints 1 + // Casting between types will attempt to preserve their numeric values + printf("%d\n", x_hex); // => Prints 1 + printf("%d\n", (short) x_hex); // => Prints 1 + printf("%d\n", (char) x_hex); // => Prints 1 - // Types will overflow without warning - printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long) + // Types will overflow without warning + printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long) - // For determining the max value of a `char`, a `signed char` and an `unsigned char`, - // respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from + // For determining the max value of a `char`, a `signed char` and an `unsigned char`, + // respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from - // Integral types can be cast to floating-point types, and vice-versa. - printf("%f\n", (float)100); // %f formats a float - printf("%lf\n", (double)100); // %lf formats a double - printf("%d\n", (char)100.0); + // Integral types can be cast to floating-point types, and vice-versa. + printf("%f\n", (float)100); // %f formats a float + printf("%lf\n", (double)100); // %lf formats a double + printf("%d\n", (char)100.0); - /////////////////////////////////////// - // Pointers - /////////////////////////////////////// + /////////////////////////////////////// + // Pointers + /////////////////////////////////////// - // A pointer is a variable declared to store a memory address. Its declaration will - // also tell you the type of data it points to. You can retrieve the memory address - // of your variables, then mess with them. + // A pointer is a variable declared to store a memory address. Its declaration will + // also tell you the type of data it points to. You can retrieve the memory address + // of your variables, then mess with them. - int x = 0; - printf("%p\n", (void *)&x); // Use & to retrieve the address of a variable - // (%p formats an object pointer of type void *) - // => Prints some address in memory; + int x = 0; + printf("%p\n", (void *)&x); // Use & to retrieve the address of a variable + // (%p formats an object pointer of type void *) + // => Prints some address in memory; - // Pointers start with * in their declaration - int *px, not_a_pointer; // px is a pointer to an int - px = &x; // Stores the address of x in px - printf("%p\n", (void *)px); // => Prints some address in memory - printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); - // => Prints "8, 4" on a typical 64-bit system + // Pointers start with * in their declaration + int *px, not_a_pointer; // px is a pointer to an int + px = &x; // Stores the address of x in px + printf("%p\n", (void *)px); // => Prints some address in memory + printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); + // => Prints "8, 4" on a typical 64-bit system - // To retrieve the value at the address a pointer is pointing to, - // put * in front to dereference it. - // Note: yes, it may be confusing that '*' is used for _both_ declaring a - // pointer and dereferencing it. - printf("%d\n", *px); // => Prints 0, the value of x + // To retrieve the value at the address a pointer is pointing to, + // put * in front to dereference it. + // Note: yes, it may be confusing that '*' is used for _both_ declaring a + // pointer and dereferencing it. + printf("%d\n", *px); // => Prints 0, the value of x - // You can also change the value the pointer is pointing to. - // We'll have to wrap the dereference in parenthesis because - // ++ has a higher precedence than *. - (*px)++; // Increment the value px is pointing to by 1 - printf("%d\n", *px); // => Prints 1 - printf("%d\n", x); // => Prints 1 + // You can also change the value the pointer is pointing to. + // We'll have to wrap the dereference in parenthesis because + // ++ has a higher precedence than *. + (*px)++; // Increment the value px is pointing to by 1 + printf("%d\n", *px); // => Prints 1 + printf("%d\n", x); // => Prints 1 - // Arrays are a good way to allocate a contiguous block of memory - int x_array[20]; //declares array of size 20 (cannot change size) - int xx; - for (xx = 0; xx < 20; xx++) { - x_array[xx] = 20 - xx; - } // Initialize x_array to 20, 19, 18,... 2, 1 + // Arrays are a good way to allocate a contiguous block of memory + int x_array[20]; //declares array of size 20 (cannot change size) + int xx; + for (xx = 0; xx < 20; xx++) { + x_array[xx] = 20 - xx; + } // Initialize x_array to 20, 19, 18,... 2, 1 // Declare a pointer of type int and initialize it to point to x_array - int* x_ptr = x_array; - // x_ptr now points to the first element in the array (the integer 20). - // This works because arrays often decay into pointers to their first element. - // For example, when an array is passed to a function or is assigned to a pointer, - // it decays into (implicitly converted to) a pointer. - // Exceptions: when the array is the argument of the `&` (address-of) operator: - int arr[10]; - int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`! - // It's of type "pointer to array" (of ten `int`s). - // or when the array is a string literal used for initializing a char array: - char arr[] = "foobarbazquirk"; - // or when it's the argument of the `sizeof` or `alignof` operator: - int arr[10]; - int *ptr = arr; // equivalent with int *ptr = &arr[0]; - printf("%zu, %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8" - - - // Pointers are incremented and decremented based on their type - // (this is called pointer arithmetic) - printf("%d\n", *(x_ptr + 1)); // => Prints 19 - printf("%d\n", x_array[1]); // => Prints 19 - - // You can also dynamically allocate contiguous blocks of memory with the - // standard library function malloc, which takes one argument of type size_t - // representing the number of bytes to allocate (usually from the heap, although this - // may not be true on e.g. embedded systems - the C standard says nothing about it). - int *my_ptr = malloc(sizeof(*my_ptr) * 20); - for (xx = 0; xx < 20; xx++) { - *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx - } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) + int* x_ptr = x_array; + // x_ptr now points to the first element in the array (the integer 20). + // This works because arrays often decay into pointers to their first element. + // For example, when an array is passed to a function or is assigned to a pointer, + // it decays into (implicitly converted to) a pointer. + // Exceptions: when the array is the argument of the `&` (address-of) operator: + int arr[10]; + int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`! + // It's of type "pointer to array" (of ten `int`s). + // or when the array is a string literal used for initializing a char array: + char otherarr[] = "foobarbazquirk"; + // or when it's the argument of the `sizeof` or `alignof` operator: + int arraythethird[10]; + int *ptr = arraythethird; // equivalent with int *ptr = &arr[0]; + printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr); // probably prints "40, 4" or "40, 8" + + + // Pointers are incremented and decremented based on their type + // (this is called pointer arithmetic) + printf("%d\n", *(x_ptr + 1)); // => Prints 19 + printf("%d\n", x_array[1]); // => Prints 19 + + // You can also dynamically allocate contiguous blocks of memory with the + // standard library function malloc, which takes one argument of type size_t + // representing the number of bytes to allocate (usually from the heap, although this + // may not be true on e.g. embedded systems - the C standard says nothing about it). + int *my_ptr = malloc(sizeof(*my_ptr) * 20); + for (xx = 0; xx < 20; xx++) { + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx + } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) // Dereferencing memory that you haven't allocated gives // "unpredictable results" - the program is said to invoke "undefined behavior" - printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash. - - // When you're done with a malloc'd block of memory, you need to free it, - // or else no one else can use it until your program terminates - // (this is called a "memory leak"): - free(my_ptr); - - // Strings are arrays of char, but they are usually represented as a - // pointer-to-char (which is a pointer to the first element of the array). - // It's good practice to use `const char *' when referring to a string literal, - // since string literals shall not be modified (i.e. "foo"[0] = 'a' is ILLEGAL.) - const char *my_str = "This is my very own string literal"; - printf("%c\n", *my_str); // => 'T' - - // This is not the case if the string is an array - // (potentially initialized with a string literal) - // that resides in writable memory, as in: - char foo[] = "foo"; - foo[0] = 'a'; // this is legal, foo now contains "aoo" - - function_1(); + printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash. + + // When you're done with a malloc'd block of memory, you need to free it, + // or else no one else can use it until your program terminates + // (this is called a "memory leak"): + free(my_ptr); + + // Strings are arrays of char, but they are usually represented as a + // pointer-to-char (which is a pointer to the first element of the array). + // It's good practice to use `const char *' when referring to a string literal, + // since string literals shall not be modified (i.e. "foo"[0] = 'a' is ILLEGAL.) + const char *my_str = "This is my very own string literal"; + printf("%c\n", *my_str); // => 'T' + + // This is not the case if the string is an array + // (potentially initialized with a string literal) + // that resides in writable memory, as in: + char foo[] = "foo"; + foo[0] = 'a'; // this is legal, foo now contains "aoo" + + function_1(); } // end main function /////////////////////////////////////// @@ -427,12 +426,12 @@ int main() { int add_two_ints(int x1, int x2) { - return x1 + x2; // Use return to return a value + return x1 + x2; // Use return to return a value } /* Functions are call by value. When a function is called, the arguments passed to -the function are copies of the original arguments (except arrays). Anything you +≈the function are copies of the original arguments (except arrays). Anything you do to the arguments in the function do not change the value of the original argument where the function was called. @@ -444,14 +443,14 @@ Example: in-place string reversal // A void function returns no value void str_reverse(char *str_in) { - char tmp; - int ii = 0; - size_t len = strlen(str_in); // `strlen()` is part of the c standard library - for (ii = 0; ii < len / 2; ii++) { - tmp = str_in[ii]; - str_in[ii] = str_in[len - ii - 1]; // ii-th char from end - str_in[len - ii - 1] = tmp; - } + char tmp; + int ii = 0; + size_t len = strlen(str_in); // `strlen()` is part of the c standard library + for (ii = 0; ii < len / 2; ii++) { + tmp = str_in[ii]; + str_in[ii] = str_in[len - ii - 1]; // ii-th char from end + str_in[len - ii - 1] = tmp; + } } /* @@ -463,13 +462,13 @@ printf("%s\n", c); // => ".tset a si sihT" //if referring to external variables outside function, must use extern keyword. int i = 0; void testFunc() { - extern int i; //i here is now using external variable i + extern int i; //i here is now using external variable i } //make external variables private to source file with static: -static int i = 0; //other files using testFunc() cannot access variable i -void testFunc() { - extern int i; +static int j = 0; //other files using testFunc() cannot access variable i +void testFunc2() { + extern int j; } //**You may also declare functions as static to make them private** @@ -486,8 +485,8 @@ my_type my_type_var = 0; // Structs are just collections of data, the members are allocated sequentially, // in the order they are written: struct rectangle { - int width; - int height; + int width; + int height; }; // It's not generally true that @@ -497,20 +496,20 @@ struct rectangle { void function_1() { - struct rectangle my_rec; + struct rectangle my_rec; - // Access struct members with . - my_rec.width = 10; - my_rec.height = 20; + // Access struct members with . + my_rec.width = 10; + my_rec.height = 20; - // You can declare pointers to structs - struct rectangle *my_rec_ptr = &my_rec; + // You can declare pointers to structs + struct rectangle *my_rec_ptr = &my_rec; - // Use dereferencing to set struct pointer members... - (*my_rec_ptr).width = 30; + // Use dereferencing to set struct pointer members... + (*my_rec_ptr).width = 30; - // ... or even better: prefer the -> shorthand for the sake of readability - my_rec_ptr->height = 10; // Same as (*my_rec_ptr).height = 10; + // ... or even better: prefer the -> shorthand for the sake of readability + my_rec_ptr->height = 10; // Same as (*my_rec_ptr).height = 10; } // You can apply a typedef to a struct for convenience @@ -518,14 +517,14 @@ typedef struct rectangle rect; int area(rect r) { - return r.width * r.height; + return r.width * r.height; } // if you have large structs, you can pass them "by pointer" to avoid copying // the whole struct: -int area(const rect *r) +int areaptr(const rect *r) { - return r->width * r->height; + return r->width * r->height; } /////////////////////////////////////// @@ -540,12 +539,12 @@ However, definition syntax may be initially confusing. Example: use str_reverse from a pointer */ void str_reverse_through_pointer(char *str_in) { - // Define a function pointer variable, named f. - void (*f)(char *); // Signature should exactly match the target function. - f = &str_reverse; // Assign the address for the actual function (determined at run time) - // f = str_reverse; would work as well - functions decay into pointers, similar to arrays - (*f)(str_in); // Just calling the function through the pointer - // f(str_in); // That's an alternative but equally valid syntax for calling it. + // Define a function pointer variable, named f. + void (*f)(char *); // Signature should exactly match the target function. + f = &str_reverse; // Assign the address for the actual function (determined at run time) + // f = str_reverse; would work as well - functions decay into pointers, similar to arrays + (*f)(str_in); // Just calling the function through the pointer + // f(str_in); // That's an alternative but equally valid syntax for calling it. } /* @@ -560,36 +559,37 @@ typedef void (*my_fnp_type)(char *); // my_fnp_type f; //Special characters: -'\a' // alert (bell) character -'\n' // newline character -'\t' // tab character (left justifies text) -'\v' // vertical tab -'\f' // new page (form feed) -'\r' // carriage return -'\b' // backspace character -'\0' // NULL character. Usually put at end of strings in C. - // hello\n\0. \0 used by convention to mark end of string. -'\\' // backslash -'\?' // question mark -'\'' // single quote -'\"' // double quote -'\xhh' // hexadecimal number. Example: '\xb' = vertical tab character -'\ooo' // octal number. Example: '\013' = vertical tab character +/* +'\a'; // alert (bell) character +'\n'; // newline character +'\t'; // tab character (left justifies text) +'\v'; // vertical tab +'\f'; // new page (form feed) +'\r'; // carriage return +'\b'; // backspace character +'\0'; // NULL character. Usually put at end of strings in C. +// hello\n\0. \0 used by convention to mark end of string. +'\\'; // backslash +'\?'; // question mark +'\''; // single quote +'\"'; // double quote +'\xhh'; // hexadecimal number. Example: '\xb' = vertical tab character +'\ooo'; // octal number. Example: '\013' = vertical tab character //print formatting: -"%d" // integer -"%3d" // integer with minimum of length 3 digits (right justifies text) -"%s" // string -"%f" // float -"%ld" // long -"%3.2f" // minimum 3 digits left and 2 digits right decimal float -"%7.4s" // (can do with strings too) -"%c" // char -"%p" // pointer -"%x" // hexadecimal -"%o" // octal -"%%" // prints % - +"%d"; // integer +"%3d"; // integer with minimum of length 3 digits (right justifies text) +"%s"; // string +"%f"; // float +"%ld"; // long +"%3.2f"; // minimum 3 digits left and 2 digits right decimal float +"%7.4s"; // (can do with strings too) +"%c"; // char +"%p"; // pointer +"%x"; // hexadecimal +"%o"; // octal +"%%"; // prints % +*/ /////////////////////////////////////// // Order of Evaluation /////////////////////////////////////// -- cgit v1.2.3 From 4fb3361655e59e9314d1a4f48fe76def08bc07fe Mon Sep 17 00:00:00 2001 From: masdeseiscaracteres Date: Thu, 17 Jul 2014 15:45:53 +0200 Subject: Small correction: "flipl" should be "fliplr" Added "flipud" also --- matlab.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 9baefe68..d9a82890 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -423,7 +423,8 @@ tril(x) % Returns the lower triangular part of x cross(A,B) % Returns the cross product of the vectors A and B 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 +fliplr(A) % Flip matrix left to right +flipud(A) % Flip matrix up to down % Matrix Factorisations [L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix -- cgit v1.2.3 From 50fe4d985952e6fd978df7a97e491cb0456fe11c Mon Sep 17 00:00:00 2001 From: iirelu Date: Thu, 17 Jul 2014 17:08:30 +0100 Subject: Commented out two broken lines in learnc.c --- c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index bc9a959a..b0c77e16 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -281,10 +281,10 @@ int main() { // branching with multiple choices: switch() switch (a) { case 0: // labels need to be integral *constant* expressions - do_stuff(); + //do_stuff(); break; // if you don't break, control flow falls over labels case 1: - do_something_else(); + //do_something_else(); break; default: // if `some_integral_expression` didn't match any of the labels -- cgit v1.2.3 From a9f51d5bbf977859093d26823f327c0d6003352c Mon Sep 17 00:00:00 2001 From: iirelu Date: Thu, 17 Jul 2014 20:37:52 +0100 Subject: Made learnc's switch statement clearer Also cleaned up trailing whitespace. --- c.html.markdown | 67 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index b0c77e16..8e170300 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -23,9 +23,9 @@ Multi-line comments look like this. They work in C89 as well. // Constants: #define #define DAYS_IN_YEAR 365 - // Enumeration constants are also ways to declare constants. + // Enumeration constants are also ways to declare constants. enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; -// MON gets 2 automatically, TUE gets 3, etc. +// MON gets 2 automatically, TUE gets 3, etc. // Import headers with #include #include @@ -43,7 +43,7 @@ int function_2(void); // Must declare a 'function prototype' before main() when functions occur after // your main() function. -int add_two_ints(int x1, int x2); // function prototype +int add_two_ints(int x1, int x2); // function prototype // Your program's entry point is a function called // main with an integer return type. @@ -57,7 +57,7 @@ int main() { // Types /////////////////////////////////////// - // ints are usually 4 bytes + // ints are usually 4 bytes int x_int = 0; // shorts are usually 2 bytes @@ -70,7 +70,7 @@ int main() { // longs are often 4 to 8 bytes; long longs are guaranteed to be at least // 64 bits long x_long = 0; - long long x_long_long = 0; + long long x_long_long = 0; // floats are usually 32-bit floating point numbers float x_float = 0.0; @@ -83,9 +83,9 @@ int main() { unsigned int ux_int; unsigned long long ux_long_long; - // chars inside single quotes are integers in machine's character set. - '0'; // => 48 in the ASCII character set. - 'A'; // => 65 in the ASCII character set. + // chars inside single quotes are integers in machine's character set. + '0'; // => 48 in the ASCII character set. + 'A'; // => 65 in the ASCII character set. // sizeof(T) gives you the size of a variable with type T in bytes // sizeof(obj) yields the size of the expression (variable, literal, etc.). @@ -96,7 +96,7 @@ int main() { // is not evaluated (except VLAs (see below)). // The value it yields in this case is a compile-time constant. int a = 1; - // size_t is an unsigned integer type of at least 2 bytes used to represent + // size_t is an unsigned integer type of at least 2 bytes used to represent // the size of an object. size_t size = sizeof(a++); // a++ is not evaluated printf("sizeof(a++) = %zu where a = %d\n", size, a); @@ -163,7 +163,7 @@ int main() { /////////////////////////////////////// // Shorthands for multiple declarations: - int i1 = 1, i2 = 2; + int i1 = 1, i2 = 2; float f1 = 1.0, f2 = 2.0; int b, c; @@ -184,7 +184,7 @@ int main() { // Comparison operators are probably familiar, but // there is no Boolean type in c. We use ints instead. // (Or _Bool or bool in C99.) - // 0 is false, anything else is true. (The comparison + // 0 is false, anything else is true. (The comparison // operators always yield 0 or 1.) 3 == 2; // => 0 (false) 3 != 2; // => 1 (true) @@ -211,14 +211,14 @@ int main() { int e = 5; int f = 10; int z; - z = (a > b) ? a : b; // => 10 "if a > b return a, else return b." + z = (a > b) ? a : b; // => 10 "if a > b return a, else return b." //Increment and decrement operators: char *s = "iLoveC"; int j = 0; s[j++]; // => "i". Returns the j-th item of s THEN increments value of j. - j = 0; - s[++j]; // => "L". Increments value of j THEN returns j-th value of s. + j = 0; + s[++j]; // => "L". Increments value of j THEN returns j-th value of s. // same with j-- and --j // Bitwise operators! @@ -249,7 +249,7 @@ int main() { // While loops exist int ii = 0; - while (ii < 10) { //ANY value not zero is true. + while (ii < 10) { //ANY value not zero is true. printf("%d, ", ii++); // ii++ increments ii AFTER using its current value. } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " @@ -281,10 +281,10 @@ int main() { // branching with multiple choices: switch() switch (a) { case 0: // labels need to be integral *constant* expressions - //do_stuff(); + printf("Hey, 'a' equals 0!\n"); break; // if you don't break, control flow falls over labels case 1: - //do_something_else(); + printf("Huh, 'a' equals 1!\n"); break; default: // if `some_integral_expression` didn't match any of the labels @@ -292,7 +292,6 @@ int main() { exit(-1); break; } - /////////////////////////////////////// // Typecasting @@ -324,7 +323,7 @@ int main() { /////////////////////////////////////// // A pointer is a variable declared to store a memory address. Its declaration will - // also tell you the type of data it points to. You can retrieve the memory address + // also tell you the type of data it points to. You can retrieve the memory address // of your variables, then mess with them. int x = 0; @@ -362,7 +361,7 @@ int main() { // Declare a pointer of type int and initialize it to point to x_array int* x_ptr = x_array; - // x_ptr now points to the first element in the array (the integer 20). + // x_ptr now points to the first element in the array (the integer 20). // This works because arrays often decay into pointers to their first element. // For example, when an array is passed to a function or is assigned to a pointer, // it decays into (implicitly converted to) a pointer. @@ -396,7 +395,7 @@ int main() { // "unpredictable results" - the program is said to invoke "undefined behavior" printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash. - // When you're done with a malloc'd block of memory, you need to free it, + // When you're done with a malloc'd block of memory, you need to free it, // or else no one else can use it until your program terminates // (this is called a "memory leak"): free(my_ptr); @@ -430,12 +429,12 @@ int add_two_ints(int x1, int x2) } /* -Functions are call by value. When a function is called, the arguments passed to -≈the function are copies of the original arguments (except arrays). Anything you -do to the arguments in the function do not change the value of the original -argument where the function was called. +Functions are call by value. When a function is called, the arguments passed to +≈the function are copies of the original arguments (except arrays). Anything you +do to the arguments in the function do not change the value of the original +argument where the function was called. -Use pointers if you need to edit the original argument values. +Use pointers if you need to edit the original argument values. Example: in-place string reversal */ @@ -528,18 +527,18 @@ int areaptr(const rect *r) } /////////////////////////////////////// -// Function pointers +// Function pointers /////////////////////////////////////// /* At run time, functions are located at known memory addresses. Function pointers are -much like any other pointer (they just store a memory address), but can be used +much like any other pointer (they just store a memory address), but can be used to invoke functions directly, and to pass handlers (or callback functions) around. However, definition syntax may be initially confusing. Example: use str_reverse from a pointer */ void str_reverse_through_pointer(char *str_in) { - // Define a function pointer variable, named f. + // Define a function pointer variable, named f. void (*f)(char *); // Signature should exactly match the target function. f = &str_reverse; // Assign the address for the actual function (determined at run time) // f = str_reverse; would work as well - functions decay into pointers, similar to arrays @@ -556,7 +555,7 @@ typedef void (*my_fnp_type)(char *); // Then used when declaring the actual pointer variable: // ... -// my_fnp_type f; +// my_fnp_type f; //Special characters: /* @@ -567,8 +566,8 @@ typedef void (*my_fnp_type)(char *); '\f'; // new page (form feed) '\r'; // carriage return '\b'; // backspace character -'\0'; // NULL character. Usually put at end of strings in C. -// hello\n\0. \0 used by convention to mark end of string. +'\0'; // NULL character. Usually put at end of strings in C. +// hello\n\0. \0 used by convention to mark end of string. '\\'; // backslash '\?'; // question mark '\''; // single quote @@ -582,13 +581,13 @@ typedef void (*my_fnp_type)(char *); "%s"; // string "%f"; // float "%ld"; // long -"%3.2f"; // minimum 3 digits left and 2 digits right decimal float +"%3.2f"; // minimum 3 digits left and 2 digits right decimal float "%7.4s"; // (can do with strings too) "%c"; // char "%p"; // pointer "%x"; // hexadecimal "%o"; // octal -"%%"; // prints % +"%%"; // prints % */ /////////////////////////////////////// // Order of Evaluation -- cgit v1.2.3 From e7b07b56a9dd3d8a51c9b8aa03e3892ad9b2e713 Mon Sep 17 00:00:00 2001 From: santifa Date: Fri, 18 Jul 2014 00:33:59 +0200 Subject: [haskell/de] German translation for learnxinyminutes-docs/haskell-en --- de-de/haskell-de.html.markdown | 425 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 425 insertions(+) create mode 100644 de-de/haskell-de.html.markdown diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown new file mode 100644 index 00000000..df6267f9 --- /dev/null +++ b/de-de/haskell-de.html.markdown @@ -0,0 +1,425 @@ +--- +language: haskell +lang: de-de +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["Henrik Jürges", "https://github.com/santifa"] +filename: haskell-de.hs + +--- + +Haskell wurde als praktische und funktionale Sprache entworfen. +Es ist berühmt für das Schema der Monaden und des Typsystems, aber +es sticht vor allem die Einfachheit und Eleganz hervor. + +```haskell +-- Einfache Kommentare beginnen mit 2 Bindestriche. +{- So wird ein Kommentar +über mehrere Zeilen angelegt. +-} + +---------------------------------------------------- +-- 1. Primitive Datentypen und Operatoren +---------------------------------------------------- + +-- Normale Zahlen. +3 -- 3 + +-- Einfache Rechenoperationen. +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- Die Division ist per se auf Fließkommazahlen. +35 / 4 -- 8.75 + +-- Ganzzahlige Division +35 `div` 4 -- 8 + +-- Boolesche Werte sind Primitiven. +True +False + +-- Logik Operationen +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- `not` ist eine Funktion die ein Argument entgegenimmt. +-- Haskell benötigt keine Klammern um Argumente. +-- Sie werden einfach aufgelistet: func arg1 arg2 arg3... +-- Wie man Funktionen definiert kommt weiter unten. + + +-- Strings und Zeichen +"Das ist ein String." +'a' -- Zeichen +'Einfache Anfuehrungszeichen gehen nicht.' -- error! + +-- Strings können konkateniert werden. +"Hello " ++ "world!" -- "Hello world!" + +-- Ein String ist eine Liste von Zeichen. +"Das ist eine String" !! 0 -- 'D' + + +---------------------------------------------------- +-- Listen und Tupel +---------------------------------------------------- + +-- Jedes Element einer Liste muss vom gleichen Typ sein. +-- Zwei gleiche Listen +[1, 2, 3, 4, 5] +[1..5] + +-- Haskell unterstuetzt unendliche Listen! +[1..] -- Die Liste aller natuerlichen Zahlen + +-- Unendliche Listen funktionieren in Haskell, da es "lazy evaluation" +-- unterstuetzt. Haskell evaluiert erst etwas, wenn es benötigt wird. +-- Somit kannst du nach dem 1000. Element fragen und Haskell gibt es dir: + +[1..] !! 999 -- 1000 + +-- Haskell evaluiert nun die ersten 1 - 1000 Elemente, aber der Rest der Liste +-- bleibt unangetastet. Haskell wird sie solange nicht weiterevalieren +-- bis es muss. + +-- Zwei Listen konkatenieren +[1..5] ++ [6..10] + +-- Ein Element als Head hinzufuegen +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- Gibt den 5. Index zurueck +[0..] !! 5 -- 5 + +-- Weitere Listenoperationen +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +-- list comprehensions | Listen erschaffen +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- Mit Bedingungen +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Tupel haben eine feste Länge, jedes Element darf aber ein anderen Typ haben. +-- Ein Tupel: +("haskell", 1) + +-- Auf Elemente eines Tupels zugreifen: +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Funktionen +---------------------------------------------------- +-- Eine einfache Funktion die zwei Argumente hat. +add a b = a + b + +-- Wenn man ghci (den Haskell Interpreter) benutzt, muss ein `let` davor. +-- let add a b = a + b + +-- Eine Funktion aufrufen +add 1 2 -- 3 + +-- Man kann eine Funktion auch Infix verwenden, +-- wenn man sie mit backticks umgibt +1 `add` 2 -- 3 + +-- So sieht die Definition eines eigenen Operators aus. +-- Also einer Funktion deren Name aus Symbolen besteht. +-- Die Integer Division: +(//) a b = a `div` b +35 // 4 -- 8 + +-- Guards sind eine einfache Möglichkeit fuer Fallunterscheidungen. +fib x + | x < 2 = x + | otherwise = fib (x - 1) + fib (x - 2) + +-- Pattern Matching funktioniert ähnlich. +-- Hier sind drei Definitionen von fib. Haskell wird automatisch +-- die erste Funktionen nehmen die dem Pattern der Eingabe entspricht. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Pattern matching auf Tupeln: +foo (x, y) = (x + 1, y + 2) + +-- Pattern matching auf Listen. +-- `x` ist das erste Element der Liste und `xs` der Rest der Liste. +-- Damit können wir unsere eigene map Funktion bauen: +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Anonyme Funktionen (Lambda-Funktionen) werden mit einem +-- Backslash eingeleitet, gefolgt von allen Argumenten. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- Fold (`inject` in einigen Sprachen) +-- Foldl1 bedeutet: fold von links nach rechts und nehme den ersten +-- Wert der Liste als Basiswert f[r den Akkumulator. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Mehr Funktionen +---------------------------------------------------- + +-- currying: Wenn man nicht alle Argumente an eine Funktion uebergibt, +-- so wird sie eine neue Funktion gebildet ("curried"). +-- Es findet eine partielle Applikation statt und die neue Funktion +-- nimmt die fehlenden Argumente auf. + +add a b = a + b +foo = add 10 -- foo ist nun Funktion die ein Argument nimmt und 10 addiert +foo 5 -- 15 + +-- Ein alternativer Weg +foo = (+10) +foo 5 -- 15 + +-- Funktionskomposition +-- Die (.) Funktion verkettet Funktionen. +-- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und +-- multipliziert dieses Ergebnis mit 5. +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + + +-- Haskell hat eine Funktion `$`. Diese ändert den Vorrang, +-- so dass alles links von ihr zuerst berechnet wird und +-- und dann an die rechte Seite weitergegeben wird. +-- Mit `.` und `$` kann man sich viele Klammern ersparen. + +-- Vorher +(even (fib 7)) -- true + +-- Danach +even . fib $ 7 -- true + +---------------------------------------------------- +-- 5. Typensystem +---------------------------------------------------- + +-- Haskell hat ein sehr starkes Typsystem. +-- Alles hat einen Typ und eine Typsignatur. + +-- Einige grundlegende Typen: +5 :: Integer +"hello" :: String +True :: Bool + +-- Funktionen haben genauso Typen. +-- `not` ist Funktion die ein Bool annimmt und ein Bool zurueckgibt: +-- not :: Bool -> Bool + +-- Eine Funktion die zwei Integer Argumente annimmt: +-- add :: Integer -> Integer -> Integer + +-- Es ist guter Stil zu jeder Funktionsdefinition eine +-- Typdefinition darueber zu schreiben: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. If-Anweisung und Kontrollstrukturen +---------------------------------------------------- + +-- If-Anweisung: +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- If-Anweisungen können auch ueber mehrere Zeilen verteilt sein. +-- Das Einruecken ist dabei äußerst wichtig. +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- Case-Anweisung: Zum Beispiel "commandline" Argumente parsen. +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- Haskell nutzt Rekursion anstatt Schleifen. +-- map wendet eine Funktion auf jedes Element einer Liste an. + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- So kann man auch eine for-Funktion kreieren. +for array func = map func array + +-- und so benutzt man sie: +for [0..5] $ \i -> show i + +-- wir hätten sie auch so benutzen können: +for [0..5] show + +-- foldl oder foldr reduziren Listen auf einen Wert. +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- die Abarbeitung sieht so aus: +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl ist linksseitig und foldr rechtsseitig. +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- die Abarbeitung sieht so aus: +(2 * 3 + (2 * 2 + (2 * 1 + 4))) + +---------------------------------------------------- +-- 7. Datentypen +---------------------------------------------------- + +-- So kann man seine eigenen Datentypen in Haskell anlegen: + +data Color = Red | Blue | Green + +-- Nun können wir sie in einer Funktion benutzen. + +say :: Color -> String +say Red = "You are Red!" +say Blue = "You are Blue!" +say Green = "You are Green!" + +-- Datentypen können auch Parameter aufnehmen: + +data Maybe a = Nothing | Just a + +-- Diese sind alle vom Typ Maybe: +Just "hello" -- vom Typ `Maybe String` +Just 1 -- vom Typ `Maybe Int` +Nothing -- vom Typ `Maybe a` fuer jedes `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- IO kann nicht völlig erklärt werden ohne Monaden zu erklären, +-- aber man kann die grundlegenden Dinge erklären. + +-- Wenn eine Haskell Programm ausgefuehrt wird, so wird `main` aufgerufen. +-- Diese muss etwas vom Typ `IO ()` zurueckgeben. Zum Beispiel: + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- putStrLn hat den Typ String -> IO () + +-- Es ist am einfachsten, wenn man sein Programm als Funktion von +-- String nach String implementiert. +-- Zum Beispiel die Funktion interact :: (String -> String) -> IO () +-- nimmt einen Text, tut etwas damit und gibt diesen wieder aus. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- Man kann den Typ `IO ()` als Repräsentation einer Sequenz von +-- Aktionen sehen, die der Computer abarbeiten muss. +-- Wie bei einem Programm das in einer Imperativen Sprache geschreiben wurde. +-- Mit der `do` Notation können Aktionen verbunden werden. + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + name <- getLine -- eine Zeile wird geholt und + -- an die Variable "name" gebunden + putStrLn $ "Hello, " ++ name + +-- Uebung: Schreibe deine eigene Version von `interact`, +-- die nur eine Zeile einliest. + +-- `sayHello` wird niemals ausgefuehrt, nur `main` wird ausgefuehrt. +-- Um `sayHello` laufen zulassen kommentiere die Definition von `main` +-- aus und ersetze sie mit: +-- main = sayHello + +-- Lass uns untersuchen wie `getLine` arbeitet. +-- Der Typ ist: getLine :: IO String +-- Man kann sich vorstellen das der Wert vom Typ `IO a` ein +-- Programm repräsentiert das etwas vom Typ `a` generiert. +-- Der Wert wird mit `<-` gespeichert und kann wieder benutzt werden. +-- Wir könne auch eigene Funktionen vom Typ `IO String` definieren: + +action :: IO String +action = do + putStrLn "This is a line. Duh" + input1 <- getLine + input2 <- getLine + -- Der Typ von `do` ergibt sich aus der letzten Zeile. + -- `return` ist eine Funktion und keine Schluesselwort + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- Nun können wir `action` wie `getLine` benutzen: + +main'' = do + putStrLn "I will echo two lines!" + result <- action + putStrLn result + putStrLn "This was all, folks!" + +-- Der Typ `IO` ist ein Beispiel fuer eine Monade. +-- Haskell benutzt Monaden Seiteneffekte zu kapseln und somit +-- eine rein funktional Sprache zu sein. +-- Jede Funktion die mit der Außenwelt interagiert (z.B. IO) +-- hat den Typ `IO` in seiner Signatur. +-- Damit kann man zwischen "reinen" Funktionen (interagieren nicht +-- mit der Außenwelt oder ändern ihren Zustand) und Anderen unterscheiden. + +-- Nebenläufigkeit ist in Haskell sehr einfach, da reine Funktionen +-- leicht nebenläufig arbeiten können. + +---------------------------------------------------- +-- 9. Die Haskell REPL +---------------------------------------------------- + +-- Starte die REPL mit dem Befehl `ghci` +-- Nun kann man Haskell Code eingeben. +-- Alle neuen Werte muessen mit `let` gebunden werden: + +let foo = 5 + +-- `:t` zeigt den Typen von jedem Wert an: + +>:t foo +foo :: Integer + +-- Auch jede `IO ()` Funktion kann ausgefuehrt werden. + +> sayHello +What is your name? +Friend! +Hello, Friend! + +``` + +Es gibt noch viel mehr in Haskell, wie zum Beispiel Typklassen und Monaden. +Dies sind die Ideen durch die Haskell Programmierung zum Spaß wird. +Mit dem folgenden kleinen Beispiel werde ich euch verlassen: +Quicksort in Haskell: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell ist sehr einfach zu installieren. +Hohl es dir von [hier](http://www.haskell.org/platform/). + +Eine sehr viele langsamere Einfuehrung findest du unter: +[Learn you a Haskell](http://learnyouahaskell.com/) oder +[Real World Haskell](http://book.realworldhaskell.org/). -- cgit v1.2.3 From 1652740cb92b73ce1b441484c7a5e1ae1e835764 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sat, 19 Jul 2014 01:49:07 +0200 Subject: Well met Sequence / FF --- perl6.html.markdown | 44 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index d9dce641..b4918115 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -204,14 +204,16 @@ $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an ar # this also works as a shortcut for `0..^N` ^10; # 0..^10 -# This also allows us to demonstrate that Perl 6 has lazy arrays : +# This also allows us to demonstrate that Perl 6 has lazy arrays, using the Whatever Star : my @array = 1..*; # 1 to Infinite ! say @array[^10]; # you can pass arrays as subscripts and it'll return an array of results # this will print "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 juste 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 +# so you'll end with an infinite loop. ## * And, Or 3 && 4; # True. Calls `.Bool` on `3` @@ -222,8 +224,19 @@ $a && $b && $c; # returns the first argument that evaluates to False, or the las $a || $b; ## Sequence operator -# !TODO! -1, 2, 3 ... 10; +# The sequence operator is one of Perl 6's most powerful features : +# it's composed of first, on the left, the list you want Perl 6 to deduce from (and might include a closure), +# and on the right, a value or the predicate for when to stop, or even Whatever for a lazy infinite list +my @list = 1, 2, 3 ... 10; # basic deducing +#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, because Perl 6 can't figure out the end +my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element (when the predicate matches) +my @list = 1, 3, 9 ... * > 30; # you can use a predicate (with the Whatever Star, here) +my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above) +my @primes = 1, 1, *+* ... *; # lazy infinite list of prime numbers, computed using a closure ! +my @primes = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above) +say @primes[^10]; #=> 1 1 2 3 5 8 13 21 34 55 +# Note : as for ranges, once reified, elements aren't re-calculated. +# That's why `@primes[^100]` will take a long time the first time you print it, then be instant ## More on Subs ! # Perl 6 likes functions. So, in Perl 6, functions are very powerful: @@ -415,7 +428,7 @@ $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` !$a! # with right-associative `!`, this is `!($a!)` !$a! # with non-associative `!`, this is illegal -## And to end the list of operators ... +## Last part of the operator list : ## * Sort comparison # They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1). @@ -427,4 +440,25 @@ $obj eqv $obj2; # sort comparison using eqv semantics 3 before 4; # True 'b' after 'a'; # True +## * Flip Flop +# The flip flop operator (spelled `ff` in Perl 6 and sometimes `..` in other languages such as Perl 5 and Ruby), +# is an operator that takes two boolean values (like a predicate) and keep track of their change as internal state. +# The flip-flop will return `false` until its left side return true, then return true until its right side return true. +# You can also exclude either side (iteration when the left side became true, or the right side became true), +# using the `^` like with ranges. +# Let's start with an example : +for { + if $_ eq 'met' ^ff $_ eq 'meet' { # excludes "met" + .say + } +} +# This will print "young hero we shall meet" (excluding "met"): +# the flip-flop will start returning `True` when it first encounters "met" +# (but will still return `False` for "met" itself, due to the leading `^` on `ff`), +# until it sees "meet", which is when it'll start returning `False`. +# A flip-flop can change state as many times as needed: +for { + .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", + # this prints "print this printing again" +} ``` -- cgit v1.2.3 From 7314a87f9d49128376cf1320ea85e7a4411e5758 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sat, 19 Jul 2014 01:54:05 +0200 Subject: ff * --- perl6.html.markdown | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index b4918115..76f08248 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -11,6 +11,9 @@ Perl 6 is a highly capable, feature-rich programming language made for the upcom Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM and [the MoarVM](http://moarvm.com). +Meta-note : the triple pound signs are here to denote headlines, double paragraphs, single notes. +`#=>` represents the output of a command. + ```perl # Single line comment start with a pound @@ -459,6 +462,19 @@ for { # A flip-flop can change state as many times as needed: for { .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", - # this prints "print this printing again" + #=> "print this printing again" +} + +# you might also use a Whatever Star, which is equivalent to `True` for the left side or `False` for the right : +for (1, 3, 60, 3, 40, 60) { + .say if $_ > 50 ff *; # Once the flip-flop reached a number greater than 50, it'll never go back to `False` + #=> 60 3 40 60 +} + +# You can also use this property to create an `If` that'll not execute the first time : +for { + .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, + # but the `^` makes it *not run* on the first iteration + #=> b c } ``` -- cgit v1.2.3 From be796e988a522260aedc380e7f10e3e50b65138e Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sun, 20 Jul 2014 01:25:20 +0200 Subject: Phasers ! and more: Add default Add a bit on exceptions (TODO fail/warn) --- perl6.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 81 insertions(+), 3 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 76f08248..44fc94e9 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -116,14 +116,18 @@ say "Quite truthy" if True; # - Ternary conditional my $a = $condition ?? $value-if-true !! $value-if-false; # `??` and `!!` are like `?` and `:` in other languages' -# - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching : -given "foo bar" { # given just puts its argument into `$_`, and `when` uses it using the "smart matching" operator. - when /foo/ { # you'll read about the smart-matching operator below +# - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching. +# given just puts its argument into `$_`, and `when` uses it using the "smart matching" operator. +given "foo bar" { + when /foo/ { # you'll read about the smart-matching operator below -- just know `when` uses it say "Yay !"; } when $_.chars > 50 { # smart matching anything with True gives True, so you can also put "normal" conditionals say "Quite a long string !"; } + default { # same as `when *` (using the Whatever Star) + say "Something else" + } } ## Looping constructs @@ -150,6 +154,12 @@ for @array { say "I've got $_"; } +for @array { + next if $_ == 3; # you can skip to the next iteration (like `continue` in C-like languages) + redo if $_ == 4; # you can re-do the iteration, keeping the same topic variable (`$_`) + last if $_ == 5; # you can also break out of a loop (like `break` in C-like languages) +} + # Note - the "lambda" `->` syntax isn't reserved to `for` : if long-computation() -> $result { say "The result is $result"; @@ -411,6 +421,74 @@ class Item does PrintableVal { # since the compiler will consider `ROLE` to be a class } +### Exceptions +# Exceptions are built on top of classes, usually in the package `X` (like `X::IO`). +# Unlike many other languages, in Perl 6, you put the `CATCH` block *within* the block to `try`. +# By default, a `try` has a `CATCH` block that catches any exception (`CATCH { default {} }`). +# You can redefine it using `when`s (and `default`) to handle the exceptions you want: +try { + open 'foo'; + CATCH { + when X::AdHoc { say "unable to open file !" } + # any other exception will be re-raised, since we don't have a `default` + } +} + +# You can throw an exception using `die`: +die X::AdHoc.new(payload => 'Error !'); +# TODO warn +# TODO fail +# TODO CONTROL + +### Phasers +# Phasers in Perl 6 are blocks that happen at determined points of time in your program +# When the program is compiled, when a for loop runs, when you leave a block, when +# an exception gets thrown ... (`CATCH` is actually a phaser !) +# Some of them can be used for their return values, some of them can't +# (those that can have a "[*]" in the beginning of their explanation text). +# Let's have a look ! + +## * Compile-time phasers +BEGIN { say "[*] Runs at compile time, as soon as possible, only once" } +CHECK { say "[*] Runs at compile time, instead as late as possible, only once" } + +## * Run-time phasers +INIT { say "[*] Runs at run time, as soon as possible, only once" } +END { say "Runs at run time, as late as possible, only once" } + +## * Block phasers +ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" } +LEAVE { say "Runs everytime you leave a block, even when an exception happened. Repeats on loop blocks." } + +PRE { say "Asserts a precondition at every block entry, before ENTER (especially useful for loops)" } +POST { say "Asserts a postcondition at every block exit, after LEAVE (especially useful for loops)" } + +## * Block/exceptions phasers +sub { + KEEP { say "Runs when you exit a block successfully (without throwing an exception)" } + UNDO { say "Runs when you exit a block unsuccessfully (by throwing an exception)" } +} + +## * Loop phasers +for ^5 { + FIRST { say "[*] The first time the loop is run, before ENTER" } + NEXT { say "At loop continuation time, before LEAVE" } + LAST { say "At loop termination time, after LEAVE" } +} + +## * Role/class phasers +COMPOSE { "When a role is composed into a class. /!\ NOT YET IMPLEMENTED /!\" } + +# They allow for cute trick or clever code ...: +say "This code took " ~ (time - CHECK time) ~ "s to run"; + +# ... or clever organization: +sub do-db-stuff { + ENTER $db.start-transaction; # create a new transaction everytime we enter the sub + KEEP $db.commit; # commit the transaction if all went well + UNDO $db.rollback; # or rollback if all hell broke loose +} + ### More operators thingies ! -- cgit v1.2.3 From 37a38181a82c6cf3897ea357dab57f71d51f94e8 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Mon, 21 Jul 2014 23:18:55 +0200 Subject: Scoping explanations (lexical / dynamic) Start on packages. ff/fff like `when` ff vs fff ~~ on Bool // and ^^ operators TODO warn/fail/control --- perl6.html.markdown | 95 ++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 87 insertions(+), 8 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 44fc94e9..70799b29 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -113,7 +113,7 @@ say "Quite truthy" if True; # if (true) say; # This doesn't work ! -# - Ternary conditional +# - Ternary conditional, "?? !!" my $a = $condition ?? $value-if-true !! $value-if-false; # `??` and `!!` are like `?` and `:` in other languages' # - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching. @@ -202,6 +202,7 @@ if long-computation() -> $result { 'key' ~~ %hash; # true if key exists in hash $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an argument, returns True 1 ~~ Int; # "is of type" +1 ~~ True; # smart-matching against a boolean always returns that boolean (and will warn). # - `===` is value identity and uses `.WHICH` on the objects to compare them # - `=:=` is container identity and uses `VAR()` on the objects to compare them @@ -323,7 +324,38 @@ map({ $^a + $^b + 3 }, @array); # same as the above # Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $ b / $a }` - +### Scoping +# In Perl 6, contrarily to many scripting languages (Python, Ruby, PHP, for example), +# you are to declare your variables before using them. You already saw it, with `my`. +# (there are other declarator keywords, like `our`, `has` and `state`, but we'll talk about them later) +# This is called "lexical scoping", where in inner blocks, you can access variables from outer blocks. +my $foo = 'Foo'; +sub foo { + my $bar = 'Bar'; + sub bar { + say "$foo $bar"; + } + &bar; # return the function +} +foo()(); #=> 'Foo Bar' + +# As you can see, `$foo` and `$bar` were captured. +# But if we were to try and use `$bar` outside of `foo`, the variable would be undefined. +# (and you'd get a compile time error) + +# Perl 6 has another kind of scope : dynamic scope. +# They use the twigil (composed sigil) `*` to mark dynamically-scoped variables: +my $*a = 1; +# Dyamically-scoped variables depend on the current call stack, instead of the current block stack. +sub foo { + my $*foo = 1; + bar(); # call `bar` in-place +} +sub bar { + say $*foo; # Perl 6 will look into the call stack instead, and find `foo`'s `$*a`, + # even though the blocks aren't nested (they're call-nested). + #=> 1 +} ### Object Model @@ -440,6 +472,28 @@ die X::AdHoc.new(payload => 'Error !'); # TODO fail # TODO CONTROL +### Packages +# Packages play a big part in a language, and Perl is well-known for CPAN, +# the Comprehensive Perl Archive Network. +# You can declare a mdule using the `module` keyword, and they can be nested: +module Hello::World { # bracketed form + # declarations here +} +module Parse::Text; # file-scoped form + +# You can use a module (bring its declarations into scope) with `use` +use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module +say from-json('[1]').perl; #=> [1] + +# Any class, role, is also a module +my $actions = JSON::Tiny::Actions.new; + +# We'll see how to export variables and subs in the next part: + +### Declarators +TODO: my, our, state, constant. + + ### Phasers # Phasers in Perl 6 are blocks that happen at determined points of time in your program # When the program is compiled, when a for loop runs, when you leave a block, when @@ -521,22 +575,47 @@ $obj eqv $obj2; # sort comparison using eqv semantics 3 before 4; # True 'b' after 'a'; # True +## * Short-circuit default operator +# Like `or` and `||`, but instead returns the first *defined* value : +say Any // Nil // 0 // 5; #=> 5 + +## * Short-circuit exclusive or (XOR) +# Returns `True` if one (and only one) of its arguments is true +say True ^^ False; #=> True + ## * Flip Flop -# The flip flop operator (spelled `ff` in Perl 6 and sometimes `..` in other languages such as Perl 5 and Ruby), -# is an operator that takes two boolean values (like a predicate) and keep track of their change as internal state. -# The flip-flop will return `false` until its left side return true, then return true until its right side return true. -# You can also exclude either side (iteration when the left side became true, or the right side became true), -# using the `^` like with ranges. +# The flip flop operators (`ff` and `fff`, equivalent to Perl 5/Ruby's `..` and `...`). +# are operators that take two predicates to test: +# They are `False` until their left side returns `True`, then are `True` until their right side returns `True`. +# Like for ranges, you can exclude the iteration when it became `True`/`False` by using `^` on either side. # Let's start with an example : for { - if $_ eq 'met' ^ff $_ eq 'meet' { # excludes "met" + # by default, `ff`/`fff` smart-match (`~~`) against `$_`: + if 'met' ^ff 'meet' { # won't enter the if for "met" (explained in details below). .say } + + if rand == 0 ff rand == 1 { # compare variables other than `$_` + say "This ... probably will never run ..."; + } } # This will print "young hero we shall meet" (excluding "met"): # the flip-flop will start returning `True` when it first encounters "met" # (but will still return `False` for "met" itself, due to the leading `^` on `ff`), # until it sees "meet", which is when it'll start returning `False`. + +# The difference between `ff` (flip-flop) and `fff` (flip-flop) is that +# `ff` will test its right side just as its left side changes to `True`, +# and can get back to `False` right away (*except* it'll be `True` for the iteration that matched) +# while `fff` will wait for the next iteration to try its right side, once its left side changed: +.say if 'B' ff 'B' for ; #=> B B + # because the right-hand-side was tested directly (and returned `True`). + # "B"s are still printed since it matched that time + # (it just went back to `False` right away) +.say if 'B' fff 'B' for ; #=> B C B + # because the right-hand-side wasn't tested until `$_` became "C" + # (and thus did not match directly). + # A flip-flop can change state as many times as needed: for { .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", -- cgit v1.2.3 From 3aa5f6aaaff181ebf2b1762326ec1f6e286dd3b9 Mon Sep 17 00:00:00 2001 From: Akira Hirose Date: Tue, 22 Jul 2014 15:49:20 +0900 Subject: translation finished. --- ja-jp/r-jp.html.markdown | 212 +++++++++++++++++++++++------------------------ 1 file changed, 103 insertions(+), 109 deletions(-) diff --git a/ja-jp/r-jp.html.markdown b/ja-jp/r-jp.html.markdown index 66c451dd..0ef6bddf 100644 --- a/ja-jp/r-jp.html.markdown +++ b/ja-jp/r-jp.html.markdown @@ -4,7 +4,7 @@ contributors: - ["e99n09", "http://github.com/e99n09"] - ["isomorphismes", "http://twitter.com/isomorphisms"] translators: - - ["akirahirose", "https://www.facebook.com/akira.hirose"] + - ["akirahirose", "https://twitter.com/akirahirose"] filename: learnr-jp.r lang: ja-jp --- @@ -180,10 +180,10 @@ rnorm(9) # 整数型 -# 整数型の長さは、Lで指定します +# 整数型はLで指定します 5L # 5 class(5L) # "integer" -# (?class を実行すると、class()関数についてさらなる情報が得られます) +# (?class を実行すると、class()関数について、さらなる情報が得られます) # Rでは、この5Lのような単一の値は、長さ1のベクトルとして扱われます length(5L) # 1 # 整数型のベクトルはこのようにつくります @@ -196,7 +196,7 @@ class(c(4L, 5L, 8L, 3L)) # "integer" # 倍精度浮動小数点数です 5 # 5 class(5) # "numeric" -# くどいですが、すべてはベクトルです +# しつこいですが、すべてはベクトルです # 1つ以上の要素がある数字のベクトルも、作ることができます c(3,3,3,2,2,1) # 3 3 3 2 2 1 # 指数表記もできます @@ -218,7 +218,7 @@ class(-Inf) # "numeric" 2.0 * 2L # 4 # 数字かける整数は数字 3L / 4 # 0.75 # 整数割る数字は数字 3 %% 2 # 1 # 二つの数字を割った余りは数字 -# 不正な計算は "not-a-number"になる +# 不正な計算は "not-a-number"になります 0 / 0 # NaN class(NaN) # "numeric" # 長さが1より大きなベクター同士で計算ができます @@ -231,12 +231,12 @@ c(1,2,3) + c(1,2,3) # 2 4 6 class("Horatio") # "character" class('H') # "character" # 上記は両方とも、長さ1のベクターです -# 以下は、より長いものです +# 以下は、より長い場合です c('alef', 'bet', 'gimmel', 'dalet', 'he') # => # "alef" "bet" "gimmel" "dalet" "he" length(c("Call","me","Ishmael")) # 3 -# 正規表現処理を文字ベクターに使えます +# 正規表現処理を文字ベクターに適用できます substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." # Rはいくつかの文字ベクターを組み込みで持っています @@ -251,7 +251,7 @@ month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "D # Rでは、Booleanは論理(logical)型です class(TRUE) # "logical" class(FALSE) # "logical" -# 以下は正しい動きです +# 以下は比較演算子の例です TRUE == TRUE # TRUE TRUE == FALSE # FALSE FALSE != FALSE # FALSE @@ -264,7 +264,7 @@ c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE # ファクター -# ファクタークラスは、カテゴリカルデータようのクラスです +# ファクタークラスは、カテゴリカルデータ用のクラスです # ファクターは、子供の学年のように順序がつけられるものか、性別のように順序がないものがあります factor(c("female", "female", "male", "NA", "female")) # female female male NA female @@ -280,7 +280,7 @@ levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" # NULL -# "NULL" は変わった型です。ベクターを空にするときに使います +# "NULL" は特殊な型なのですが、ベクターを空にするときに使います class(NULL) # NULL parakeet # => @@ -292,7 +292,7 @@ parakeet # 型の強制 -# 型の強制は、ある値を、強制的にある型として利用する事です +# 型の強制とは、ある値を、強制的に別の型として利用する事です as.character(c(6, 8)) # "6" "8" as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE # さまざまな要素が入っているベクターに対して型の強制を行うと、おかしなことになります @@ -327,7 +327,7 @@ as.numeric("Bilbo") # 代入する方法はいろいろあります x = 5 # これはできます y <- "1" # これがおすすめです -TRUE -> z # これも使えますが、変です +TRUE -> z # これも使えますが、ちょっとわかりにくいですね # ループ @@ -342,8 +342,8 @@ while (a > 4) { a <- a - 1 } # Rでは、forやwhileは遅いことを覚えておいてください -# 処理を行う場合は、ベクター丸ごと処理する(つまり、行全体や、列全体)を指定して行うか、 -# 後述する、apply()系の関数を使うのがお勧めです +# ベクターを丸ごと処理する(つまり、行全体や、列全体を指定して処理する)か、 +# 後述する、apply()系の関数を使うのが、速度的にはお勧めです # IF/ELSE @@ -363,7 +363,7 @@ jiggle <- function(x) { x = x + rnorm(1, sd=.1) #すこしだけ(制御された)ノイズを入れます return(x) } -# 他のR関数と同じように呼びます +# 他の関数と同じように、呼びます jiggle(5) # 5±ε. set.seed(2716057)をすると、jiggle(5)==5.005043 @@ -394,24 +394,24 @@ which(vec %% 2 == 0) # 1 3 # 最初か最後の数個を取り出すこともできます head(vec, 1) # 8 tail(vec, 2) # 10 11 -# or figure out if a certain value is in the vector +# ある値がベクターにあるかどうかをみることができます any(vec == 10) # TRUE -# If an index "goes over" you'll get NA: +# ベクターの数より大きなインデックスを指定すると、NAが返ります vec[6] # NA -# You can find the length of your vector with length() +# ベクターの長さは、length()で取得できます length(vec) # 4 -# You can perform operations on entire vectors or subsets of vectors +# ベクター全体、または一部に対して、操作ができます vec * 4 # 16 20 24 28 vec[2:3] * 5 # 25 30 any(vec[2:3] == 8) # FALSE -# and R has many built-in functions to summarize vectors +# R には、ベクターにある値を要約するための様々な関数があります mean(vec) # 9.5 var(vec) # 1.666667 sd(vec) # 1.290994 max(vec) # 11 min(vec) # 8 sum(vec) # 38 -# Some more nice built-ins: +# 他にも、ベクター関連ではいろいろな関数があります 5:15 # 5 6 7 8 9 10 11 12 13 14 15 seq(from=0, to=31337, by=1337) # => @@ -419,10 +419,10 @@ seq(from=0, to=31337, by=1337) # [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 -# TWO-DIMENSIONAL (ALL ONE CLASS) +# 2次元配列 (すべての値が同じ型の場合) -# You can make a matrix out of entries all of the same type like so: +# 同じ型の値が含まれる配列は、このように作れます mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) mat # => @@ -430,17 +430,17 @@ mat # [1,] 1 4 # [2,] 2 5 # [3,] 3 6 -# Unlike a vector, the class of a matrix is "matrix", no matter what's in it +# ベクターとは違い、配列のクラス名は"matrix"です。 class(mat) # => "matrix" -# Ask for the first row +# 最初の行 mat[1,] # 1 4 -# Perform operation on the first column +# 最初の列に対する操作 3 * mat[,1] # 3 6 9 -# Ask for a specific cell +# 特定のセルを取り出し mat[3,2] # 6 -# Transpose the whole matrix +# 配列全体を転置します t(mat) # => # [,1] [,2] [,3] @@ -448,7 +448,7 @@ t(mat) # [2,] 4 5 6 -# Matrix multiplication +# 配列の積 mat %*% t(mat) # => # [,1] [,2] [,3] @@ -457,7 +457,7 @@ mat %*% t(mat) # [3,] 27 36 45 -# cbind() sticks vectors together column-wise to make a matrix +# cbind() は、複数のベクターを、別々の列に並べて配列を作ります mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) mat2 # => @@ -467,34 +467,33 @@ mat2 # [3,] "3" "bird" # [4,] "4" "dog" class(mat2) # matrix -# Again, note what happened! -# Because matrices must contain entries all of the same class, -# everything got converted to the character class +# ここでいま一度、型について注意してください! +# 配列にある値は、すべて同じ型にする必要があります。そのため、すべて文字型に変換されています c(class(mat2[,1]), class(mat2[,2])) -# rbind() sticks vectors together row-wise to make a matrix +# rbind() は、複数のベクターを、別々の行に並べて配列を作ります mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) mat3 # => # [,1] [,2] [,3] [,4] # [1,] 1 2 4 5 # [2,] 6 7 0 4 -# Ah, everything of the same class. No coercions. Much better. +# 全ての値は同じ型になります。この例の場合は、強制変換がされないのでよかったです -# TWO-DIMENSIONAL (DIFFERENT CLASSES) +# 2次元配列 (いろいろな型を含む場合) -# For columns of different types, use a data frame -# This data structure is so useful for statistical programming, -# a version of it was added to Python in the package "pandas". +# 異なる型の値を含む配列をつくりたい場合、データフレームを使ってください +# データフレームは、統計処理を行うプログラムをする際にとても便利です +# Pythonでも、 "pandas"というパッケージにて、似たものが利用可能です students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), c(3,2,2,1,0,-1), c("H", "G", "G", "R", "S", "G")) -names(students) <- c("name", "year", "house") # name the columns +names(students) <- c("name", "year", "house") #カラム名 class(students) # "data.frame" students # => @@ -507,29 +506,28 @@ students # 6 Ginny -1 G class(students$year) # "numeric" class(students[,3]) # "factor" -# find the dimensions +# 次元の数をみます nrow(students) # 6 ncol(students) # 3 dim(students) # 6 3 -# The data.frame() function converts character vectors to factor vectors -# by default; turn this off by setting stringsAsFactors = FALSE when -# you create the data.frame +# このdata.frame() 関数は、デフォルトでは文字列ベクターをファクターのベクターに変換します +# stringsAsFactors = FALSE に設定してからデータフレームを作成すると、変換されません ?data.frame -# There are many twisty ways to subset data frames, all subtly unalike +# データフレームの一部を取り出すには、いろいろな(変な)、似たような方法があります students$year # 3 2 2 1 0 -1 students[,2] # 3 2 2 1 0 -1 students[,"year"] # 3 2 2 1 0 -1 -# An augmented version of the data.frame structure is the data.table -# If you're working with huge or panel data, or need to merge a few data -# sets, data.table can be a good choice. Here's a whirlwind tour: -install.packages("data.table") # download the package from CRAN -require(data.table) # load it +# データフレームの拡張版が、データテーブルです。 +# 大きなデータやパネルデータ、データセットの結合が必要な場合には、データテーブルを使うべきです。 +# 以下に駆け足で説明します +install.packages("data.table") # CRANからパッケージをダウンロードします +require(data.table) # ロードします students <- as.data.table(students) -students # note the slightly different print-out +students # 若干異なる出力がされることに注意 # => # name year house # 1: Cedric 3 H @@ -538,17 +536,17 @@ students # note the slightly different print-out # 4: Cho 1 R # 5: Draco 0 S # 6: Ginny -1 G -students[name=="Ginny"] # get rows with name == "Ginny" +students[name=="Ginny"] # name == "Ginny"の行を取り出します # => # name year house # 1: Ginny -1 G -students[year==2] # get rows with year == 2 +students[year==2] # year == 2の行を取り出します # => # name year house # 1: Fred 2 G # 2: George 2 G -# data.table makes merging two data sets easy -# let's make another data.table to merge with students +# データテーブルは、二つのデータセットを結合するのにも便利です +# 結合用に、生徒データが入った別のデータテーブルをつくります founders <- data.table(house=c("G","H","R","S"), founder=c("Godric","Helga","Rowena","Salazar")) founders @@ -560,7 +558,7 @@ founders # 4: S Salazar setkey(students, house) setkey(founders, house) -students <- founders[students] # merge the two data sets by matching "house" +students <- founders[students] # 二つのデータテーブルを、"house"をキーとして結合します setnames(students, c("house","houseFounderName","studentName","year")) students[,order(c("name","year","house","houseFounderName")), with=F] # => @@ -573,7 +571,7 @@ students[,order(c("name","year","house","houseFounderName")), with=F] # 6: Draco 0 S Salazar -# data.table makes summary tables easy +# データテーブルは、要約を作るのも簡単です students[,sum(year),by=house] # => # house V1 @@ -583,8 +581,7 @@ students[,sum(year),by=house] # 4: S 0 -# To drop a column from a data.frame or data.table, -# assign it the NULL value +# データフレームやデータテーブルから列を消したい場合は、NULL値を代入します students$houseFounderName <- NULL students # => @@ -597,8 +594,7 @@ students # 6: Draco 0 S -# Drop a row by subsetting -# Using data.table: +# 行を消す場合は、データテーブルから、一部を除くことによってできます students[studentName != "Draco"] # => # house studentName year @@ -607,7 +603,7 @@ students[studentName != "Draco"] # 3: G Ginny -1 # 4: H Cedric 3 # 5: R Cho 1 -# Using data.frame: +# データフレームの場合も同様 students <- as.data.frame(students) students[students$house != "G",] # => @@ -617,18 +613,18 @@ students[students$house != "G",] # 6 S Salazar Draco 0 -# MULTI-DIMENSIONAL (ALL ELEMENTS OF ONE TYPE) +# 多次元 (すべての値が同じ型の場合) -# Arrays creates n-dimensional tables -# All elements must be of the same type -# You can make a two-dimensional table (sort of like a matrix) +# 配列でN次元の表を作ります +# すべての値は同じ型にする必要があります +# この方法で、配列のような2次元表も作成可能です array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) # => # [,1] [,2] [,3] [,4] # [1,] 1 4 8 3 # [2,] 2 5 9 6 -# You can use array to make three-dimensional matrices too +# 配列から3次元行列を作ることもできます array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # => # , , 1 @@ -646,58 +642,56 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # [3,] 0 847 -# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES) +# リスト(多次元、不完全なのか複数の型が使われているもの) -# Finally, R has lists (of vectors) +# ついにRのリストです list1 <- list(time = 1:40) list1$price = c(rnorm(40,.5*list1$time,4)) # random list1 -# You can get items in the list like so -list1$time # one way -list1[["time"]] # another way -list1[[1]] # yet another way +# リストの要素は以下のようにして取得できます +list1$time # ある方法 +list1[["time"]] # 別の方法 +list1[[1]] # また別の方法 # => # [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 # [34] 34 35 36 37 38 39 40 -# You can subset list items like any other vector +# 他のベクターと同じく、一部を取り出すことができます list1$price[4] -# Lists are not the most efficient data structure to work with in R; -# unless you have a very good reason, you should stick to data.frames -# Lists are often returned by functions that perform linear regressions +# リストは、Rで一番効率的なデータ型ではありません +# なにか特別な理由がない限りは、データフレームを使い続けるべきです +# リストは、線形回帰関数の返値として、しばしば使われます ################################################## -# The apply() family of functions +# apply() 系の関数 ################################################## -# Remember mat? +# matは覚えていますよね? mat # => # [,1] [,2] # [1,] 1 4 # [2,] 2 5 # [3,] 3 6 -# Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X -# over rows (MAR = 1) or columns (MAR = 2) -# That is, R does FUN to each row (or column) of X, much faster than a -# for or while loop would do +# apply(X, MARGIN, FUN) は、行列Xの行(MARGIN=1)または列(MARGIN=2)に対して、関数FUNを実行します +# RでこのようにXの全行か全列に関数を実行すると、forやwhileループを使うより、遥かに速くできます apply(mat, MAR = 2, jiggle) # => # [,1] [,2] # [1,] 3 15 # [2,] 7 19 # [3,] 11 23 -# Other functions: ?lapply, ?sapply +# 他にも関数があります。?lapply, ?sapply で確認してみてください -# Don't feel too intimidated; everyone agrees they are rather confusing +# このやり方がちょっとややこしいという事は、みんな同意です。なので、あまり怖がりすぎないでください -# The plyr package aims to replace (and improve upon!) the *apply() family. +# plyr パッケージは、*apply() 系の関数を置き換えて(さらに改善して)いこうとしています install.packages("plyr") require(plyr) ?plyr @@ -708,24 +702,24 @@ require(plyr) ######################### -# Loading data +# データロード ######################### -# "pets.csv" is a file on the internet -# (but it could just as easily be be a file on your own computer) +# "pets.csv"は、インターネット上に置いてあるファイルです +# (しかし、自分のPCにあるのと同じぐらい簡単に扱う事ができます) pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") pets -head(pets, 2) # first two rows -tail(pets, 1) # last row +head(pets, 2) # 最初の2行 +tail(pets, 1) # 最後の行 -# To save a data frame or matrix as a .csv file -write.csv(pets, "pets2.csv") # to make a new .csv file -# set working directory with setwd(), look it up with getwd() +# データフレームか行列をcsvファイルとして保存します +write.csv(pets, "pets2.csv") # 新しくcsvファイルを作ります +# ワーキングディレクトリを、setwd()で設定します。 ワーキングディレクトリは getwd()で確認可能です -# Try ?read.csv and ?write.csv for more information +# ?read.csv や ?write.csv を入力すると、よりたくさんの情報を確認できます @@ -733,29 +727,29 @@ write.csv(pets, "pets2.csv") # to make a new .csv file ######################### -# Plots +# プロット ######################### -# BUILT-IN PLOTTING FUNCTIONS -# Scatterplots! +# 組み込みのプロット関数です +# 散布図です! plot(list1$time, list1$price, main = "fake data") -# Regressions! +# 回帰図です! linearModel <- lm(price ~ time, data = list1) linearModel # outputs result of regression -# Plot regression line on existing plot +# 回帰直線を既存の図上に引きます abline(linearModel, col = "red") -# Get a variety of nice diagnostics +# いろいろな診断方法を見ましょう plot(linearModel) -# Histograms! +# ヒストグラムです! hist(rpois(n = 10000, lambda = 5), col = "thistle") -# Barplots! +# 棒グラフです! barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) # GGPLOT2 -# But these are not even the prettiest of R's plots -# Try the ggplot2 package for more and better graphics +# 上記よりも、もっときれいな図を描くこともできます +# より多くよい図を描くために、ggplot2 パッケージを使ってみましょう install.packages("ggplot2") require(ggplot2) ?ggplot2 @@ -764,7 +758,7 @@ pp + geom_histogram() ll <- as.data.table(list1) pp <- ggplot(ll, aes(x=time,price)) pp + geom_point() -# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/) +# ggplot2 には、素晴らしい関連ドキュメントがそろっています (http://docs.ggplot2.org/current/) @@ -774,8 +768,8 @@ pp + geom_point() ``` -## How do I get R? +## Rの入手方法 -* Get R and the R GUI from [http://www.r-project.org/](http://www.r-project.org/) -* [RStudio](http://www.rstudio.com/ide/) is another GUI \ No newline at end of file +* RとR GUIはこちら [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) はまた別のGUIです \ No newline at end of file -- cgit v1.2.3 From cf3ea24d41cade2420c85c54e71228561f43b354 Mon Sep 17 00:00:00 2001 From: Amar Sood Date: Tue, 22 Jul 2014 13:06:18 +0100 Subject: Fix 'filename' collision between csharp{,-fr}.html.markdown Both were set to LearnCSharp.cs, so the live site has been serving the French version for English. (see set_rawcode: https://github.com/adambard/learnxinyminutes-site/blob/547a620dd8dc78f8518b0072e456ae2d384a0465/config.rb#L103) --- fr-fr/csharp-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown index c1641716..e51eacc8 100644 --- a/fr-fr/csharp-fr.html.markdown +++ b/fr-fr/csharp-fr.html.markdown @@ -7,7 +7,7 @@ contributors: - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] translators: - ["Olivier Hoarau", "https://github.com/Olwaro"] -filename: LearnCSharp.cs +filename: LearnCSharp-fr.cs lang: fr-fr --- -- cgit v1.2.3 From 1d931a37f2d428bc2d783f1a8597455db70a23de Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Tue, 22 Jul 2014 22:55:27 +0200 Subject: Declarators mention the six model clearer description of package/module etc clearer description of `$.` vs `$!` --- perl6.html.markdown | 97 +++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 80 insertions(+), 17 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 70799b29..5ead6560 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -360,29 +360,27 @@ sub bar { ### Object Model ## Perl 6 has a quite comprehensive object model -## You declare a class with the keyword `class`, fields with `has`, methods with `method` -## `$.` declares a public field, `$!` declares a private field -## (a public field also has `$!`, which is its private interface) +## You declare a class with the keyword `class`, fields with `has`, methods with `method`. +## In Perl 6, every field is private, and named `$!attr`, but if you declare it with `$.`, +## you get a public (immutable) accessor along with it. # (Perl 6's object model ("P6Model") is very flexible, and allows you to dynamically add methods, # change semantics, etc -- This will not be covered here, and you should refer to the Synopsis) class A { - has $.field; + has $.field; # `$.field` is immutable. Use `$!field` from inside the class to modify it. + has $.other-field is rw; # You can, however, mark a public field as being read/write. has Int $!private-field = 10; - + method get-value { $.field + $!private-field + $n; } method set-value($n) { - # $.field = $n; # This fails, because a public field is actually an immutable container - # (even from inside the class) - # You either need to use `is rw` on the `has` - # (which will make it mutable, even from outside the class) - # or you need to use the `$!` version : - - $!field = $n; # This works, because `$!` is always mutable + # $.field = $n; # As stated before, you can't use the `$.` immutable version. + $!field = $n; # This works, because `$!` is always mutable. + + $.other-field = 5; # This works, because `$.other-field` was declared `rw` (mutable). } method !private-method { @@ -394,7 +392,8 @@ class A { # note : you can't set private-field from here (more later on) my $a = A.new(field => 5); $a.get-value; #=> 18 -#$a.field = 5; # This fails, because the `has $.field` is lacking the `is rw` +#$a.field = 5; # This fails, because the `has $.field` is immutable +$a.other-field = 10; # This, however, works, because the public field is mutable (`rw`). ## Perl 6 also has inheritance (along with multiple inheritance ... Considered a misfeature by many) @@ -473,25 +472,89 @@ die X::AdHoc.new(payload => 'Error !'); # TODO CONTROL ### Packages -# Packages play a big part in a language, and Perl is well-known for CPAN, +# Packages are a way to reuse code. Packages are like "namespaces", and any element of the six model +# (`module`, `role`, `class`, `grammar`, `subset` and `enum`) are actually packages. +# (you can say that packages are the lowest common denomitor between them) +# Packages play a big part in a language, as Perl is well-known for CPAN, # the Comprehensive Perl Archive Network. -# You can declare a mdule using the `module` keyword, and they can be nested: +# You usually don't use packages directly : you use `class Package::Name::Here;`, or if you +# only want to export variables/subs, you can use `module`: module Hello::World { # bracketed form + # if `Hello` doesn't exist yet, it'll just be created as an "empty package stub" + # that can be redeclared as something else later. # declarations here } module Parse::Text; # file-scoped form +grammar Parse::Text::Grammar { # A grammar is a fine package, which you could `use` +} + +# NOTE for Perl 5 users: even though the `package` keyword exists, +# the braceless form is invalid (to catch a "perl5ism"). This will error out: +# package Foo; # because Perl 6 will think the entire file is Perl 5 +# Just use `module` or the brace version of `package`. # You can use a module (bring its declarations into scope) with `use` use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module say from-json('[1]').perl; #=> [1] -# Any class, role, is also a module +# As said before, any part of the six model is also a package. +# Since `JSON::Tiny` uses (its own) `JSON::Tiny::Actions` class, you can use it: my $actions = JSON::Tiny::Actions.new; # We'll see how to export variables and subs in the next part: ### Declarators -TODO: my, our, state, constant. +# In Perl 6, you get different behaviors based on how you declare a variable. +# You've already seen `my` and `has`, we'll now explore the others. + +## * `our` (happens at `INIT` time -- see "Phasers" below) +# Along with `my`, there are several others declarators you can use. +# The first one you'll want for the previous part is `our`. +# (All packagish things (`class`, `role`, etc) are `our` by default) +# it's like `my`, but it also creates a package variable: +module Foo::Bar { + our $n = 1; # note: you can't put a type constraint on an `our` variable + our sub inc { + our sub available { # if you try to make scoped `sub`s `our` ... Better know what you're doing (Don't !). + say "Don't do that. Seriously. You'd get burned."; + } + my sub unavailable { # `my sub` is the default + say "Can't access me from outside, I'm my !"; + } + } + + say ++$n; # lexically-scoped variables are still available +} +say $Foo::Bar::n; #=> 1 +Foo::Bar::inc; #=> 2 +Foo::Bar::inc; #=> 3 + +## * `constant` (happens at `BEGIN` time) +# You can use the `constant` keyword to declare a compile-time variable/symbol: +constant Pi = 3.14; +constant $var = 1; + +## * `state` (happens at run time, but only once) +# State variables are only executed one time +# (they exist in other langages such as C as `static`) +sub fixed-rand { + state $val = rand; + say $rand; +} +fixed-rand for ^10; # will print the same number 10 times + +# Note, however, that they exist separately in different enclosing contexts. +# If you declare a function with a `state` within a loop, it'll re-create the variable +# for each iteration of loop. See: +for ^5 -> $a { + sub foo { + state $val = rand; # This will be a different value for every value of `$a` + } + for ^5 -> $b { + say foo; # This will print the same value 5 times, but only 5. Next iteration will re-run `rand` + } +} + ### Phasers -- cgit v1.2.3 From 2f29a176cfa52b7236aad4c0e2fa1d338c1fc8ac Mon Sep 17 00:00:00 2001 From: Akira Hirose Date: Wed, 23 Jul 2014 10:43:05 +0900 Subject: Updated the Japanese comment to be more understandable. --- ja-jp/r-jp.html.markdown | 106 +++++++++++++++++++++++------------------------ 1 file changed, 53 insertions(+), 53 deletions(-) diff --git a/ja-jp/r-jp.html.markdown b/ja-jp/r-jp.html.markdown index 0ef6bddf..3e6621f5 100644 --- a/ja-jp/r-jp.html.markdown +++ b/ja-jp/r-jp.html.markdown @@ -11,18 +11,18 @@ lang: ja-jp R は統計計算用の言語です。 -データの取得やクリーニング、統計処理やグラフ作成をするために使える、たくさんのライブラリがあります。また、LaTeX文書からRコマンドを呼び出すこともできます。 +データの取得やクリーニング、統計処理やグラフ作成をするために便利な、たくさんのライブラリがあります。また、LaTeX文書からRコマンドを呼び出すこともできます ```python # コメント行は、#で開始します -# コメントを複数の行に分けたい場合は、 -# このように、コメント行を複数連続させるとできます +# 複数行をまとめてコメントにすることはできないので、 +# コメントを複数の行に分けたい場合、このように、単に毎行をコメントにしてください -# WindowsやMacでは、 COMMAND-ENTERで1行のコマンド実行ができます +# WindowsやMacでは、 COMMAND-ENTERで、コマンドを1行実行できます @@ -79,7 +79,7 @@ stem(rivers) # 36 | 1 -stem(log(rivers)) # このデータは、正規分布でも対数正規分布でもないので注意! +stem(log(rivers)) # このデータは、正規分布でも対数正規分布でもないので、注意! # 特に正規分布原理主義のみなさん @@ -175,8 +175,8 @@ rnorm(9) # ここからは、プログラミングをつかうチュートリアルです -# この節ではRで重要なデータ型の、整数型、数字型、文字型、論理型と因子型をつかいます -# 他にもいろいろありますが、まずは最小限必要な、これらから始めましょう +# この節ではRで重要なデータ型(データクラス)の、整数型、数字型、文字型、論理型と因子(ファクター)型をつかいます +# 他にもいろいろありますが、これらの必要最小限なものから始めましょう # 整数型 @@ -184,7 +184,7 @@ rnorm(9) 5L # 5 class(5L) # "integer" # (?class を実行すると、class()関数について、さらなる情報が得られます) -# Rでは、この5Lのような単一の値は、長さ1のベクトルとして扱われます +# Rでは、この5Lのような1つの値は、長さ1のベクトルとして扱われます length(5L) # 1 # 整数型のベクトルはこのようにつくります c(4L, 5L, 8L, 3L) # 4 5 8 3 @@ -221,7 +221,7 @@ class(-Inf) # "numeric" # 不正な計算は "not-a-number"になります 0 / 0 # NaN class(NaN) # "numeric" -# 長さが1より大きなベクター同士で計算ができます +# 長さが1より大きなベクター同士の計算もできます # どちらかが長い場合、短い方は何度も繰り返して使われます c(1,2,3) + c(1,2,3) # 2 4 6 @@ -263,18 +263,18 @@ c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE -# ファクター -# ファクタークラスは、カテゴリカルデータ用のクラスです -# ファクターは、子供の学年のように順序がつけられるものか、性別のように順序がないものがあります +# 因子(ファクター) +# 因子型は、カテゴリカルデータ用の型です +# 因子には、子供の学年のように順序がつけられるものか、性別のように順序がないものがあります factor(c("female", "female", "male", "NA", "female")) # female female male NA female # Levels: female male NA # "levels" は、カテゴリカルデータがとりうる値を返します levels(factor(c("male", "male", "female", "NA", "female"))) # "female" "male" "NA" -# ファクターベクターの長さが1ならば、そのlevelも1です +# 因子ベクターの長さが1ならば、そのlevelも1です length(factor("male")) # 1 length(levels(factor("male"))) # 1 -# ファクターは、この後で紹介するデータフレーム(というデータ型)内で、よくみられます +# 因子型は、この後で紹介するデータフレーム(というデータ型)内で、よくみられます data(infert) # "Infertility after Spontaneous and Induced Abortion" levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" @@ -379,7 +379,7 @@ jiggle(5) # 5±ε. set.seed(2716057)をすると、jiggle(5)==5.005043 # 1次元 -# まずは基本からです。すでにご存じのベクターからです +# まずは基本からです。ご存じベクターからです vec <- c(8, 9, 10, 11) vec # 8 9 10 11 # 特定の要素を、[角括弧]による指定で取り出せます @@ -400,7 +400,7 @@ any(vec == 10) # TRUE vec[6] # NA # ベクターの長さは、length()で取得できます length(vec) # 4 -# ベクター全体、または一部に対して、操作ができます +# ベクター全体、または1部に対して、操作ができます vec * 4 # 16 20 24 28 vec[2:3] * 5 # 25 30 any(vec[2:3] == 8) # FALSE @@ -411,7 +411,7 @@ sd(vec) # 1.290994 max(vec) # 11 min(vec) # 8 sum(vec) # 38 -# 他にも、ベクター関連ではいろいろな関数があります +# 他にも、ベクター関連ではいろいろな関数があります。以下はベクターをつくるための方法です 5:15 # 5 6 7 8 9 10 11 12 13 14 15 seq(from=0, to=31337, by=1337) # => @@ -422,7 +422,7 @@ seq(from=0, to=31337, by=1337) # 2次元配列 (すべての値が同じ型の場合) -# 同じ型の値が含まれる配列は、このように作れます +# 同じ型の値が含まれる2次元配列は、このように作れます mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) mat # => @@ -430,7 +430,7 @@ mat # [1,] 1 4 # [2,] 2 5 # [3,] 3 6 -# ベクターとは違い、配列のクラス名は"matrix"です。 +# ベクターとは違い、2次元配列の型名は"matrix"です。 class(mat) # => "matrix" # 最初の行 mat[1,] # 1 4 @@ -440,7 +440,7 @@ mat[1,] # 1 4 mat[3,2] # 6 -# 配列全体を転置します +# 2次元配列全体を転置します t(mat) # => # [,1] [,2] [,3] @@ -448,7 +448,7 @@ t(mat) # [2,] 4 5 6 -# 配列の積 +# 2次元配列の積 mat %*% t(mat) # => # [,1] [,2] [,3] @@ -457,7 +457,7 @@ mat %*% t(mat) # [3,] 27 36 45 -# cbind() は、複数のベクターを、別々の列に並べて配列を作ります +# cbind() は、複数のベクターを、別々の列に並べて2次元配列を作ります mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) mat2 # => @@ -467,19 +467,19 @@ mat2 # [3,] "3" "bird" # [4,] "4" "dog" class(mat2) # matrix -# ここでいま一度、型について注意してください! -# 配列にある値は、すべて同じ型にする必要があります。そのため、すべて文字型に変換されています +# ここでいま1度、2次元配列内の型について注意してください! +# 2次元配列にある値は、すべて同じ型にする必要があります。そのため、すべて文字型に変換されています c(class(mat2[,1]), class(mat2[,2])) -# rbind() は、複数のベクターを、別々の行に並べて配列を作ります +# rbind() は、複数のベクターを、別々の行に並べて2次元配列を作ります mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) mat3 # => # [,1] [,2] [,3] [,4] # [1,] 1 2 4 5 # [2,] 6 7 0 4 -# 全ての値は同じ型になります。この例の場合は、強制変換がされないのでよかったです +# 全ての値は同じ型になります。上記例は幸い、強制変換がされないものでした # 2次元配列 (いろいろな型を含む場合) @@ -506,16 +506,16 @@ students # 6 Ginny -1 G class(students$year) # "numeric" class(students[,3]) # "factor" -# 次元の数をみます +# 行と列の数をみます nrow(students) # 6 ncol(students) # 3 dim(students) # 6 3 -# このdata.frame() 関数は、デフォルトでは文字列ベクターをファクターのベクターに変換します +# このdata.frame() 関数は、デフォルトでは文字列ベクターを因子ベクターに変換します # stringsAsFactors = FALSE に設定してからデータフレームを作成すると、変換されません ?data.frame -# データフレームの一部を取り出すには、いろいろな(変な)、似たような方法があります +# データフレームの1部を取り出すには、いろいろな(変な)、似たような方法があります students$year # 3 2 2 1 0 -1 students[,2] # 3 2 2 1 0 -1 students[,"year"] # 3 2 2 1 0 -1 @@ -594,7 +594,7 @@ students # 6: Draco 0 S -# 行を消す場合は、データテーブルから、一部を除くことによってできます +# データテーブルから行を消す場合は、以下のように除く行を指定すればできます students[studentName != "Draco"] # => # house studentName year @@ -603,7 +603,7 @@ students[studentName != "Draco"] # 3: G Ginny -1 # 4: H Cedric 3 # 5: R Cho 1 -# データフレームの場合も同様 +# データフレームの場合も同様です students <- as.data.frame(students) students[students$house != "G",] # => @@ -616,15 +616,15 @@ students[students$house != "G",] # 多次元 (すべての値が同じ型の場合) -# 配列でN次元の表を作ります -# すべての値は同じ型にする必要があります -# この方法で、配列のような2次元表も作成可能です +# 配列を並べて、N次元の表を作ります +# 配列なので、すべての値は同じ型にする必要があります +# ちなみに、以下のようにすれば2次元配列・2次元表も作成可能です array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) # => # [,1] [,2] [,3] [,4] # [1,] 1 4 8 3 # [2,] 2 5 9 6 -# 配列から3次元行列を作ることもできます +# 2次元配列を並べて、3次元配列を作ることもできます array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # => # , , 1 @@ -642,7 +642,7 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # [3,] 0 847 -# リスト(多次元、不完全なのか複数の型が使われているもの) +# リスト(多次元、不完全または複数の型が使われているもの) # ついにRのリストです @@ -656,13 +656,13 @@ list1[[1]] # また別の方法 # => # [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 # [34] 34 35 36 37 38 39 40 -# 他のベクターと同じく、一部を取り出すことができます +# 他のベクターと同じく、1部を取り出すことができます list1$price[4] -# リストは、Rで一番効率的なデータ型ではありません -# なにか特別な理由がない限りは、データフレームを使い続けるべきです -# リストは、線形回帰関数の返値として、しばしば使われます +# リストは、Rで1番効率的なデータ型ではありません +# 特別な理由がない限りは、リストの代わりにデータフレームを使うべきです +# リストは、線形回帰関数の返値として、しばしば使われています ################################################## @@ -677,18 +677,18 @@ mat # [1,] 1 4 # [2,] 2 5 # [3,] 3 6 -# apply(X, MARGIN, FUN) は、行列Xの行(MARGIN=1)または列(MARGIN=2)に対して、関数FUNを実行します -# RでこのようにXの全行か全列に関数を実行すると、forやwhileループを使うより、遥かに速くできます +# apply(X, MARGIN, FUN) は、行列Xの行(MARGIN=1で指定)または列(MARGIN=2で指定)に対して、関数FUNを実行します +# Rで、このように指定してXの全行または全列に関数を実行するのは、forやwhileループを使うよりも、遥かに速いです apply(mat, MAR = 2, jiggle) # => # [,1] [,2] # [1,] 3 15 # [2,] 7 19 # [3,] 11 23 -# 他にも関数があります。?lapply, ?sapply で確認してみてください +# 他にも便利な関数があります。?lapply, ?sapply で確認してみてください -# このやり方がちょっとややこしいという事は、みんな同意です。なので、あまり怖がりすぎないでください +# apply()系関数の使い方は、ちょっとややこしいです(みんなそう思ってます)。なので、あまり怖がりすぎないでください # plyr パッケージは、*apply() 系の関数を置き換えて(さらに改善して)いこうとしています @@ -731,25 +731,25 @@ write.csv(pets, "pets2.csv") # 新しくcsvファイルを作ります ######################### -# 組み込みのプロット関数です -# 散布図です! +# Rに組込まれているプロット関数をつかいます +# 散布図! plot(list1$time, list1$price, main = "fake data") -# 回帰図です! +# 回帰図! linearModel <- lm(price ~ time, data = list1) linearModel # outputs result of regression # 回帰直線を既存の図上に引きます abline(linearModel, col = "red") -# いろいろな診断方法を見ましょう +# いろいろな散布図をつくって、確認できます plot(linearModel) -# ヒストグラムです! +# ヒストグラム! hist(rpois(n = 10000, lambda = 5), col = "thistle") -# 棒グラフです! +# 棒グラフ! barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) # GGPLOT2 -# 上記よりも、もっときれいな図を描くこともできます -# より多くよい図を描くために、ggplot2 パッケージを使ってみましょう +# 上記の組込み関数を使うよりも、もっときれいな図を描くこともできます +# ggplot2 パッケージを使って、より多くのよい図を描いてみましょう install.packages("ggplot2") require(ggplot2) ?ggplot2 @@ -772,4 +772,4 @@ pp + geom_point() * RとR GUIはこちら [http://www.r-project.org/](http://www.r-project.org/) -* [RStudio](http://www.rstudio.com/ide/) はまた別のGUIです \ No newline at end of file +* [RStudio](http://www.rstudio.com/ide/) 別のGUI \ No newline at end of file -- cgit v1.2.3 From a472308c38702e026b9d301cdfe6637e54b69346 Mon Sep 17 00:00:00 2001 From: Akira Hirose Date: Wed, 23 Jul 2014 15:15:50 +0900 Subject: bash document Japanese version --- ja-jp/bash-jp.html.markdown | 171 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 ja-jp/bash-jp.html.markdown diff --git a/ja-jp/bash-jp.html.markdown b/ja-jp/bash-jp.html.markdown new file mode 100644 index 00000000..b4d8eaed --- /dev/null +++ b/ja-jp/bash-jp.html.markdown @@ -0,0 +1,171 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] +translators: + - ["akirahirose", "https://twitter.com/akirahirose"] +filename: LearnBash-jp.sh +lang: ja-jp +--- + +Bash はunixシェルの1つです。GNUオペレーションシステムのシェルとして配布されています。LinuxやMac OS Xのデフォルトシェルにもなっています。 +以下にいろいろな例がありますが、ほぼ全部シェルスクリプトの一部として使えます。また、一部はそのままシェルから実行できます。 + +[ちゃんとした説明は、こちらをどうぞ](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# 最初の行はShebang(シェバング、シバン)というもので、システムに対して何を使って実行するのかを教えるためのものです +# ちゃんとした説明、こちらをどうぞ: http://en.wikipedia.org/wiki/Shebang_(Unix) +# 既にお気づきのように、コメント行は#で始まります. Shebangもコメントです + +# まずは Hello world です +echo Hello world! + +# コマンド毎に改行を入れるか、セミコロンで区切ります +echo 'This is the first line'; echo 'This is the second line' + +# 変数の宣言はこのようにやります +VARIABLE="Some string" + +# が、以下のようにやってはダメです +VARIABLE = "Some string" +# このように(空白を入れて)書くと、Bash はVARIABLEを実行するべきコマンドとみなし、実行します。 +# そして、VARIABLEというコマンドはない(はずな)ので、エラーになります + + +# 変数の使い方 +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' +# 変数の値(中身)を使わず、変数名だけを使うとき(代入するときや渡すときなど)は、$なしで変数名を書いてください +# 変数の値(中身)を使うときは、$をつけます +# 上記例の最後にある、' (シングルクォート) で囲んだ場合は、変数の値は表示されません! + +# 変数値の文字列置換 +echo ${VARIABLE/Some/A} +# 最初に出てくる "Some" を "A" で置換します + +# 変数値の一部を取り出します +echo ${VARIABLE:0:7} +# 最初の7文字だけを取り出します + +# デフォルトの変数値設定(訳注:シェル実行時に引数で変数値を設定できるが、設定しなかった場合の値を指定できる) +echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} +# 上記は、FOO番目の引数がnullだったとき(FOO番目=)や、空文字が指定されたとき(FOO番目="")に、変数に0を入れます +# ( 当然ですが、引数に0を指定したとき(FOO番目=0) も、0は入ります) + +# 組込み変数 +# 以下のような便利な組込み変数があります +echo "Last program return value: $?" +echo "Script's PID: $$" +echo "Number of arguments: $#" +echo "Scripts arguments: $@" +echo "Scripts arguments seperated in different variables: $1 $2..." + +# 入力値の読み込み +echo "What's your name?" +read NAME # 新しく変数を宣言する必要はないことに注意 +echo Hello, $NAME! + +# 普通のif文も使えます +# 利用できる判定条件については、'man test' で参照してください +if [ $NAME -ne $USER ] +then + echo "Your name is your username" +else + echo "Your name isn't your username" +fi + +# 他にも、条件判定ができます +echo "Always executed" || echo "Only executed if first command fails" +echo "Always executed" && echo "Only executed if first command does NOT fail" + +# 数式は以下のように書きます +echo $(( 10 + 5 )) + +# 他のプログラム言語とは違ってbashはシェルなので、現在いるディレクトリ位置が異なると、異なる結果になります +# lsコマンドで、現在いるディレクトリにあるファイルと、ディレクトリのリストが取得できます +ls + +# これらのコマンドには、実行オプションがいろいろあります +ls -l # ファイルとディレクトリのリストを行に分けて表示します + +# あるコマンド実行による返値を、次のコマンドの入力値としてつかえます +# 例えばですが、lsコマンドの返値を、grepコマンドによって指定したルールに基づいてフィルタできます。 +# 以下は、現在いるディレクトリにある、.txtファイルのリストを表示する例です +ls -l | grep "\.txt" + +# コマンドに対する入力元や出力先、またエラー出力先などを変更できます +python2 hello.py < "input.in" +python2 hello.py > "output.out" +python2 hello.py 2> "error.err" +# 出力先として指定したファイルが既に存在する場合は、上書きされます +# もしもファイルに追記したい場合は、代わりに">>" を使ってください + +# コマンド文中で、$()内に別コマンドを入れると、その別コマンドの返値をコマンド文の一部として使う事ができます +# 次のコマンドは、現在いるディレクトリにあるファイルの数を表示します +echo "There are $(ls | wc -l) items here." + +# バッククォート(backticks) `` でも同じことができますが、入れ子にはできません +# そのため、$()がお勧めです +echo "There are `ls | wc -l` items here." + +# BashはJavaやC++のように、case文による分岐ができます +case "$VARIABLE" in + #分岐条件として使いたいパターンを並べてください + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# 指定した回数、処理を繰り返し +# 変数の値 $VARIABLE が3回表示されます +for VARIABLE in {1..3} +do + echo "$VARIABLE" +done + +# while ループです +while [true] +do + echo "loop body here..." + break +done + +# 関数の定義もできます +function foo () +{ + echo "Arguments work just like script arguments: $@" + echo "And: $1 $2..." + echo "This is a function" + return 0 +} + +# 以下のように、もっと簡単な書き方もあります +bar () +{ + echo "Another way to declare functions!" + return 0 +} + +# 自作関数を呼びます +foo "My name is" $NAME + +# 他にもいろいろと、知っておくと便利なコマンドがあります +# file.txtの最後10行を表示します +tail -n 10 file.txt +# file.txtの最初10行を表示します +head -n 10 file.txt +# file.txt's の行を並び替えます +sort file.txt +# 重複している行を表示するか、削除できます。-dオプションをつけると、表示します +uniq -d file.txt +# 1行ごとに、','が最初に出てくる前の部分を表示します +cut -d ',' -f 1 file.txt + +``` -- cgit v1.2.3 From 2fb3fc35705689083fd2ebf5b4d2f486607231ad Mon Sep 17 00:00:00 2001 From: Akira Hirose Date: Wed, 23 Jul 2014 15:20:24 +0900 Subject: just an update of Japanese introduction part --- ja-jp/bash-jp.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ja-jp/bash-jp.html.markdown b/ja-jp/bash-jp.html.markdown index b4d8eaed..88e5ff1c 100644 --- a/ja-jp/bash-jp.html.markdown +++ b/ja-jp/bash-jp.html.markdown @@ -12,8 +12,9 @@ filename: LearnBash-jp.sh lang: ja-jp --- -Bash はunixシェルの1つです。GNUオペレーションシステムのシェルとして配布されています。LinuxやMac OS Xのデフォルトシェルにもなっています。 -以下にいろいろな例がありますが、ほぼ全部シェルスクリプトの一部として使えます。また、一部はそのままシェルから実行できます。 +Bash はunixシェルの1つです。GNUオペレーションシステムのシェルとして配布されています。 +LinuxやMac OS Xの、デフォルトシェルにもなっています。 +以下にある例は、ほぼ全部シェルスクリプトの一部として使えます。また、一部はそのままシェルから実行できます。 [ちゃんとした説明は、こちらをどうぞ](http://www.gnu.org/software/bash/manual/bashref.html) -- cgit v1.2.3 From e859a4edde405fc020cccc04a806ea877e26ed75 Mon Sep 17 00:00:00 2001 From: Akira Hirose Date: Wed, 23 Jul 2014 15:32:50 +0900 Subject: just collected the order of comments and commands of last part --- bash.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index d5d08e9d..29b0c8db 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -155,14 +155,14 @@ bar () 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 +tail -n 10 file.txt # prints first 10 lines of file.txt -sort file.txt +head -n 10 file.txt # sort file.txt's lines -uniq -d file.txt +sort file.txt # report or omit repeated lines, with -d it reports them -cut -d ',' -f 1 file.txt +uniq -d file.txt # prints only the first column before the ',' character +cut -d ',' -f 1 file.txt ``` -- cgit v1.2.3 From 4f97478d6beba127180f7f6d3278aef79b901441 Mon Sep 17 00:00:00 2001 From: Akira Hirose Date: Wed, 23 Jul 2014 15:43:18 +0900 Subject: add a contributor line :) --- bash.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/bash.html.markdown b/bash.html.markdown index 29b0c8db..15d1c068 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Darren Lin", "https://github.com/CogBear"] - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] filename: LearnBash.sh --- -- cgit v1.2.3 From c27993c85a9daec2b7152da9de5ee1593a3d3b64 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 23 Jul 2014 13:27:53 -0500 Subject: [json/es] Spanish translation for JSON --- es-es/json-es.html.markdown | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 es-es/json-es.html.markdown diff --git a/es-es/json-es.html.markdown b/es-es/json-es.html.markdown new file mode 100644 index 00000000..c3294636 --- /dev/null +++ b/es-es/json-es.html.markdown @@ -0,0 +1,59 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + -["Daniel Zendejas","https://github.com/DanielZendejas"] +lang: es-es +--- + +Siendo JSON un formato de intercambio de infomación tan sencillo, probablemente este será el Learn X in Y más sencillo jamás. + +JSON en su forma más pura no tiene comentarios, pero la mayoría de los parseadores aceptarán comentarios de C (//, /\* \*/). De todas formas, para el propóstio de esto todo será JSON 100% válido. Por suerte, habla por sí mismo. + +```json + +{ + "llave": "valor", + + "llaves": "siempre debe estar entre comillas (ya sean dobles o simples)", + "numeros": 0, + "strings": "Høla, múndo. Todo el unicode está permitido, así como \"escapar\".", + "soporta booleanos?": true, + "vacios": null, + + "numero grande": 1.2e+100, + + "objetos": { + "comentario": "La mayoria de tu estructura vendra de objetos.", + + "arreglo": [0, 1, 2, 3, "Los arreglos pueden contener cualquier cosa.", 5], + + "otro objeto": { + "comentario": "Estas cosas pueden estar anidadas, muy util." + } + }, + + "tonteria": [ + { + "fuentes de potasio": ["bananas"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "estilo alternativo": { + "comentario": "Mira esto!" + , "posicion de la coma": "no importa - mientras este antes del valor, entonces sera valido" + , "otro comentario": "que lindo" + }, + + "eso fue rapido": "Y, estas listo. Ahora sabes todo lo que JSON tiene para ofrecer." +} +``` -- cgit v1.2.3 From 29858f6845a5b1982b1ba746d0cad4d41240bfa4 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 23 Jul 2014 13:28:55 -0500 Subject: Update json-es.html.markdown --- es-es/json-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/json-es.html.markdown b/es-es/json-es.html.markdown index c3294636..de52f76d 100644 --- a/es-es/json-es.html.markdown +++ b/es-es/json-es.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] translators: - -["Daniel Zendejas","https://github.com/DanielZendejas"] + - ["Daniel Zendejas","https://github.com/DanielZendejas"] lang: es-es --- -- cgit v1.2.3 From b393334dad1e67daf0ffd0fa89681581440868f9 Mon Sep 17 00:00:00 2001 From: Miguel Araujo Date: Wed, 23 Jul 2014 16:26:54 -0300 Subject: translating Markdown to pt-br --- pt-br/markdown-pt.html.markdown | 251 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 251 insertions(+) create mode 100644 pt-br/markdown-pt.html.markdown diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown new file mode 100644 index 00000000..cac4a13e --- /dev/null +++ b/pt-br/markdown-pt.html.markdown @@ -0,0 +1,251 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +filename: learnmarkdown-pt.md +--- + +Markdown foi criado por John Gruber in 2004. Originado para ser fácil de ler e +escrever sintaxe que converte facilmente em HTML (hoje, suporta outros formatos também). + +Dê-me feedback tanto quanto você quiser! / Sinta-se livre para a garfar (fork) e +puxar o projeto (pull request) + +``` + + + + + + +# Isto é um cabeçalho

+## Isto é um cabeçalho

+### Isto é um cabeçalho

+#### Isto é um cabeçalho

+##### Isto é um cabeçalho

+###### Isto é um cabeçalho
+ + +Isto é um cabeçalho h1 +====================== + +Isto é um cabeçalho h2 +---------------------- + + + + +*Este texto está em itálico* +_E este também está._ + +**Este texto está em negrito** +__E este também está._ + +***Este texto está em negrito e itálico.*** +**_E este também está_** +*--Danouse! Este também__* + + + +~~Este texto é processado com tachado.~~ + + + +Este é um parágrafo. Eu estou digitando em um parágrafo, não é legal? + +Agora, eu estou no parágrado 2. +... Ainda continuo no parágrafo 2! :) + +Eu estou no parágrafo três. + + + +Termino com dois espaços (destacar-me para vê-los). + +Há um
acima de mim! + + + +> Este é um bloco de citação. Você pode +> Enrolar manualmente suas linhas e colocar um `>` antes de cada linha ou você pode +> deixar suas linhas ficarem muito longas e enrolar por conta própria. Não faz diferença, +> desde que eles começam com um `>`. + +> Você também pode usar mais de um nível +>> De recuo? +> Como pura é isso? + + + + +* Item +* Item +* Outro item + +ou + ++ Item ++ Item ++ Outro item + +ou + +- Item +- Item +- Um último item + + + +1. Item um +2. Item dois +3. Tem três + + + +1. Item um +1. Item dois +1. Item três + + + + +1. Item um +2. Item dois +3. Item três + * Sub-item + * Sub-item +4. Item quatro + + + + + Isto é código + É assim, sacou? + + + + my_array.each do |item| + puts item + end + + + +John não sabia nem o que o função 'goto()' fazia! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + +<-- O texto acima não requer recuo, mas o Github vai usar a sintaxe +destacando do idioma que você especificar após a ``` --> + + + + +*** +--- +- - - +**************** + + + + +[Click aqui!](http://test.com/) + + + +[Click aqui!](http://test.com/ "Link para Test.com") + + + +[Ir para música](/música/). + + + +[Clique neste link] [link1] para mais informações sobre isso! +[Além disso, verifique este link] [foobar] se você quiser. + +[link1]: http://test.com/ "Legal!" +[foobar]: http://foobar.biz/ "OK!" + + + + + +[Este] [] é um link. + +[este]: http://thisisalink.com/ + + + + + + +![Este é pairar-texto (texto alternativo) para minha imagem](http://imgur.com/myimage.jpg "Um título opcional") + + + +![Este é o pairar-texto.][Myimage] + +[myimage]: relative/urls/legal/image.jpg "se você precisa de um título, é aqui" + + + + + é equivalente a +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +Quero digitar * Este texto entre asteriscos *, mas eu não quero que ele seja +em itálico, então eu faço o seguinte: \*Este texto entre asteriscos \*. + + + + +| Col1 | Col2 | Col3 | +| :----------- | :------: | ------------: | +| esquerda-alin| Centrado | direita-alinh | +| blah | blah | blah | + + + +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ugh isso é tão feio | faça isto | parar + + + +``` +Para mais informações, confira o post oficial de John Gruber de sintaxe [aqui](http://daringfireball.net/projects/markdown/syntax) +e de Adam Pritchard grande cheatsheet [aqui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 19a5676798f2315778d07e9271fd5e9d750bb5ef Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 23 Jul 2014 19:07:48 -0500 Subject: Update json-es.html.markdown --- es-es/json-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/json-es.html.markdown b/es-es/json-es.html.markdown index de52f76d..fff678eb 100644 --- a/es-es/json-es.html.markdown +++ b/es-es/json-es.html.markdown @@ -1,6 +1,6 @@ --- language: json -filename: learnjson.json +filename: learnjson-es.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] -- cgit v1.2.3 From 2c511db07ac4cc4d4fa8f438a200d4fb98a80884 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 23 Jul 2014 20:19:10 -0500 Subject: Create markdown-es.html.markdown --- es-es/markdown-es.html.markdown | 234 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 234 insertions(+) create mode 100644 es-es/markdown-es.html.markdown diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown new file mode 100644 index 00000000..c7d408b5 --- /dev/null +++ b/es-es/markdown-es.html.markdown @@ -0,0 +1,234 @@ + + + + + + + + +# This is an

+## This is an

+### This is an

+#### This is an

+##### This is an

+###### This is an
+ + +This is an h1 +============= + +This is an h2 +------------- + + + + +*This text is in italics.* +_And so is this text._ + +**This text is in bold.** +__And so is this text.__ + +***This text is in both.*** +**_As is this!_** +*__And this!__* + + + +~~This text is rendered with strikethrough.~~ + + + +This is a paragraph. I'm typing in a paragraph isn't this fun? + +Now I'm in paragraph 2. +I'm still in paragraph 2 too! + + +I'm in paragraph three! + + + +I end with two spaces (highlight me to see them). + +There's a
above me! + + + +> This is a block quote. You can either +> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. +> It doesn't make a difference so long as they start with a `>`. + +> You can also use more than one level +>> of indentation? +> How neat is that? + + + + +* Item +* Item +* Another item + +or + ++ Item ++ Item ++ One more item + +or + +- Item +- Item +- One last item + + + +1. Item one +2. Item two +3. Item three + + + +1. Item one +1. Item two +1. Item three + + + + +1. Item one +2. Item two +3. Item three + * Sub-item + * Sub-item +4. Item four + + + + + This is code + So is this + + + + my_array.each do |item| + puts item + end + + + +John didn't even know what the `go_to()` function did! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + +<-- The above text doesn't require indenting, plus Github will use syntax +highlighting of the language you specify after the ``` --> + + + + +*** +--- +- - - +**************** + + + + +[Click me!](http://test.com/) + + + +[Click me!](http://test.com/ "Link to Test.com") + + + +[Go to music](/music/). + + + +[Click this link][link1] for more info about it! +[Also check out this link][foobar] if you want to. + + + + + + + + +[This][] is a link. + + + + + + + + +![This is hover-text (alt text) for my image](http://imgur.com/myimage.jpg "An optional title") + + + +![This is the hover-text.][myimage] + + + + + + + is equivalent to +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +I want to type *this text surrounded by asterisks* but I don't want it to be +in italics, so I do this: \*this text surrounded by asterisks\*. + + + + +| Col1 | Col2 | Col3 | +| :----------- | :------: | ------------: | +| Left-aligned | Centered | Right-aligned | +| blah | blah | blah | + + + +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ugh this is so ugly | make it | stop + + -- cgit v1.2.3 From 4bf1ed2fedcb916b26f92a744d2a20c6bc9f6652 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 23 Jul 2014 21:48:35 -0500 Subject: Completed translation --- es-es/markdown-es.html.markdown | 255 ++++++++++++++++++++-------------------- 1 file changed, 126 insertions(+), 129 deletions(-) diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index c7d408b5..ae7b201b 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -1,234 +1,231 @@ - - +válido, eso significa que podemos usar elementos HTML en Markdown como, por +ejemplo, el comentario y no serán afectados por un parseador Markdown. Aún +así si creas un elemento HTML en tu archivo Markdown no podrás usar sintaxis +Markdown dentro de él. --> - + - -# This is an

-## This is an

-### This is an

-#### This is an

-##### This is an

-###### This is an
- - -This is an h1 + + +# Esto es un

+## Esto es un

+### Esto es un

+#### Esto es un

+##### Esto es un

+###### Esto es un
+ + +Esto es un h1 ============= -This is an h2 +Esto es un h2 ------------- - - - -*This text is in italics.* -_And so is this text._ + + -**This text is in bold.** -__And so is this text.__ +*Este texto está en itálicas.* +_Al igual que este texto._ -***This text is in both.*** -**_As is this!_** -*__And this!__* +**Este texto está en negritas.** +__Al igual que este texto.__ - +***Este texto tiene ambos estilos.*** +**_Al igual que este!_** +*__¡Y este!__* -~~This text is rendered with strikethrough.~~ + - +~~Este texto está tachado.~~ -This is a paragraph. I'm typing in a paragraph isn't this fun? + -Now I'm in paragraph 2. -I'm still in paragraph 2 too! +Este es un párrafo. Estoy escribiendo un párrafo, ¿No es divertido? +Ahora estoy en el párrafo dos. +¡Sigo en el párrafo dos! -I'm in paragraph three! +¡Estoy en el párrafo tres! - + -I end with two spaces (highlight me to see them). +Termino con dos espacios (selecciona esta línea completa para que los veas). -There's a
above me! +¡Hay un
arriba de mí! - + -> This is a block quote. You can either -> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. -> It doesn't make a difference so long as they start with a `>`. +> Esta es una cita de bloque. Puedes +> envolver tus líneas manualmente y poner un `>` antes de cada línea o puedes dejar que tus líneas sean muy largas y que se envuelvan solas. +> No hay diferencia, siempre y cuando empiecen con `>`. -> You can also use more than one level ->> of indentation? -> How neat is that? +> ¿También puedes usar más de un nivel +>> de indentación? +> Esto es muy útil ¿No? - - + + * Item * Item -* Another item +* Otro item -or +o + Item + Item -+ One more item ++ Un item más -or +o - Item - Item -- One last item +- El último item - + -1. Item one -2. Item two -3. Item three +1. Item uno +2. Item dos +3. Item tres - + -1. Item one -1. Item two -1. Item three - +1. Item uno +1. Item dos +1. Item tres + - + -1. Item one -2. Item two -3. Item three +1. Item uno +2. Item dos +3. Item tres * Sub-item * Sub-item -4. Item four +4. Item cuatro - - + + - This is code - So is this + Esto es código + Esto también - + my_array.each do |item| puts item end - + -John didn't even know what the `go_to()` function did! +¡John no sabía lo que la función `go_to()` hacía! - + -\`\`\`ruby +\`\`\`ruby def foobar puts "Hello world!" end -\`\`\` +\`\`\` -<-- The above text doesn't require indenting, plus Github will use syntax -highlighting of the language you specify after the ``` --> + - - + + *** --- - - - **************** - - + + -[Click me!](http://test.com/) +[¡Haz click!](http://test.com/) - + -[Click me!](http://test.com/ "Link to Test.com") +[¡Haz click!](http://test.com/ "Liga al test.com") - + -[Go to music](/music/). +[Ir a la música](/music/). - + -[Click this link][link1] for more info about it! -[Also check out this link][foobar] if you want to. +¡[Has click a esta liga][liga1] para más información! +[También mira esta liag][foobar] si quieres. - + - + -[This][] is a link. +[Esta][] es una liga. - + - - + + -![This is hover-text (alt text) for my image](http://imgur.com/myimage.jpg "An optional title") +![Esta es una etiqueta (texto alternativo) para mi imagen](http://imgur.com/myimage.jpg "Un titulo opcional") - + -![This is the hover-text.][myimage] +![Esta es una etiqueta.][myimage] - - + + - is equivalent to + equivale a [http://testwebsite.com/](http://testwebsite.com/) - + - + -I want to type *this text surrounded by asterisks* but I don't want it to be -in italics, so I do this: \*this text surrounded by asterisks\*. +Quiero escribir *este texto rodeado por asteriscos* pero no quiero que esté en itálicas, +así que hago esto: \*Este texto está rodeado de asteriscos\*. - - + + | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | -| Left-aligned | Centered | Right-aligned | +| Izquierda | Centrado | Derecha | | blah | blah | blah | - + Col 1 | Col2 | Col3 :-- | :-: | --: -Ugh this is so ugly | make it | stop +Ugh esto es feo | has que | pare. - + -- cgit v1.2.3 From a5ca7174262e9fe73d4f9ed9aafafab4c9ae91a9 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 23 Jul 2014 21:51:26 -0500 Subject: Added translation and format --- es-es/markdown-es.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index ae7b201b..fd901cf4 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -1,3 +1,18 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Daniel Zendejas", "https://github.com/DanielZendejas"] +-filename: es-markdown.md +--- + +Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). + +Give me as much feedback as you want! / Feel free to fork and pull request! + + +``` + +``` + +For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 248ab5a182718be2c63a0b83f7e55ce42afe349c Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 23 Jul 2014 21:52:43 -0500 Subject: Added lang --- es-es/markdown-es.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index fd901cf4..1ffe148e 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -1,10 +1,11 @@ --- language: markdown +filename: markdown-es.md contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Daniel Zendejas", "https://github.com/DanielZendejas"] --filename: es-markdown.md +lang: es-es --- Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). -- cgit v1.2.3 From 49c2fb948dd77413fe3cedc961ad4ed428b6c9ef Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 23 Jul 2014 21:56:21 -0500 Subject: Update markdown-es.html.markdown --- es-es/markdown-es.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index 1ffe148e..228e0a18 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -10,7 +10,10 @@ lang: es-es Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). -Give me as much feedback as you want! / Feel free to fork and pull request! +Markdown fue creado por John Gruber en 2004. Su propósito es ser una sintaxis fácil de leer y escribir que se convierta +fácilmente a HTML (y, actualmente, otros formatos también). + +¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! ``` @@ -248,4 +251,4 @@ Ugh esto es feo | has que | pare. ``` -For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). +Para más información, mira el post oficial de John Gruber's [aquí](http://daringfireball.net/projects/markdown/syntax) y la gran referencia de Adam Pritchard's [aquí](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 41406fdce69c5a7dece0938f522a3c3a8b5c6c6f Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 23 Jul 2014 21:56:46 -0500 Subject: finalizado --- es-es/markdown-es.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index 228e0a18..3865126c 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -8,8 +8,6 @@ translators: lang: es-es --- -Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). - Markdown fue creado por John Gruber en 2004. Su propósito es ser una sintaxis fácil de leer y escribir que se convierta fácilmente a HTML (y, actualmente, otros formatos también). -- cgit v1.2.3 From 38c167867203d6192060a853ceae4c47eee581ad Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Thu, 24 Jul 2014 23:05:44 +0200 Subject: More on sub arguments. Declare your own subs !! More on hash: add colonpair syntax Flatten argument list with `|` Multi on :$! TODO: `MAIN` TODO: meta ops --- perl6.html.markdown | 232 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 222 insertions(+), 10 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 5ead6560..d7864b7f 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -35,6 +35,10 @@ my $str2 = "String"; # double quotes allow for interpolation # variable names can contain but not end with simple quotes and dashes, and can contain (and end with) underscores : # my $weird'variable-name_ = 5; # works ! +my $bool = True; # `True` and `False` are Perl 6's boolean +my $inverse = !$bool; # You can invert a bool with the prefix `!` operator +my $forced-bool = so $str; # And you can use the prefix `so` operator which turns its operand into a Bool + ## - Arrays. They represent multiple values. They start with `@` my @array = 1, 2, 3; @@ -44,14 +48,26 @@ my @array =
; # array of words, delimited by space. similar to perl5's qw say @array[2]; # Array indices start at 0 -- This is the third element -## - Hashes +say "Interpolate an array using [] : @array[]"; #=> Interpolate an array using [] : a b c + +## - Hashes. Key-Value Pairs. +# Hashes are actually arrays of Pairs (`Key => Value`), "flattened" to remove duplicated keys. my %hash = 1 => 2, 3 => 4; -my %hash = autoquoted => "key", +my %hash = autoquoted => "key", # keys are auto-quoted "some other" => "value", # trailing commas are okay ; -my %hash = # you can also create a hash from an even-numbered array +my %hash = ; # you can also create a hash from an even-numbered array +my %hash = key1 => 'value1', key2 => 'value2'; # same as this + +# You can also use the "colon pair" syntax: (especially handy for named parameters that you'll see later) +my %hash = :w(1), # equivalent to `w => 1` + # this is useful for the `True` shortcut: + :truey, # equivalent to `:truey(True)`, or `truey => True` + # and for the `False` one: + :!falsey, # equivalent to `:falsey(False)`, or `falsey => False` + ; say %hash{'key1'}; # You can use {} to get the value from a key say %hash; # if it's a string, you can actually use <> @@ -69,6 +85,123 @@ sub say-hello-to(Str $name) { # you can provide the type of an argument my &s = &say-hello; my &other-s = sub { say "anonymous function !" } +# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" +sub as-many($head, *@rest) { # the `*@` slurpy will basically "take everything else". + # Note: you can have parameters *before* (like here) a slurpy one, but not *after*. + say @rest.join(' / ') ~ " !"; +} +say as-many('Happy', 'Happy', 'Birthday'); #=> Happy Birthday ! + # Note that the splat did not consume the parameter before. + +## You can call a function with an array using the "argument list flattening" operator `|` +# (it's not actually the only feature of the operator, but it's one of them) +sub concat3($a, $b, $c) { + say "$a, $b, $c"; +} +concat3(|@array); #=> a, b, c + # `@array` got "flattened" as a part of the argument list + +## It can also have optional arguments: +sub with-optional($arg?) { # the "?" marks the argument optional + say "I might return `(Any)` if I don't have an argument passed, or I'll return my argument"; + $arg; +} +with-optional; # returns Any +with-optional(); # returns Any +with-optional(1); # returns 1 + +## You can also give them a default value when they're not passed: +sub hello-to($name = "World") { + say "Hello, $name !"; +} +hello-to; #=> Hello, World ! +hello-to(); #=> Hello, World ! +hello-to('You'); #=> Hello, You ! + +## You can also, by using a syntax akin to the one of hashes (yay unification !), +## pass *named* arguments to a `sub`. +sub with-named($normal-arg, :$named) { + say $normal-arg + $named; +} +with-named(1, named => 6); #=> 7 +with-named(2, :named(5)); #=> 7 +with-named(3, :4named); #=> 7 + # (special colon pair syntax for numbers) + +with-named(3); # warns, because we tried to use the undefined $named + # in a `+`: by default, named arguments are *optional* + +# To make a named argument mandatory, you can use `?`'s inverse, `!` +sub with-mandatory-named(:$str!) { + say "$named !"; +} +with-mandatory-named(str => "My String"); #=> My String +with-mandatory-named; # run time error: "Required named parameter not passed" +with-mandatory-named(3); # run time error: "Too many positional parameters passed" + +## If a sub takes a named boolean argument ... +sub takes-a-bool($name, :$bool) { + say "$name takes $bool"; +} +# ... you can use the same "short boolean" hash syntax: +takes-a-bool('config', :bool); # config takes True +takes-a-bool('config', :!bool); # config takes False +# or you can use the "adverb" form: +takes-a-bool('config'):bool; #=> config takes True +takes-a-bool('config'):!bool; #=> config takes False +# You'll learn to love (or maybe hate, eh) that syntax later. + + +## You can also provide your named arguments with defaults: +sub named-def(:$def = 5) { + say $def; +} +named-def; #=> 5 +named-def(:10def); #=> 10 +named-def(def => 15); #=> 15 + +## There's more to come, but we're going to end this paragraph with a really powerful feature: +## Unpacking ! It's the ability to "extract" arrays and keys. It'll work in `my`s and parameters. +my ($a, $b) = 1, 2; +say $a; #=> 1 +my ($, $, $c) = 1, 2, 3; # keep the non-interesting anonymous +say $c; #=> 3 + +my ($head, *@tail) = 1, 2, 3; # Yes, it's the same as with "slurpy subs" +my (*@small) = 1; + +sub foo(@array [$fst, $snd]) { + say "My first is $fst, my second is $snd ! All in all, I'm @array[]."; # (remember the `[]` to interpolate the array) +} +foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 1 2 + + +# If you're not using the array itself, you can also keep it anonymous, much like a scalar: +sub first-of-array(@ [$fst]) { $fst } +first-of-array(@small); #=> 1 +first-of-array(@tail); # errors with "Too many positional parameters passed" (the array is too big) + +# You can also use a slurp ... +sub slurp-in-array(@ [$fst, *@rest]) { # you could decide to keep `*@rest` anonymous + say $fst + @rest.elems; +} +slurp-in-array(@tail); #=> 3 + +# You could even extract on a slurpy (but it's pretty useless ;-).) +sub fst(*@ [$fst]) { # or simply : `sub fst($fst) { ... }` + say $fst; +} +fst(1); #=> 1 +fst(1, 2); # errors with "Too many positional parameters passed" + +# Lou can also destructure hashes (and classes, which you'll learn about later !) +sub key-of(% (:value($val), :qua($qua))) { + say "Got val $val, $qua times."; +} +# Then call it with a hash: (you need to keep the brackets for it to be a hash) +key-of({value => 1}); +#key-of(%hash); # the same (for an equivalent `%hash`) + # `->`, lambda with arguments, and string interpolation my &lambda = -> $argument { "The argument passed to this lambda is $argument" } # We're going to see how powerful Perl 6 subs are just a little down below, after seeing the basics of operators @@ -225,7 +358,7 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return an array o # 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 juste put `1..*`, +# Warning, though: if you try this example in the REPL and juste 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. @@ -252,12 +385,12 @@ say @primes[^10]; #=> 1 1 2 3 5 8 13 21 34 55 # Note : as for ranges, once reified, elements aren't re-calculated. # That's why `@primes[^100]` will take a long time the first time you print it, then be instant -## More on Subs ! -# Perl 6 likes functions. So, in Perl 6, functions are very powerful: +### More on Subs ! +# Perl 6 likes functions. So, in Perl 6, they are very powerful: ## Multiple Dispatch # Perl 6 can decide which variant of a `sub` to call based on the type of the arguments, -# or on arbitrary preconditions, using `where` : +# or on arbitrary preconditions, like with a type or a `where`: # with types multi sub sayit(Int $n) { # note the `multi` keyword here @@ -270,13 +403,32 @@ sayit("foo"); # prints "String: foo" sayit(True); # fails at *compile time* with "calling 'sayit' will never work with arguments of types ..." # with arbitrary precondition: -multi is-big(Int $n where * > 10) { True } -multi is-big(Int $) { False } +multi is-big(Int $n where * > 50) { "Yes !" } # using a closure +multi is-big(Int $ where 10..50) { "Quite." } # this uses smart-matching (could use a regexp, etc) +multi is-big(Int $) { "No" } # you can also name these checks, by creating "subsets": subset Even of Int where * %% 2; +multi odd-or-even(Even) { "Even" } # the main case using the type. We don't name the argument +multi odd-or-even($) { "Odd" } # "else" + +# You can even dispatch based on a positional's argument presence ! +multi with-or-without-you(:$with!) { # make it mandatory to be able to dispatch against it + say "I can live ! Actually, I can't."; +} +multi with-or-without-you { + say "Definitely can't live."; +} +# This is very, very useful for many purposes, like `MAIN` subs (covered later), +# and even the language itself is using it in several places. +# `is`, for example, is actually a `multi sub` named `trait_mod:`, and it works off that. +# `is rw`, for example, is a dispatch to a function with this signature: +# sub trait_mod:(Routine $r, :$rw!) {} +# (commented because running this would probably lead to some surprising side-effects !) + +# ---- # The last expression of a sub is returned automatically (though you may use the `return` keyword, of course): sub next-index($n) { $n + 1; @@ -626,7 +778,67 @@ $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` !$a! # with right-associative `!`, this is `!($a!)` !$a! # with non-associative `!`, this is illegal -## Last part of the operator list : +## Create your own operators ! +# Okay, you've been reading all of that, so I guess I should try to show you something exciting. +# I'll tell you a little secret (actually not): In Perl 6, all operators are actually just funny-looking subroutines. +# You can declare an operator just like you declare a sub: +sub prefix:($winner) { # refer to the operator categories + # (yes, it's the "words operator" `<>`) + say "$winner Won !"; +} +win "The King"; #=> The King Won ! + # (prefix is before) + +# you can still call the sub with its "full name" +say prefix:(True); #=> False + +sub postfix:(Int $n) { + [*] 2..$n; # using the reduce meta-operator ... See below ;-) ! +} +say 5!; #=> 120 + # (postfix is after) + + +sub infix:(Int $n, Block $r) { # infix in the middle + for ^$n { + $r(); # needs the parentheses because it's a scalar + } +} +3 times -> { say "hello" }; #=> hello + #=> hello + #=> hello + +# For circumfix and post-circumfix ones +sub circumfix:<[ ]>(Int $n) { + $n ** $n +} +say [5]; #=> 3125 + # circumfix is around + +sub postcircumfix:<{ }>(Str $s, Int $idx) { # post-circumfix is "after a term, around something" + $s.substr($idx, 1); +} +say "abc"{1}; #=> b + # after the term `"abc"`, and around the index (1) + +# This really means a lot -- because everything in Perl 6 uses this. +# For example, to delete a key from a hash, you use the `:delete` adverb (named argument) +%h{$key}:delete; +# equivalent to: +postcircumfix:<{ }>(%h, $key, :delete); +# It's *all* using the same building blocks! Syntactic categories (prefix infix ...), +# named arguments (adverbs), ..., used to build the language are available to you. + +# (you are, obviously, recommended against making an operator out of *everything* -- +# with great power comes great responsibility) + +## Meta operators ! +# Oh boy, get ready. Get ready, because we're dwelving deep into the rabbit's hole, and you probably won't want +# to go back to other languages after reading that (I'm sure you don't want to already at that point). + +# - Reduce meta-operator + +## End of the operator list: ## * Sort comparison # They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1). -- cgit v1.2.3 From 4c6e3e772334b29bfc14985e84b05136db0e52e1 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Thu, 24 Jul 2014 23:06:44 +0200 Subject: Fix compose's inside ... --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index d7864b7f..ad68ccb3 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -746,7 +746,7 @@ for ^5 { } ## * Role/class phasers -COMPOSE { "When a role is composed into a class. /!\ NOT YET IMPLEMENTED /!\" } +COMPOSE { "When a role is composed into a class. /!\ NOT YET IMPLEMENTED" } # They allow for cute trick or clever code ...: say "This code took " ~ (time - CHECK time) ~ "s to run"; -- cgit v1.2.3 From 82d65fb3b20e17c90a35fc9cea05d33b961a963c Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Fri, 25 Jul 2014 11:30:50 +0200 Subject: Move stuff around. ventica++ --- perl6.html.markdown | 100 +++++++++++++++++++++++++++------------------------- 1 file changed, 52 insertions(+), 48 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index ad68ccb3..0e6b55fc 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -226,6 +226,58 @@ sub mod() is rw { $x } mod() = 52; # in this case, the parentheses are mandatory say $x; #=> 52 +# The last expression of a sub is returned automatically (though you may use the `return` keyword, of course): +sub next-index($n) { + $n + 1; +} +my $new-n = next-index(3); # $new-n is now 4 +# This is true for everything, except for the looping constructs (due to performance reasons): +# there's no purpose in building a list if we're just going to discard all the results. +# If you still want to build one, you can use the `do` prefix: (or the `gather` prefix, which we'll see later) +sub list-of($n) { + do for ^$n { # note the use of the range-to prefix operator `^` (`0..^N`) + $_ # current loop iteration + } +} +my @list3 = list-of(3); #=> (0, 1, 2) + +# We can, for example, add 3 to each value of an array using map : +my @arrayplus3 = map({ $_ + 3 }, @array); # $_ is the implicit argument (the same as for `given` and `for`) + +# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`) : +# a block doesn't have a function context (though it can have arguments), which means that if you +# return from it, you're going to return from the parent function, compare: +sub is-in(@array, $elem) { + # this will `return` out of `is-in` sub + # once the condition evaluated to True, the loop won't be run anymore + map({ return True if $_ == $elem }, @array); +} +sub truthy-array(@array) { + # this will produce an array of `True` and `False` : + # (you can also say `anon sub` for "anonymous subroutine") + map(sub { if $_ { return True } else { return False } }, @array); # returns the correct value, even in a `if` +} + +# `-> {}` and `{}` are pretty much the same thing, except that the former can take arguments, +# and that the latter can be mistaken as a hash by the compiler + +# You can also use the "whatever star" to create an anonymous function +# (it'll stop at the furthest operator in the current expression) +my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` +my @arrayplus3 = map(*+*+3, @array); # also works. Same as `-> $a, $b { $a + $b + 3 }` +say (*/2)(4); #=> 2 + # Immediatly execute the function Whatever created. +say ((*+3)/5)(5); #=> 1.6 + # works even in parens ! + +# but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`), +# you can also use the implicit argument syntax, `$^` : +map({ $^a + $^b + 3 }, @array); # same as the above + +# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $ b / $a }` + + + ### Control Flow Structures # You don't need to put parenthesis around the condition, but that also means you always have to use brackets (`{ }`) for their body : @@ -428,54 +480,6 @@ multi with-or-without-you { # (commented because running this would probably lead to some surprising side-effects !) -# ---- -# The last expression of a sub is returned automatically (though you may use the `return` keyword, of course): -sub next-index($n) { - $n + 1; -} -my $new-n = next-index(3); # $new-n is now 4 -# This is true for everything, except for the looping constructs (due to performance reasons): -# there's no purpose in building a list if we're just going to discard all the results. -# If you still want to build one, you can use the `do` prefix: (or the `gather` prefix, which we'll see later) -sub list-of($n) { - do for ^$n { # note the use of the range-to prefix operator `^` (`0..^N`) - $_ # current loop iteration - } -} -my @list3 = list-of(3); #=> (0, 1, 2) - -# We can, for example, add 3 to each value of an array using map : -my @arrayplus3 = map({ $_ + 3 }, @array); # $_ is the implicit argument (the same as for `given` and `for`) - -# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`) : -# a block doesn't have a function context (though it can have arguments), which means that if you -# return from it, you're going to return from the parent function, compare: -sub is-in(@array, $elem) { - # this will `return` out of `is-in` sub - # once the condition evaluated to True, the loop won't be run anymore - map({ return True if $_ == $elem }, @array); -} -sub truthy-array(@array) { - # this will produce an array of `True` and `False` : - # (you can also say `anon sub` for "anonymous subroutine") - map(sub { if $_ { return True } else { return False } }, @array); # returns the correct value, even in a `if` -} - -# `-> {}` and `{}` are pretty much the same thing, except that the former can take arguments, -# and that the latter can be mistaken as a hash by the compiler - -# You can also use the "whatever star" to create an anonymous function -# (it'll stop at the furthest operator in the current expression) -my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` -my @arrayplus3 = map(*+*+3, @array); # also works. Same as `-> $a, $b { $a + $b + 3 }` -say ((*+3)/5)(5); # immediatly execute the function Whatever created -- works even in parens ! - -# but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`), -# you can also use the implicit argument syntax, `$^` : -map({ $^a + $^b + 3 }, @array); # same as the above - -# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $ b / $a }` - ### Scoping # In Perl 6, contrarily to many scripting languages (Python, Ruby, PHP, for example), # you are to declare your variables before using them. You already saw it, with `my`. -- cgit v1.2.3 From a85a05a139c8c2e23686987b0cc5deffe599283d Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Fri, 25 Jul 2014 11:47:56 +0200 Subject: Move stuff around, again. Need to teach it in the right order ... --- perl6.html.markdown | 247 ++++++++++++++++++++++++++-------------------------- 1 file changed, 123 insertions(+), 124 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 0e6b55fc..599f207c 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -126,7 +126,7 @@ sub with-named($normal-arg, :$named) { with-named(1, named => 6); #=> 7 with-named(2, :named(5)); #=> 7 with-named(3, :4named); #=> 7 - # (special colon pair syntax for numbers) + # (special colon pair syntax for numbers, mainly useful for `:2nd` etc) with-named(3); # warns, because we tried to use the undefined $named # in a `+`: by default, named arguments are *optional* @@ -160,53 +160,6 @@ named-def; #=> 5 named-def(:10def); #=> 10 named-def(def => 15); #=> 15 -## There's more to come, but we're going to end this paragraph with a really powerful feature: -## Unpacking ! It's the ability to "extract" arrays and keys. It'll work in `my`s and parameters. -my ($a, $b) = 1, 2; -say $a; #=> 1 -my ($, $, $c) = 1, 2, 3; # keep the non-interesting anonymous -say $c; #=> 3 - -my ($head, *@tail) = 1, 2, 3; # Yes, it's the same as with "slurpy subs" -my (*@small) = 1; - -sub foo(@array [$fst, $snd]) { - say "My first is $fst, my second is $snd ! All in all, I'm @array[]."; # (remember the `[]` to interpolate the array) -} -foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 1 2 - - -# If you're not using the array itself, you can also keep it anonymous, much like a scalar: -sub first-of-array(@ [$fst]) { $fst } -first-of-array(@small); #=> 1 -first-of-array(@tail); # errors with "Too many positional parameters passed" (the array is too big) - -# You can also use a slurp ... -sub slurp-in-array(@ [$fst, *@rest]) { # you could decide to keep `*@rest` anonymous - say $fst + @rest.elems; -} -slurp-in-array(@tail); #=> 3 - -# You could even extract on a slurpy (but it's pretty useless ;-).) -sub fst(*@ [$fst]) { # or simply : `sub fst($fst) { ... }` - say $fst; -} -fst(1); #=> 1 -fst(1, 2); # errors with "Too many positional parameters passed" - -# Lou can also destructure hashes (and classes, which you'll learn about later !) -sub key-of(% (:value($val), :qua($qua))) { - say "Got val $val, $qua times."; -} -# Then call it with a hash: (you need to keep the brackets for it to be a hash) -key-of({value => 1}); -#key-of(%hash); # the same (for an equivalent `%hash`) - -# `->`, lambda with arguments, and string interpolation -my &lambda = -> $argument { "The argument passed to this lambda is $argument" } -# We're going to see how powerful Perl 6 subs are just a little down below, after seeing the basics of operators -# and control flow structures - ### Containers # In Perl 6, values are actually stored in "containers". # the assignment operator asks the container on the left to store the value on its right @@ -226,57 +179,6 @@ sub mod() is rw { $x } mod() = 52; # in this case, the parentheses are mandatory say $x; #=> 52 -# The last expression of a sub is returned automatically (though you may use the `return` keyword, of course): -sub next-index($n) { - $n + 1; -} -my $new-n = next-index(3); # $new-n is now 4 -# This is true for everything, except for the looping constructs (due to performance reasons): -# there's no purpose in building a list if we're just going to discard all the results. -# If you still want to build one, you can use the `do` prefix: (or the `gather` prefix, which we'll see later) -sub list-of($n) { - do for ^$n { # note the use of the range-to prefix operator `^` (`0..^N`) - $_ # current loop iteration - } -} -my @list3 = list-of(3); #=> (0, 1, 2) - -# We can, for example, add 3 to each value of an array using map : -my @arrayplus3 = map({ $_ + 3 }, @array); # $_ is the implicit argument (the same as for `given` and `for`) - -# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`) : -# a block doesn't have a function context (though it can have arguments), which means that if you -# return from it, you're going to return from the parent function, compare: -sub is-in(@array, $elem) { - # this will `return` out of `is-in` sub - # once the condition evaluated to True, the loop won't be run anymore - map({ return True if $_ == $elem }, @array); -} -sub truthy-array(@array) { - # this will produce an array of `True` and `False` : - # (you can also say `anon sub` for "anonymous subroutine") - map(sub { if $_ { return True } else { return False } }, @array); # returns the correct value, even in a `if` -} - -# `-> {}` and `{}` are pretty much the same thing, except that the former can take arguments, -# and that the latter can be mistaken as a hash by the compiler - -# You can also use the "whatever star" to create an anonymous function -# (it'll stop at the furthest operator in the current expression) -my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` -my @arrayplus3 = map(*+*+3, @array); # also works. Same as `-> $a, $b { $a + $b + 3 }` -say (*/2)(4); #=> 2 - # Immediatly execute the function Whatever created. -say ((*+3)/5)(5); #=> 1.6 - # works even in parens ! - -# but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`), -# you can also use the implicit argument syntax, `$^` : -map({ $^a + $^b + 3 }, @array); # same as the above - -# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $ b / $a }` - - ### Control Flow Structures @@ -298,11 +200,11 @@ say "Quite truthy" if True; # if (true) say; # This doesn't work ! -# - Ternary conditional, "?? !!" -my $a = $condition ?? $value-if-true !! $value-if-false; # `??` and `!!` are like `?` and `:` in other languages' +# - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages) +my $a = $condition ?? $value-if-true !! $value-if-false; # - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching. -# given just puts its argument into `$_`, and `when` uses it using the "smart matching" operator. +# given just puts its argument into `$_` (like a block), and `when` uses it using the "smart matching" operator. given "foo bar" { when /foo/ { # you'll read about the smart-matching operator below -- just know `when` uses it say "Yay !"; @@ -329,12 +231,12 @@ loop (my $i = 0; $i < 5; $i++) { say "This is a C-style for loop !"; } -# - `for` - Foreaches an array +# - `for` - Passes through an array for @array -> $variable { say "I've found $variable !"; } -# default variable is $_ +# default variable is $_ (like a block) for @array { say "I've got $_"; } @@ -378,7 +280,7 @@ if long-computation() -> $result { 'a' ne 'b'; # not equal 'a' !eq 'b'; # same as above -# - `eqv` is canonical equivalence +# - `eqv` is canonical equivalence (or "deep equality") (1, 2) eqv (1, 3); # - `~~` is smart matching @@ -401,7 +303,7 @@ $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an ar # `^` on either side them exclusive on that side : 3 ^..^ 7; # 3 to 7, not included (basically `4 .. 6`) # this also works as a shortcut for `0..^N` -^10; # 0..^10 +^10; # means 0..^10 # This also allows us to demonstrate that Perl 6 has lazy arrays, using the Whatever Star : my @array = 1..*; # 1 to Infinite ! @@ -422,23 +324,102 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return an array o $a && $b && $c; # returns the first argument that evaluates to False, or the last argument $a || $b; -## Sequence operator -# The sequence operator is one of Perl 6's most powerful features : -# it's composed of first, on the left, the list you want Perl 6 to deduce from (and might include a closure), -# and on the right, a value or the predicate for when to stop, or even Whatever for a lazy infinite list -my @list = 1, 2, 3 ... 10; # basic deducing -#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, because Perl 6 can't figure out the end -my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element (when the predicate matches) -my @list = 1, 3, 9 ... * > 30; # you can use a predicate (with the Whatever Star, here) -my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above) -my @primes = 1, 1, *+* ... *; # lazy infinite list of prime numbers, computed using a closure ! -my @primes = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above) -say @primes[^10]; #=> 1 1 2 3 5 8 13 21 34 55 -# Note : as for ranges, once reified, elements aren't re-calculated. -# That's why `@primes[^100]` will take a long time the first time you print it, then be instant +### More on subs ! -### More on Subs ! -# Perl 6 likes functions. So, in Perl 6, they are very powerful: +## There's more to come, but we're going to end this paragraph with a really powerful feature: +## Unpacking ! It's the ability to "extract" arrays and keys. It'll work in `my`s and parameters. +my ($a, $b) = 1, 2; +say $a; #=> 1 +my ($, $, $c) = 1, 2, 3; # keep the non-interesting anonymous +say $c; #=> 3 + +my ($head, *@tail) = 1, 2, 3; # Yes, it's the same as with "slurpy subs" +my (*@small) = 1; + +sub foo(@array [$fst, $snd]) { + say "My first is $fst, my second is $snd ! All in all, I'm @array[]."; # (remember the `[]` to interpolate the array) +} +foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 1 2 + + +# If you're not using the array itself, you can also keep it anonymous, much like a scalar: +sub first-of-array(@ [$fst]) { $fst } +first-of-array(@small); #=> 1 +first-of-array(@tail); # errors with "Too many positional parameters passed" (the array is too big) + +# You can also use a slurp ... +sub slurp-in-array(@ [$fst, *@rest]) { # you could decide to keep `*@rest` anonymous + say $fst + @rest.elems; +} +slurp-in-array(@tail); #=> 3 + +# You could even extract on a slurpy (but it's pretty useless ;-).) +sub fst(*@ [$fst]) { # or simply : `sub fst($fst) { ... }` + say $fst; +} +fst(1); #=> 1 +fst(1, 2); # errors with "Too many positional parameters passed" + +# You can also destructure hashes (and classes, which you'll learn about later !) +sub key-of(% (:value($val), :qua($qua))) { + say "Got val $val, $qua times."; +} + +# Then call it with a hash: (you need to keep the brackets for it to be a hash) +key-of({value => 1}); +#key-of(%hash); # the same (for an equivalent `%hash`) + +## The last expression of a sub is returned automatically (though you may use the `return` keyword, of course): +sub next-index($n) { + $n + 1; +} +my $new-n = next-index(3); # $new-n is now 4 +# This is true for everything, except for the looping constructs (due to performance reasons): +# there's no purpose in building a list if we're just going to discard all the results. +# If you still want to build one, you can use the `do` prefix: (or the `gather` prefix, which we'll see later) +sub list-of($n) { + do for ^$n { # note the use of the range-to prefix operator `^` (`0..^N`) + $_ # current loop iteration + } +} +my @list3 = list-of(3); #=> (0, 1, 2) + +## You can create a lambda with `-> {}` ("pointy block") or `{}` ("block") +my &lambda = -> $argument { "The argument passed to this lambda is $argument" } +# `-> {}` and `{}` are pretty much the same thing, except that the former can take arguments, +# and that the latter can be mistaken as a hash by the parser. + +# We can, for example, add 3 to each value of an array using map: +my @arrayplus3 = map({ $_ + 3 }, @array); # $_ is the implicit argument + +# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`) : +# a block doesn't have a function context (though it can have arguments), which means that if you +# return from it, you're going to return from the parent function, compare: +sub is-in(@array, $elem) { + # this will `return` out of `is-in` sub + # once the condition evaluated to True, the loop won't be run anymore + map({ return True if $_ == $elem }, @array); +} +sub truthy-array(@array) { + # this will produce an array of `True` and `False` : + # (you can also say `anon sub` for "anonymous subroutine") + map(sub { if $_ { return True } else { return False } }, @array); # returns the correct value, even in a `if` +} + +# You can also use the "whatever star" to create an anonymous function +# (it'll stop at the furthest operator in the current expression) +my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` +my @arrayplus3 = map(*+*+3, @array); # also works. Same as `-> $a, $b { $a + $b + 3 }` +say (*/2)(4); #=> 2 + # Immediatly execute the function Whatever created. +say ((*+3)/5)(5); #=> 1.6 + # works even in parens ! + +# but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`), +# you can also use the implicit argument syntax, `$^` : +map({ $^a + $^b + 3 }, @array); # same as the above + +# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $ b / $a }` ## Multiple Dispatch # Perl 6 can decide which variant of a `sub` to call based on the type of the arguments, @@ -448,7 +429,7 @@ say @primes[^10]; #=> 1 1 2 3 5 8 13 21 34 55 multi sub sayit(Int $n) { # note the `multi` keyword here say "Number: $n"; } -multi sayit(Str $s) } # the `sub` is implicit +multi sayit(Str $s) } # the `sub` is the default say "String: $s"; } sayit("foo"); # prints "String: foo" @@ -477,7 +458,7 @@ multi with-or-without-you { # `is`, for example, is actually a `multi sub` named `trait_mod:`, and it works off that. # `is rw`, for example, is a dispatch to a function with this signature: # sub trait_mod:(Routine $r, :$rw!) {} -# (commented because running this would probably lead to some surprising side-effects !) +# (commented because running this would probably lead to some very surprising side-effects !) ### Scoping @@ -844,6 +825,24 @@ postcircumfix:<{ }>(%h, $key, :delete); ## End of the operator list: + +## Sequence operator +# The sequence operator is one of Perl 6's most powerful features: +# it's composed of first, on the left, the list you want Perl 6 to deduce from (and might include a closure), +# and on the right, a value or the predicate for when to stop, or even Whatever for a lazy infinite list. +my @list = 1, 2, 3 ... 10; # basic deducing +#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, because Perl 6 can't figure out the end +my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element (when the predicate matches) +my @list = 1, 3, 9 ... * > 30; # you can use a predicate (with the Whatever Star, here) +my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above) +my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers, computed using a closure ! +my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above) +say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55 + # (using a range as the index) +# Note : as for ranges, once reified, elements aren't re-calculated. +# That's why `@primes[^100]` will take a long time the first time you print it, then be instant + + ## * Sort comparison # They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1). 1 <=> 4; # sort comparison for numerics -- cgit v1.2.3 From 540dd89202d03735ee1bff8b4f2806030a5541ca Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Fri, 25 Jul 2014 11:04:49 -0500 Subject: [css/es] created --- es-es/css-es.html.markdown | 243 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 243 insertions(+) create mode 100644 es-es/css-es.html.markdown diff --git a/es-es/css-es.html.markdown b/es-es/css-es.html.markdown new file mode 100644 index 00000000..2ac192c5 --- /dev/null +++ b/es-es/css-es.html.markdown @@ -0,0 +1,243 @@ +--- +language: css +filename: learncss-es.css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Daniel Zendejas","https://github.com/DanielZendejas"] +--- + +Tutorial de CSS en español + +En los primeros días de la web no había elementos visuales, todo +era texto plano. Pero después, con el desarrollo de los navegadores, +las páginas con contenido visual empezaron a ser más comunes. +CSS es el lenguaje estándar que existe para separar el contenido +(HTML) y el aspecto visual de las páginas web. + +Lo que CSS hace es proveer con una sintaxis que te permite apuntar a distintos +elementos HTML y asignarles diferentes propiedades visuales. + +CSS ,como cualquier otro lenguaje, tiene múltiples versiones. Aquí nos enfocamos +en CSS 2.0. No es la más reciente pero sí la más soportada y compatible. + +**NOTA:** Como los resultados de CSS son efectos visuales, para aprenderlo, +necesitarás probar todo tipo de cosas en ambientes como +[dabblet](http://dabblet.com/). El principal enfoque de este artículo es en +la sintaxis y consejos generales. + +```css +/* ¡Los comentarios aparecen dentro de diagonal-asterisco, justo como esta línea! */ + +/* #################### + ## SELECTORES + ####################*/ + +/* Generalmente, la sentencia principal en CSS es muy simple */ +selector { propiedad: valor; /* más propiedades...*/ } + +/* El selector es usado para apuntar a un elemento en la página. + +¡Puedes apuntar a todos los elementos en la página! */ +* { color:red; } + +/* +Dado un elemento como este en la página: + +
+*/ + +/* puedes seleccionarlo por el nombre de su clase */ +.una-clase { } + +/*¡O por sus dos clases! */ +.una-clase.clase2 { } + +/* O por el nombre de su elemento */ +div { } + +/* O por su Id */ +#unaId { } + +/* ¡O por el hecho de que tiene un atributo! */ +[attr] { font-size:smaller; } + +/* O por el hecho de que el atributo tiene un valor determinado */ +[attr='valor'] { font-size:smaller; } + +/* Empieza con un valor ('val' en este caso)*/ +[attr^='val'] { font-size:smaller; } + +/* O termina con un valor ('or' en este caso) */ +[attr$='or'] { font-size:smaller; } + +/* O incluso contiene un valor ('lo' en este caso) */ +[attr~='lo'] { font-size:smaller; } + +/*y, más importante, puedes combinar estos criterios de búsqueda entre sí. +No debe existir ningún espacio entre estas partes porque hace que tenga otro +significado.*/ +div.una-clase[attr$='or'] { } + +/* También puedes seleccionar un elemento HTML basado en sus padres*/ + +/* Un elemento que es hijo directo de otro elemento (Seleccionado de la forma que +vimos anteriormente) */ + +div.un-padre > .nombre-clase {} + +/* O cualquiera de sus padres en un árbol*/ +/* Lo siguiente básicamente significa que cualquier elemento que tenga una clase +"nombre-clase" y es hijo de un div con clase "un-padre" EN CUALQUIER PROFUNDIDAD*/ +div.un-padre .nombre-clase {} + +/* advertencia: el mismo selector sin espacio tiene otro significado. ¿Puedes +identificar la diferencia?*/ + +/* También puedes seleccionar un elemento basado en su hermano inmediato previo*/ +.yo-estoy-antes + .este-elemento { } + +/*o cualquier hermano previo */ +.yo-soy-cualquiera-antes ~ .estes-elemento {} + +/* Existen algunas pseudo-clases que permiten seleccionar un elemento +basado en el comportamiendo de la página (a diferencia de la estructura de +la página) */ + +/* Por ejemplo, para cuando pasas el mouse por encima de un elemento */ +:hover {} + +/* o una liga visitada*/ +:visited {} + +/* o una liga no visitada aún*/ +:link {} + +/* o un elemento de un formulario que esté seleccionado */ +:focus {} + + +/* #################### + ## PROPIEDADES + ####################*/ + +selector { + + /* Unidades */ + width: 50%; /* en porcentaje */ + font-size: 2em; /* dos veces el tamaño de la fuente actual */ + width: 200px; /* en pixeles */ + font-size: 20pt; /* en puntos */ + width: 5cm; /* en centimetros */ + width: 50mm; /* en milimetros */ + width: 5in; /* en pulgadas */ + + /* Colores */ + background-color: #F6E; /* en hexadecimal corto */ + background-color: #F262E2; /* en hexadecimal largo */ + background-color: tomato; /* puede ser un color con nombre */ + background-color: rgb(255, 255, 255); /* en rgb */ + background-color: rgb(10%, 20%, 50%); /* en rgb percent */ + background-color: rgba(255, 0, 0, 0.3); /* en rgb semi-transparente (con valor alfa)*/ + + /* Imagenes */ + background-image: url(/ruta-a-la-imagen/imagen.jpg); + + /* Fuentes */ + font-family: Arial; + font-family: "Courier New"; /* si el nombre contiene espacios, debe ir entre comillas */ + font-family: "Courier New", Trebuchet, Arial; /* si la primera fuente no se encontró + entonces se busca la seguna, o la tercera, así recursivamente*/ +} + +``` + +## Uso + +Guarda cualquier CSS que quieras en un archivo con extensión `.css`. + +```xml + + + + + + + +
+
+ +``` + +## Preferencia y orden + +Como te habrás dado cuenta un elemento puede ser seleccionado por más +de un selector. En este caso alguna de las reglas cobra preferencia +sobre las otras: + +Dado el siguiente CSS: + +```css +/*A*/ +p.clase1[attr='valor'] + +/*B*/ +p.clase1 {} + +/*C*/ +p.clase2 {} + +/*D*/ +p {} + +/*E*/ +p { propiedad: valor !important; } + +``` + +Y el siguiente HTML: + +```xml +

+

+``` + +El orden respetado es el siguiente: +Recuerda, la preferencia es por cada **property**, no para el bloque completo. + +* `E` tiene la preferencia más elevada gracias a la palabra `!important`. + Es recomendado evitar esto a menos que sea estrictamente necesario incluirlo. +* `F` le sigue, porque es estilo incrustado directamente en el HTML. +* `A` le sigue, porque es más específico que cualquier otra opción. + más específico = más especificadores. Aquí hay tres especificadores: elemento `p` + + nombre de la clase `clase1` + un atributo `attr='valor'` +* `C` le sigue. Aunque tiene el mismo número de especificadores como `B` + pero aparece después. +* Luego va `B` +* y al final `D`. + +## Compatibilidad + +La mayoría de las funcionalidades de CSS2 (y gradualmente de CSS3) son compatibles +en todos los navegadores y dispositivos. Pero siempre es vital tener en mente la +compatibilidad y disponibilidad del CSS que uses con respecto a los navegadores +y dispositivos para los que desarrolles. + + +[QuirksMode CSS](http://www.quirksmode.org/css/) es una excelente referencia para esto. + +## Referencias + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) + -- cgit v1.2.3 From de1d175eb69a6f8239ab9078eb8915a25a35c691 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Fri, 25 Jul 2014 11:05:49 -0500 Subject: Added lang:es-es --- es-es/css-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/css-es.html.markdown b/es-es/css-es.html.markdown index 2ac192c5..e298af91 100644 --- a/es-es/css-es.html.markdown +++ b/es-es/css-es.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Marco Scannadinari", "https://github.com/marcoms"] translators: - ["Daniel Zendejas","https://github.com/DanielZendejas"] +lang: es-es --- Tutorial de CSS en español -- cgit v1.2.3 From e2a19c0969eb97990fb90f8ca18382bbd8e8c040 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Fri, 25 Jul 2014 11:29:05 -0500 Subject: Little orthography fixes. --- es-es/css-es.html.markdown | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/es-es/css-es.html.markdown b/es-es/css-es.html.markdown index e298af91..1450b12e 100644 --- a/es-es/css-es.html.markdown +++ b/es-es/css-es.html.markdown @@ -6,7 +6,6 @@ contributors: - ["Marco Scannadinari", "https://github.com/marcoms"] translators: - ["Daniel Zendejas","https://github.com/DanielZendejas"] -lang: es-es --- Tutorial de CSS en español @@ -20,12 +19,12 @@ CSS es el lenguaje estándar que existe para separar el contenido Lo que CSS hace es proveer con una sintaxis que te permite apuntar a distintos elementos HTML y asignarles diferentes propiedades visuales. -CSS ,como cualquier otro lenguaje, tiene múltiples versiones. Aquí nos enfocamos -en CSS 2.0. No es la más reciente pero sí la más soportada y compatible. +CSS, como cualquier otro lenguaje, tiene múltiples versiones. Aquí nos enfocamos +en CSS 2.0. No es la versión más reciente pero sí la más soportada y compatible. **NOTA:** Como los resultados de CSS son efectos visuales, para aprenderlo, necesitarás probar todo tipo de cosas en ambientes como -[dabblet](http://dabblet.com/). El principal enfoque de este artículo es en +[dabblet](http://dabblet.com/). Este artículo se enfoca, principalmente, en la sintaxis y consejos generales. ```css @@ -35,12 +34,12 @@ la sintaxis y consejos generales. ## SELECTORES ####################*/ -/* Generalmente, la sentencia principal en CSS es muy simple */ -selector { propiedad: valor; /* más propiedades...*/ } +/* Generalmente, la sentencia principal en CSS es muy simple. */ +selector { propiedad: valor; /* más propiedades separados por punto y coma...*/ } -/* El selector es usado para apuntar a un elemento en la página. +/* El selector es usado para apuntar a (seleccionar) un elemento en la página. -¡Puedes apuntar a todos los elementos en la página! */ +¡Puedes apuntar a todos los elementos en la página con el asterisco! */ * { color:red; } /* @@ -49,7 +48,7 @@ Dado un elemento como este en la página:
*/ -/* puedes seleccionarlo por el nombre de su clase */ +/* puedes seleccionar el
por el nombre de su clase */ .una-clase { } /*¡O por sus dos clases! */ @@ -76,21 +75,21 @@ div { } /* O incluso contiene un valor ('lo' en este caso) */ [attr~='lo'] { font-size:smaller; } -/*y, más importante, puedes combinar estos criterios de búsqueda entre sí. -No debe existir ningún espacio entre estas partes porque hace que tenga otro -significado.*/ +/*Más importante, puedes combinar estos criterios de búsqueda entre sí. +No debe existir ningún espacio entre estas partes porque hace que el +significado cambie.*/ div.una-clase[attr$='or'] { } -/* También puedes seleccionar un elemento HTML basado en sus padres*/ +/* También puedes seleccionar un elemento HTML basándote en sus padres*/ /* Un elemento que es hijo directo de otro elemento (Seleccionado de la forma que vimos anteriormente) */ div.un-padre > .nombre-clase {} -/* O cualquiera de sus padres en un árbol*/ -/* Lo siguiente básicamente significa que cualquier elemento que tenga una clase -"nombre-clase" y es hijo de un div con clase "un-padre" EN CUALQUIER PROFUNDIDAD*/ +/* O cualquiera de sus ancestros en la jerarquía*/ +/* La siguiente sentencia selecciona a cualquier elemento que tenga una clase +"nombre-clase" y sea hijo de un div con clase "un-padre" EN CUALQUIER PROFUNDIDAD*/ div.un-padre .nombre-clase {} /* advertencia: el mismo selector sin espacio tiene otro significado. ¿Puedes -- cgit v1.2.3 From d587d9b1c45d545ff9dc7eea99dcb8d649d598f3 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Sat, 26 Jul 2014 01:36:47 +0800 Subject: Changed filename --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 96b0244c..58ef2d6d 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Fangzhou Chen"] -filename: Markdown.md +filename: Markdown-cn.md lang: zh-cn --- -- cgit v1.2.3 From 8631ca09f48b7fdbc3becbb232b67e53c1206ae1 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Fri, 25 Jul 2014 23:23:13 +0200 Subject: More fixes thanks to @timo++'s feedback. --- perl6.html.markdown | 82 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 52 insertions(+), 30 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 599f207c..6cacc672 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -24,7 +24,7 @@ Meta-note : the triple pound signs are here to denote headlines, double paragrap ### Variables # In Perl 6, you declare a lexical variable using `my` - +a # Perl 6 has 4 variable types : ## - Scalars. They represent a single value. They start with a `$` @@ -39,7 +39,7 @@ my $bool = True; # `True` and `False` are Perl 6's boolean my $inverse = !$bool; # You can invert a bool with the prefix `!` operator my $forced-bool = so $str; # And you can use the prefix `so` operator which turns its operand into a Bool -## - Arrays. They represent multiple values. They start with `@` +## - Arrays. They represent multiple values. Their name start with `@`. my @array = 1, 2, 3; my @array = 'a', 'b', 'c'; @@ -51,11 +51,11 @@ say @array[2]; # Array indices start at 0 -- This is the third element say "Interpolate an array using [] : @array[]"; #=> Interpolate an array using [] : a b c ## - Hashes. Key-Value Pairs. -# Hashes are actually arrays of Pairs (`Key => Value`), "flattened" to remove duplicated keys. - +# Hashes are actually arrays of Pairs (`Key => Value`), +# except they get "flattened", removing duplicated keys. my %hash = 1 => 2, 3 => 4; -my %hash = autoquoted => "key", # keys are auto-quoted +my %hash = autoquoted => "key", # keys *can* get auto-quoted "some other" => "value", # trailing commas are okay ; my %hash = ; # you can also create a hash from an even-numbered array @@ -81,13 +81,15 @@ sub say-hello-to(Str $name) { # you can provide the type of an argument say "Hello, $name !"; } -# since you can omit parenthesis to call a function with no arguments, you need to use `&` also to capture `say-hello` +# since you can omit parenthesis to call a function with no arguments, +# you need "&" in the name to capture `say-hello` my &s = &say-hello; my &other-s = sub { say "anonymous function !" } # A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" sub as-many($head, *@rest) { # the `*@` slurpy will basically "take everything else". - # Note: you can have parameters *before* (like here) a slurpy one, but not *after*. + # Note: you can have parameters *before* (like here) a slurpy one, + # but not *after*. say @rest.join(' / ') ~ " !"; } say as-many('Happy', 'Happy', 'Birthday'); #=> Happy Birthday ! @@ -124,18 +126,22 @@ sub with-named($normal-arg, :$named) { say $normal-arg + $named; } with-named(1, named => 6); #=> 7 +# There's one gotcha to be aware of, here: +# If you quote your key, Perl 6 won't be able to see it as compile time, +# and you'll have a single Pair object as a positional paramater. + with-named(2, :named(5)); #=> 7 with-named(3, :4named); #=> 7 # (special colon pair syntax for numbers, mainly useful for `:2nd` etc) -with-named(3); # warns, because we tried to use the undefined $named - # in a `+`: by default, named arguments are *optional* +with-named(3); # warns, because we tried to use the undefined $named in a `+`: + # by default, named arguments are *optional* # To make a named argument mandatory, you can use `?`'s inverse, `!` sub with-mandatory-named(:$str!) { say "$named !"; } -with-mandatory-named(str => "My String"); #=> My String +with-mandatory-named(str => "My String"); #=> My String ! with-mandatory-named; # run time error: "Required named parameter not passed" with-mandatory-named(3); # run time error: "Too many positional parameters passed" @@ -160,6 +166,9 @@ named-def; #=> 5 named-def(:10def); #=> 10 named-def(def => 15); #=> 15 +# -- Note: we're going to learn *more* on subs really soon, +# but we need to grasp a few more things to understand their real power. Ready? + ### Containers # In Perl 6, values are actually stored in "containers". # the assignment operator asks the container on the left to store the value on its right @@ -176,13 +185,14 @@ sub mutate($n is rw) { # A sub itself returns a container, which means it can be marked as rw : my $x = 42; sub mod() is rw { $x } -mod() = 52; # in this case, the parentheses are mandatory +mod() = 52; # in this case, the parentheses are mandatory (else Perl 6 thinks it's a "term") say $x; #=> 52 ### Control Flow Structures -# You don't need to put parenthesis around the condition, but that also means you always have to use brackets (`{ }`) for their body : +# You don't need to put parenthesis around the condition, +# but that also means you always have to use brackets (`{ }`) for their body : ## Conditionals @@ -204,12 +214,14 @@ say "Quite truthy" if True; my $a = $condition ?? $value-if-true !! $value-if-false; # - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching. -# given just puts its argument into `$_` (like a block), and `when` uses it using the "smart matching" operator. +# given just puts its argument into `$_` (like a block), +# and `when` uses it using the "smart matching" operator. given "foo bar" { when /foo/ { # you'll read about the smart-matching operator below -- just know `when` uses it say "Yay !"; } - when $_.chars > 50 { # smart matching anything with True gives True, so you can also put "normal" conditionals + when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True, + # so you can also put "normal" conditionals. say "Quite a long string !"; } default { # same as `when *` (using the Whatever Star) @@ -325,8 +337,9 @@ $a && $b && $c; # returns the first argument that evaluates to False, or the las $a || $b; ### More on subs ! +# As we said before, Perl 6 has *really* powerful subs. +# We're going to see a few more key concepts that make them better than in any other language :-). -## There's more to come, but we're going to end this paragraph with a really powerful feature: ## Unpacking ! It's the ability to "extract" arrays and keys. It'll work in `my`s and parameters. my ($a, $b) = 1, 2; say $a; #=> 1 @@ -337,7 +350,8 @@ my ($head, *@tail) = 1, 2, 3; # Yes, it's the same as with "slurpy subs" my (*@small) = 1; sub foo(@array [$fst, $snd]) { - say "My first is $fst, my second is $snd ! All in all, I'm @array[]."; # (remember the `[]` to interpolate the array) + say "My first is $fst, my second is $snd ! All in all, I'm @array[]."; + # (^ remember the `[]` to interpolate the array) } foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 1 2 @@ -361,6 +375,8 @@ fst(1); #=> 1 fst(1, 2); # errors with "Too many positional parameters passed" # You can also destructure hashes (and classes, which you'll learn about later !) +# The syntax is basically `%hash-name (:key($variable-to-store-value-in))`. +# The hash can stay anonymous if you only need the values you extracted. sub key-of(% (:value($val), :qua($qua))) { say "Got val $val, $qua times."; } @@ -392,18 +408,19 @@ my &lambda = -> $argument { "The argument passed to this lambda is $argument" } # We can, for example, add 3 to each value of an array using map: my @arrayplus3 = map({ $_ + 3 }, @array); # $_ is the implicit argument -# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`) : -# a block doesn't have a function context (though it can have arguments), which means that if you +# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`): +# a block doesn't have a "function context" (though it can have arguments), which means that if you # return from it, you're going to return from the parent function, compare: sub is-in(@array, $elem) { - # this will `return` out of `is-in` sub + # this will `return` out of the `is-in` sub # once the condition evaluated to True, the loop won't be run anymore map({ return True if $_ == $elem }, @array); } sub truthy-array(@array) { - # this will produce an array of `True` and `False` : + # this will produce an array of `True` and `False`: # (you can also say `anon sub` for "anonymous subroutine") - map(sub { if $_ { return True } else { return False } }, @array); # returns the correct value, even in a `if` + map(sub { if $_ { return True } else { return False } }, @array); + # ^ the `return` only returns from the anonymous `sub` } # You can also use the "whatever star" to create an anonymous function @@ -419,7 +436,7 @@ say ((*+3)/5)(5); #=> 1.6 # you can also use the implicit argument syntax, `$^` : map({ $^a + $^b + 3 }, @array); # same as the above -# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $ b / $a }` +# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $b / $a }` ## Multiple Dispatch # Perl 6 can decide which variant of a `sub` to call based on the type of the arguments, @@ -501,7 +518,7 @@ sub bar { ## In Perl 6, every field is private, and named `$!attr`, but if you declare it with `$.`, ## you get a public (immutable) accessor along with it. -# (Perl 6's object model ("P6Model") is very flexible, and allows you to dynamically add methods, +# (Perl 6's object model ("SixModel") is very flexible, and allows you to dynamically add methods, # change semantics, etc -- This will not be covered here, and you should refer to the Synopsis) class A { @@ -552,9 +569,10 @@ class B is A { # inheritance uses `is` method bar { $.val * 10 } # this shadows A's `bar` } -my B $b .= new(val => 5); # When you use `my T $var`, `$var` starts off with `T` itself in it, so you can call `new` on it - # (`.=` is just the compound operator composed of the dot-call and of the assignment operator) - # +my B $b .= new(val => 5); # When you use `my T $var`, `$var` starts off with `T` itself in it, + # so you can call `new` on it. + # (`.=` is just the compound operator composed of the dot-call and of the assignment operator + # `$a .= b` is the same as `$a = $a.b`) # Also note that `BUILD` (the method called inside `new`) will set parent properties too, # so you can pass `val => 5` # $b.not-inherited; # This won't work, for reasons explained above @@ -765,7 +783,9 @@ $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` ## Create your own operators ! # Okay, you've been reading all of that, so I guess I should try to show you something exciting. -# I'll tell you a little secret (actually not): In Perl 6, all operators are actually just funny-looking subroutines. +# I'll tell you a little secret (actually not): +# In Perl 6, all operators are actually just funny-looking subroutines. + # You can declare an operator just like you declare a sub: sub prefix:($winner) { # refer to the operator categories # (yes, it's the "words operator" `<>`) @@ -818,8 +838,9 @@ postcircumfix:<{ }>(%h, $key, :delete); # with great power comes great responsibility) ## Meta operators ! -# Oh boy, get ready. Get ready, because we're dwelving deep into the rabbit's hole, and you probably won't want -# to go back to other languages after reading that (I'm sure you don't want to already at that point). +# Oh boy, get ready. Get ready, because we're dwelving deep into the rabbit's hole, +# and you probably won't want to go back to other languages after reading that. +# (I'm guessing you don't want to already at that point). # - Reduce meta-operator @@ -900,7 +921,8 @@ for "print this printing again" } -# you might also use a Whatever Star, which is equivalent to `True` for the left side or `False` for the right : +# you might also use a Whatever Star, +# which is equivalent to `True` for the left side or `False` for the right: for (1, 3, 60, 3, 40, 60) { .say if $_ > 50 ff *; # Once the flip-flop reached a number greater than 50, it'll never go back to `False` #=> 60 3 40 60 -- cgit v1.2.3 From e1440b1678b8af250531f9464e00988a28aae5df Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Fri, 25 Jul 2014 16:36:18 -0500 Subject: Added lang:es-es --- es-es/css-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/css-es.html.markdown b/es-es/css-es.html.markdown index 1450b12e..31000785 100644 --- a/es-es/css-es.html.markdown +++ b/es-es/css-es.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Marco Scannadinari", "https://github.com/marcoms"] translators: - ["Daniel Zendejas","https://github.com/DanielZendejas"] +lang: es-es --- Tutorial de CSS en español -- cgit v1.2.3 From 61351ee266141d57ee83fe5be08f480cf2de3969 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sat, 26 Jul 2014 00:37:36 +0200 Subject: Fix explanations about $_ @masak++ --- perl6.html.markdown | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 6cacc672..f804ef86 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -213,11 +213,18 @@ say "Quite truthy" if True; # - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages) my $a = $condition ?? $value-if-true !! $value-if-false; -# - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching. -# given just puts its argument into `$_` (like a block), +# - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching, +# and thanks to Perl 6's "topic variable", $_. +# This variable contains the default argument of a block, +# a loop's current iteration (unless explicitly named), etc. +# Given simply puts its argument into `$_` (like a block would do), # and `when` uses it using the "smart matching" operator. +# Since other Perl 6 constructs use this variable (as said before, like `for`, blocks, etc), +# this means the powerful `when` is not only applicable along with a `given`, +# but instead anywhere a `$_` exists. given "foo bar" { when /foo/ { # you'll read about the smart-matching operator below -- just know `when` uses it + # this is equivalent to `if $_ ~~ /foo/` say "Yay !"; } when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True, @@ -248,9 +255,14 @@ for @array -> $variable { say "I've found $variable !"; } -# default variable is $_ (like a block) +# As we saw with given, for's default "current iteration" variable is `$_`. +# That means you can use `when` in a `for` just like you were in a when. for @array { say "I've got $_"; + + .say; # This is also allowed. + # A dot call with no "topic" (receiver) is sent to `$_` by default + $_.say; # the above and this are equivalent. } for @array { -- cgit v1.2.3 From 8b168d41cca11286de283fdebf2549afdb186fc0 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sat, 26 Jul 2014 01:11:31 +0200 Subject: More clarifications. @masak++ --- perl6.html.markdown | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index f804ef86..6c13b793 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -197,6 +197,10 @@ say $x; #=> 52 ## Conditionals # - `if` +# Before talking about `if`, we need to know which values are "Truthy" (represent True), +# and which are "Falsey" (or "Falsy") -- meaning they represent False. +# Only these values are Falsey: (), 0, "0", Nil, A type, and of course False itself. +# Every other value is Truthy. if True { say "It's true !"; } @@ -341,7 +345,7 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return an array o # so you'll end with an infinite loop. ## * And, Or -3 && 4; # True. Calls `.Bool` on `3` +3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`. 0 || False; # False. Calls `.Bool` on `0` ## Short-circuit (and tight) versions of the above @@ -448,7 +452,7 @@ say ((*+3)/5)(5); #=> 1.6 # you can also use the implicit argument syntax, `$^` : map({ $^a + $^b + 3 }, @array); # same as the above -# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, b { $b / $a }` +# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` ## Multiple Dispatch # Perl 6 can decide which variant of a `sub` to call based on the type of the arguments, @@ -813,24 +817,28 @@ sub postfix:(Int $n) { [*] 2..$n; # using the reduce meta-operator ... See below ;-) ! } say 5!; #=> 120 - # (postfix is after) + # Postfix operators (after) have to come *directly* after the term. + # No whitespace. You can use parentheses to disambiguate, i.e. `(5!)!` sub infix:(Int $n, Block $r) { # infix in the middle for ^$n { - $r(); # needs the parentheses because it's a scalar + $r(); # You need the explicit parentheses to call the function in `$r`, + # else you'd be referring at the variable itself, kind of like with `&r`. } } 3 times -> { say "hello" }; #=> hello #=> hello #=> hello + # You're very recommended to put spaces + # around your infix operator calls. # For circumfix and post-circumfix ones sub circumfix:<[ ]>(Int $n) { $n ** $n } say [5]; #=> 3125 - # circumfix is around + # circumfix is around. Again, not whitespace. sub postcircumfix:<{ }>(Str $s, Int $idx) { # post-circumfix is "after a term, around something" $s.substr($idx, 1); @@ -915,7 +923,7 @@ for { # (but will still return `False` for "met" itself, due to the leading `^` on `ff`), # until it sees "meet", which is when it'll start returning `False`. -# The difference between `ff` (flip-flop) and `fff` (flip-flop) is that +# The difference between `ff` (awk-style) and `fff` (sed-style) is that # `ff` will test its right side just as its left side changes to `True`, # and can get back to `False` right away (*except* it'll be `True` for the iteration that matched) # while `fff` will wait for the next iteration to try its right side, once its left side changed: @@ -935,8 +943,8 @@ for 50 ff *; # Once the flip-flop reached a number greater than 50, it'll never go back to `False` +for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here -- sometimes called "superstitious" + .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, it'll never go back to `False` #=> 60 3 40 60 } -- cgit v1.2.3 From 5ce43af7b741a9ea1e9db8dbd5eee5d0ff3b4c2a Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sun, 27 Jul 2014 23:11:46 +0200 Subject: Meta operator: reduce and zip (and combined !) Little note about compound operators --- perl6.html.markdown | 80 +++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 65 insertions(+), 15 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 6c13b793..b21cb1fa 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -27,7 +27,7 @@ Meta-note : the triple pound signs are here to denote headlines, double paragrap a # Perl 6 has 4 variable types : -## - Scalars. They represent a single value. They start with a `$` +## * Scalars. They represent a single value. They start with a `$` my $str = 'String'; my $str2 = "String"; # double quotes allow for interpolation @@ -39,7 +39,7 @@ my $bool = True; # `True` and `False` are Perl 6's boolean my $inverse = !$bool; # You can invert a bool with the prefix `!` operator my $forced-bool = so $str; # And you can use the prefix `so` operator which turns its operand into a Bool -## - Arrays. They represent multiple values. Their name start with `@`. +## * Arrays. They represent multiple values. Their name start with `@`. my @array = 1, 2, 3; my @array = 'a', 'b', 'c'; @@ -50,7 +50,7 @@ say @array[2]; # Array indices start at 0 -- This is the third element say "Interpolate an array using [] : @array[]"; #=> Interpolate an array using [] : a b c -## - Hashes. Key-Value Pairs. +## * Hashes. Key-Value Pairs. # Hashes are actually arrays of Pairs (`Key => Value`), # except they get "flattened", removing duplicated keys. my %hash = 1 => 2, @@ -72,7 +72,7 @@ my %hash = :w(1), # equivalent to `w => 1` say %hash{'key1'}; # You can use {} to get the value from a key say %hash; # if it's a string, you can actually use <> -## - Subs (subroutines, or functions in most other languages). Stored in variable, they use `&` +## * Subs (subroutines, or functions in most other languages). Stored in variable, they use `&` sub say-hello { say "Hello, world" } sub say-hello-to(Str $name) { # you can provide the type of an argument @@ -348,10 +348,15 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return an array o 3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`. 0 || False; # False. Calls `.Bool` on `0` -## Short-circuit (and tight) versions of the above +## * Short-circuit (and tight) versions of the above $a && $b && $c; # returns the first argument that evaluates to False, or the last argument $a || $b; +# And because you're going to want them, you also have composed assignment operators: +$a *= 2; # multiply and assignment +$b %%= 5; # divisible by and assignment +$c .= say; # method call and assignment + ### More on subs ! # As we said before, Perl 6 has *really* powerful subs. # We're going to see a few more key concepts that make them better than in any other language :-). @@ -619,7 +624,7 @@ class Item does PrintableVal { # is an error, since the compiler wouldn't know which `print` to use : # contrarily to inheritance, methods mixed in can't be shadowed - they're put at the same "level" - # NOTE : You can use a role as a class (with `is ROLE`). In this case, methods will be shadowed, + # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods will be shadowed, # since the compiler will consider `ROLE` to be a class } @@ -785,14 +790,14 @@ sub do-db-stuff { ## The precedence list can be found here : http://perlcabal.org/syn/S03.html#Operator_precedence ## But first, we need a little explanation about associativity : -# - Binary operators: +# * Binary operators: $a ! $b ! $c; # with a left-associative `!`, this is `($a ! $b) ! $c` $a ! $b ! $c; # with a right-associative `!`, this is `$a ! ($b ! $c)` $a ! $b ! $c; # with a non-associative `!`, this is illegal $a ! $b ! $c; # with a chain-associative `!`, this is `($a ! $b) and ($b ! $c)` $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` -# - Unary operators: +# * Unary operators: !$a! # with left-associative `!`, this is `(!$a)!` !$a! # with right-associative `!`, this is `!($a!)` !$a! # with non-associative `!`, this is illegal @@ -861,13 +866,58 @@ postcircumfix:<{ }>(%h, $key, :delete); # Oh boy, get ready. Get ready, because we're dwelving deep into the rabbit's hole, # and you probably won't want to go back to other languages after reading that. # (I'm guessing you don't want to already at that point). - -# - Reduce meta-operator - -## End of the operator list: - - -## Sequence operator +# Meta-operators, as their name suggests, are *composed* operators. +# Basically, they're operators that apply another operator. + +## * Reduce meta-operator +# It's a prefix meta-operator that takes a binary functions and one or many lists. +# If it doesn't get passed any argument, it either return a "default value" for this operator +# (a value that'd be non-meaningful if contained in a list) or `Any` if there's none. +# Otherwise, it pops an element from the list(s) one at a time, and applies the binary function +# to the last result (or the list's first element) and the popped element. +# To sum a list, you could use the reduce meta-operator with `+`, i.e.: +say [+] 1, 2, 3; #=> 6 +# equivalent to `(1+2)+3` +say [*] 1..5; #=> 120 +# equivalent to `((((1*2)*3)*4)*5)`. + +# You can reduce with any operator, not just with mathematical ones. +# For example, you could reduce with `//` to get the first defined element of a list: +say [//] Nil, Any, False, 1, 5; #=> False + # (Falsey, but still defined) + + +# Default value examples: +say [*] (); #=> 1 +say [+] (); #=> 0 + # In both cases, they're results that, if they were contained in the lists, + # wouldn't have any impact on the final value (since N*1=N and N+0=N). +say [//]; #=> (Any) + # There's no "default value" for `//` + +# You can also call it with a function you made up, using double brackets: +sub add($a, $b) { $a + $b } +say [[&add]] 1, 2, 3; #=> 6 + +## * Zip meta-operator +# This one is an infix meta-operator than also can be used as a "normal" operator. +# It takes an optional binary function (by default, it just creates a pair), +# and will pop one value off of each array and call its binary function on these +# until it runs out of elements. It runs the an array with all these new elements. +(1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function makes an array +1..3 Z+ 4..6; # (5, 7, 9), using the custom infix:<+> function + +# Since `Z` is list-associative (see the list above), +# you can use it on more than one list +(True, False) Z|| (False, False) Z|| (False, False); # (True, False) + +# And, as it turns out, you can also use the reduce meta-operator with it: +[Z||] (True, False), (False, False), (False, False); # (True, False) + + +## And to end the operator list: + +## * Sequence operator # The sequence operator is one of Perl 6's most powerful features: # it's composed of first, on the left, the list you want Perl 6 to deduce from (and might include a closure), # and on the right, a value or the predicate for when to stop, or even Whatever for a lazy infinite list. -- cgit v1.2.3 From 8f81fe39d7298233cc5638e48dc57a8f205a169e Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 28 Jul 2014 01:21:22 +0200 Subject: Update julia-cn.html.markdown Fix frontmatter --- zh-cn/julia-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index b7239786..b91cd7a3 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -4,7 +4,7 @@ filename: learn-julia-zh.jl contributors: - ["Jichao Ouyang", "http://oyanglul.us"] translators: - - ["Jichao Ouyang"] + - ["Jichao Ouyang", "http://oyanglul.us"] lang: zh-cn --- -- cgit v1.2.3 From 2b1762fdd86e17b99581f17df47ab9fee8233108 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Mon, 28 Jul 2014 11:48:25 -0500 Subject: Create livescript-es.html.markdown --- es-es/livescript-es.html.markdown | 338 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 338 insertions(+) create mode 100644 es-es/livescript-es.html.markdown diff --git a/es-es/livescript-es.html.markdown b/es-es/livescript-es.html.markdown new file mode 100644 index 00000000..538c0a2a --- /dev/null +++ b/es-es/livescript-es.html.markdown @@ -0,0 +1,338 @@ +--- +language: LiveScript +filename: learnLivescript-es.ls +contributors: + - ["Christina Whyte", "http://github.com/kurisuwhyte/"] +translators: + - ["Daniel Zendejas", "http://github.com/DanielZendejas/"] +--- + +LiveScript es un lenguaje funcional compilado sobre Javascript. Comparte +la mayoría de la semántica con este mismo lenguaje. Composición de funciones, +comparación de patrones y muchas otras cosas son las adiciones que hace +LiveScript. Está inspirado en lenguajes como Haskell, F# y Scala. + +Livescript es un bifurcación de [Coco][], que en sí mismo es una bifurcación +de [CoffeeScript][]. El lenguaje es estable, y una nueva versión está en +desarrollo activo para traer aún más funciones. + +[Coco]: http://satyr.github.io/coco/ +[CoffeeScript]: http://coffeescript.org/ + +La retroalimentación siempre es bienvenida, así que sientete libre de +contactarme en [@kurisuwhyte](https://twitter.com/kurisuwhyte) :) + +```coffeescript +# Justo como su primo CoffeeScript, LiveScript usa símbolos de gato para +# comentarios de una sola línea + +/* + Comentarios multi-línea son escritos con estilo de C. Usa este estilo si quieres + que los comentarios se preserven en el output de Javascript + */ +``` +```coffeescript +# En lo que a la sintaxis se refiere, LiveScript usa indentación para delimitar +# bloques en lugar de llaves {} y espacios para aplicar funciones, en lugar de +# paréntesis. + +######################################################################## +## 1. Valores básicos +######################################################################## + +# La carencia de valor se define con la palabra `void` en lugar de `undefined` +void # igual que `undefined` pero más seguro (no puede ser sobre escrito) + +# Ningún valor válido se representa con Null. +null + +# El valor básico más pequeño es de tipo lógico: +true +false + +# Y tiene múltiples alias que significan lo mismo: +on; off +yes; no + +# Luego vienen los números. Estos número con punto flotante tienen la misma +# precisión que los de JS: +10 +0.4 # Note que el `0` al inicio es requerido + +# Para fines de fácil lectura, puedes usar guiones bajos y sufijos en un +# número, y estos serán ignorados por el compilador. +12_344km + +# Los Strings son secuencias de caracteres inmutables, como en JS: +"Christina" # ¡Los apóstrofes están bien! +"""Strings + de muchas + líneas + están + bien + también.""" + +# A veces quieres codificar un palabra clave, la diagonal invertida sirve para esto: +\keyword # => 'keyword' + + +# Los arreglos son colecciones ordenadas de datos: +frutas = + * \manzana + * \naranja + * \pera + +# Una forma más concisa de representarlos son con corchetes: +frutas = [ \manzana, \naranja, \pera ] + +# Esta es una conveniente de crear listas de Strings, usando +# espacio en blanco para delimitar los items: +frutas = <[ manzana naranja pera ]> + +# Puedes recuperar un item usando su índice (empezando en 0): +frutas[0] # => "manzana" + +# Los objetos son colecciones de pares llave/valor sin ordenar, entre otras cosas, +# (detallaremos más al respecto en un momento): +persona = + nombre: "Christina" + gusta: + * "gatitos" + * "otras cosas" + +# Otra vez, puedes expresar el objeto con más consistencia con llaves {}: +persona = {nombre: "Christina", gusta: ["gatitos", "otras cosas"]} + +# Puedes conseguir un valor por medio de su llave: +persona.nombre # => "Christina" +persona["nombre"] # => "Christina" + + +# Las expresiones regulares tienen la misma sintaxis que en JavaScript: +expresion-regular = /\s$/ + +# A excepción de que puedes hacer expresiones de múltiples líneas +# (los comentarios y espacios se ignoran): +expresion-regular = // + function\s+(.+) # nombre + \s* \((.*)\) \s* # argumentos + { (.*) } # cuerpo + // + + +######################################################################## +## 2. Operaciones básicas +######################################################################## + +# Los operadores aritméticos son los mismos que en JavaScript: +1 + 2 # => 3 +2 - 1 # => 1 +2 * 3 # => 6 +4 / 2 # => 2 +3 % 2 # => 1 + + +# Las comparaciones son casi las mismas, excepto `==` que es igual +# a `===` en. El operador `==` de JS en LiveScript es `~=`, y `===` +# permite comparaciones entre objetos y arreglos, y también +# comparasiones más estrictas: +2 == 2 # => true +2 == "2" # => false +2 ~= "2" # => true +2 === "2" # => false + +[1,2,3] == [1,2,3] # => false +[1,2,3] === [1,2,3] # => true + ++0 == -0 # => true ++0 === -0 # => false + +# Otros operadores relacionales incluyen <, <=, > and >= + +# Los valores lógicos pueden ser combinados mediante los operadores +# lógicos `or`, `and` and `not`: +true and false # => false +false or true # => true +not false # => true + +# Las colecciones también tienen algunos operadores adicionales: +[1, 2] ++ [3, 4] # => [1, 2, 3, 4] +'a' in <[ a b c ]> # => true +'nombre' of { nombre: 'Chris' } # => true + + +######################################################################## +## 3. Funciones +######################################################################## + +# Como LiveScript es funcional, uno esperaría que las funciones recibirían +# un buen tratamiento. En LiveScript es más que aparente que las funciones +# son de primera clase: +suma = (primerElemento, segundoElemento) -> primerElemento + segundoElemento +add 1, 2 # => 3 + +# Las funciones que no reciben argumentos son llamadas rápidamente +dos = -> 2 +dos! + +# LiveScript, al igual que JS, aplica ámbitos (alcance) a sus variables y +# tiene cierres (closures) también. A diferencia de JavaScript, el operador +# `=` sirve como declaración y siempre declarará la variable en lado izquierdo. + +# El operador `:=` está disponible para *reusar* un nombre del ámbito del padre. + +# Puedes acceder a los argumentos de una función para conseguir +# los datos internos de una estructura de datos rápidamente: +cola = ([cabeza, ...resto]) -> resto +cola [1, 2, 3] # => [2, 3] + +# También puedes transformar argumentos usando operadores binarios o unarios. +# Argumentos por defecto también son posibles +foo = (a = 1, b = 2) -> a + b +foo! # => 3 + +# También puedes usarlo para clonar un argumento en particular para evitar efectos +# secundarios, por ejemplo: +copiar = (^^objetivo, fuente) -> + for k,v of fuente => objetivo[k] = v + objetivo +a = { a: 1 } +copiar a, { b: 2 } # => { a: 1, b: 2 } +a # => { a: 1 } + +# Una función puede ser abreviada usando una flecha larga en lugar de una corta: +suma = (primerElemento, segundoElemento) --> primerElemento + segundoElemento +sumaAbreviada = suma 1 +sumaAbreviada 2 # => 3 + +# Las funciones obtienen un argumento `it` implícito, incluso si no declaras +# ningún argument +identidad = -> it +identidad 1 # => 1 + +# Los operadores no son funciones en LiveScript. ¡Pero se pueden convertir fácilmente +# en una! Presentamos el seccionamiento de operadores: +dividir-entre-2 = (/ 2) +[2, 4, 8, 16].map(dividir-entre-2) .reduce (+) + +# LiveScript vive de otras cosas aparte de las funciones. Como en cualquier lenguaje +# funcional obtienes medios para componer (juntar) funciones: +doble-menos-uno = (- 1) . (* 2) + +# A parte de la clásica fórmula matemática `f . g`, también cuentas co los operadores +# `>>` y `<<`, que describen el flujo de los valores dentro de las funciones: +double-minus-one = (* 2) >> (- 1) +double-minus-one = (- 1) << (* 2) + +# Hablando del flujo de los valores, LiveScript también tiene los operadores `|>` y `<|` +# que aplican un valor a una función: +map = (f, xs) --> xs.map f +[1 2 3] |> map (* 2) # => [2 4 6] + +# También puedes escoger dónde quieres que el valor se posicione, sólo márcalo con un +# guíon bajo: +reducir = (f, xs, initial) --> xs.reducir f, initial +[1 2 3] |> reducir (+), _, 0 # => 6 + +# El guíon bajo también se usa para apartar lugares para tus argumentos, por ejemplo: +division = (dividendo,divisor) -> dividendo / divisor +dividir-entre-2 = division _, 2 +dividir-entre-2 4 # => 2 + +# Por último, LiveScript tiene back-calls (útiles mecanismos para hacer +# callbacks.). A pesar de esto deberías intentar formas más funcionales de hacerlo, +# como Promises: +leerArchivo = (nombre, f) -> f name +a <- leerArchivo 'foo' +b <- leerArchivo 'bar' +console.log a + b + +# Igual a: +leerArchivo 'foo', (a) -> leerArchivo 'bar', (b) -> console.log a + b + + +######################################################################## +## 4. Patrones, guardias y control de flujo +######################################################################## + +# Puedes bifurcar cálculos con la expresión `if...else`: +x = if n > 0 then \positive else \negative + +# En lugar de `then`, puedes usar `=>` +x = if n > 0 => \positivo + else \negativo + +# A pesar de esto, a las condiciones complejas es mejor expresarlas con el `switch`: +y = {} +x = switch + | (typeof y) is \number => \numero + | (typeof y) is \string => \string + | 'length' of y => \arreglo + | otherwise => \objeto # `otherwise` y `_` son lo mismo. + +# Los cuerpos de las funciones, declaraciones y asignaciones tienen un `switch` por defecto, +# así que no necesitas escribirlo nuevamente: + +take = (n, [x, ...xs]) --> + | n == 0 => [] + | _ => [x] ++ take (n - 1), xs + + +######################################################################## +## 5. Comprehensions (Auxiliares) +######################################################################## + +# Mientras que los auxiliares funcionales (para lidiar con listas y objetos) +# están en la librería estándar de JavaScript (y complementada con prelude-ls, +# que es una "librería estándar" de LiveScipt) los "comprehensions" (Auxiliares) +# usualemente te permiten hacer lo mismo pero más rápido y con una sintaxis más +# comprehensible (de ahí su nombre en inglés): +unoAVeinte = [1 to 20] +pares = [x for x in oneToTwenty when x % 2 == 0] + +# `when` y `unless` pueden ser usados como filtros en el auxiliar. + +# Los auxiliares para objetos funcionan de la misma forma, excepto que regresa un +# objeto en lugar de un arreglo: +copiar = { [k, v] for k, v of source } + + +######################################################################## +## 4. PROGRAMACIÓN ORIENTADA A OBJETOS +######################################################################## + +# Mientras que LiveScript es un lenguaje funcional en la mayoría de los +# aspectos, también brinda ayudas para la programación orientada a objetos. +# Algunas de estas ayudas son la sintaxis para las clases y un poco de "azucar" +# para las clases heredada de CoffeeScript: +class Animal + (@nombre, tipo) -> + @tipo = tipo + action: (accion) -> "*#{@nombre} (un #{@tipo}) #{accion}*" + +class Gato extends Animal + (@nombre) -> super @nombre, 'gato' + ronronear: -> @action 'ronronea' + +gatito = new Gato 'Mei' +gatito.purr! # => "*Mei (un gato) ronronea*" + +# A parte del clásico patrón de herencia simple, también puedes proveer +# cuantas mezclas quieras para una clase. Las mezclas sólo son objetos: +Abrazable = + abrazar: -> @action 'es abrazado' + +class GatoAbrazable extends Gato implements Abrazable + +gatito = new GatoAbrazable 'Ronroneo' +gatito.abrazar! # => "*Mei (un gato) es abrazado*" +``` + +## Más recursos + +Existe mucho más sobre LiveScript, pero esto debe bastar para que empieces. +El [sitio oficial](http://livescript.net/) tiene mucha información sobre el +lenguaje, y un compilador en linea para que pruebes cosas inmediatamente. + +También querras probar un poco de [prelude.ls](http://gkz.github.io/prelude-ls/), +y probar el canal `#livescript` en la red Freenode. -- cgit v1.2.3 From ac8b79daf422ad71d3cda34e9dd7810530c1d620 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Mon, 28 Jul 2014 12:16:02 -0500 Subject: Added lang:es-es --- es-es/livescript-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/livescript-es.html.markdown b/es-es/livescript-es.html.markdown index 538c0a2a..103a3142 100644 --- a/es-es/livescript-es.html.markdown +++ b/es-es/livescript-es.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Christina Whyte", "http://github.com/kurisuwhyte/"] translators: - ["Daniel Zendejas", "http://github.com/DanielZendejas/"] +lang: es-es --- LiveScript es un lenguaje funcional compilado sobre Javascript. Comparte -- cgit v1.2.3 From c87923fd5ce323cd891407e9abf00db5648c7172 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 29 Jul 2014 00:23:32 +0200 Subject: Also we don't support julia highlighting yet. --- zh-cn/julia-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index b91cd7a3..7afc9043 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -8,7 +8,7 @@ translators: lang: zh-cn --- -```julia +```ruby # 单行注释只需要一个井号 #= 多行注释 只需要以 '#=' 开始 '=#' 结束 -- cgit v1.2.3 From 615ee2794184949591f49ff36b3e58c5e166ed39 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Tue, 29 Jul 2014 12:08:24 +0800 Subject: updated the filename into learnmarkdown-cn.md --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 58ef2d6d..975ebcb5 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Fangzhou Chen"] -filename: Markdown-cn.md +filename: learnmarkdown-cn.md lang: zh-cn --- -- cgit v1.2.3 From 739ab0c7cfc741849910f76b3230792db084092e Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Tue, 29 Jul 2014 11:05:24 -0500 Subject: [javascript/es] created --- es-es/javascript-es.html.markdown | 530 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 530 insertions(+) create mode 100644 es-es/javascript-es.html.markdown diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown new file mode 100644 index 00000000..6f7f7c7f --- /dev/null +++ b/es-es/javascript-es.html.markdown @@ -0,0 +1,530 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +translators: + -["Daniel Zendejas","https://github.com/DanielZendejas"] +filename: javascript-es.js +lang: es-es +--- +Tutorial de JavaScript en español. + +JavaScript fue creado por Brendan Eich en 1995 mientras trabajaba en Netscape. +Su intención original era crear un lenguaje simple para sitios web, complementándolo +con Java para aplicaciones más complejas. Debido a su integracion estrecha con sitios +web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común +para front-end que Java. + +JavaScript no sólo se limita a los navegadores web: +* Node.js: Un proyecto que provee con un ambiente para el motor V8 de Google Chrome. + +¡La retroalimentación es bienvenida! Puedes encontrarme en: +[@adambrenecki](https://twitter.com/adambrenecki), o +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// Los comentarios son como en C. Los comentarios de una sola línea comienzan con //, +/* y los comentarios multilínea comienzan + y terminan con */ + +// Cada sentencia puede ser terminada con punto y coma ; +hazAlgo(); + +// ... aunque no es necesario, ya que el punto y coma se agrega automaticamente +// cada que se detecta una nueva línea, a excepción de algunos casos. +hazAlgo() + +// Dado que esta práctica puede llevar a resultados inesperados, seguiremos agregando +// punto y coma en esta guía. + +/////////////////////////////////// +// 1. Números, Strings y Operadores + +// JavaScript tiene un solo tipo de número (doble de 64-bit IEEE 754). +// Así como con Lua, no te espantes por la falta de enteros: los dobles tienen 52 bits +// de mantisa, lo cual es suficiente para guardar enteros de hasta 9✕10¹⁵. +3; // = 3 +1.5; // = 1.5 + +// Toda la aritmética básica funciona como uno esperaría. +1 + 1; // = 2 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Incluyendo divisiones con resultados no enteros. +5 / 2; // = 2.5 + +// Las operaciones con bits también funcionan; cuando ejecutas una operación con bits +// el número flotante se convierte a entero con signo *hasta* 32 bits. +1 << 2; // = 4 + +// La jerarquía de las operaciones se aplica con paréntesis. +(1 + 3) * 2; // = 8 + +// Hay tres casos especiales de valores con los números: +Infinity; // por ejemplo: 1/0 +-Infinity; // por ejemplo: -1/0 +NaN; // por ejemplo: 0/0 + +// También hay booleanos: +true; +false; + +// Los Strings se pueden crear con ' o ". +'abc'; +"Hola, mundo"; + +// La negación se aplica con la expresión ! +!true; // = false +!false; // = true + +// Para comprobar una igualdad se usa == +1 == 1; // = true +2 == 1; // = false + +// Para comprobar una desigualdad se usa != +1 != 1; // = false +2 != 1; // = true + +// Más comparaciones +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Los Strings se concatenan con + +"¡Hola " + "mundo!"; // = "¡Hola mundo!" + +// y se comparan con < y con > +"a" < "b"; // = true + +// Los tipos no importan con el operador ==... +"5" == 5; // = true + +// ...a menos que uses === +"5" === 5; // = false + +// Los Strings funcionan como arreglos de caracteres +// Puedes accesar a cada caracter con la función charAt() +"Este es un String".charAt(0); // = 'E' + +// ...o puedes usar la función substring() para acceder a pedazos más grandes +"Hola Mundo".substring(0, 4); // = "Hola" + +// length es una propiedad, así que no uses () +"Hola".length; // = 4 + +// También hay null y undefined +null; // usado para indicar una falta de valor deliberada +undefined; // usado para indicar que un valor no está presente actualmente + // (aunque undefined es un valor en sí mismo) + +// false, null, undefined, NaN, 0 y "" es false; todo lo demás es true. +// Note que 0 is false y "0" es true, a pesar de que 0 == "0". +// Aunque 0 === "0" sí es false. + +/////////////////////////////////// +// 2. Variables, Arreglos y Objetos + +// Las variables se declaran con la palabra var. JavaScript cuenta con tipado dinámico, +// así que no se necesitan aplicar tipos. La asignación se logra con el operador =. +var miPrimeraVariable = 5; + +// si no escribes la palabra var no se marcará ningún error... +miSegundaVariable = 10; + +// ...pero tu variable se declarará en el ámbito global, no en el ámbito +// en el que se definió. + +// Las variables que no están aún asignadas tienen el valor undefined. +var miTerceraVariable; // = undefined + +// Existen atajos para realizar operaciones aritméticas: +miPrimeraVariable += 5; // equivalente a miPrimeraVariable = miPrimeraVariable + 5; + // miPrimeraVariable ahora es 10 +miPrimeraVariable *= 10; // ahora miPrimeraVariable es 100 + +// Y atajos aún más cortos para sumar y restar 1 +miPrimeraVariable++; // ahora miPrimeraVariable es 101 +miPrimeraVariable--; // de vuelta a 100 + +// Los arreglos son listas ordenadas de valores, de cualquier tipo. +var miArreglo = ["Hola", 45, true]; + +// Los miembros de un arreglo pueden ser accesados con la sintaxis +// de indices dentro de corchetes []. +// Los índices empiezan en cero. +miArreglo[1]; // = 45 + +// Los arreglos son mutables y pueden cambiar de longitud. +miArreglo.push("Mundo"); +miArreglo.length; // = 4 + +// Agregar/Modificar en un determinado índice +miArreglo[3] = "Hola"; + +// Los objetos en JavaScript son equivalentes a los 'diccionarios' o 'mapas' en otros +// lenguajes: una colección de pares llave/valor desordenada. +var miObjeto = {llave1: "Hola", llave2: "Mundo"}; + +// Las llaves son strings, pero no se necesitan las comillas si son un identificador +// válido de JavaScript. Los valores pueden ser de cualquier tipo. +var miObjeto = {miLlave: "miValor", "mi otra llave": 4}; + +// Los atributos de los objetos también pueden ser accesadas usando +// la sintaxis de corchetes, +miObjeto["mi otra llave"]; // = 4 + +// ... o usando la sintaxis de punto, dado que la llave es un identificador válido. +miObjeto.miLlave; // = "miValor" + +// Los objetos son mutables; los valores pueden ser cambiados y se pueden +// agregar nuevas llaves. +miObjeto.miTerceraLlave = true; + +// Si intentas accesar con una llave que aún no está asignada tendrás undefined. +miObjeto.miCuartaLlave; // = undefined + +/////////////////////////////////// +// 3. Lógica y estructura de control + +// La sintaxis de esta sección es casi idéntica a la de Java. + +// La estructura if funciona de la misma forma. +var contador = 1; +if (contador == 3){ + // evaluar si contador es igual a 3 +} else if (contador == 4){ + // evaluar si contador es igual a 4 +} else { + // evaluar si contador no es igual a 3 ni a 4 +} + +// De la misma forma la estructura while. +while (true){ + // ¡Loop infinito! +} + +// La estructura Do-while es igual al while, excepto que se ejecuta al menos una vez. +var input +do { + input = conseguirInput(); +} while (!esValido(input)) + +// la esctructura for es la misma que la de C y Java: +// inicialización; condición; iteración. +for (var i = 0; i < 5; i++){ + // correrá cinco veces +} + +// && es un "y" lógico, || es un "o" lógico +var casa = {tamano:"grande",casa:"color"}; +if (casa.tamano == "grande" && casa.color == "azul"){ + casa.contiene = "oso"; +} +if (color == "rojo" || color == "azul"){ + // el color es rojo o azul +} + +// && y || "corto circuito", lo cual es útil para establecer valores por defecto. +var nombre = otroNombre || "default"; + + +// la estructura switch usa === para sus comparaciones +// usa 'break' para terminar cada caso +// o los casos después del caso correcto serán ejecutados también. +calificacion = 'B'; +switch (calificacion) { + case 'A': + console.log("Excelente trabajo"); + break; + case 'B': + console.log("Buen trabajo"); + break; + case 'C': + console.log("Puedes hacerlo mejor"); + break; + default: + console.log("Muy mal"); + break; +} + + +/////////////////////////////////// +// 4. Funciones, ámbitos y closures + +// Las funciones en JavaScript son declaradas con la palabra clave "function". +function miFuncion(miArgumentoString){ + return miArgumentoString.toUpperCase(); //la funcion toUpperCase() vuelve todo + // el String a mayúsculas +} +miFuncion("foo"); // = "FOO" + +// Note que el valor a ser regresado debe estar en la misma línea que la +// palabra clave 'return', de otra forma la función siempre regresará 'undefined' +// debido a la inserción automática de punto y coma. +function miFuncion() +{ + return // <- punto y coma insertado aquí automáticamente + { + estaEsUna: 'propiedad' + } +} +miFuncion(); // = undefined al mandar a llamar la función + +// Las funciones en JavaScript son de primera clase, así que pueden ser asignadas +// a variables y pasadas a otras funciones como argumentos - por ejemplo: +function miFuncion(){ + // este código será llamado cada cinco segundos +} +setTimeout(miFuncion, 5000); +// Note: setTimeout no es parte de JS, pero lo puedes obtener de los browsers +// y Node.js. + +// Es posible declarar funciones sin nombre - se llaman funciones anónimas +// y se definen como argumentos de otras funciones. +setTimeout(function(){ + // este código se ejecuta cada cinco segundos +}, 5000); + +// JavaScript tiene ámbitos de funciones; las funciones tienen su propio ámbito pero +// otros bloques no. +if (true){ + var i = 5; +} +i; // = 5 - en un lenguaje que da ámbitos por bloque esto sería undefined, pero no aquí. + +// Este conlleva a un patrón de diseño común llamado "ejecutar funciones anónimas +//inmediatamente", que preveé variables temporales de fugarse al ámbito global +(function(){ + var temporal = 5; + // Podemos accesar al ámbito global asignando al 'objeto global', el cual + // en un navegador siempre es 'window'. El objeto global puede tener + // un nombre diferente en ambientes distintos, por ejemplo Node.js . + window.permanente = 10; +})(); +temporal; // da ReferenceError +permanente; // = 10 + +// Una de las características más útiles de JavaScript son los closures. +// Si una función es definida dentro de otra función, la función interna tiene acceso +// a todas las variables de la función externa, incluso aunque la función +// externa ya haya terminado. +function decirHolaCadaCincoSegundos(nombre){ + var texto = "¡Hola, " + nombre + "!"; + // Las funciones internas son puestas en el ámbito local por defecto + // como si fueran declaradas con 'var'. + function interna(){ + alert(texto); + } + setTimeout(interna, 5000); + // setTimeout es asíncrono, así que la funcion decirHolaCadaCincoSegundos + // terminará inmediatamente, y setTimeout llamará a interna() a los cinco segundos + // Como interna está "cerrada dentro de" decirHolaCadaCindoSegundos, interna todavía tiene + // acceso a la variable 'texto' cuando es llamada. +} +decirHolaCadaCincoSegundos("Adam"); // mostrará una alerta con "¡Hola, Adam!" en 5s + +/////////////////////////////////// +// 5. Más sobre objetos; constructores y prototipos + +// Los objetos pueden contener funciones. +var miObjeto = { + miFuncion: function(){ + return "¡Hola Mundo!"; + } +}; +miObjeto.miFuncion(); // = "¡Hola Mundo!" + +// Cuando las funciones de un objeto son llamadas, pueden accesar a las variables +// del objeto con la palabra clave 'this'. +miObjeto = { + miString: "¡Hola Mundo!", + miFuncion: function(){ + return this.miString; + } +}; +miObjeto.miFuncion(); // = "¡Hola Mundo!" + +// Las funciones de un objeto deben ser llamadas dentro del contexto de ese objeto. +var miFuncion = myObj.miFuncion; +miFuncion(); // = undefined + +// Una función puede ser asignada al objeto y ganar acceso a él gracias a esto, +// incluso si no estaba dentro del objeto cuando este se definió. +var miOtraFuncion = function(){ + return this.miString.toUpperCase(); +} +miObjeto.miOtraFuncion = myOtherFunc; +miObjeto.miOtraFuncion(); // = "¡HOLA MUNDO!" + +// Podemos especificar el contexto en el que una función será llamada con los comandos +// 'call' o 'apply'. + +var otraFuncion = function(otroString){ + return this.miString + otroString; +} +otraFuncion.call(miObjeto, " y hola Luna!"); // = "¡Hola Mundo! y hola Luna!" + +// 'apply' es casi idéntico, pero recibe un arreglo como argumento. + +otraFuncion.apply(miObjeto, [" y hola Sol!"]); // = "¡Hola Mundo! y hola Sol!" + +// Esto es útil cuando estás trabajando con una función que acepta una secuencia de +// argumentos y quieres pasar un arreglo. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Pero 'call' y 'apply' sólo son temporales. Cuando queremos que se quede, usamos bind. + +var funcionUnida = otraFuncion.bind(miObjeto); +funcionUnida(" y hola Saturno!"); // = "¡Hola Mundo! y hola Saturno!" + +// Bind también puede ser usada para aplicar parcialmente (curry) una función. + +var producto = function(a, b){ return a * b; } +var porDos = producto.bind(this, 2); +porDos(8); // = 16 + +// Cuando llamas a una función con la palabra clave 'new' un nuevo objeto es creado. +// Se hace disponible a la función. Las funciones diseñadas para ser usadas así se +// llaman constructores. + +var MiConstructor = function(){ + this.miNumero = 5; +} +miNuevoObjeto = new MiConstructor(); // = {miNumero: 5} +miNuevoObjeto.miNumero; // = 5 + +// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a accesar a una +// propiedad en un objeto que no existe en el objeto el intérprete buscará en +// el prototipo. + +// Algunas implementaciones de JavaScript te permiten accesar al prototipo de +// un objeto con la propiedad __proto__. Mientras que esto es útil para explicar +// prototipos, no es parte del estándar; veremos formas estándar de usar prototipos +// más adelante. + +var miObjeto = { + miString: "¡Hola Mundo!" +}; +var miPrototipo = { + sentidoDeLaVida: 42, + miFuncion: function(){ + return this.miString.toLowerCase() + } +}; + +miObjeto.__proto__ = miPrototipo; +miObjeto.sentidoDeLaVida; // = 42 + +// Esto funcionan también para funciones. +miObjeto.miFuncion(); // = "hello world!" + +// Por supuesto, si la propiedad que buscas no está en el prototipo, +// se buscará en el prototipo del prototipo. +miPrototipo.__proto__ = { + miBoolean: true +}; +miObjeto.miBoolean; // = true + +// Esto no involucra ningún copiado, cada objeto guarda una referencia a su +// prototipo. Esto significa que podemos alterar el prototipo y nuestros +// cambios serán reflejados en todos lados. +miPrototipo.sentidoDeLaVida = 43; +miObjeto.sentidoDeLaVida; // = 43 + +// Mencionabamos anteriormente que __proto__ no está estandarizado, y que no +// existe una forma estándar de accesar al prototipo de un objeto. De todas formas. +// hay dos formas de crear un nuevo objeto con un prototipo dado. + +// El primer método es Object.create, el cual es una adición reciente a JavaScript, +// y por lo tanto, no disponible para todas las implementaciones aún. +var miObjeto = Object.create(miPrototipo); +miObjeto.sentidoDeLaVida; // = 43 + +// El segundo método, el cual trabaja en todos lados, tiene que ver con los +// constructores. Los constructores tienen una propiedad llamada prototype. +// Este NO ES el prototipo de la función constructor; es el prototipo que +// se le da a los nuevos objetos cuando son creados con la palabra clave +// new. + +MiConstructor.prototype = { + miNumero: 5, + getMiNumero: function(){ + return this.miNumero; + } +}; +var miNuevoObjeto2 = new MiConstructor(); +miNuevoObjeto2.getMiNumero(); // = 5 +miNuevoObjeto2.miNumero = 6 +miNuevoObjeto2.getMiNumero(); // = 6 + +// Los tipos que vienen por defecto en JavaScript (como Strings y números) +// también tienen constructores que crean objetos equivalentes. +var miNumero = 12; +var miNumeroObjeto = new Number(12); +miNumero == miNumeroObjeto; // = true + +// No son exactamente iguales. +typeof(miNumero); // = 'number' +typeof(miNumeroObjeto); // = 'object' +miNumero === miNumeroObjeyo; // = false +if (0){ + // Este código no se ejecutara porque 0 es false. +} +if (Number(0)){ + // Este código sí se ejecutara, puesto que Number(0) es true. +} + +// Aún así, los objetos que envuelven y los prototipos por defecto comparten +// un prototipo. así que puedes agregar funcionalidades a un string de la +// siguiente forma: +String.prototype.primerCaracter = function(){ + return this.charAt(0); +} +"abc".primerCaracter(); // = "a" + +// Este hecho se usa normalmente en "polyfilling", lo cual es implementar +// nuevas funciones a JavaScript en un JavaScript más viejo, así que pueda ser +// compatible con ambintes más viejos de JavaScript (por ejemplo, navegadores viejos). + +// Por ejemplo, mencionabamos que Object.create no está aún disponible en todas +// las implementaciones, pero podemos hacerlo con polyfill: +if (Object.create === undefined){ // esta validación sirve para no sobreescribir + Object.create = function(proto){ + // hace un constructor temporal con el prototipo correcto + var Constructor = function(){}; + Constructor.prototype = proto; + // y luego lo usamos para hacer un objeto con el prototipo + // correcto. + return new Constructor(); + } +} +``` + +## Fuentes y Referencias + +La [Red para Desarroladores de Mozilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript) +proveé excelente documentación para JavaScript para navegadores. Además, está en formato de wiki, +por lo que mientras vayas aprendiendo podrás ayudar a los demás con tu experiencia. + +MDN [Una re-introducción a JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +cubre muchos de los conceptos que vimos aquí pero a mayor detalle. Esta guía cubre, más que nada, +el lenguaje JavaScript solo. Si quieres aprender a cómo usarlo en un ambiente web empieza aprendiendo +sobre el [DOM](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Aprende JavaScript con ejemplos y retos](http://www.learneroo.com/modules/64/nodes/350) es una +variante de esta guía pero con retos. + +[Jardín JavaScript](http://bonsaiden.github.io/JavaScript-Garden/) es una guía para todas las +funciones y características contra-intuitivas del lenguaje. + +[JavaScript: La guía definitiva](http://www.amazon.com/gp/product/0596805527/) es una guía clásica / libro de referencia. + +Aparte de las contribuciones directas para este artículo, algo del contenido se adaptó +del tutorial de Python por Louie Dinh en este sitio. y el [Tutorial JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) en la Red de Desarrolladores de Mozilla. -- cgit v1.2.3 From 3a2d6d2f67f012af162231dc1bdab571f12a3add Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Tue, 29 Jul 2014 14:35:15 -0500 Subject: Markdown syntax error corrected --- es-es/javascript-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index 6f7f7c7f..9b412f6e 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - -["Daniel Zendejas","https://github.com/DanielZendejas"] + - ["Daniel Zendejas","https://github.com/DanielZendejas"] filename: javascript-es.js lang: es-es --- -- cgit v1.2.3 From 2ff257b551c4a156887b2c630e81f225ea318236 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Tue, 29 Jul 2014 23:42:52 +0200 Subject: Statement prefixes also MAIN. some links under "Going further" TODO start TODO flattening TODO regexps --- perl6.html.markdown | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/perl6.html.markdown b/perl6.html.markdown index b21cb1fa..e2c82a58 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -411,6 +411,7 @@ sub next-index($n) { $n + 1; } my $new-n = next-index(3); # $new-n is now 4 + # This is true for everything, except for the looping constructs (due to performance reasons): # there's no purpose in building a list if we're just going to discard all the results. # If you still want to build one, you can use the `do` prefix: (or the `gather` prefix, which we'll see later) @@ -710,6 +711,10 @@ Foo::Bar::inc; #=> 3 constant Pi = 3.14; constant $var = 1; +# And if you're wondering, yes, it can also contain infinite lists. +constant why-not = 5, 15 ... *; +say why-not[^5]; #=> 5 15 25 35 45 + ## * `state` (happens at run time, but only once) # State variables are only executed one time # (they exist in other langages such as C as `static`) @@ -782,6 +787,62 @@ sub do-db-stuff { UNDO $db.rollback; # or rollback if all hell broke loose } +### Statement prefixes +# Those act a bit like phasers: they affect the behavior of the following code. +# Though, they run in-line with the executable code, so they're in lowercase. +# (`try` and `start` are theoretically in that list, but explained somewhere else) +# Note: all of these (except start) don't need explicit brackets (`{` and `}`) for their block. + +# - `do` (that you already saw) - runs a block or a statement as a term +# You can't normally use a statement as a value (or "term"): +# +# my $value = if True { 1 } # `if` is a statement - parse error +# +# This works: +my $a = do if True { 5 } # with `do`, `if` is now a term. + +# - `once` - Makes sure a piece of code only runs once +for ^5 { once say 1 }; #=> 1 + # Only prints ... once. +# Like `state`, they're cloned per-scope +for ^5 { sub { once say 1 }() } #=> 1 1 1 1 1 + # Prints once per lexical scope + +# - `gather` - Co-routine thread +# Gather allows you to `take` several values in an array, +# much like `do`, but allows you to take any expression. +say gather for ^5 { + take $_ * 3 - 1; + take $_ * 3 + 1; +} #=> -1 1 2 4 5 7 8 10 11 13 +say join ',', gather if False { + take 1; + take 2; + take 3; +} # Doesn't print anything. + +# - `eager` - Evaluate statement eagerly (forces eager context) +# Don't try this at home: +# +# eager 1..*; # this will probably hang for a while (and might crash ...). +# +# 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 + +# - `lazy` - Defer actual evaluation until value is fetched (forces lazy context) +# Not yet implemented !! + +# - `sink` - An `eager` that discards the results (forces sink context) +constant nilthingie = sink for ^3 { .say } #=> 0 1 2 +say nilthingie.perl; #=> Nil + +# - `quietly` - Supresses warnings +# Not yet implemented ! + +# - `contend` - Attempts side effects under STM +# Not yet implemented ! ### More operators thingies ! @@ -1004,4 +1065,37 @@ for { # but the `^` makes it *not run* on the first iteration #=> b c } + +### Extra: the MAIN subroutime +# The `MAIN` subroutine is called when you run a Perl 6 file directly. +# It's very powerful, because Perl 6 actually parses the argument +# and pass them as such to the sub. It also handles named argument (`--foo`) +# and will even go as far as to autogenerate a `--help` +sub MAIN($name) { say "Hello, you !" } +# This produces: +# $ perl6 cli.pl +# Usage: +# t.pl + +# And since it's a regular Perl 6 sub, you can haz multi-dispatch: +# (using a "Bool" for the named argument so that we get `--replace` instead of `--replace=`) +subset File of Str where *.IO.d; # convert to IO object, then check the file exists + +multi MAIN('add', $key, $value, Bool :$replace) { ... } +multi MAIN('remove', $key) { ... } +multi MAIN('import', File, Str :$as) { ... } # omitting parameter name +# This produces: +# $ perl 6 cli.pl +# Usage: +# t.pl [--replace] add +# t.pl remove +# t.pl [--as=] import (File) +# As you can see, this is *very* powerful. It even went as far as to show inline the constants. +# (the type is only displayed if 1. there's no argument name 2. it's a named argument) ``` + +If you want to go further, you can: + - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This is probably the greatest source of Perl 6 information, snippets and such. + - Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful. + - Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize). + - Read the [Synopses](perlcabal.org/syn). They explain it from an implementor point-of-view, but it's still very interesting. -- cgit v1.2.3 From fe228e44e61f09f570dbb91635c46bbae8d382a0 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 30 Jul 2014 10:33:33 -0500 Subject: [xml/es] created --- es-es/xml-es.html.markdown | 131 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 es-es/xml-es.html.markdown diff --git a/es-es/xml-es.html.markdown b/es-es/xml-es.html.markdown new file mode 100644 index 00000000..2e9326cf --- /dev/null +++ b/es-es/xml-es.html.markdown @@ -0,0 +1,131 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Daniel Zendejas", "https://github.com/DanielZendejas"] +lang: es-es +--- +XML es un lenguaje diseñado para guardar y transportar datos + +A diferencia de HTML, XML no especifica cómo desplegar la información, +sólo la guarda. + +* Sintaxis XML + +```xml + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + + + +computer.gif + + +``` + +* Documentos con buen formato x Validación + +Un documento XML está bien formado cuando es sintácticamente correcto. +Aún esto, es posible inyectar más restricciones en el documento, +usando definiciones de documento, así como DTD o XML Schemas. + +Un documento XML que sigue a una definición de documento (un esquema) es +válida. + +Con esta herramienta puedes validar datos XML fuera de la aplicación + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + +]> + + + Everyday Italian + 30.00 + + +``` -- cgit v1.2.3 From 9680347c90bfc36f44a95176eab153793d34d838 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 30 Jul 2014 12:09:18 -0500 Subject: [yaml/es] created --- es-es/yaml-es.html.markdown | 150 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 es-es/yaml-es.html.markdown diff --git a/es-es/yaml-es.html.markdown b/es-es/yaml-es.html.markdown new file mode 100644 index 00000000..0423261a --- /dev/null +++ b/es-es/yaml-es.html.markdown @@ -0,0 +1,150 @@ +--- +language: yaml +filename: learnyaml-es.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Daniel Zendejas","https://github.com/DanielZendejas"] +--- +Tutorial de YAML en español. + +YAML es un lenguaje de serialización de datos diseñado para ser +leído y escrito por humanos. + +Basa su funcionalidad en JSON, con la adición de líneas nuevas +e indentación inspirada en Python. A diferencia de Python, YAML +no permite tabs literales. + +```yaml +# Los comentarios en YAML se ven así. + +################### +# TIPOS ESCALARES # +################### + +# Nuestro objeto raíz (el cual es el mismo a lo largo de todo el +# documento) será un mapa, equivalente a un diccionario, hash, +# u objeto en otros lenguajes. + +llave: valor +otra_llave: Otro valor +un_valor_numerico: 100 +notacion_cientifica: 1e+12 +booleano: true +valor_nulo: null +llave con espacios: valor +# Nótese que los strings no deben estar entre comillas, aunqué también es válido. +llave: "Un string, entre comillas." +"Las llaves tambien pueden estar entre comillas.": "valor entre comillas" + +# Los strings de líneas múltiples pueden ser escritos +# como un 'bloque literal' (usando pipes |) +# o como un 'bloque doblado' (usando >) + +bloque_literal: | + Este bloque completo de texto será preservado como el valor de la llave + 'bloque_literal', incluyendo los saltos de línea. + + Se continúa guardando la literal hasta que se cese la indentación. + Cualquier línea que tenga más indentación, mantendrá los espacios dados + (por ejemplo, estas líneas se guardarán con cuatro espacios) + +nloque_doblado: > + De la misma forma que el valor de 'bloque_literal', todas estas + líneas se guardarán como una sola literal, pero en esta ocasión todos los + saltos de línea serán reemplazados por espacio. + + Las líneas en blanco, como la anterior, son convertidos a un salto de línea. + + Las líneas con mayor indentación guardan sus saltos de línea. + Esta literal ocuparán dos líneas. + +######################## +# TIPOS DE COLECCIONES # +######################## + +# La indentación se usa para anidar. +un_mapa_indentado: + llave: valor + otra_llave: otro valor + otro_mapa_indentado: + llave_interna: valor_interno + +# Las llaves de los mapas no deben ser strings necesariamente +0.25: una llave numérica + +# Las llaves también pueden ser objetos de multi línea, usando ? para indicar +# el inicio de una llave +? | + Esto es una llave + que tiene múltiples líneas +: y este es su valor + +# YAML tambien permite colecciones como llaves, pero muchos lenguajes de +# programación se quejarán. + +# Las secuencias (equivalentes a listas o arreglos) se ven así: +una_secuencia: + - Item 1 + - Item 2 + - 0.5 # las secuencias pueden tener distintos tipos en su contenido. + - Item 4 + - llave: valor + otra_llave: otro_valor + - + - Esta es una secuencia + - ...dentro de otra secuencia + +# Dado que todo JSON está incluído dentro de YAML, también puedes escribir +# mapas con la sintaxis de JSON y secuencias: +mapa_de_json: {"llave": "valor"} +secuencia_de_json: [3, 2, 1, "despegue"] + +################################## +# CARACTERÍSTICAS EXTRAS DE YAML # +################################## + +# YAML tiene funciones útiles llamadas 'anchors' (anclas), que te permiten +# duplicar fácilmente contenido a lo largo de tu documento. En el ejemplo +# a continuación, ambas llaves tendrán el mismo valor: +contenido_anclado: &nombre_del_ancla Este string será el valor de las llaves +otra_ancla: *nombre_del_ancla + +# YAML también tiene tags, que puedes usar para declarar tipos explícitamente. +string_explícito: !!str 0.5 +# Algunos parseadores implementar tags específicas del lenguaje, como el +# que se muestra a continuación, encargado de manejar números complejos en +# Python: +numero_complejo_python: !!python/complex 1+2j + +######################## +# TIPOS EXTRAS EN YAML # +######################## + +# Stirngs y números no son los únicos escalares que YAML puede entener. +# YAML también puede parsear fechas en formato ISO . +fechaHora: 2001-12-15T02:59:43.1Z +fechaHora_con_espacios: 2001-12-14 21:59:43.10 -5 +fecha: 2002-12-14 + +# La tag !!binary indica que un string es, en realidad, un blob +# representado en base-64. +archivo_gif: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML también tiene un tipo set, que se ve de la siguiente forma: +set: + ? item1 + ? item2 + ? item3 + +# Al igual que Python, los sets sólo son mapas con valores nulos. +# El ejemplo de arriba es equivalente a: +set2: + item1: null + item2: null + item3: null +``` -- cgit v1.2.3 From 10c07f30d50d9cda4b2ad193b212581c0b32152f Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Thu, 31 Jul 2014 23:28:46 +0200 Subject: REGULAAAAAAR EXPREEEESSSIIIIOOOOOONS. GO! TODO nested sub signatures TODO start TODO flattening --- perl6.html.markdown | 128 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) diff --git a/perl6.html.markdown b/perl6.html.markdown index e2c82a58..567c4629 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1066,6 +1066,134 @@ for { #=> b c } + +### Regular Expressions +# I'm sure a lot of you have been waiting for this one. +# Well, now that you know a good deal of Perl 6 already, we can get started. +# First off, you'll have to forget about "PCRE regexps" (perl-compatible regexps). +# +# IMPORTANT: You may feel like you already know these because you know PCRE. You'd be wrong. +# Some things are the same (like `?`, `+`, and `*`), but sometimes the semantics change (`|`). +# Make sure you read carefully, because you might trip over a new behavior. +# +# Perl 6 has a looot of features related to RegExps. After all, Rakudo parses itself. +# We're first going to look at the syntax itself, then talk about grammars (PEG-like), +# differences between the `token`, `regex` and `rule` keywords, and some more. +# Side note: you still have access to PCRE regexps using the `:P5` modifier. +# (we won't be discussing this in this tutorial, however) +# +# In essence, Perl 6 natively implements PEG ("Parsing Expression Grammars"). +# The pecking order for ambiguous parses is determined by a multi-level tie-breaking test: +# - Longest token matching. `foo\s+` beats `foo` (by 2 or more positions) +# - Longest literal prefix. `food\w*` beats `foo\w*` (by 1) +# - Declaration from most-derived to less derived grammars (grammars are actually classes) +# - Earliest declaration wins +say so 'a' ~~ /a/; #=> True +say so 'a' ~~ / a /; # More readable with some spaces! + +# In all our examples, we're going to use the smart-matching operator against a regexp. +# We're converting the result using `so`, but in fact, it's returning a `Match` object. +# They know how to respond to list indexing, hash indexing (and return the matched string). +# The results of the match are also available as `$/` (implicitly lexically-scoped). +# You can also use the capture variables (`$0`, `$1`, ... - starting at 0, not 1 !). +# +# You can also note that `~~` does not perform start/end checking +# (meaning the regexp can be matched with just one char of the string), +# we're going to explain later how you can do it. + +# In Perl 6, you can have any alphanumeric as a literal, everything else has to be escaped, +# using a backslash or quotes. +say so 'a|b' ~~ / a '|' b /; # `True`. Wouln't mean the same if `|` wasn't escaped +say so 'a|b' ~~ / a \| b /; # `True`. Another way to escape it. + +# The whitespace in a regexp is actually not significant, +# unless you use the `:s` (`:sigspace`, significant space) modifier. +say so 'a b c' ~~ / a b c /; # `False`. Space is not significant here +say so 'a b c' ~~ /:s a b c /; # `True`. We added the modifier `:s` here. + +# It is, however, important as for how modifiers (that you're gonna see just below) +# are applied ... + +## Quantifying - `?`, `+`, `*` and `**`. +# - `?` - 0 or 1 +so 'ac' ~~ / a b c /; # `False` +so 'ac' ~~ / a b? c /; # `True`, the "b" matched 0 times. +so 'abc' ~~ / a b? c /; # `True`, the "b" matched 1 time. + +# ... As you read just before, whitespace is important because it determines +# which part of the regexp is the target of the modifier: +so 'def' ~~ / a b c? /; # `False`. Only the `c` is optional +so 'def' ~~ / ab?c /; # `False`. Whitespace is not significant +so 'def' ~~ / 'abc'? /; # `True`. The whole "abc" group is optional. + +# Here (and below) the quantifier applies only to the `b` + +# - `+` - 1 or more +so 'ac' ~~ / a b+ c /; # `False`; `+` wants at least one matching +so 'abc' ~~ / a b+ c /; # `True`; one is enough +so 'abbbbc' ~~ / a b+ c /; # `True`, matched 4 "b"s + +# - `*` - 0 or more +so 'ac' ~~ / a b* c /; # `True`, they're all optional. +so 'abc' ~~ / a b* c /; # `True` +so 'abbbbc' ~~ / a b* c /; # `True` +so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, but can't be something else. + +# - `**` - "Quantify It Yourself". +# If you squint hard enough, you might understand the why exponentation means quantity. +so 'abc' ~~ / a b ** 1 c /; # `True` (exactly one time) +so 'abc' ~~ / a b ** 1..3 c /; # `True` (one to three times) +so 'abbbc' ~~ / a b ** 1..3 c /; # `True` +so 'abbbbbbc' ~~ / a b ** 1..3 c /; # `False` (too much) +so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay) + +## Grouping and capturing +# Group: you can group parts of your regexp with `[]`. +# These groups are *not* captured (like PCRE's `(?:)`). +so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing +so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; # `True`. + # We match the "abc" 1 or more time. + # (the `+` was applied to the group) + +# But this does not go far enough, because we can't actually get back what we matched. +# Capture: We can actually *capture* the results of the regexp, using parentheses. +so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (we keep `so` here and use `$/` below) + +# So, starting with the grouping explanations. +# As we said before, our `Match` object is available as `$/`: +say $/; # Will print some weird stuff (we'll explain) (or "Nil" if nothing matched). + +# As we also said before, it has array indexing: +say $/[0]; #=> 「ABC」 「ABC」 + # These weird brackets are `Match` objects. So here, we have an array of that. +say $0; # the same as above. + +# Our capture is `$0` because it's the first and only one capture in the regexp. +# You might be wondering why it's an array, and the answer is simple: +# Some capture (indexed using `$0`, `$/[0]` or a named one) will be an array +# IF it can have more than one element (so, with `*`, `+` and any `**`, but not with `?`). +# Let's use examples to see that: +so 'fooABCbar' ~~ / foo ( A B C )? bar /; # `True` +say $/[0]; #=> 「ABC」 +say $0.WHAT; #=> (Match) + # It can't be more than one, so it's only a single match object. +so 'foobar' ~~ / foo ( A B C )? bar /; #=> True +say $0.WHAT; #=> (Any) + # This capture did not match, so it's empty +so 'foobar' ~~ / foo ( A B C ) ** 0..1 bar /; # `True` +say $0.WHAT; #=> (Array) + # A specific quantifier will always capture an Array, + # may it be a range or a specific value (even 1). + +# If you're wondering how the captures are numbered, here's an explanation: +TODO use graphs from s05 + + +## Alternatives - the `or` of regexps +# WARNING: They are DIFFERENT from PCRE regexps. +so 'abc' ~~ / a [ b | y ] c /; # `True`. Either "b" or "y". +so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... + ### Extra: the MAIN subroutime # The `MAIN` subroutine is called when you run a Perl 6 file directly. # It's very powerful, because Perl 6 actually parses the argument -- cgit v1.2.3 From e6a289be491c9b0f1a7c2d5b364de0c4c8241bd9 Mon Sep 17 00:00:00 2001 From: Shashwat986 Date: Sat, 2 Aug 2014 19:37:28 +0530 Subject: Update python.html.markdown Added more details to try/except section. --- python.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index aa077e57..5bec5190 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -334,6 +334,10 @@ try: 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 #################################################### -- cgit v1.2.3 From abc06a620bcb41d3e59c5f0c969d819294edc78e Mon Sep 17 00:00:00 2001 From: Shashwat986 Date: Sun, 3 Aug 2014 21:56:26 +0530 Subject: Update python3.html.markdown Added more info to try/except. Corrected some trivial bugs. --- python3.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index bc0c05bd..531d3b5a 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -330,9 +330,12 @@ try: 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's offers a fundamental abstraction called the Iterable. +# 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. @@ -340,7 +343,7 @@ 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 -i We can loop over it. +# We can loop over it. for i in our_iterable: print(i) # Prints one, two, three -- cgit v1.2.3 From 65a1b6279fa1038efa013f64d98e7e947b527567 Mon Sep 17 00:00:00 2001 From: Shashwat986 Date: Tue, 5 Aug 2014 01:06:54 +0530 Subject: Update python.html.markdown range() is not a generator in python 2.x --- python.html.markdown | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 5bec5190..b7d5895a 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -523,11 +523,13 @@ def double_numbers(iterable): # 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 -_range = range(1, 900000000) +# Note xrange is a generator that does the same thing range does. +# Creating a list 1-900000000 would take lot of time and space to be made. +# xrange creates an xrange generator object instead of creating the entire list like range does. +_xrange = xrange(1, 900000000) + # will double all numbers until a result >=30 found -for i in double_numbers(_range): +for i in double_numbers(_xrange): print(i) if i >= 30: break -- cgit v1.2.3 From cfa26f23fd4f65896f01df2997f64c5ca184f484 Mon Sep 17 00:00:00 2001 From: Jean-Christophe Bohin Date: Mon, 4 Aug 2014 22:23:24 +0200 Subject: [go/en] add an example for range - fixes #351 --- go.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/go.html.markdown b/go.html.markdown index a1be08af..77961524 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -177,6 +177,14 @@ func learnFlowControl() { break // Just kidding. continue // Unreached. } + + // you can use range to iterate over an array, a slice, a string, a map, or a channel. + // range returns one (channel) or two values (array, slice, string and map) + for key, value := range map[string]int{"one": 1, "two": 2, "three": 3} { + // for each pair in the map, print key and value + fmt.Printf("key=%s, value=%d\n", key, value) + } + // As with for, := in an if statement means to declare and assign // y first, then test y > x. if y := expensiveComputation(); y > x { -- cgit v1.2.3 From 0078b03707eeccf50e5bb1d7230e88b4ce3d36be Mon Sep 17 00:00:00 2001 From: Jean-Christophe Bohin Date: Mon, 4 Aug 2014 22:38:53 +0200 Subject: Array initialization disambiguation - fixes #257 simply added proposed comment, which seems fine --- go.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index a1be08af..6c4d88bd 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -92,7 +92,8 @@ can include line breaks.` // Same string type. // Arrays have size fixed at compile time. var a4 [4]int // An array of 4 ints, initialized to all 0. - a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown. + a3 := [...]int{3, 1, 5} // An array initialzed with a fixed size of three + //elements, with values 3,1, and 5 // Slices have dynamic size. Arrays and slices each have advantages // but use cases for slices are much more common. -- cgit v1.2.3 From 2ffd79293239dd5c0a85a18500e83f362991e062 Mon Sep 17 00:00:00 2001 From: Jean-Christophe Bohin Date: Tue, 5 Aug 2014 09:03:21 +0200 Subject: Adding Go playground link with code - fixes #318 Just removed networking code, since Go playground's sandbox prevent it to work. --- go.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/go.html.markdown b/go.html.markdown index a1be08af..88c98c21 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -378,6 +378,8 @@ There you can follow the tutorial, play interactively, and read lots. The language definition itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) +You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! + On the reading list for students of Go is the [source code to the standard library](http://golang.org/src/pkg/). Comprehensively documented, it demonstrates the best of readable and understandable Go, Go style, and Go -- cgit v1.2.3 From 57036f128f5e874116729e67d8a77cd763f206d5 Mon Sep 17 00:00:00 2001 From: Evgeniy Ginzburg Date: Tue, 5 Aug 2014 17:41:28 +0300 Subject: aded negative integer division --- python3.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index bc0c05bd..de6d552a 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -38,9 +38,11 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Except division which returns floats by default 35 / 5 # => 7.0 -# Truncation or Integer division +# Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 5.0 // 3.0 # => 1.0 +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 # When you use a float, results are floats 3 * 2.0 # => 6.0 @@ -51,7 +53,6 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Enforce precedence with parentheses (1 + 3) * 2 # => 8 - # Boolean values are primitives True False @@ -60,7 +61,6 @@ False not True # => False not False # => True - # Equality is == 1 == 1 # => True 2 == 1 # => False @@ -79,7 +79,6 @@ not False # => True 1 < 2 < 3 # => True 2 < 3 < 2 # => False - # Strings are created with " or ' "This is a string." 'This is also a string.' -- cgit v1.2.3 From 170de5223165b0f9aa763b171bed153c4073648d Mon Sep 17 00:00:00 2001 From: Patrick Sebastian Zimmermann Date: Tue, 5 Aug 2014 19:50:19 +0200 Subject: Minor fixes to return values. --- perl6.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 567c4629..92219708 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -92,7 +92,7 @@ sub as-many($head, *@rest) { # the `*@` slurpy will basically "take everything e # but not *after*. say @rest.join(' / ') ~ " !"; } -say as-many('Happy', 'Happy', 'Birthday'); #=> Happy Birthday ! +say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! # Note that the splat did not consume the parameter before. ## You can call a function with an array using the "argument list flattening" operator `|` @@ -127,7 +127,7 @@ sub with-named($normal-arg, :$named) { } with-named(1, named => 6); #=> 7 # There's one gotcha to be aware of, here: -# If you quote your key, Perl 6 won't be able to see it as compile time, +# If you quote your key, Perl 6 won't be able to see it at compile time, # and you'll have a single Pair object as a positional paramater. with-named(2, :named(5)); #=> 7 @@ -171,9 +171,9 @@ named-def(def => 15); #=> 15 ### Containers # In Perl 6, values are actually stored in "containers". -# the assignment operator asks the container on the left to store the value on its right +# The assignment operator asks the container on the left to store the value on its right. # When passed around, containers are marked as immutable. Which means that, in a function, -# you'll get an error if you try to mutate one of your argument. +# you'll get an error if you try to mutate one of your arguments. # If you really need to, you can ask for a mutable container using `is rw` : sub mutate($n is rw) { $n++; @@ -374,7 +374,7 @@ sub foo(@array [$fst, $snd]) { say "My first is $fst, my second is $snd ! All in all, I'm @array[]."; # (^ remember the `[]` to interpolate the array) } -foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 1 2 +foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 2 3 # If you're not using the array itself, you can also keep it anonymous, much like a scalar: -- cgit v1.2.3 From 472142d11f8052f6042a8cd4366c7ea7d6680c0d Mon Sep 17 00:00:00 2001 From: "Mikael E. Wikner" Date: Wed, 30 Jul 2014 11:28:21 +0200 Subject: Squashed commits to prepare for merge moved underscore for range variable, added comment renamed parameter in beg decorator added comment about double underscores Update python.html.markdown --- python.html.markdown | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index b7d5895a..73963a3c 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -439,7 +439,10 @@ class Human(object): # A class attribute. It is shared by all instances of this class species = "H. sapiens" - # Basic initializer + # 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. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name @@ -526,10 +529,12 @@ def double_numbers(iterable): # Note xrange is a generator that does the same thing range does. # Creating a list 1-900000000 would take lot of time and space to be made. # xrange creates an xrange generator object instead of creating the entire list like range does. -_xrange = xrange(1, 900000000) +# We use a trailing underscore in variable names when we want to use a name that +# would normally collide with a python keyword +xrange_ = xrange(1, 900000000) # will double all numbers until a result >=30 found -for i in double_numbers(_xrange): +for i in double_numbers(xrange_): print(i) if i >= 30: break @@ -542,10 +547,10 @@ for i in double_numbers(_xrange): from functools import wraps -def beg(_say): - @wraps(_say) +def beg(target_function): + @wraps(target_function) def wrapper(*args, **kwargs): - msg, say_please = _say(*args, **kwargs) + msg, say_please = target_function(*args, **kwargs) if say_please: return "{} {}".format(msg, "Please! I am poor :(") return msg -- cgit v1.2.3 From a30c76789e12e9b73278b382c42f2046692cd678 Mon Sep 17 00:00:00 2001 From: "Mikael E. Wikner" Date: Wed, 6 Aug 2014 00:20:24 +0200 Subject: Added changes to the python3 file aswell --- python3.html.markdown | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 531d3b5a..08eeb86b 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -471,7 +471,10 @@ class Human(object): # A class attribute. It is shared by all instances of this class species = "H. sapiens" - # Basic initializer + # 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. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name @@ -557,9 +560,11 @@ def double_numbers(iterable): # double_numbers. # Note range is a generator too. Creating a list 1-900000000 would take lot of # time to be made -_range = range(1, 900000000) +# 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): +for i in double_numbers(range_): print(i) if i >= 30: break @@ -572,10 +577,10 @@ for i in double_numbers(_range): from functools import wraps -def beg(_say): - @wraps(_say) +def beg(target_function): + @wraps(target_function) def wrapper(*args, **kwargs): - msg, say_please = _say(*args, **kwargs) + msg, say_please = target_function(*args, **kwargs) if say_please: return "{} {}".format(msg, "Please! I am poor :(") return msg -- cgit v1.2.3 From 3f8dbe8e77ca8b1602a317e218b78df94afd8f66 Mon Sep 17 00:00:00 2001 From: LumenTeun Date: Wed, 6 Aug 2014 19:30:15 +0100 Subject: && and || in Bash if statements. --- bash.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 15d1c068..845ebead 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] - ["Denis Arh", "https://github.com/darh"] - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] filename: LearnBash.sh --- @@ -81,6 +82,17 @@ fi echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" +# To use && and || with if statements, you need multiple pairs of square brackets: +if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] +then + echo "This will run if $NAME is Steve AND $AGE is 15." +fi + +if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] +then + echo "This will run if $NAME is Daniya OR Zach." +fi + # Expressions are denoted with the following format: echo $(( 10 + 5 )) -- cgit v1.2.3 From daf83c91232a259eee4cadef5f28210b7c83316d Mon Sep 17 00:00:00 2001 From: Evgeniy Ginzburg Date: Wed, 6 Aug 2014 23:43:37 +0300 Subject: aded negative integer division same as in python3 --- python.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index b7d5895a..312e3c15 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -45,9 +45,11 @@ to Python 2.x. Look for another tour of Python 3 soon! 2.0 # This is a float 11.0 / 4.0 # => 2.75 ahhh...much better -# Truncation or Integer division +# 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 # Modulo operation 7 % 3 # => 1 -- cgit v1.2.3 From 7bcf65278c28cffd32ef051965c2e6401563acc9 Mon Sep 17 00:00:00 2001 From: Evgeniy Ginzburg Date: Wed, 6 Aug 2014 23:45:37 +0300 Subject: comment about floats in integer division --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index 6e901b6a..dc972196 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -40,7 +40,7 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 -5.0 // 3.0 # => 1.0 +5.0 // 3.0 # => 1.0 # works on floats too -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 -- cgit v1.2.3 From 09b19309862cde84d68e05f1f3aa5e534a9185ae Mon Sep 17 00:00:00 2001 From: Kado Date: Thu, 7 Aug 2014 09:55:27 +0300 Subject: Spelling error From datetype to datatype --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 50875491..3484aee5 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -103,7 +103,7 @@ public class LearnJava { //The array size must be decided upon instantiation //The following formats work for declaring an arrow // [] = new []; - // [] = new []; + // [] = new []; int [] intArray = new int[10]; String [] stringArray = new String[1]; boolean boolArray [] = new boolean[100]; -- cgit v1.2.3 From e110db4db65b3a3dcc21b2088bf6278334279065 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 7 Aug 2014 17:53:03 +0400 Subject: 1 part of Russian translation. --- ru-ru/lua-ru.html.markdown | 422 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 422 insertions(+) create mode 100644 ru-ru/lua-ru.html.markdown diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown new file mode 100644 index 00000000..55fc7bb9 --- /dev/null +++ b/ru-ru/lua-ru.html.markdown @@ -0,0 +1,422 @@ +--- +language: lua +filename: learnlua-ru.lua +contributors: + - ["Tyler Neylon", "http://tylerneylon.com/"] +translators: + - ["Max Solomonov", "https://vk.com/solomonovmaksim"] +lang: ru-ru +--- + +```lua +-- Два дефиса начинают однострочный комментарий. + +--[[ + Добавление двух квадратных скобок + делает комментарий многострочным. +--]] +-------------------------------------------------------------------------------- +-- 1. Переменные, циклы и условия. +-------------------------------------------------------------------------------- + +num = 42 -- Все числа являются типом double. +--[[ + Не волнуйся, 64-битные double имеют 52 бита + для хранения именно целочисленных значений; + точность не является проблемой для + целочисленных значений, занимающих меньше + 52 бит. +--]] + +s = 'walternate' -- Неизменные строки как в Python. +t = "Двойные кавычки также приветствуются" +u = [[ Двойные квадратные скобки + начинают и заканчивают + многострочные значения.]] +t = nil -- Удаляет определение переменной t; Lua имеет мусорку. + +-- Циклы и условия имеют ключевые слова, такие как do/end: +while num < 50 do + num = num + 1 -- Здесь нет ++ или += операторов. +end + +-- Условие "если": +if num > 40 then + print('больше 40') +elseif s ~= 'walternate' then -- ~= обозначает "не равно". + -- Проверка равенства это == как в Python; ok для строк. + io.write('не больше 40\n') -- По умолчанию стандартный вывод. +else + -- По умолчанию переменные являются глобальными. + thisIsGlobal = 5 -- Стиль CamelСase является общим. + + -- Как сделать локальную переменную: + local line = io.read() -- Считывает введённую строку. + + -- Конкатенация строк использует .. оператор: + print('Зима пришла, ' .. line) +end + +-- Неопределённые переменные возвращают nil. +-- Этот пример не является ошибочным: +foo = anUnknownVariable -- Теперь foo = nil. + +aBoolValue = false + +-- Только значения nil и false являются ложными; 0 и '' являются истинными! +if not aBoolValue then print('это значение ложно') end + +--[[ + Для 'or' и 'and' действует принцип "какой оператор дальше, + тот и применается". Это действует аналогично a?b:c + операторам в C/js: +--]] +ans = aBoolValue and 'yes' or 'no' --> 'no' + +karlSum = 0 +for i = 1, 100 do -- The range includes both ends. + karlSum = karlSum + i +end + +-- Use "100, 1, -1" as the range to count down: +fredSum = 0 +for j = 100, 1, -1 do fredSum = fredSum + j end + +-- In general, the range is begin, end[, step]. + +-- Another loop construct: +repeat + print('the way of the future') + num = num - 1 +until num == 0 + +-------------------------------------------------------------------------------- +-- 2. Functions. +-------------------------------------------------------------------------------- + +function fib(n) + if n < 2 then return n end + return fib(n - 2) + fib(n - 1) +end + +-- Closures and anonymous functions are ok: +function adder(x) + -- The returned function is created when adder is called, and remembers the + -- value of x: + return function (y) return x + y end +end +a1 = adder(9) +a2 = adder(36) +print(a1(16)) --> 25 +print(a2(64)) --> 100 + +-- Returns, func calls, and assignments all work with lists that may be +-- mismatched in length. Unmatched receivers are nil; unmatched senders are +-- discarded. + +x, y, z = 1, 2, 3, 4 +-- Now x = 1, y = 2, z = 3, and 4 is thrown away. + +function bar(a, b, c) + print(a, b, c) + return 4, 8, 15, 16, 23, 42 +end + +x, y = bar('zaphod') --> prints "zaphod nil nil" +-- Now x = 4, y = 8, values 15..42 are discarded. + +-- Functions are first-class, may be local/global. These are the same: +function f(x) return x * x end +f = function (x) return x * x end + +-- And so are these: +local function g(x) return math.sin(x) end +local g = function(x) return math.sin(x) end +-- Equivalent to local function g(x)..., except referring to g in the function +-- body won't work as expected. +local g; g = function (x) return math.sin(x) end +-- the 'local g' decl makes g-self-references ok. + +-- Trig funcs work in radians, by the way. + +-- Calls with one string param don't need parens: +print 'hello' -- Works fine. + +-- Calls with one table param don't need parens either (more on tables below): +print {} -- Works fine too. + +-------------------------------------------------------------------------------- +-- 3. Tables. +-------------------------------------------------------------------------------- + +-- Tables = Lua's only compound data structure; they are associative arrays. +-- Similar to php arrays or js objects, they are hash-lookup dicts that can +-- also be used as lists. + +-- Using tables as dictionaries / maps: + +-- Dict literals have string keys by default: +t = {key1 = 'value1', key2 = false} + +-- String keys can use js-like dot notation: +print(t.key1) -- Prints 'value1'. +t.newKey = {} -- Adds a new key/value pair. +t.key2 = nil -- Removes key2 from the table. + +-- Literal notation for any (non-nil) value as key: +u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} +print(u[6.28]) -- prints "tau" + +-- Key matching is basically by value for numbers and strings, but by identity +-- for tables. +a = u['@!#'] -- Now a = 'qbert'. +b = u[{}] -- We might expect 1729, but it's nil: +-- b = nil since the lookup fails. It fails because the key we used is not the +-- same object as the one used to store the original value. So strings & +-- numbers are more portable keys. + +-- A one-table-param function call needs no parens: +function h(x) print(x.key1) end +h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'. + +for key, val in pairs(u) do -- Table iteration. + print(key, val) +end + +-- _G is a special table of all globals. +print(_G['_G'] == _G) -- Prints 'true'. + +-- Using tables as lists / arrays: + +-- List literals implicitly set up int keys: +v = {'value1', 'value2', 1.21, 'gigawatts'} +for i = 1, #v do -- #v is the size of v for lists. + print(v[i]) -- Indices start at 1 !! SO CRAZY! +end +-- A 'list' is not a real type. v is just a table with consecutive integer +-- keys, treated as a list. + +-------------------------------------------------------------------------------- +-- 3.1 Metatables and metamethods. +-------------------------------------------------------------------------------- + +-- A table can have a metatable that gives the table operator-overloadish +-- behavior. Later we'll see how metatables support js-prototypey behavior. + +f1 = {a = 1, b = 2} -- Represents the fraction a/b. +f2 = {a = 2, b = 3} + +-- This would fail: +-- s = f1 + f2 + +metafraction = {} +function metafraction.__add(f1, f2) + local sum = {} + sum.b = f1.b * f2.b + sum.a = f1.a * f2.b + f2.a * f1.b + return sum +end + +setmetatable(f1, metafraction) +setmetatable(f2, metafraction) + +s = f1 + f2 -- call __add(f1, f2) on f1's metatable + +-- f1, f2 have no key for their metatable, unlike prototypes in js, so you must +-- retrieve it as in getmetatable(f1). The metatable is a normal table with +-- keys that Lua knows about, like __add. + +-- But the next line fails since s has no metatable: +-- t = s + s +-- Class-like patterns given below would fix this. + +-- An __index on a metatable overloads dot lookups: +defaultFavs = {animal = 'gru', food = 'donuts'} +myFavs = {food = 'pizza'} +setmetatable(myFavs, {__index = defaultFavs}) +eatenBy = myFavs.animal -- works! thanks, metatable + +-------------------------------------------------------------------------------- +-- Direct table lookups that fail will retry using the metatable's __index +-- value, and this recurses. + +-- An __index value can also be a function(tbl, key) for more customized +-- lookups. + +-- Values of __index,add, .. are called metamethods. +-- Full list. Here a is a table with the metamethod. + +-- __add(a, b) for a + b +-- __sub(a, b) for a - b +-- __mul(a, b) for a * b +-- __div(a, b) for a / b +-- __mod(a, b) for a % b +-- __pow(a, b) for a ^ b +-- __unm(a) for -a +-- __concat(a, b) for a .. b +-- __len(a) for #a +-- __eq(a, b) for a == b +-- __lt(a, b) for a < b +-- __le(a, b) for a <= b +-- __index(a, b) for a.b +-- __newindex(a, b, c) for a.b = c +-- __call(a, ...) for a(...) + +-------------------------------------------------------------------------------- +-- 3.2 Class-like tables and inheritance. +-------------------------------------------------------------------------------- + +-- Classes aren't built in; there are different ways to make them using +-- tables and metatables. + +-- Explanation for this example is below it. + +Dog = {} -- 1. + +function Dog:new() -- 2. + local newObj = {sound = 'woof'} -- 3. + self.__index = self -- 4. + return setmetatable(newObj, self) -- 5. +end + +function Dog:makeSound() -- 6. + print('I say ' .. self.sound) +end + +mrDog = Dog:new() -- 7. +mrDog:makeSound() -- 'I say woof' -- 8. + +-- 1. Dog acts like a class; it's really a table. +-- 2. "function tablename:fn(...)" is the same as +-- "function tablename.fn(self, ...)", The : just adds a first arg called +-- self. Read 7 & 8 below for how self gets its value. +-- 3. newObj will be an instance of class Dog. +-- 4. "self" is the class being instantiated. Often self = Dog, but inheritance +-- can change it. newObj gets self's functions when we set both newObj's +-- metatable and self's __index to self. +-- 5. Reminder: setmetatable returns its first arg. +-- 6. The : works as in 2, but this time we expect self to be an instance +-- instead of a class. +-- 7. Same as Dog.new(Dog), so self = Dog in new(). +-- 8. Same as mrDog.makeSound(mrDog); self = mrDog. + +-------------------------------------------------------------------------------- + +-- Inheritance example: + +LoudDog = Dog:new() -- 1. + +function LoudDog:makeSound() + local s = self.sound .. ' ' -- 2. + print(s .. s .. s) +end + +seymour = LoudDog:new() -- 3. +seymour:makeSound() -- 'woof woof woof' -- 4. + +-------------------------------------------------------------------------------- +-- 1. LoudDog gets Dog's methods and variables. +-- 2. self has a 'sound' key from new(), see 3. +-- 3. Same as "LoudDog.new(LoudDog)", and converted to "Dog.new(LoudDog)" as +-- LoudDog has no 'new' key, but does have "__index = Dog" on its metatable. +-- Result: seymour's metatable is LoudDog, and "LoudDog.__index = Dog". So +-- seymour.key will equal seymour.key, LoudDog.key, Dog.key, whichever +-- table is the first with the given key. +-- 4. The 'makeSound' key is found in LoudDog; this is the same as +-- "LoudDog.makeSound(seymour)". + +-- If needed, a subclass's new() is like the base's: +function LoudDog:new() + local newObj = {} + -- set up newObj + self.__index = self + return setmetatable(newObj, self) +end + +-------------------------------------------------------------------------------- +-- 4. Modules. +-------------------------------------------------------------------------------- + + +--[[ I'm commenting out this section so the rest of this script remains +-- runnable. +``` + +```lua +-- Suppose the file mod.lua looks like this: +local M = {} + +local function sayMyName() + print('Hrunkner') +end + +function M.sayHello() + print('Why hello there') + sayMyName() +end + +return M + +-- Another file can use mod.lua's functionality: +local mod = require('mod') -- Run the file mod.lua. + +-- require is the standard way to include modules. +-- require acts like: (if not cached; see below) +local mod = (function () + +end)() +-- It's like mod.lua is a function body, so that locals inside mod.lua are +-- invisible outside it. + +-- This works because mod here = M in mod.lua: +mod.sayHello() -- Says hello to Hrunkner. + +-- This is wrong; sayMyName only exists in mod.lua: +mod.sayMyName() -- error + +-- require's return values are cached so a file is run at most once, even when +-- require'd many times. + +-- Suppose mod2.lua contains "print('Hi!')". +local a = require('mod2') -- Prints Hi! +local b = require('mod2') -- Doesn't print; a=b. + +-- dofile is like require without caching: +dofile('mod2') --> Hi! +dofile('mod2') --> Hi! (runs again, unlike require) + +-- loadfile loads a lua file but doesn't run it yet. +f = loadfile('mod2') -- Calling f() runs mod2.lua. + +-- loadstring is loadfile for strings. +g = loadstring('print(343)') -- Returns a function. +g() -- Prints out 343; nothing printed before now. + +--]] + +``` +## References + +I was excited to learn Lua so I could make games +with the Love 2D game engine. That's the why. + +I started with BlackBulletIV's Lua for programmers. +Next I read the official Programming in Lua book. +That's the how. + +It might be helpful to check out the Lua short +reference on lua-users.org. + +The main topics not covered are standard libraries: + +* string library +* table library +* math library +* io library +* os library + +By the way, the entire file is valid Lua; save it +as learn.lua and run it with "lua learn.lua" ! + +This was first written for tylerneylon.com, and is +also available as a github gist. Have fun with Lua! -- cgit v1.2.3 From 82eb0f99584eab17a96c210606a12732ba483422 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 7 Aug 2014 18:11:17 +0400 Subject: Fix of 1 mistake --- ru-ru/lua-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index 55fc7bb9..e94f4c00 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -68,7 +68,7 @@ if not aBoolValue then print('это значение ложно') end --[[ Для 'or' и 'and' действует принцип "какой оператор дальше, - тот и применается". Это действует аналогично a?b:c + тот и применяется". Это действует аналогично a?b:c операторам в C/js: --]] ans = aBoolValue and 'yes' or 'no' --> 'no' -- cgit v1.2.3 From 825a22f6fe34fa21dfaa677d93ae3ddf8e9857ee Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 7 Aug 2014 18:19:40 +0400 Subject: 2 part of Russian translation Full translation of 1st section and begin of 2nd. --- ru-ru/lua-ru.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index e94f4c00..72a3fd9f 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -74,24 +74,24 @@ if not aBoolValue then print('это значение ложно') end ans = aBoolValue and 'yes' or 'no' --> 'no' karlSum = 0 -for i = 1, 100 do -- The range includes both ends. +for i = 1, 100 do -- Здесь указан диапазон, ограниченный с двух сторон. karlSum = karlSum + i end --- Use "100, 1, -1" as the range to count down: +-- Используйте "100, 1, -1" как нисходящий диапазон: fredSum = 0 for j = 100, 1, -1 do fredSum = fredSum + j end --- In general, the range is begin, end[, step]. +-- В основном, диапазон устроен так: начало, конец[, шаг]. --- Another loop construct: +-- Другая конструкция цикла: repeat - print('the way of the future') + print('путь будущего') num = num - 1 until num == 0 -------------------------------------------------------------------------------- --- 2. Functions. +-- 2. Функции. -------------------------------------------------------------------------------- function fib(n) @@ -99,10 +99,10 @@ function fib(n) return fib(n - 2) + fib(n - 1) end --- Closures and anonymous functions are ok: +-- Вложенные и анонимные функции являются нормой: function adder(x) - -- The returned function is created when adder is called, and remembers the - -- value of x: + -- Возращаемая функция создаётся когда adder вызывается, тот в свою очередь + -- запоминает значение переменной x: return function (y) return x + y end end a1 = adder(9) -- cgit v1.2.3 From cbd804412a48a532e4f81ba781a8ed1a61acd0c7 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 7 Aug 2014 19:49:53 +0400 Subject: 3 part of Russian translation Little piece of translation. --- ru-ru/lua-ru.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index 72a3fd9f..ee0fe870 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] translators: - ["Max Solomonov", "https://vk.com/solomonovmaksim"] + - ["Max Truhonin", "https://vk.com/maximmax42"] lang: ru-ru --- @@ -110,20 +111,20 @@ a2 = adder(36) print(a1(16)) --> 25 print(a2(64)) --> 100 --- Returns, func calls, and assignments all work with lists that may be --- mismatched in length. Unmatched receivers are nil; unmatched senders are --- discarded. +-- Возвраты, вызовы функций и присвоения, вся работа с перечисленным может иметь +-- неодинаковое кол-во аргументов/элементов. Неиспользуемые аргументы являются nil и +-- отбрасываются на приёме. x, y, z = 1, 2, 3, 4 --- Now x = 1, y = 2, z = 3, and 4 is thrown away. +-- Теперь x = 1, y = 2, z = 3, и 4 просто отбрасывается. function bar(a, b, c) print(a, b, c) return 4, 8, 15, 16, 23, 42 end -x, y = bar('zaphod') --> prints "zaphod nil nil" --- Now x = 4, y = 8, values 15..42 are discarded. +x, y = bar('zaphod') --> выводит "zaphod nil nil" +-- Теперь x = 4, y = 8, а значения 15..42 отбрасываются. -- Functions are first-class, may be local/global. These are the same: function f(x) return x * x end -- cgit v1.2.3 From a4b4a7927f958370ff706919fefa653d98a1f1ce Mon Sep 17 00:00:00 2001 From: Jean-Christophe Bohin Date: Thu, 7 Aug 2014 22:31:20 +0200 Subject: Adding a direct link to play.golang.org --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 88c98c21..088d4fe6 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -378,7 +378,7 @@ There you can follow the tutorial, play interactively, and read lots. The language definition itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) -You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! +You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://play.golang.org](https://play.golang.org) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. On the reading list for students of Go is the [source code to the standard library](http://golang.org/src/pkg/). Comprehensively documented, it -- cgit v1.2.3 From c0d49cdb88a41ecea12cc98ca8ee04956b9c0d7b Mon Sep 17 00:00:00 2001 From: Jean-Christophe Bohin Date: Thu, 7 Aug 2014 22:37:52 +0200 Subject: Fixing missing space and dot. --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 6c4d88bd..5247ecf8 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -93,7 +93,7 @@ can include line breaks.` // Same string type. // Arrays have size fixed at compile time. var a4 [4]int // An array of 4 ints, initialized to all 0. a3 := [...]int{3, 1, 5} // An array initialzed with a fixed size of three - //elements, with values 3,1, and 5 + // elements, with values 3, 1, and 5. // Slices have dynamic size. Arrays and slices each have advantages // but use cases for slices are much more common. -- cgit v1.2.3 From 26166afc65772f31b4f189124019d9df85bbbadf Mon Sep 17 00:00:00 2001 From: Jean-Christophe Bohin Date: Thu, 7 Aug 2014 22:43:59 +0200 Subject: Fixed style Didn't uppercased 'range' in the beginning of the sentence since it's a language keyword. --- go.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 77961524..02ea280d 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -178,8 +178,8 @@ func learnFlowControl() { continue // Unreached. } - // you can use range to iterate over an array, a slice, a string, a map, or a channel. - // range returns one (channel) or two values (array, slice, string and map) + // You can use range to iterate over an array, a slice, a string, a map, or a channel. + // range returns one (channel) or two values (array, slice, string and map). for key, value := range map[string]int{"one": 1, "two": 2, "three": 3} { // for each pair in the map, print key and value fmt.Printf("key=%s, value=%d\n", key, value) -- cgit v1.2.3 From e6df8f849a2572f809167743a45b8633c5e4580e Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Thu, 7 Aug 2014 16:52:47 -0500 Subject: [brainfuck/es] created --- es-es/brainfuck-es.html.markdown | 87 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 es-es/brainfuck-es.html.markdown diff --git a/es-es/brainfuck-es.html.markdown b/es-es/brainfuck-es.html.markdown new file mode 100644 index 00000000..e33d672d --- /dev/null +++ b/es-es/brainfuck-es.html.markdown @@ -0,0 +1,87 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Daniel Zendejas", "https://github.com/DanielZendejas"] +lang: es-es +--- + +Brainfuck (con mayúscula sólo al inicio de una oración) es un +lenguaje de programación mínimo, computacionalmente universal +en tamaño con sólo 8 comandos. + +``` + +Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas) +será ignorado. + +Brainfuck es representado por un arreglo de 30,000 celdas inicializadas +en cero y un apuntador en la celda actual. + +Existen ocho comandos: + ++ : Incrementa 1 al valor de la celda actual. +- : Decrementa 1 al valor de la celda actual. +> : Mueve el apuntador a la siguiente celda. (a la derecha) +< : Mueve el apuntador a la celda anterior. (a la izquierda) +. : Imprime el valor en ASCII de la celda actual (i.e. 65 = 'A') +, : Lee un caracter como input y lo escribe en la celda actual. +[ : Si el valor en la celda actual es cero mueve el apuntador + hasta el primer ']' que encuentre. Si no es cero sigue a la + siguiente instrucción. +] : Si el valor en la celda actual es cero, entonces sigue con + la siguiente instrucción. Si no entonces mueve el apuntador + hacia atrás hasta encontrar el primer '['. + +[ y ] forman un while. Obviamente, deben estar balanceados. + +Ahora unos ejemplos de programas escritos con brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime la letra 'A'. Primero, incrementa la celda #1 a +6. La celda #1 será usada para hacer los ciclos. Después entra al ciclo +([) y se mueve a la celda #2 (>). Después incrementa la celda #2 10 veces, +y se regresa a la celda #1 (<), para después decrementarla en 1 (-). +Este ciclo ocurre 6 veces (le toma 6 decrementos a la celda #1 volverse 0), +cuando esto pasa se salta a (]) y continúa. + +En este punto estamos en la celda #1, que tiene un valor de 0, mientras +que la celda #2 tiene un valor de 60. Nos movemos a la celda #2 (>), +la incrementamos 5 veces para tener un valor de 65 y luego imprimimos +el valor de la celda #2 (.). 65 es 'A' en ASCII así que la letra 'A' +se imprime. + +, [ > + < - ] > . + +Este programa lee un caracter del input y lo copia en la celda #2 (,). +Después empieza un ciclo. Nos movemos a la celda #2 (>) e incrementamos su +valor (+). Regresamos a la celda #1 y decrementamos su valor en 1 (-). +Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un +cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre +terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.). + +Ten en mente que los espacios son sólo para fines de legibilidad. +Es lo mismo escribir el ejemplo de arriba que esto: +,[>+<-]>. + +Intenta descrifrar lo que hace este programa: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa toma dos números como input y los multiplica. + +Primero recibe dos números del usuario. Luego empieza el ciclo externo, +condicionado en la celda #1. Luego se mueve a la celda #2, comenzando +el ciclo interno condicionado en la celda #2 incrementando la celda #3. +Sin embargo viene un problema: El ciclo interior no funcionará nuevamente +hasta la próxima vez. Para resolver este problema también incrementamos la +celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene +el resultado. +``` +Y eso es brainfuck. ¿No tan difícil o sí? Como diversión, puedes escribir +tu propio intérprete de brainfuck o tu propio programa en brainfuck. El +intérprete es relativamente sencillo de hacer, pero si eres masoquista, +intenta construir tu proprio intérprete de brainfuck... en brainfuck. -- cgit v1.2.3 From 8be20de321b2331ab717319ca3c57c460a85de7f Mon Sep 17 00:00:00 2001 From: LumenTeun Date: Fri, 8 Aug 2014 18:11:17 +0100 Subject: Fixed while loop. --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index 845ebead..96f2414d 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -141,7 +141,7 @@ do done # while loop: -while [true] +while [ true ] do echo "loop body here..." break -- cgit v1.2.3 From 43209662626cdb4ed4b9e656a72c092512c4e9cc Mon Sep 17 00:00:00 2001 From: LumenTeun Date: Fri, 8 Aug 2014 18:24:29 +0100 Subject: Fixed typo. --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index 96f2414d..2056a9ea 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -134,7 +134,7 @@ case "$VARIABLE" in esac # for loops iterate for as many arguments given: -# The contents of var $VARIABLE is printed three times. +# The contents of $VARIABLE is printed three times. for VARIABLE in {1..3} do echo "$VARIABLE" -- cgit v1.2.3 From e1365274f7f9217a035b3e078fd7586eeef5f886 Mon Sep 17 00:00:00 2001 From: LumenTeun Date: Fri, 8 Aug 2014 18:24:43 +0100 Subject: Added two new ways to use for loops. --- bash.html.markdown | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 2056a9ea..061d35b0 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -140,6 +140,20 @@ do echo "$VARIABLE" done +# They can also be used to act on files.. +# This will run the command 'cat' on file1 and file2 +for VARIABLE in file1 file2 +do + cat "$VARIABLE" +done + +# ..or the output from a command +# This will cat the output from ls. +for OUTPUT in $(ls) +do + cat "$OUTPUT" +done + # while loop: while [ true ] do -- cgit v1.2.3 From 7cf0bcb8283a0be92f77b40568355f02ac1811af Mon Sep 17 00:00:00 2001 From: m90 Date: Sat, 9 Aug 2014 21:41:12 +0200 Subject: [javascript/*] typeof is an operand and not a function/method - fix usage / remove parens --- de-de/javascript-de.html.markdown | 4 ++-- es-es/javascript-es.html.markdown | 4 ++-- fa-ir/javascript.html.markdown | 4 ++-- javascript.html.markdown | 4 ++-- ko-kr/javascript-kr.html.markdown | 4 ++-- zh-cn/javascript-cn.html.markdown | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index 0418b2b6..38ce28e2 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -397,8 +397,8 @@ var myNumberObj = new Number(12); myNumber == myNumberObj; // = true // Genau genommen: Sie sind nicht exakt äquivalent. -typeof(myNumber); // = 'number' -typeof(myNumberObj); // = 'object' +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ // Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist. diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index 9b412f6e..a1348508 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -471,8 +471,8 @@ var miNumeroObjeto = new Number(12); miNumero == miNumeroObjeto; // = true // No son exactamente iguales. -typeof(miNumero); // = 'number' -typeof(miNumeroObjeto); // = 'object' +typeof miNumero; // = 'number' +typeof miNumeroObjeto; // = 'object' miNumero === miNumeroObjeyo; // = false if (0){ // Este código no se ejecutara porque 0 es false. diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown index 922fe416..5c64d24a 100644 --- a/fa-ir/javascript.html.markdown +++ b/fa-ir/javascript.html.markdown @@ -493,8 +493,8 @@ myNumber == myNumberObj; // = true

به جز این که این سازنده ها دقیقا مانند سازنده های دیگر نیستند.

```js -typeof(myNumber); // = 'number' -typeof(myNumberObj); // = 'object' +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. diff --git a/javascript.html.markdown b/javascript.html.markdown index c59a90c3..7c869b28 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -460,8 +460,8 @@ var myNumberObj = new Number(12); myNumber == myNumberObj; // = true // Except, they aren't exactly equivalent. -typeof(myNumber); // = 'number' -typeof(myNumberObj); // = 'object' +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index f651fbe7..4ca3bb5c 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -381,8 +381,8 @@ var myNumberObj = new Number(12) myNumber == myNumberObj // = true // 하지만 정확히 같지는 않습니다. -typeof(myNumber) // = 'number' -typeof(myNumberObj) // = 'object' +typeof myNumber // = 'number' +typeof myNumberObj // = 'object' myNumber === myNumberObj // = false if (0){ // 0은 거짓이라서 이 코드는 실행되지 않습니다. diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 86ad1d07..7dee9cc4 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -363,8 +363,8 @@ var myNumberObj = new Number(12) myNumber == myNumberObj // = true // 但是它们并非严格等价 -typeof(myNumber) // = 'number' -typeof(myNumberObj) // = 'object' +typeof myNumber // = 'number' +typeof myNumberObj // = 'object' myNumber === myNumberObj // = false if (0){ // 这段代码不会执行,因为0代表假 -- cgit v1.2.3 From d246b103a3ac48d6a8bf57f3931b07166dea1e80 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 10 Aug 2014 22:54:27 +0400 Subject: 4 part of Russian translation Other part of translation. --- ru-ru/lua-ru.html.markdown | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index ee0fe870..ebcd9a74 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -126,11 +126,11 @@ end x, y = bar('zaphod') --> выводит "zaphod nil nil" -- Теперь x = 4, y = 8, а значения 15..42 отбрасываются. --- Functions are first-class, may be local/global. These are the same: +-- Функции могут быть локальными и глобальными. Эти строки делают одно и то же: function f(x) return x * x end f = function (x) return x * x end --- And so are these: +-- Эти тоже: local function g(x) return math.sin(x) end local g = function(x) return math.sin(x) end -- Equivalent to local function g(x)..., except referring to g in the function @@ -140,17 +140,17 @@ local g; g = function (x) return math.sin(x) end -- Trig funcs work in radians, by the way. --- Calls with one string param don't need parens: -print 'hello' -- Works fine. +-- Вызов функции с одним текстовым параметром не требует круглых скобок: +print 'hello' -- Работает без ошибок. --- Calls with one table param don't need parens either (more on tables below): +-- Вызов функции с одним табличным параметром так же не требуют круглых скобок (про таблицы в след.части): print {} -- Works fine too. -------------------------------------------------------------------------------- --- 3. Tables. +-- 3. Таблицы. -------------------------------------------------------------------------------- --- Tables = Lua's only compound data structure; they are associative arrays. +-- Таблицы = структура данных, свойственная только для Lua; это ассоциативные массивы. -- Similar to php arrays or js objects, they are hash-lookup dicts that can -- also be used as lists. @@ -160,9 +160,9 @@ print {} -- Works fine too. t = {key1 = 'value1', key2 = false} -- String keys can use js-like dot notation: -print(t.key1) -- Prints 'value1'. -t.newKey = {} -- Adds a new key/value pair. -t.key2 = nil -- Removes key2 from the table. +print(t.key1) -- Печатает 'value1'. +t.newKey = {} -- Добавляет новую пару ключ-значение. +t.key2 = nil -- Удаляет key2 из таблицы. -- Literal notation for any (non-nil) value as key: u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} @@ -170,7 +170,7 @@ print(u[6.28]) -- prints "tau" -- Key matching is basically by value for numbers and strings, but by identity -- for tables. -a = u['@!#'] -- Now a = 'qbert'. +a = u['@!#'] -- Теперь a = 'qbert'. b = u[{}] -- We might expect 1729, but it's nil: -- b = nil since the lookup fails. It fails because the key we used is not the -- same object as the one used to store the original value. So strings & @@ -180,7 +180,7 @@ b = u[{}] -- We might expect 1729, but it's nil: function h(x) print(x.key1) end h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'. -for key, val in pairs(u) do -- Table iteration. +for key, val in pairs(u) do -- Итерация цикла с таблицей. print(key, val) end -- cgit v1.2.3 From 19bd3cdd0b938ece7de01f685b5c99e927b53b1e Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Sun, 10 Aug 2014 20:02:31 -0700 Subject: In golang slices are dynamic, so a mention of append() for slice updates seems to be appropriate. --- go.html.markdown | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/go.html.markdown b/go.html.markdown index 656b1051..ba65d1e5 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -101,6 +101,20 @@ can include line breaks.` // Same string type. var d2 [][]float64 // Declaration only, nothing allocated here. bs := []byte("a slice") // Type conversion syntax. + // Because they are dynamic, slices can be appended to on-demand. + // To append elements to a slice, built-in append() function is used. + // First argument is a slice to which we are appending. Commonly, + // the array variable is updated in place, as in example below. + s := []int{1, 2, 3} // Result is a slice of length 3. + s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] + // To append another slice, instead of list of atomic elements we can + // pass a reference to a slice or a slice literal like this, with a + // trailing elipsis, meaning take an array and unpack its elements, + // appending them to the slice. + s = append(s, []int{7, 8, 9}...) // Second argument is an array literal. + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] + p, q := learnMemory() // Declares p, q to be type pointer to int. fmt.Println(*p, *q) // * follows a pointer. This prints two ints. -- cgit v1.2.3 From 5ed3d5455e5441d1b756f86f3ea9b4895384bcd3 Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Sun, 10 Aug 2014 20:04:49 -0700 Subject: Fixed indentation error created in previous commit. --- go.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index ba65d1e5..f383b641 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -107,13 +107,13 @@ can include line breaks.` // Same string type. // the array variable is updated in place, as in example below. s := []int{1, 2, 3} // Result is a slice of length 3. s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. - fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] - // To append another slice, instead of list of atomic elements we can + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] + // To append another slice, instead of list of atomic elements we can // pass a reference to a slice or a slice literal like this, with a // trailing elipsis, meaning take an array and unpack its elements, // appending them to the slice. s = append(s, []int{7, 8, 9}...) // Second argument is an array literal. - fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] p, q := learnMemory() // Declares p, q to be type pointer to int. fmt.Println(*p, *q) // * follows a pointer. This prints two ints. -- cgit v1.2.3 From 4abce50bfeab63cfb1b66acbf1622a47d85b3a2a Mon Sep 17 00:00:00 2001 From: m90 Date: Mon, 11 Aug 2014 10:02:06 +0200 Subject: add german coffeescript introduction --- de-de/coffeescript-de.html.markdown | 104 ++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 de-de/coffeescript-de.html.markdown diff --git a/de-de/coffeescript-de.html.markdown b/de-de/coffeescript-de.html.markdown new file mode 100644 index 00000000..5a5ccbde --- /dev/null +++ b/de-de/coffeescript-de.html.markdown @@ -0,0 +1,104 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Frederik Ring", "https://github.com/m90"] +filename: coffeescript-de.coffee +lang: de-de +--- + +CoffeeScript ist eine kleine Sprache die eins zu eins nach JavaScript transpiliert wird, es gibt keinen Laufzeitinterpreter für sie. +Als Nachfolger von JavaScript konzipiert, gibt CoffeeScript sein Bestes lesbaren, gut formatierten und effizienten JavaScript-Code zu erzeugen der in allen Laufzeiten einwandfrei funktioniert. + +Auf [der CoffeeScript Website](http://coffeescript.org/) gibt es ein ausführliches Tutorial. + +``` coffeescript +# CoffeeScript ist eine dieser Sprachen für "Hipster" +# und folgt daher vielen Trends und Einflüssen aus modernen Sprachen. +# Kommentare werden daher wie in Ruby und Python mit Hashes gekennzeichnet + +### +Kommentarblöcke sehen aus wie diese und werden direkt nach '/ *s und '* /s im erzeugten JavaScript transpiliert. + +Vorweg: bevor du mit CoffeeScript anfängst solltest du einen guten Überblick +über die Eigenheiten von JavaScript an sich haben. +### + +# Zuweisung: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Bedingungen: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Funktionen: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +fill = (container, liquid = "Kaffee") -> + "#{container} wird mit #{liquid} gefüllt..." +#=>var fill; +# +#fill = function(container, liquid) { +# if (liquid == null) { +# liquid = "Kaffee"; +# } +# return container + " wird mit " + liquid + " gefüllt..."; +#}; + +# "Ranges": +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objekte: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +#} + +# "Splats": +race = (winner, runners...) -> + print winner, runners +#=>race = function() { +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +#}; + +# Existenz-Operator: +alert "Hab ich's nicht gesagt?" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Hab ich's nicht gesagt?"); } + +# Collection-Mapping: +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +foods = ['Brokkoli', 'Spinat', 'Schokolade'] +eat food for food in foods when food isnt 'Schokolade' +#=>foods = ['Brokkoli', 'Spinat', 'Schokolade']; +# +#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) { +# food = foods[_k]; +# if (food !== 'Schokolade') { +# eat(food); +# } +#} +``` + +## Weiterführende Links + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) -- cgit v1.2.3 From 7ba211d85b9e5c3f658854444e5831c4e20a7efd Mon Sep 17 00:00:00 2001 From: m90 Date: Mon, 11 Aug 2014 10:04:38 +0200 Subject: fix overflowing line --- de-de/coffeescript-de.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/de-de/coffeescript-de.html.markdown b/de-de/coffeescript-de.html.markdown index 5a5ccbde..f8aeb502 100644 --- a/de-de/coffeescript-de.html.markdown +++ b/de-de/coffeescript-de.html.markdown @@ -20,7 +20,8 @@ Auf [der CoffeeScript Website](http://coffeescript.org/) gibt es ein ausführlic # Kommentare werden daher wie in Ruby und Python mit Hashes gekennzeichnet ### -Kommentarblöcke sehen aus wie diese und werden direkt nach '/ *s und '* /s im erzeugten JavaScript transpiliert. +Kommentarblöcke sehen aus wie diese und werden direkt nach '/ *s und '* /s +im erzeugten JavaScript transpiliert. Vorweg: bevor du mit CoffeeScript anfängst solltest du einen guten Überblick über die Eigenheiten von JavaScript an sich haben. -- cgit v1.2.3 From 949215560586fb051b8ddf733c763cbbb67705c9 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 11 Aug 2014 17:13:46 +0200 Subject: Update yaml-es.html.markdown --- es-es/yaml-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/yaml-es.html.markdown b/es-es/yaml-es.html.markdown index 0423261a..a5157b5d 100644 --- a/es-es/yaml-es.html.markdown +++ b/es-es/yaml-es.html.markdown @@ -1,5 +1,6 @@ --- language: yaml +lang: es-es filename: learnyaml-es.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] -- cgit v1.2.3 From 5b8f64f5bbb91ac094b95181b46c8220cbd657a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC?= Date: Tue, 12 Aug 2014 01:50:10 +0600 Subject: Update lua-ru.html.markdown --- ru-ru/lua-ru.html.markdown | 50 +++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index ebcd9a74..3fd478ef 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -144,7 +144,7 @@ local g; g = function (x) return math.sin(x) end print 'hello' -- Работает без ошибок. -- Вызов функции с одним табличным параметром так же не требуют круглых скобок (про таблицы в след.части): -print {} -- Works fine too. +print {} -- Тоже сработает. -------------------------------------------------------------------------------- -- 3. Таблицы. @@ -166,7 +166,7 @@ t.key2 = nil -- Удаляет key2 из таблицы. -- Literal notation for any (non-nil) value as key: u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} -print(u[6.28]) -- prints "tau" +print(u[6.28]) -- пишет "tau" -- Key matching is basically by value for numbers and strings, but by identity -- for tables. @@ -178,14 +178,14 @@ b = u[{}] -- We might expect 1729, but it's nil: -- A one-table-param function call needs no parens: function h(x) print(x.key1) end -h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'. +h{key1 = 'Sonmi~451'} -- Печатает 'Sonmi~451'. for key, val in pairs(u) do -- Итерация цикла с таблицей. print(key, val) end --- _G is a special table of all globals. -print(_G['_G'] == _G) -- Prints 'true'. +-- _G - это таблица со всеми глобалями. +print(_G['_G'] == _G) -- Печатает 'true'. -- Using tables as lists / arrays: @@ -198,7 +198,7 @@ end -- keys, treated as a list. -------------------------------------------------------------------------------- --- 3.1 Metatables and metamethods. +-- 3.1 Мета-таблицы и мета-методы. -------------------------------------------------------------------------------- -- A table can have a metatable that gives the table operator-overloadish @@ -207,7 +207,7 @@ end f1 = {a = 1, b = 2} -- Represents the fraction a/b. f2 = {a = 2, b = 3} --- This would fail: +-- Это не сработает: -- s = f1 + f2 metafraction = {} @@ -221,7 +221,7 @@ end setmetatable(f1, metafraction) setmetatable(f2, metafraction) -s = f1 + f2 -- call __add(f1, f2) on f1's metatable +s = f1 + f2 -- вызывает __add(f1, f2) на мета-таблице f1 -- f1, f2 have no key for their metatable, unlike prototypes in js, so you must -- retrieve it as in getmetatable(f1). The metatable is a normal table with @@ -235,7 +235,7 @@ s = f1 + f2 -- call __add(f1, f2) on f1's metatable defaultFavs = {animal = 'gru', food = 'donuts'} myFavs = {food = 'pizza'} setmetatable(myFavs, {__index = defaultFavs}) -eatenBy = myFavs.animal -- works! thanks, metatable +eatenBy = myFavs.animal -- работает! спасибо, мета-таблица. -------------------------------------------------------------------------------- -- Direct table lookups that fail will retry using the metatable's __index @@ -247,21 +247,21 @@ eatenBy = myFavs.animal -- works! thanks, metatable -- Values of __index,add, .. are called metamethods. -- Full list. Here a is a table with the metamethod. --- __add(a, b) for a + b --- __sub(a, b) for a - b --- __mul(a, b) for a * b --- __div(a, b) for a / b --- __mod(a, b) for a % b --- __pow(a, b) for a ^ b --- __unm(a) for -a --- __concat(a, b) for a .. b --- __len(a) for #a --- __eq(a, b) for a == b --- __lt(a, b) for a < b --- __le(a, b) for a <= b --- __index(a, b) for a.b --- __newindex(a, b, c) for a.b = c --- __call(a, ...) for a(...) +-- __add(a, b) для a + b +-- __sub(a, b) для a - b +-- __mul(a, b) для a * b +-- __div(a, b) для a / b +-- __mod(a, b) для a % b +-- __pow(a, b) для a ^ b +-- __unm(a) для -a +-- __concat(a, b) для a .. b +-- __len(a) для #a +-- __eq(a, b) для a == b +-- __lt(a, b) для a < b +-- __le(a, b) для a <= b +-- __index(a, b) для a.b +-- __newindex(a, b, c) для a.b = c +-- __call(a, ...) для a(...) -------------------------------------------------------------------------------- -- 3.2 Class-like tables and inheritance. @@ -335,7 +335,7 @@ function LoudDog:new() end -------------------------------------------------------------------------------- --- 4. Modules. +-- 4. Модули. -------------------------------------------------------------------------------- -- cgit v1.2.3 From 6e9dc12151d9ed9eea98e1aa36a00861c330ec18 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Tue, 12 Aug 2014 20:27:40 -0500 Subject: [whip/es] created. --- es-es/whip-es.html.markdown | 255 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 es-es/whip-es.html.markdown diff --git a/es-es/whip-es.html.markdown b/es-es/whip-es.html.markdown new file mode 100644 index 00000000..db929504 --- /dev/null +++ b/es-es/whip-es.html.markdown @@ -0,0 +1,255 @@ +--- +language: whip +contributors: + - ["Tenor Biel", "http://github.com/L8D"] +translators: + - ["Daniel Zendejas", "https://github.com/DanielZendejas"] +author: Tenor Biel +author_url: http://github.com/L8D +filename: whip-es.lisp +lang: es-es +--- +Tutorial de Whip en español. + +Whip es un dialecto de LISP hecho para escribir código y conceptos +simples. Ha tomado prestado bastante de la sintaxis de Haskell +(un lenguaje no relacionado). + +Esta documentación fue escrita por el creador del lenguaje + +```scheme +; Los comentarios son como en LISP, con punto y coma... + +; La mayoría de las sentencias de primer nivel están dentro de +; "formas". Una forma no es más que cosas dentro de paréntesis +no_en_la_forma +(en_la_form) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 1. Números, Strings y Operadores + +;Whip tiene un tipo para números (es el estándar 64-bit IEEE 754 double, de JS) +3 ; => 3 +1.5 ; => 1.5 + +; Las funciones son llamadas si son el primer elemento de una forma +(funcion_llamada argumentos) + +; La mayoría de los operadores se hacen con funciones +; Toda la aritmética básica es bastante estándar +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 +; incluso el módulo +(% 9 4) ; => 1 +; división impar al estilo de JavaScript. +(/ 5 2) ; => 2.5 + +; Las formas anidadas funcionan como se espera. +(* 2 (+ 1 3)) ; => 8 + +; Hay un tipo booleano. +true +false + +; Los Strings son creados con comillas dobles ". +"Hola mundo" + +; Los caracteres solos se declaran con comillas simples '. +'a' + +; La negación usa la función 'not'. +(not true) ; => false +(not false) ; => true + +; La mayoría de las funcions que no vienen de Haskell tienen +; atajos. La función 'not' también se puede declarar con '!'. +(! (! true)) ; => true + +; La igualdad es `equal` o `=`. +(= 1 1) ; => true +(equal 2 1) ; => false + +; Por ejemplo, la desigualdad sería combinar la función 'not' con +; la función de igualdad +(! (= 2 1)) ; => true + +; Más comparaciones +(< 1 10) ; => true +(> 1 10) ; => false +; y su contraparte textual. +(lesser 1 10) ; => true +(greater 1 10) ; => false + +; Los Strings pueden concatenarse con la función +. +(+ "Hola " "mundo!") ; => "Hello world!" + +; También puedes usar las comparativas de JavaScript +(< 'a' 'b') ; => true +; ...y la coerción de tipos +(= '5' 5) + +; La función 'at' o @ accesa a los caracteres dentro de los strings, +; empezando en 0. +(at 0 'a') ; => 'a' +(@ 3 "foobar") ; => 'b' + +; También están las variables `null` and `undefined`. +null; usado para indicar una falta de valor deliberada. +undefined; usado para indicar un valor que aún no está definido. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 2. Variables, Listas y Diccionarios + +; Las variables son declaradas con las funciones `def` o `let`. +; Las variables que aún no son asignadas tendrán el valor `undefined`. +(def mi_variable 5) +; `def` asignará la variable al contexto global. +; `let` asignará la variable al contexto local, +; y tiene una sintaxis distinta. +(let ((mi_variable 5)) (+ mi_variable 5)) ; => 10 +(+ mi_variable 5) ; = undefined + 5 => undefined + +; Las listas son arreglos de valores de cualquier tipo. +; Básicamente, son formas sin funciones al inicio. +(1 2 3) ; => [1, 2, 3] (sintaxis JavaScript) + +; Los diccionarios son el equivalente en Whip de los 'objetos' de JavaScript, +; los 'dicts' de Python o los 'hashes' de Ruby: una colección desordenada +; de pares llave-valor +{"llave1" "valor1" "llave2" 2 3 3} + +; Las llaves son sólo valores, identificadores, números o strings. +(def mi_diccionario {mi_llave "mi_valor" "mi otra llave" 4}) +; Pero con Whip, los diccionarios son leidos así: +; "llave" "espacio en blanco" "valor" "espacio en blanco" +{"llave" "valor" +"otra llave" +1234 +} + +; Las definiciones de los diccionarios pueden accesarse con la función @ +; (como los strings y las listas) +(@ "mi otra llave" mi_diccionario) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 3. Logica y secuencias de control + +; La funcion `if` es bastante simple, aunque distinta que en otros lenguajes. +(if true "regresa esto si es true" "regresa esto si es false") +; => "regresa esto si es true" + +; Y para el operador ternario `?` +(? false true false) ; => false + +? `both` es un 'y' lógico, mientras que la función `either` es un 'o'. +(both true true) ; => true +(both true false) ; => false +(either true false) ; => true +(either false false) ; => false +; Y sus atajos son '&' y '^' respectivamente +; & => both +; ^ => either +(& true true) ; => true +(^ false true) ; => true + +;;;;;;;;; +; Lambdas + +; Las Lambdas en Whip son declaradas con las funciones `lambda` o `->`. +; Las funciones regulares en realidad sólo son lambdas con nombre. +(def mi_funcion (-> (x y) (+ (+ x y) 10))) +; | | | | +; | | | valor regresado(estas son las variables argumentos) +; | | argumentos +; | declaración de lambda +; | +; nombre de la lambda + +(mi_funcion 10 10) ; = (+ (+ 10 10) 10) => 30 + +; Obviamente, todas las lambdas por definición son anónimas y +; técnicamente siempre usadas anónimamente. Redundancia. +((lambda (x) x) 10) ; => 10 + +;;;;;;;;;;;;;;;; +; Comprensiones + +; `range` o `..` genera una lista de números que comprende +; cada entero dentro de los argumentos. +(range 1 5) ; => (1 2 3 4 5) +(.. 0 2) ; => (0 1 2) + +; `map` aplica su primer argumento (que debe ser una función) +; al siguiente argumento (que es una lista). +(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) + +; Reducir +(reduce + (.. 1 5)) +; equivale a +((+ (+ (+ 1 2) 3) 4) 5) + +; Nota: map y reduce no tienen atajos. + +; `slice` o `\` es idéntico a la función .slice() de JavaScript +; Pero toma la lista del primer argumento, no del último. +(slice (.. 1 5) 2) ; => (3 4 5) +(\ (.. 0 100) -5) ; => (96 97 98 99 100) + +; `append` o `<<` se explica solo. +(append 4 (1 2 3)) ; => (1 2 3 4) +(<< "bar" ("foo")) ; => ("foo" "bar") + +; Length se explica solo. +(length (1 2 3)) ; => 3 +(_ "foobar") ; => 6 + +;;;;;;;;;;;;;;; +; Elementos de Haskell + +; Primer elemento en una lista +(head (1 2 3)) ; => 1 + +; Lista del segundo elemento al último en una lista +(tail (1 2 3)) ; => (2 3) + +; Último elemento en una lista +(last (1 2 3)) ; => 3 + +; Contrario a `tail` +(init (1 2 3)) ; => (1 2) + +; Lista del primer elemento al argumento +(take 1 (1 2 3 4)) ; (1 2) + +; Contrario a `take` +(drop 1 (1 2 3 4)) ; (3 4) + +; Valor más pequeño de una lista +(min (1 2 3 4)) ; 1 + +; Valor más grande de una lista +(max (1 2 3 4)) ; 4 + +; Comprobar que el elemento está en la lista +(elem 1 (1 2 3)) ; true +(elem "foo" {"foo" "bar"}) ; true +(elem "bar" {"foo" "bar"}) ; false + +; Invertir el orden de la lista +(reverse (1 2 3 4)) ; => (4 3 2 1) + +; Comprobar si un elemento es par o impar +(even 1) ; => false +(odd 1) ; => true + +; Separar string en una lista de strings, separados por espacios +(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese") +; Juntar lista de strings. +(unwords ("foo" "bar")) ; => "foobar" +(pred 21) ; => 20 +(succ 20) ; => 21 +``` + +Para más información, revisa [repo](http://github.com/L8D/whip) -- cgit v1.2.3 From fbca22daeeb1cf81ed2de2e2a0b78d20a8dc06f9 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Tue, 12 Aug 2014 20:28:35 -0500 Subject: Sintax check --- es-es/whip-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/whip-es.html.markdown b/es-es/whip-es.html.markdown index db929504..7c2f4bd2 100644 --- a/es-es/whip-es.html.markdown +++ b/es-es/whip-es.html.markdown @@ -252,4 +252,4 @@ undefined; usado para indicar un valor que aún no está definido. (succ 20) ; => 21 ``` -Para más información, revisa [repo](http://github.com/L8D/whip) +Para más información, revisa el [repositorio](http://github.com/L8D/whip) -- cgit v1.2.3 From 963b2ef7a2735e54367e2b19d97ef79de0da1348 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Tue, 12 Aug 2014 20:35:42 -0500 Subject: Little typos fixed. --- whip.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/whip.html.markdown b/whip.html.markdown index dc5a0b39..3faee98a 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -31,7 +31,7 @@ not_in_form (called_function args) ; Majority of operations are done with functions -; All the basic arihmetic is pretty straight forward +; All the basic arithmetic is pretty straight forward (+ 1 1) ; => 2 (- 2 1) ; => 1 (* 1 2) ; => 2 @@ -48,7 +48,7 @@ not_in_form true false -; String are created with ". +; Strings are created with ". "Hello, world" ; Single chars are created with '. @@ -66,7 +66,7 @@ false (= 1 1) ; => true (equal 2 1) ; => false -; For example, inequality would be combinding the not and equal functions. +; For example, inequality would be combining the not and equal functions. (! (= 2 1)) ; => true ; More comparisons @@ -96,10 +96,10 @@ undefined ; user to indicate a value that hasn't been set ; 2. Vairbles, Lists, and Dicts ; Variables are declared with the `def` or `let` functions. -; Variab;es that haven't been set will be `undefined`. +; Variables that haven't been set will be `undefined`. (def some_var 5) ; `def` will keep the variable in the global context. -; `let` will only have the variable inside it's context, and has a wierder syntax. +; `let` will only have the variable inside its context, and has a wierder syntax. (let ((a_var 5)) (+ a_var 5)) ; => 10 (+ a_var 5) ; = undefined + 5 => undefined @@ -129,7 +129,7 @@ undefined ; user to indicate a value that hasn't been set ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; 3. Logic and Control sequences -; The `if` function is pretty simple, though different than most imperitave langs. +; The `if` function is pretty simple, though different than most imperative langs. (if true "returned if first arg is true" "returned if first arg is false") ; => "returned if first arg is true" @@ -159,12 +159,12 @@ undefined ; user to indicate a value that hasn't been set ; | | arguments ; | lambda declaration function ; | -; name of the to-be-decalred lambda +; name of the to-be-declared lambda (my_function 10 10) ; = (+ (+ 10 10) 10) => 30 ; Obiously, all lambdas by definition are anonymous and -; technically always used anonymouesly. Redundancy. +; technically always used anonymously. Redundancy. ((lambda (x) x) 10) ; => 10 ;;;;;;;;;;;;;;;; -- cgit v1.2.3 From 17fe88764d8283f4d3676acde0b33c2680a15509 Mon Sep 17 00:00:00 2001 From: Daniel Zendejas Date: Wed, 13 Aug 2014 09:12:50 -0500 Subject: [bash/es] created --- es-es/bash-es.html.markdown | 195 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 es-es/bash-es.html.markdown diff --git a/es-es/bash-es.html.markdown b/es-es/bash-es.html.markdown new file mode 100644 index 00000000..489fd39e --- /dev/null +++ b/es-es/bash-es.html.markdown @@ -0,0 +1,195 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] +translators: + - ["Daniel Zendejas", "https://github.com/danielzendejas"] +filename: LearnBash-es.sh +--- + +Tutorial de Shell en español. + +Bash es el nombre del shell de unix, el cual también es distribuido como +el shell del sistema operativo GNU. También es el shell +por defecto de Linux y Mac OS X. Casi todos los ejemplos abajo pueden +ser parte de un script shell o ser ejecutados directamente en la terminal. + +[Leer más aquí.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash + +# La primera línea del script es el [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) que le indica al sistema +# cómo ejecutar el script. +# Como te habrás dado cuenta, los comentarios en shell empiezan con #. +# El shebang también es un comentario. + +# Ejemplo sencillo de hola mundo: +echo ¡Hola mundo! + +# Cada comando empieza con una nueva línea, o después de un punto y coma: +echo 'Esta es la primera línea'; echo 'Esta es la segunda línea' + +# Para declarar una variable se hace lo siguiente: +VARIABLE="Mi string" + +# Pero no así: +VARIABLE = "Mi string" + +# Bash decidirá que VARIABLE es un comando a ejecutar, dando un error. + +# Usando la variable: +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' + +# Cuando la variable es usada - o asignada, exportada, etcétera - se +# escribe su nombre sin $. Si se quiere saber el valor de la variables, +# entonces sí se usa $. Note que ' (comilla simple) no expandirá las +# variables. + +# Sustitución de strings en variables. +echo ${VARIABLE/Mi/Una} +# Esto sustituirá la primera cadena "Mi" con "Una". + +# Substring de una variable. +echo ${VARIABLE:0:7} +# Esto va a regresar sólo los primeros 7 caracteres del valor. + +# Valor por defecto de una variable +echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} +# Esto trabaja para null (VARIABLE=), string vacío (VARIABLE=""), } +# cero (VARIABLE=0) regresa 0 + +# Variables del sistema: +# Aquí hay algunas variables incluídas en el sistema: +echo "El valor de regreso del último programa: $?" +echo "PID del sistema: $$" +echo "Número de argumentos: $#" +echo "Argumentos del script: $@" +echo "Argumentos del script separados en variables: $1 $2..." + +# Para leer un valor del input: +echo "¿Cuál es tu nombre?" +read NOMBRE # Note que no necesitamos declarar una variable +echo ¡Hola, $NOMBRE! + +# Tenemos la estructura 'if' usual: +# use 'man test' para más información sobre condicionales +if [ $NOMBRE -ne $USER ] +then + echo "Tu nombre es tu usuario." +else + echo "Tu nombre no es tu usuario." +fi + +# También hay ejecuciones condicionadas. +echo "Siempre ejecutado" || echo "Sólo ejecutado si el primer comando falla" +echo "Siempre ejecutado" && echo "Sólo ejecutado si el primer comando NO falla" + +# Para usar && y || con condicionales, se necesitan +# múltiples pares de corchetes: +if [ $NOMBRE == "Steve" ] && [ $EDAD -eq 15 ] +then + echo "Esto correrá si $NOMBRE es Steve Y $EDAD es 15." +fi + +if [ $NOMBRE == "Daniya" ] || [ $NOMBRE == "Zach" ] +then + echo "Esto correrá si $NOMBRE es Daniya O Zach." +fi + +# Las expresiones se denotan con el siguiente formato: +echo $(( 10 + 5 )) + +# A diferencia de otros lenguajes de programación, bash es shell , así que +# funciona en un contexto de directorio actual. Puedes listar archivos y +# directorios en un directorio actual con el comando 'ls': +ls + +# Estos comandos tienen opciones que controlan su ejecución: +ls -l # Lista todos los archivos y directorios en líneas distintas. + +# Los resultados del comando anterior pueden ser pasados al siguiente +# como input. El comando 'grep' filtra el input con los comandos provistos. +# Así es como podemos listar archivos .txt en el directorio actual: +ls -l | grep "\.txt" + +# Puedes también redireccionar el input y el error lanzado de algún comando. +python2 hello.py < "input.in" +python2 hello.py > "output.out" +python2 hello.py 2> "error.err" + +# El error lanzado eliminará el contenido del archivo si es que existe, +# para después escribir el error. Para que se concatene (en lugar de eliminar) +# use el comando ">>". + +# Los comandos pueden ser sustituidos dentro de otros comandos usando $(): +# El siguiente ejemplo despliega el número de archivos y directorios en el +# directorio actual. +echo "Hay $(ls | wc -l) elementos aquí." + +# Lo mismo puede ser hecho usando comillas invertidas `` pero no pueden ser +# anidadas. El método preferido es $(). +echo "Hay `ls | wc -l` elementos aquí." + +# Bash usa una estructura de casos similar al switch de Java o C++: +case "$VARIABLE" in + # Lista de patrones que las condiciones deben cumplir: + 0) echo "Hay un cero.";; + 1) echo "Hay un uno.";; + *) echo "No es null.";; +esac + +# Para los ciclos, se usa la estructura 'for'. Cicla para cada argumento dado: +# El contenido de $VARIABLE se imprime tres veces. +for VARIABLE in {1..3} +do + echo "$VARIABLE" +done + +# ciclos while: +while [true] +do + echo "cuerpo del ciclo..." + break +done + +# También se pueden definir sub-rutinas (funciones) +# Definición: +function miFuncion () +{ + echo "Los argumentos trabajan igual que argumentos de script: $@" + echo "Y: $1 $2..." + echo "Esto es una función" + return 0 +} + +# O simplemente: +miOtraFuncion () +{ + echo "¡Otra forma de declarar funciones!" + return 0 +} + +# Para llamar a tu función +foo "Mi nombre es:" $NOMBRE + +# Hay muchos comandos útiles que puedes aprender: +# imprime las últimas 10 líneas del archivo file.txt +tail -n 10 file.txt +# imprime las primeras 10 líneas del archivo file.txt +head -n 10 file.txt +# ordena las líneas del archivo file.txt +sort file.txt +# identifica u omite las líneas repetidas, con -d las reporta +uniq -d file.txt +# imprime sólo la primera columna antes de cada ',' en el archivo| +cut -d ',' -f 1 file.txt +``` -- cgit v1.2.3 From 3f5251edf9acb6c64d6f3dfadafe587a218b902b Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 14 Aug 2014 12:12:50 +0200 Subject: Intial file created for TypeScript Not all content but it's a good start --- typescript.html.markdown | 75 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 typescript.html.markdown diff --git a/typescript.html.markdown b/typescript.html.markdown new file mode 100644 index 00000000..f0667d49 --- /dev/null +++ b/typescript.html.markdown @@ -0,0 +1,75 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"]] +--- + +TypeScript is a language that aims at easing development of large scale applications written in JavaScript. +TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. +It is a superset of JavaScript: any JavaScript code is valid TypeScript code so it can be added seamlessly to any project. +TypeScript code compiles down to JavaScript. + +This article will focus only on TypeScript added syntax, everything else is plain [JavaScript] (../javascript/). + +```ts +//There are 4 basic types in TypeScript +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +//However, when it's impossible to know, there is the "Any" type +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // okay, definitely a boolean + +//For collections, there are typed arrays and generic arrays +var list: number[] = [1, 2, 3]; +//Or, using the generic array type +var list: Array = [1, 2, 3]; + +//For enumerations +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +//Lastly, "void" is used in the special case of a function not returning anything +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +//Interfaces are structural, anything that has the properties is compliant with the interface. +//In the bellow example, any object that has a name which is a string and an age which is a number is a Person. +//This is called "duck typing". +interface Person { + name: string; + age: number; + + //Interfaces also support optional properties + phone?: number; +} + +//Interfaces can also describe a function type, to describe a function signature +interface SearchFunc { + (source: string, subString: string): boolean; +} +//The type can then be used for functions, and the compiler will be able to check that types are compliants +//Note that only the parameters' types are important, names are not important. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + var result = source.search(subString); + if (result == -1) { + return false; + } + else { + return true; + } +} + + +``` + +To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground). + +## Further Reading + * [TypeScript Official website] (http://www.typescriptlang.org/) + * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) -- cgit v1.2.3 From fda947d93997ac1253c11ebed6a8c615c49c71f5 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 14 Aug 2014 13:34:41 +0200 Subject: Some re-phrasing and typos --- typescript.html.markdown | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index f0667d49..410cd6e4 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -6,18 +6,19 @@ contributors: TypeScript is a language that aims at easing development of large scale applications written in JavaScript. TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. -It is a superset of JavaScript: any JavaScript code is valid TypeScript code so it can be added seamlessly to any project. -TypeScript code compiles down to JavaScript. +It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. In turn, the TypeScript compiler transform the code to JavaScript. This article will focus only on TypeScript added syntax, everything else is plain [JavaScript] (../javascript/). +To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the resulting JavaScript. + ```ts -//There are 4 basic types in TypeScript +//There are 3 basic types in TypeScript var isDone: boolean = false; var lines: number = 42; var name: string = "Anders"; -//However, when it's impossible to know, there is the "Any" type +//When it's impossible to know, there is the "Any" type var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean @@ -67,7 +68,7 @@ mySearch = function(src: string, sub: string) { ``` -To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground). + ## Further Reading * [TypeScript Official website] (http://www.typescriptlang.org/) -- cgit v1.2.3 From 7f2256b2e65cb72ef87a5cff0a63bc4982a5e496 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 14 Aug 2014 15:40:21 +0200 Subject: Tutorial on classes and functions added TODO: more on indexers, check the comment emitted twice for f2 function --- typescript.html.markdown | 82 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 59 insertions(+), 23 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 410cd6e4..3363426a 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -6,11 +6,11 @@ contributors: TypeScript is a language that aims at easing development of large scale applications written in JavaScript. TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. -It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. In turn, the TypeScript compiler transform the code to JavaScript. +It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emitts JavaScript. -This article will focus only on TypeScript added syntax, everything else is plain [JavaScript] (../javascript/). +This article will focus only on TypeScript extra syntax, as oposed to [JavaScript] (../javascript/). -To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the resulting JavaScript. +To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript. ```ts //There are 3 basic types in TypeScript @@ -25,10 +25,10 @@ notSure = false; // okay, definitely a boolean //For collections, there are typed arrays and generic arrays var list: number[] = [1, 2, 3]; -//Or, using the generic array type +//Alternatively, using the generic array type var list: Array = [1, 2, 3]; -//For enumerations +//For enumerations: enum Color {Red, Green, Blue}; var c: Color = Color.Green; @@ -37,40 +37,76 @@ function bigHorribleAlert(): void { alert("I'm a little annoying box!"); } -//Interfaces are structural, anything that has the properties is compliant with the interface. -//In the bellow example, any object that has a name which is a string and an age which is a number is a Person. -//This is called "duck typing". +//Functions are first class citizens, have a shortened definition and can leverage the strong type inference +//All examples are equivalent, the same signature will be infered by the compiler and the same JavaScript will be emitted +var f1 = function(i: number) : number { return i * i; } +var f2 = function(i: number) { return i * i; } //Return type infered #TODO bug! +var f3 = (i : number) : number => { return i * i; } +var f4 = (i: number) => { return i * i; } //Return type infered +var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed + +//Interfaces are structural, anything that has the properties is compliant with the interface (duck typing) interface Person { name: string; - age: number; - - //Interfaces also support optional properties - phone?: number; + //Optional properties, marked with a "?" + age?: number; +} +//Object that implements the "Person" interface +var p : Person = { name: "Bobby" }; //Can be treated as a Person since it has the name and age properties +//Objects that have the optional property: +var validPerson : Person = { name: "Bobby", age: 42 }; +var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number + +//Interfaces can also define method signatures: +interface PersonWhoCanTalk { + sayHello(otherPersonsName: string): void; +} + +//And also indexers, both with number and string +interface PersonWhoCanBeIndexed { + [index: number]: string; } +//TODO -//Interfaces can also describe a function type, to describe a function signature +//Interfaces can also describe a function type interface SearchFunc { (source: string, subString: string): boolean; } -//The type can then be used for functions, and the compiler will be able to check that types are compliants -//Note that only the parameters' types are important, names are not important. +//Only the parameters' types are important, names are not important. var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { - var result = source.search(subString); - if (result == -1) { - return false; - } - else { - return true; - } + return src.search(sub) != -1; } +//Classes +class Point { + //Properties + x: number; + + //Constructor - the public keyword is a shortcut to generate the code for a property and it's initialization, equivalent to "x" in this case + constructor(x: number, public y: number) { + this.x = x; + } + + //Functions + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + //Static members + static origin = new Point(0, 0); +} -``` +var p = new Point(10 ,20); +//Generics +//Including references to a definition file +/// + +``` ## Further Reading * [TypeScript Official website] (http://www.typescriptlang.org/) * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) -- cgit v1.2.3 From 7d0adf66eab5d391d63c2bcf0fd6b1291d781a22 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 14 Aug 2014 15:56:30 +0200 Subject: Added inheritance and overwrite examples --- typescript.html.markdown | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 3363426a..3da7bca2 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -83,8 +83,10 @@ class Point { //Properties x: number; - //Constructor - the public keyword is a shortcut to generate the code for a property and it's initialization, equivalent to "x" in this case - constructor(x: number, public y: number) { + //Constructor - the public/private keywords are shortcuts to generate the code for a property and its initialization + //Equivalent to "x" in this case + //Default values are also supported + constructor(x: number, public y: number = 0) { this.x = x; } @@ -95,7 +97,23 @@ class Point { static origin = new Point(0, 0); } -var p = new Point(10 ,20); +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y will be 0 + +//Inheritance +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); //Explicit call to the super class constructor is mandatory + } + + /Overwrite + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +//Modules //Generics -- cgit v1.2.3 From b5ccc1d83cfbc1d11ca32e44708fc1eb339027c0 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 14 Aug 2014 15:58:34 +0200 Subject: Small typos --- typescript.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 3da7bca2..8209fedb 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -37,8 +37,8 @@ function bigHorribleAlert(): void { alert("I'm a little annoying box!"); } -//Functions are first class citizens, have a shortened definition and can leverage the strong type inference -//All examples are equivalent, the same signature will be infered by the compiler and the same JavaScript will be emitted +//Functions are first class citizens, support the lambda "fat arrow" syntax and use type inference +//All examples are equivalent, the same signature will be infered by the compiler, and same JavaScript will be emitted var f1 = function(i: number) : number { return i * i; } var f2 = function(i: number) { return i * i; } //Return type infered #TODO bug! var f3 = (i : number) : number => { return i * i; } @@ -106,7 +106,7 @@ class Point3D extends Point { super(x, y); //Explicit call to the super class constructor is mandatory } - /Overwrite + //Overwrite dist() { var d = super.dist(); return Math.sqrt(d * d + this.z * this.z); @@ -117,7 +117,7 @@ class Point3D extends Point { //Generics -//Including references to a definition file +//Including references to a definition file: /// ``` -- cgit v1.2.3 From 0b2f1ff6f1c05a35e0d5fda7dc9e9a7248b44670 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Thu, 14 Aug 2014 21:35:14 +0200 Subject: Update perl6 to fix some of its quirks --- perl6.html.markdown | 534 +++++++++++++++++++++++++++++++--------------------- 1 file changed, 318 insertions(+), 216 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 92219708..fca863af 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -7,24 +7,29 @@ contributors: - ["Nami-Doc", "http://github.com/Nami-Doc"] --- -Perl 6 is a highly capable, feature-rich programming language made for the upcoming hundred years. +Perl 6 is a highly capable, feature-rich programming language made for the +upcoming hundred years. -Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM and [the MoarVM](http://moarvm.com). +Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM +and [the MoarVM](http://moarvm.com). + +Meta-note : the triple pound signs are here to denote headlines, +double paragraphs, and single notes. -Meta-note : the triple pound signs are here to denote headlines, double paragraphs, single notes. `#=>` represents the output of a command. ```perl # Single line comment start with a pound #`( - Multiline comments use #` and a quoting construct. (), [], {}, 「」, etc, will work. + Multiline comments use #` and a quoting construct. + (), [], {}, 「」, etc, will work. ) ### Variables # In Perl 6, you declare a lexical variable using `my` -a +my $variable; # Perl 6 has 4 variable types : ## * Scalars. They represent a single value. They start with a `$` @@ -32,19 +37,22 @@ a my $str = 'String'; my $str2 = "String"; # double quotes allow for interpolation -# variable names can contain but not end with simple quotes and dashes, and can contain (and end with) underscores : +# variable names can contain but not end with simple quotes and dashes, +# and can contain (and end with) underscores : # my $weird'variable-name_ = 5; # works ! my $bool = True; # `True` and `False` are Perl 6's boolean my $inverse = !$bool; # You can invert a bool with the prefix `!` operator -my $forced-bool = so $str; # And you can use the prefix `so` operator which turns its operand into a Bool +my $forced-bool = so $str; # And you can use the prefix `so` operator + # which turns its operand into a Bool ## * Arrays. They represent multiple values. Their name start with `@`. my @array = 1, 2, 3; my @array = 'a', 'b', 'c'; # equivalent to : -my @array = ; # array of words, delimited by space. similar to perl5's qw, or Ruby's %w +my @array = ; # array of words, delimited by space. + # Similar to perl5's qw, or Ruby's %w. say @array[2]; # Array indices start at 0 -- This is the third element @@ -58,10 +66,12 @@ my %hash = 1 => 2, my %hash = autoquoted => "key", # keys *can* get auto-quoted "some other" => "value", # trailing commas are okay ; -my %hash = ; # you can also create a hash from an even-numbered array +my %hash = ; # you can also create a hash + # from an even-numbered array my %hash = key1 => 'value1', key2 => 'value2'; # same as this -# You can also use the "colon pair" syntax: (especially handy for named parameters that you'll see later) +# You can also use the "colon pair" syntax: +# (especially handy for named parameters that you'll see later) my %hash = :w(1), # equivalent to `w => 1` # this is useful for the `True` shortcut: :truey, # equivalent to `:truey(True)`, or `truey => True` @@ -70,33 +80,37 @@ my %hash = :w(1), # equivalent to `w => 1` ; say %hash{'key1'}; # You can use {} to get the value from a key -say %hash; # if it's a string, you can actually use <> +say %hash; # If it's a string, you can actually use <> + # (`{key1}` doesn't work, as Perl6 doesn't have barewords) -## * Subs (subroutines, or functions in most other languages). Stored in variable, they use `&` +## * Subs (subroutines, or functions in most other languages). +# Stored in variable, they use `&`. sub say-hello { say "Hello, world" } -sub say-hello-to(Str $name) { # you can provide the type of an argument - # and it'll be checked at compile-time +sub say-hello-to(Str $name) { # You can provide the type of an argument + # and it'll be checked at compile-time. say "Hello, $name !"; } -# since you can omit parenthesis to call a function with no arguments, -# you need "&" in the name to capture `say-hello` +# Since you can omit parenthesis to call a function with no arguments, +# you need "&" in the name to capture `say-hello`. my &s = &say-hello; -my &other-s = sub { say "anonymous function !" } +my &other-s = sub { say "Anonymous function !" } # A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" -sub as-many($head, *@rest) { # the `*@` slurpy will basically "take everything else". - # Note: you can have parameters *before* (like here) a slurpy one, - # but not *after*. +sub as-many($head, *@rest) { # The `*@` slurpy will basically "take everything else". + # Note: you can have parameters *before* (like here) + # a slurpy one, but not *after*. say @rest.join(' / ') ~ " !"; } say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! - # Note that the splat did not consume the parameter before. + # Note that the splat did not consume + # the parameter before. -## You can call a function with an array using the "argument list flattening" operator `|` -# (it's not actually the only feature of the operator, but it's one of them) +## You can call a function with an array using the +# "argument list flattening" operator `|` +# (it's not actually the only role of this operator, but it's one of them) sub concat3($a, $b, $c) { say "$a, $b, $c"; } @@ -105,7 +119,8 @@ concat3(|@array); #=> a, b, c ## It can also have optional arguments: sub with-optional($arg?) { # the "?" marks the argument optional - say "I might return `(Any)` if I don't have an argument passed, or I'll return my argument"; + say "I might return `(Any)` if I don't have an argument passed, + or I'll return my argument"; $arg; } with-optional; # returns Any @@ -132,14 +147,15 @@ with-named(1, named => 6); #=> 7 with-named(2, :named(5)); #=> 7 with-named(3, :4named); #=> 7 - # (special colon pair syntax for numbers, mainly useful for `:2nd` etc) + # (special colon pair syntax for numbers, + # to be used with s// and such, see later) with-named(3); # warns, because we tried to use the undefined $named in a `+`: # by default, named arguments are *optional* # To make a named argument mandatory, you can use `?`'s inverse, `!` sub with-mandatory-named(:$str!) { - say "$named !"; + say "$str !"; } with-mandatory-named(str => "My String"); #=> My String ! with-mandatory-named; # run time error: "Required named parameter not passed" @@ -171,9 +187,10 @@ named-def(def => 15); #=> 15 ### Containers # In Perl 6, values are actually stored in "containers". -# The assignment operator asks the container on the left to store the value on its right. -# When passed around, containers are marked as immutable. Which means that, in a function, -# you'll get an error if you try to mutate one of your arguments. +# The assignment operator asks the container on the left to store the value on +# its right. When passed around, containers are marked as immutable. +# Which means that, in a function, you'll get an error if you try to +# mutate one of your arguments. # If you really need to, you can ask for a mutable container using `is rw` : sub mutate($n is rw) { $n++; @@ -185,7 +202,8 @@ sub mutate($n is rw) { # A sub itself returns a container, which means it can be marked as rw : my $x = 42; sub mod() is rw { $x } -mod() = 52; # in this case, the parentheses are mandatory (else Perl 6 thinks it's a "term") +mod() = 52; # in this case, the parentheses are mandatory + # (else Perl 6 thinks `mod` is a "term") say $x; #=> 52 @@ -197,9 +215,10 @@ say $x; #=> 52 ## Conditionals # - `if` -# Before talking about `if`, we need to know which values are "Truthy" (represent True), -# and which are "Falsey" (or "Falsy") -- meaning they represent False. -# Only these values are Falsey: (), 0, "0", Nil, A type, and of course False itself. +# Before talking about `if`, we need to know which values are "Truthy" +# (represent True), and which are "Falsey" (or "Falsy") -- represent False. +# Only these values are Falsey: (), 0, "0", Nil, A type (like `Str` or `Int`), +# and of course False itself. # Every other value is Truthy. if True { say "It's true !"; @@ -217,18 +236,18 @@ say "Quite truthy" if True; # - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages) my $a = $condition ?? $value-if-true !! $value-if-false; -# - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching, -# and thanks to Perl 6's "topic variable", $_. +# - `given`-`when` looks like other languages `switch`, but much more +# powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_. # This variable contains the default argument of a block, # a loop's current iteration (unless explicitly named), etc. -# Given simply puts its argument into `$_` (like a block would do), -# and `when` uses it using the "smart matching" operator. -# Since other Perl 6 constructs use this variable (as said before, like `for`, blocks, etc), -# this means the powerful `when` is not only applicable along with a `given`, -# but instead anywhere a `$_` exists. +# `given` simply puts its argument into `$_` (like a block would do), +# and `when` compares it using the "smart matching" (`~~`) operator. +# Since other Perl 6 constructs use this variable (as said before, like `for`, +# blocks, etc), this means the powerful `when` is not only applicable along with +# a `given`, but instead anywhere a `$_` exists. given "foo bar" { - when /foo/ { # you'll read about the smart-matching operator below -- just know `when` uses it - # this is equivalent to `if $_ ~~ /foo/` + when /foo/ { # You'll read about the smart-matching operator below -- just know `when` uses it. + # This is equivalent to `if $_ ~~ /foo/`. say "Yay !"; } when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True, @@ -242,15 +261,17 @@ given "foo bar" { ## Looping constructs -# - `loop` is an infinite loop if you don't pass it arguments, but can also be a c-style `for` : +# - `loop` is an infinite loop if you don't pass it arguments, +# but can also be a c-style `for` : loop { say "This is an infinite loop !"; last; # last breaks out of the loop, like the `break` keyword in other languages } loop (my $i = 0; $i < 5; $i++) { - next if $i == 3; # `next` skips to the next iteration, like `continue` in other languages. - # Notice that you can also use postfix conditionals, loops, etc. + next if $i == 3; # `next` skips to the next iteration, like `continue` + # in other languages. Note that you can also use postfix conditionals, + # loops, etc. say "This is a C-style for loop !"; } @@ -270,9 +291,10 @@ for @array { } for @array { - next if $_ == 3; # you can skip to the next iteration (like `continue` in C-like languages) - redo if $_ == 4; # you can re-do the iteration, keeping the same topic variable (`$_`) - last if $_ == 5; # you can also break out of a loop (like `break` in C-like languages) + # You can... + next if $_ == 3; # Skip to the next iteration (like `continue` in C-like languages). + redo if $_ == 4; # Re-do the iteration, keeping the same topic variable (`$_`). + last if $_ == 5; # Or break out of a loop (like `break` in C-like languages). } # Note - the "lambda" `->` syntax isn't reserved to `for` : @@ -283,8 +305,8 @@ if long-computation() -> $result { ### Operators ## 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) +## Perl 6 operators are actually just funny-looking subroutines, in syntactic +## categories, like infix:<+> (addition) or prefix: (bool not). ## The categories are : # - "prefix" : before (like `!` in `!True`). @@ -312,12 +334,14 @@ if long-computation() -> $result { (1, 2) eqv (1, 3); # - `~~` is smart matching -# for a complete combinations list, use this table : http://perlcabal.org/syn/S03.html#Smart_matching +# For a complete list of combinations, use this table : http://perlcabal.org/syn/S03.html#Smart_matching 'a' ~~ /a/; # true if matches regexp 'key' ~~ %hash; # true if key exists in hash -$arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an argument, returns True -1 ~~ Int; # "is of type" -1 ~~ True; # smart-matching against a boolean always returns that boolean (and will warn). +$arg ~~ &bool-returning-function; # `True` if the function, passed `$arg` + # as an argument, returns `True`. +1 ~~ Int; # "has type" (check superclasses and roles) +1 ~~ True; # smart-matching against a boolean always returns that boolean + # (and will warn). # - `===` is value identity and uses `.WHICH` on the objects to compare them # - `=:=` is container identity and uses `VAR()` on the objects to compare them @@ -330,38 +354,44 @@ $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an ar 3 .. 7; # 3 to 7, both included # `^` on either side them exclusive on that side : 3 ^..^ 7; # 3 to 7, not included (basically `4 .. 6`) -# this also works as a shortcut for `0..^N` +# This also works as a shortcut for `0..^N`: ^10; # means 0..^10 -# This also allows us to demonstrate that Perl 6 has lazy arrays, using the Whatever Star : +# This also allows us to demonstrate that Perl 6 has lazy arrays, +# using the Whatever Star: my @array = 1..*; # 1 to Infinite ! -say @array[^10]; # you can pass arrays as subscripts and it'll return an array of results - # this will print "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. +say @array[^10]; # you can pass arrays as subscripts and it'll return + # an array of results. This will print + # "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 juste 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. +# 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. ## * And, Or 3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`. 0 || False; # False. Calls `.Bool` on `0` ## * Short-circuit (and tight) versions of the above -$a && $b && $c; # returns the first argument that evaluates to False, or the last argument +$a && $b && $c; # Returns the first argument that evaluates to False, + # or the last argument. $a || $b; -# And because you're going to want them, you also have composed assignment operators: +# And because you're going to want them, +# you also have composed assignment operators: $a *= 2; # multiply and assignment $b %%= 5; # divisible by and assignment -$c .= say; # method call and assignment +@array .= sort; # calls the `sort` method and assigns the result back ### More on subs ! -# As we said before, Perl 6 has *really* powerful subs. -# We're going to see a few more key concepts that make them better than in any other language :-). +# As we said before, Perl 6 has *really* powerful subs. We're going to see +# 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'll work in `my`s and parameters. +## Unpacking ! +# It's the ability to "extract" arrays and keys. +# It'll work in `my`s and in parameter lists. my ($a, $b) = 1, 2; say $a; #=> 1 my ($, $, $c) = 1, 2, 3; # keep the non-interesting anonymous @@ -377,14 +407,17 @@ sub foo(@array [$fst, $snd]) { foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 2 3 -# If you're not using the array itself, you can also keep it anonymous, much like a scalar: +# If you're not using the array itself, you can also keep it anonymous, +# much like a scalar: sub first-of-array(@ [$fst]) { $fst } first-of-array(@small); #=> 1 -first-of-array(@tail); # errors with "Too many positional parameters passed" (the array is too big) +first-of-array(@tail); # Throws an error "Too many positional parameters passed" + # (which means the array is too big). # You can also use a slurp ... sub slurp-in-array(@ [$fst, *@rest]) { # you could decide to keep `*@rest` anonymous - say $fst + @rest.elems; + say $fst + @rest.elems; # `.elems` returns a list's length. + # Here, `@rest` is `(3,)`, since `$fst` holds the `2`. } slurp-in-array(@tail); #=> 3 @@ -403,18 +436,21 @@ sub key-of(% (:value($val), :qua($qua))) { } # Then call it with a hash: (you need to keep the brackets for it to be a hash) -key-of({value => 1}); +key-of({value => 'foo', qua => 1}); #key-of(%hash); # the same (for an equivalent `%hash`) -## The last expression of a sub is returned automatically (though you may use the `return` keyword, of course): +## The last expression of a sub is returned automatically +# (though you may use the `return` keyword, of course): sub next-index($n) { $n + 1; } my $new-n = next-index(3); # $new-n is now 4 -# This is true for everything, except for the looping constructs (due to performance reasons): -# there's no purpose in building a list if we're just going to discard all the results. -# If you still want to build one, you can use the `do` prefix: (or the `gather` prefix, which we'll see later) +# This is true for everything, except for the looping constructs +# (due to performance reasons): there's reason to build a list +# if we're just going to discard all the results. +# If you still want to build one, you can use the `do` statement prefix: +# (or the `gather` prefix, which we'll see later) sub list-of($n) { do for ^$n { # note the use of the range-to prefix operator `^` (`0..^N`) $_ # current loop iteration @@ -424,15 +460,16 @@ my @list3 = list-of(3); #=> (0, 1, 2) ## You can create a lambda with `-> {}` ("pointy block") or `{}` ("block") my &lambda = -> $argument { "The argument passed to this lambda is $argument" } -# `-> {}` and `{}` are pretty much the same thing, except that the former can take arguments, -# and that the latter can be mistaken as a hash by the parser. +# `-> {}` and `{}` are pretty much the same thing, except that the former can +# take arguments, and that the latter can be mistaken as a hash by the parser. # We can, for example, add 3 to each value of an array using map: my @arrayplus3 = map({ $_ + 3 }, @array); # $_ is the implicit argument -# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`): -# a block doesn't have a "function context" (though it can have arguments), which means that if you -# return from it, you're going to return from the parent function, compare: +# A sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`): +# A block doesn't have a "function context" (though it can have arguments), +# which means that if you return from it, +# you're going to return from the parent function. Compare: sub is-in(@array, $elem) { # this will `return` out of the `is-in` sub # once the condition evaluated to True, the loop won't be run anymore @@ -441,7 +478,7 @@ sub is-in(@array, $elem) { sub truthy-array(@array) { # this will produce an array of `True` and `False`: # (you can also say `anon sub` for "anonymous subroutine") - map(sub { if $_ { return True } else { return False } }, @array); + map(sub ($i) { if $i { return True } else { return False } }, @array); # ^ the `return` only returns from the anonymous `sub` } @@ -454,15 +491,17 @@ say (*/2)(4); #=> 2 say ((*+3)/5)(5); #=> 1.6 # works even in parens ! -# but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`), +# But if you need to have more than one argument (`$_`) +# in a block (without wanting to resort to `-> {}`), # you can also use the implicit argument syntax, `$^` : map({ $^a + $^b + 3 }, @array); # same as the above -# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` +# Note : those are sorted lexicographically. +# `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` ## Multiple Dispatch -# Perl 6 can decide which variant of a `sub` to call based on the type of the arguments, -# or on arbitrary preconditions, like with a type or a `where`: +# Perl 6 can decide which variant of a `sub` to call based on the type of the +# arguments, or on arbitrary preconditions, like with a type or a `where`: # with types multi sub sayit(Int $n) { # note the `multi` keyword here @@ -472,21 +511,25 @@ multi sayit(Str $s) } # the `sub` is the default say "String: $s"; } sayit("foo"); # prints "String: foo" -sayit(True); # fails at *compile time* with "calling 'sayit' will never work with arguments of types ..." +sayit(True); # fails at *compile time* with + # "calling 'sayit' will never work with arguments of types ..." # with arbitrary precondition: multi is-big(Int $n where * > 50) { "Yes !" } # using a closure -multi is-big(Int $ where 10..50) { "Quite." } # this uses smart-matching (could use a regexp, etc) +multi is-big(Int $ where 10..50) { "Quite." } # Using smart-matching + # (could use a regexp, etc) multi is-big(Int $) { "No" } -# you can also name these checks, by creating "subsets": +# You can also name these checks, by creating "subsets": subset Even of Int where * %% 2; -multi odd-or-even(Even) { "Even" } # the main case using the type. We don't name the argument +multi odd-or-even(Even) { "Even" } # The main case using the type. + # We don't name the argument. multi odd-or-even($) { "Odd" } # "else" # You can even dispatch based on a positional's argument presence ! -multi with-or-without-you(:$with!) { # make it mandatory to be able to dispatch against it +multi with-or-without-you(:$with!) { # You need make it mandatory to + # be able to dispatch against it. say "I can live ! Actually, I can't."; } multi with-or-without-you { @@ -494,17 +537,21 @@ multi with-or-without-you { } # This is very, very useful for many purposes, like `MAIN` subs (covered later), # and even the language itself is using it in several places. -# `is`, for example, is actually a `multi sub` named `trait_mod:`, and it works off that. -# `is rw`, for example, is a dispatch to a function with this signature: +# +# - `is`, for example, is actually a `multi sub` named `trait_mod:`, +# and it works off that. +# - `is rw`, is simply a dispatch to a function with this signature: # sub trait_mod:(Routine $r, :$rw!) {} -# (commented because running this would probably lead to some very surprising side-effects !) +# +# (commented because running this would be a terrible idea !) ### Scoping -# In Perl 6, contrarily to many scripting languages (Python, Ruby, PHP, for example), -# you are to declare your variables before using them. You already saw it, with `my`. -# (there are other declarator keywords, like `our`, `has` and `state`, but we'll talk about them later) -# This is called "lexical scoping", where in inner blocks, you can access variables from outer blocks. +# In Perl 6, contrarily to many scripting languages (like Python, Ruby, PHP), +# you are to declare your variables before using them. You know `my`. +# (there are other declarators, `our`, `state`, ..., which we'll see later). +# This is called "lexical scoping", where in inner blocks, +# you can access variables from outer blocks. my $foo = 'Foo'; sub foo { my $bar = 'Bar'; @@ -516,36 +563,39 @@ sub foo { foo()(); #=> 'Foo Bar' # As you can see, `$foo` and `$bar` were captured. -# But if we were to try and use `$bar` outside of `foo`, the variable would be undefined. -# (and you'd get a compile time error) +# But if we were to try and use `$bar` outside of `foo`, +# the variable would be undefined (and you'd get a compile time error). # Perl 6 has another kind of scope : dynamic scope. # They use the twigil (composed sigil) `*` to mark dynamically-scoped variables: my $*a = 1; -# Dyamically-scoped variables depend on the current call stack, instead of the current block stack. +# Dyamically-scoped variables depend on the current call stack, +# instead of the current block depth. sub foo { my $*foo = 1; bar(); # call `bar` in-place } sub bar { say $*foo; # Perl 6 will look into the call stack instead, and find `foo`'s `$*a`, - # even though the blocks aren't nested (they're call-nested). + # even though the blocks aren't nested (they're call-nested). #=> 1 } ### Object Model ## Perl 6 has a quite comprehensive object model -## You declare a class with the keyword `class`, fields with `has`, methods with `method`. -## In Perl 6, every field is private, and named `$!attr`, but if you declare it with `$.`, -## you get a public (immutable) accessor along with it. +# You declare a class with the keyword `class`, fields with `has`, +# methods with `method`. Every field to private, and is named `$!attr`, +# but you have `$.` to get a public (immutable) accessor along with it. +# (using `$.` is like using `$!` plus a `method` with the same name) # (Perl 6's object model ("SixModel") is very flexible, and allows you to dynamically add methods, # change semantics, etc -- This will not be covered here, and you should refer to the Synopsis) class A { - has $.field; # `$.field` is immutable. Use `$!field` from inside the class to modify it. - has $.other-field is rw; # You can, however, mark a public field as being read/write. + has $.field; # `$.field` is immutable. + # From inside the class, use `$!field` to modify it. + has $.other-field is rw; # You can obviously mark a public field `rw`. has Int $!private-field = 10; method get-value { @@ -556,7 +606,7 @@ class A { # $.field = $n; # As stated before, you can't use the `$.` immutable version. $!field = $n; # This works, because `$!` is always mutable. - $.other-field = 5; # This works, because `$.other-field` was declared `rw` (mutable). + $.other-field = 5; # This works, because `$.other-field` is `rw`. } method !private-method { @@ -565,13 +615,15 @@ class A { }; # Create a new instance of A with $.field set to 5 : -# note : you can't set private-field from here (more later on) +# Note: you can't set private-field from here (more later on). my $a = A.new(field => 5); $a.get-value; #=> 18 #$a.field = 5; # This fails, because the `has $.field` is immutable -$a.other-field = 10; # This, however, works, because the public field is mutable (`rw`). +$a.other-field = 10; # This, however, works, because the public field + # is mutable (`rw`). -## Perl 6 also has inheritance (along with multiple inheritance ... Considered a misfeature by many) +## Perl 6 also has inheritance (along with multiple inheritance) +# (though considered a misfeature by many) class A { has $.val; @@ -591,12 +643,14 @@ class B is A { # inheritance uses `is` method bar { $.val * 10 } # this shadows A's `bar` } -my B $b .= new(val => 5); # When you use `my T $var`, `$var` starts off with `T` itself in it, - # so you can call `new` on it. - # (`.=` is just the compound operator composed of the dot-call and of the assignment operator - # `$a .= b` is the same as `$a = $a.b`) - # Also note that `BUILD` (the method called inside `new`) will set parent properties too, - # so you can pass `val => 5` +# When you use `my T $var`, `$var` starts off with `T` itself in it, +# so you can call `new` on it. +# (`.=` is just the dot-call and the assignment operator: +# `$a .= b` is the same as `$a = $a.b`) +# Also note that `BUILD` (the method called inside `new`) +# will set parent properties too, so you can pass `val => 5`. +my B $b .= new(val => 5); + # $b.not-inherited; # This won't work, for reasons explained above $b.foo; # prints 5 $b.bar; #=> 50, since it calls B's `bar` @@ -613,27 +667,30 @@ role PrintableVal { class Item does PrintableVal { has $.val; - # When `does`-ed, a `role` literally "mixes in" the class : - # the methods and fields are put together, which means a class can access - # the private fields/methods of its roles (but not the inverse !) : + # When `does`-ed, a `role` literally "mixes in" the class: + # the methods and fields are put together, which means a class can access + # the private fields/methods of its roles (but not the inverse !): method access { say $!counter++; } - # However, this : + # However, this: # method print {} - # is an error, since the compiler wouldn't know which `print` to use : - # contrarily to inheritance, methods mixed in can't be shadowed - they're put at the same "level" + # is ONLY valid when `print` isn't a `multi` with the same dispatch. + # (this means a parent class can shadow a child class's `multi print() {}`, + # but it's an error if a role does) - # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods will be shadowed, - # since the compiler will consider `ROLE` to be a class + # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods + # will be shadowed, since the compiler will consider `ROLE` to be a class. } ### Exceptions # Exceptions are built on top of classes, usually in the package `X` (like `X::IO`). -# Unlike many other languages, in Perl 6, you put the `CATCH` block *within* the block to `try`. -# By default, a `try` has a `CATCH` block that catches any exception (`CATCH { default {} }`). -# You can redefine it using `when`s (and `default`) to handle the exceptions you want: +# Unlike many other languages, in Perl 6, you put the `CATCH` block *within* the +# block to `try`. By default, a `try` has a `CATCH` block that catches +# any exception (`CATCH { default {} }`). +# You can redefine it using `when`s (and `default`) +# to handle the exceptions you want: try { open 'foo'; CATCH { @@ -649,17 +706,17 @@ die X::AdHoc.new(payload => 'Error !'); # TODO CONTROL ### Packages -# Packages are a way to reuse code. Packages are like "namespaces", and any element of the six model -# (`module`, `role`, `class`, `grammar`, `subset` and `enum`) are actually packages. -# (you can say that packages are the lowest common denomitor between them) -# Packages play a big part in a language, as Perl is well-known for CPAN, +# Packages are a way to reuse code. Packages are like "namespaces", and any +# element of the six model (`module`, `role`, `class`, `grammar`, `subset` +# and `enum`) are actually packages. (Packages are the lowest common denomitor) +# Packages play a big part in a language, especially as Perl is well-known for CPAN, # the Comprehensive Perl Archive Network. -# You usually don't use packages directly : you use `class Package::Name::Here;`, or if you -# only want to export variables/subs, you can use `module`: -module Hello::World { # bracketed form - # if `Hello` doesn't exist yet, it'll just be created as an "empty package stub" - # that can be redeclared as something else later. - # declarations here +# You usually don't use packages directly: you use `class Package::Name::Here;`, +# or if you only want to export variables/subs, you can use `module`: +module Hello::World { # Bracketed form + # If `Hello` doesn't exist yet, it'll just be a "stub", + # that can be redeclared as something else later. + # ... declarations here ... } module Parse::Text; # file-scoped form grammar Parse::Text::Grammar { # A grammar is a fine package, which you could `use` @@ -692,7 +749,8 @@ my $actions = JSON::Tiny::Actions.new; module Foo::Bar { our $n = 1; # note: you can't put a type constraint on an `our` variable our sub inc { - our sub available { # if you try to make scoped `sub`s `our` ... Better know what you're doing (Don't !). + our sub available { # If you try to make inner `sub`s `our`... + # Better know what you're doing (Don't !). say "Don't do that. Seriously. You'd get burned."; } my sub unavailable { # `my sub` is the default @@ -725,23 +783,24 @@ sub fixed-rand { fixed-rand for ^10; # will print the same number 10 times # Note, however, that they exist separately in different enclosing contexts. -# If you declare a function with a `state` within a loop, it'll re-create the variable -# for each iteration of loop. See: +# If you declare a function with a `state` within a loop, it'll re-create the +# variable for each iteration of the loop. See: for ^5 -> $a { sub foo { state $val = rand; # This will be a different value for every value of `$a` } for ^5 -> $b { - say foo; # This will print the same value 5 times, but only 5. Next iteration will re-run `rand` + say foo; # This will print the same value 5 times, but only 5. + # Next iteration will re-run `rand`. } } ### Phasers -# Phasers in Perl 6 are blocks that happen at determined points of time in your program -# When the program is compiled, when a for loop runs, when you leave a block, when -# an exception gets thrown ... (`CATCH` is actually a phaser !) +# Phasers in Perl 6 are blocks that happen at determined points of time in your +# program. When the program is compiled, when a for loop runs, when you leave a +# block, when an exception gets thrown ... (`CATCH` is actually a phaser !) # Some of them can be used for their return values, some of them can't # (those that can have a "[*]" in the beginning of their explanation text). # Let's have a look ! @@ -791,7 +850,7 @@ sub do-db-stuff { # Those act a bit like phasers: they affect the behavior of the following code. # Though, they run in-line with the executable code, so they're in lowercase. # (`try` and `start` are theoretically in that list, but explained somewhere else) -# Note: all of these (except start) don't need explicit brackets (`{` and `}`) for their block. +# Note: all of these (except start) don't need explicit brackets `{` and `}`. # - `do` (that you already saw) - runs a block or a statement as a term # You can't normally use a statement as a value (or "term"): @@ -848,8 +907,9 @@ say nilthingie.perl; #=> Nil ## Everybody loves operators ! Let's get more of them -## The precedence list can be found here : http://perlcabal.org/syn/S03.html#Operator_precedence -## But first, we need a little explanation about associativity : +# The precedence list can be found here: +# http://perlcabal.org/syn/S03.html#Operator_precedence +# But first, we need a little explanation about associativity: # * Binary operators: $a ! $b ! $c; # with a left-associative `!`, this is `($a ! $b) ! $c` @@ -864,8 +924,9 @@ $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` !$a! # with non-associative `!`, this is illegal ## Create your own operators ! -# Okay, you've been reading all of that, so I guess I should try to show you something exciting. -# I'll tell you a little secret (actually not): +# Okay, you've been reading all of that, so I guess I should try +# to show you something exciting. +# I'll tell you a little secret (or not-so-secret): # In Perl 6, all operators are actually just funny-looking subroutines. # You can declare an operator just like you declare a sub: @@ -906,36 +967,46 @@ sub circumfix:<[ ]>(Int $n) { say [5]; #=> 3125 # circumfix is around. Again, not whitespace. -sub postcircumfix:<{ }>(Str $s, Int $idx) { # post-circumfix is "after a term, around something" +sub postcircumfix:<{ }>(Str $s, Int $idx) { + # post-circumfix is + # "after a term, around something" $s.substr($idx, 1); } say "abc"{1}; #=> b # after the term `"abc"`, and around the index (1) # This really means a lot -- because everything in Perl 6 uses this. -# For example, to delete a key from a hash, you use the `:delete` adverb (named argument) +# For example, to delete a key from a hash, you use the `:delete` adverb +# (a simple named argument underneath): %h{$key}:delete; # equivalent to: -postcircumfix:<{ }>(%h, $key, :delete); -# It's *all* using the same building blocks! Syntactic categories (prefix infix ...), -# named arguments (adverbs), ..., used to build the language are available to you. +postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) +# It's *all* using the same building blocks! +# Syntactic categories (prefix infix ...), named arguments (adverbs), ..., +# - used to build the language - are available to you. -# (you are, obviously, recommended against making an operator out of *everything* -- -# with great power comes great responsibility) +# (you are, obviously, recommended against making an operator out of +# *everything* -- with great power comes great responsibility) ## Meta operators ! -# Oh boy, get ready. Get ready, because we're dwelving deep into the rabbit's hole, -# and you probably won't want to go back to other languages after reading that. +# Oh boy, get ready. Get ready, because we're dwelving deep +# into the rabbit's hole, and you probably won't want to go +# back to other languages after reading that. # (I'm guessing you don't want to already at that point). # Meta-operators, as their name suggests, are *composed* operators. # Basically, they're operators that apply another operator. ## * Reduce meta-operator -# It's a prefix meta-operator that takes a binary functions and one or many lists. -# If it doesn't get passed any argument, it either return a "default value" for this operator -# (a value that'd be non-meaningful if contained in a list) or `Any` if there's none. +# It's a prefix meta-operator that takes a binary functions and +# one or many lists. If it doesn't get passed any argument, +# it either return a "default value" for this operator +# (a value that wouldn't change the result if passed as one +# of the element of the list to be passed to the operator), +# or `Any` if there's none (examples below). +# # Otherwise, it pops an element from the list(s) one at a time, and applies the binary function # to the last result (or the list's first element) and the popped element. +# # To sum a list, you could use the reduce meta-operator with `+`, i.e.: say [+] 1, 2, 3; #=> 6 # equivalent to `(1+2)+3` @@ -943,18 +1014,20 @@ say [*] 1..5; #=> 120 # equivalent to `((((1*2)*3)*4)*5)`. # You can reduce with any operator, not just with mathematical ones. -# For example, you could reduce with `//` to get the first defined element of a list: +# For example, you could reduce with `//` to get +# the first defined element of a list: say [//] Nil, Any, False, 1, 5; #=> False # (Falsey, but still defined) # Default value examples: -say [*] (); #=> 1 -say [+] (); #=> 0 - # In both cases, they're results that, if they were contained in the lists, - # wouldn't have any impact on the final value (since N*1=N and N+0=N). +say [*] (); #=> 1 +say [+] (); #=> 0 + # In both cases, they're results that, were they in the lists, + # wouldn't have any impact on the final value + # (since N*1=N and N+0=N). say [//]; #=> (Any) - # There's no "default value" for `//` + # There's no "default value" for `//`. # You can also call it with a function you made up, using double brackets: sub add($a, $b) { $a + $b } @@ -980,23 +1053,31 @@ say [[&add]] 1, 2, 3; #=> 6 ## * Sequence operator # The sequence operator is one of Perl 6's most powerful features: -# it's composed of first, on the left, the list you want Perl 6 to deduce from (and might include a closure), -# and on the right, a value or the predicate for when to stop, or even Whatever for a lazy infinite list. +# it's composed of first, on the left, the list you want Perl 6 to deduce from +# (and might include a closure), and on the right, a value or the predicate +# that says when to stop (or Whatever for a lazy infinite list). my @list = 1, 2, 3 ... 10; # basic deducing -#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, because Perl 6 can't figure out the end -my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element (when the predicate matches) -my @list = 1, 3, 9 ... * > 30; # you can use a predicate (with the Whatever Star, here) +#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, + # because Perl 6 can't figure out the end +my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element + # (the iteration when the predicate matches). +my @list = 1, 3, 9 ... * > 30; # you can use a predicate + # (with the Whatever Star, here). my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above) -my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers, computed using a closure ! + +my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers, + # computed using a closure! my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above) say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55 # (using a range as the index) # Note : as for ranges, once reified, elements aren't re-calculated. -# That's why `@primes[^100]` will take a long time the first time you print it, then be instant +# That's why `@primes[^100]` will take a long time the first time you print +# it, then be instant. ## * Sort comparison -# They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1). +# They return one value of the `Order` enum : `Less`, `Same` and `More` +# (which numerify to -1, 0 or +1). 1 <=> 4; # sort comparison for numerics 'a' leg 'b'; # sort comparison for string $obj eqv $obj2; # sort comparison using eqv semantics @@ -1014,14 +1095,17 @@ say Any // Nil // 0 // 5; #=> 5 say True ^^ False; #=> True ## * Flip Flop -# The flip flop operators (`ff` and `fff`, equivalent to Perl 5/Ruby's `..` and `...`). +# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`). # are operators that take two predicates to test: -# They are `False` until their left side returns `True`, then are `True` until their right side returns `True`. -# Like for ranges, you can exclude the iteration when it became `True`/`False` by using `^` on either side. +# They are `False` until their left side returns `True`, then are `True` until +# their right side returns `True`. +# Like for ranges, you can exclude the iteration when it became `True`/`False` +# by using `^` on either side. # Let's start with an example : for { # by default, `ff`/`fff` smart-match (`~~`) against `$_`: - if 'met' ^ff 'meet' { # won't enter the if for "met" (explained in details below). + if 'met' ^ff 'meet' { # Won't enter the if for "met" + # (explained in details below). .say } @@ -1031,20 +1115,24 @@ for { } # This will print "young hero we shall meet" (excluding "met"): # the flip-flop will start returning `True` when it first encounters "met" -# (but will still return `False` for "met" itself, due to the leading `^` on `ff`), -# until it sees "meet", which is when it'll start returning `False`. +# (but will still return `False` for "met" itself, due to the leading `^` +# on `ff`), until it sees "meet", which is when it'll start returning `False`. # The difference between `ff` (awk-style) and `fff` (sed-style) is that -# `ff` will test its right side just as its left side changes to `True`, -# and can get back to `False` right away (*except* it'll be `True` for the iteration that matched) -# while `fff` will wait for the next iteration to try its right side, once its left side changed: +# `ff` will test its right side right when its left side changes to `True`, +# and can get back to `False` right away +# (*except* it'll be `True` for the iteration that matched) - +# While `fff` will wait for the next iteration to +# try its right side, once its left side changed: .say if 'B' ff 'B' for ; #=> B B - # because the right-hand-side was tested directly (and returned `True`). + # because the right-hand-side was tested + # directly (and returned `True`). # "B"s are still printed since it matched that time - # (it just went back to `False` right away) + # (it just went back to `False` right away). .say if 'B' fff 'B' for ; #=> B C B - # because the right-hand-side wasn't tested until `$_` became "C" - # (and thus did not match directly). + # because the right-hand-side wasn't tested until + # `$_` became "C" + # (and thus did not match instantly). # A flip-flop can change state as many times as needed: for { @@ -1054,12 +1142,15 @@ for 50 ff *; # Once the flip-flop reaches a number greater than 50, it'll never go back to `False` +for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here + # (sometimes called "superstitious parentheses") + .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, + # it'll never go back to `False` #=> 60 3 40 60 } -# You can also use this property to create an `If` that'll not execute the first time : +# You can also use this property to create an `If` +# that'll not go through the first time : for { .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, # but the `^` makes it *not run* on the first iteration @@ -1072,28 +1163,33 @@ for { # Well, now that you know a good deal of Perl 6 already, we can get started. # First off, you'll have to forget about "PCRE regexps" (perl-compatible regexps). # -# IMPORTANT: You may feel like you already know these because you know PCRE. You'd be wrong. -# Some things are the same (like `?`, `+`, and `*`), but sometimes the semantics change (`|`). +# IMPORTANT: Don't skip them because you know PCRE. They're different. +# Some things are the same (like `?`, `+`, and `*`), +# but sometimes the semantics change (`|`). # Make sure you read carefully, because you might trip over a new behavior. # -# Perl 6 has a looot of features related to RegExps. After all, Rakudo parses itself. -# We're first going to look at the syntax itself, then talk about grammars (PEG-like), -# differences between the `token`, `regex` and `rule` keywords, and some more. +# Perl 6 has many features related to RegExps. After all, Rakudo parses itself. +# We're first going to look at the syntax itself, +# then talk about grammars (PEG-like), differences between +# `token`, `regex` and `rule` declarators, and some more. # Side note: you still have access to PCRE regexps using the `:P5` modifier. # (we won't be discussing this in this tutorial, however) # # In essence, Perl 6 natively implements PEG ("Parsing Expression Grammars"). -# The pecking order for ambiguous parses is determined by a multi-level tie-breaking test: +# The pecking order for ambiguous parses is determined by a multi-level +# tie-breaking test: # - Longest token matching. `foo\s+` beats `foo` (by 2 or more positions) # - Longest literal prefix. `food\w*` beats `foo\w*` (by 1) -# - Declaration from most-derived to less derived grammars (grammars are actually classes) +# - Declaration from most-derived to less derived grammars +# (grammars are actually classes) # - Earliest declaration wins say so 'a' ~~ /a/; #=> True say so 'a' ~~ / a /; # More readable with some spaces! -# In all our examples, we're going to use the smart-matching operator against a regexp. -# We're converting the result using `so`, but in fact, it's returning a `Match` object. -# They know how to respond to list indexing, hash indexing (and return the matched string). +# In all our examples, we're going to use the smart-matching operator against +# a regexp. We're converting the result using `so`, but in fact, it's +# returning a `Match` object. They know how to respond to list indexing, +# hash indexing, and return the matched string. # The results of the match are also available as `$/` (implicitly lexically-scoped). # You can also use the capture variables (`$0`, `$1`, ... - starting at 0, not 1 !). # @@ -1101,8 +1197,8 @@ say so 'a' ~~ / a /; # More readable with some spaces! # (meaning the regexp can be matched with just one char of the string), # we're going to explain later how you can do it. -# In Perl 6, you can have any alphanumeric as a literal, everything else has to be escaped, -# using a backslash or quotes. +# In Perl 6, you can have any alphanumeric as a literal, +# everything else has to be escaped, using a backslash or quotes. say so 'a|b' ~~ / a '|' b /; # `True`. Wouln't mean the same if `|` wasn't escaped say so 'a|b' ~~ / a \| b /; # `True`. Another way to escape it. @@ -1140,7 +1236,8 @@ so 'abbbbc' ~~ / a b* c /; # `True` so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, but can't be something else. # - `**` - "Quantify It Yourself". -# If you squint hard enough, you might understand the why exponentation means quantity. +# If you squint hard enough, you might understand +# why exponentation is used for quantity. so 'abc' ~~ / a b ** 1 c /; # `True` (exactly one time) so 'abc' ~~ / a b ** 1..3 c /; # `True` (one to three times) so 'abbbc' ~~ / a b ** 1..3 c /; # `True` @@ -1151,11 +1248,12 @@ so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay) # Group: you can group parts of your regexp with `[]`. # These groups are *not* captured (like PCRE's `(?:)`). so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing -so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; # `True`. - # We match the "abc" 1 or more time. - # (the `+` was applied to the group) +so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; +# The previous line returns `True`. +# We match the "abc" 1 or more time (the `+` was applied to the group). -# But this does not go far enough, because we can't actually get back what we matched. +# But this does not go far enough, because we can't actually get back what +# we matched. # Capture: We can actually *capture* the results of the regexp, using parentheses. so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (we keep `so` here and use `$/` below) @@ -1165,13 +1263,15 @@ say $/; # Will print some weird stuff (we'll explain) (or "Nil" if nothing match # As we also said before, it has array indexing: say $/[0]; #=> 「ABC」 「ABC」 - # These weird brackets are `Match` objects. So here, we have an array of that. -say $0; # the same as above. + # These weird brackets are `Match` objects. + # Here, we have an array of these. +say $0; # The same as above. # Our capture is `$0` because it's the first and only one capture in the regexp. # You might be wondering why it's an array, and the answer is simple: # Some capture (indexed using `$0`, `$/[0]` or a named one) will be an array -# IF it can have more than one element (so, with `*`, `+` and any `**`, but not with `?`). +# IFF it can have more than one element +# (so, with `*`, `+` and any `**`, but not with `?`). # Let's use examples to see that: so 'fooABCbar' ~~ / foo ( A B C )? bar /; # `True` say $/[0]; #=> 「ABC」 @@ -1206,7 +1306,8 @@ sub MAIN($name) { say "Hello, you !" } # t.pl # And since it's a regular Perl 6 sub, you can haz multi-dispatch: -# (using a "Bool" for the named argument so that we get `--replace` instead of `--replace=`) +# (using a "Bool" for the named argument so that we get `--replace` +# instead of `--replace=1`) subset File of Str where *.IO.d; # convert to IO object, then check the file exists multi MAIN('add', $key, $value, Bool :$replace) { ... } @@ -1218,8 +1319,9 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name # t.pl [--replace] add # t.pl remove # t.pl [--as=] import (File) -# As you can see, this is *very* powerful. It even went as far as to show inline the constants. -# (the type is only displayed if 1. there's no argument name 2. it's a named argument) +# As you can see, this is *very* powerful. +# It even went as far as to show inline the constants. +# (the type is only displayed if the argument is `$`/is named) ``` If you want to go further, you can: -- cgit v1.2.3 From 3cb8d2bcc56332a814d0ae69492782ee4ddbd473 Mon Sep 17 00:00:00 2001 From: "a.vandijk" Date: Fri, 8 Aug 2014 15:19:14 +0200 Subject: - [ADD] PrintWriter example from Java - [CHANGE] Extended regex matching with more examples with switch / case - [CHANGE] String interpolation with formatting and expressions explained. --- scala.html.markdown | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 432933c2..4dc87a94 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -299,7 +299,6 @@ Person("George", "1234") == Person("Kate", "1236") - // Pattern matching val me = Person("George", "1234") @@ -322,15 +321,22 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions - val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex - -val email(user, domain) = "henry@zkpr.com" - -"mrbean@pyahoo.com" match { - case email(name, domain) => "I know your name, " + name +val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using multiline string syntax + +val matcher = (value: String) => { + println(value match { + case email(name, domain) => s"It was an email: $name" + case serialKey(p1, p2, p3, p4) => s"Serial key: $p1, $p2, $p3, $p4" + case _ => s"No match on '$value'" // default if no match found + }) } +matcher("mrbean@pyahoo.com") +matcher("nope..") +matcher("52917") +matcher("52752-16432-22178-47917") + // Strings @@ -347,17 +353,27 @@ println("ABCDEF".length) println("ABCDEF".substring(2, 6)) println("ABCDEF".replace("C", "3")) +// String interpolation val n = 45 println(s"We have $n apples") +// Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -println(s"My second daughter is ${a(2-1)} years old") +println(s"My second daughter is ${a(0) - a(2)} years old") +println(s"We have double the amount of ${n / 2.0} in apples.") +println(s"Power of 2: ${math.pow(2, 2)}") // Power of 2: 4.0 + +// Formatting with interpolated strings (note the prefixed f) +println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // Power of 5: 25 +println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // Square root of 122 + +// Ignoring special characters. +println(raw"New line feed: \n. Carriage return: \r.") // Some characters need to be 'escaped', e.g. a double quote inside a string: val a = "They stood outside the \"Rose and Crown\"" // Triple double-quotes let strings span multiple rows and contain quotes - val html = """

Press belo', Joe

| @@ -403,7 +419,10 @@ for(line <- Source.fromFile("myfile.txt").getLines()) println(line) // To write a file use Java's 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 07b6229ee608ae37283a827112b5eab4c58a5333 Mon Sep 17 00:00:00 2001 From: "a.vandijk" Date: Fri, 8 Aug 2014 15:23:46 +0200 Subject: [CHANGE] Comment match on serial key now mentions verbatim (multiline) --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 4dc87a94..619c8aae 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -322,7 +322,7 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex -val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using multiline string syntax +val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using verbatim (multiline) syntax val matcher = (value: String) => { println(value match { -- cgit v1.2.3 From d2cf0062822ec364a21afa6550d4d0538857a7fe Mon Sep 17 00:00:00 2001 From: "a.vandijk" Date: Fri, 15 Aug 2014 15:47:12 +0200 Subject: [CHANGE] Output examples added to matcher part and string interpolation part. --- scala.html.markdown | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 619c8aae..eae39abb 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -332,11 +332,10 @@ val matcher = (value: String) => { }) } -matcher("mrbean@pyahoo.com") -matcher("nope..") -matcher("52917") -matcher("52752-16432-22178-47917") - +matcher("mrbean@pyahoo.com") // => "It was an email: mrbean" +matcher("nope..") // => "No match on 'nope..'" +matcher("52917") // => "No match on '52917'" +matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" // Strings @@ -359,13 +358,13 @@ println(s"We have $n apples") // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -println(s"My second daughter is ${a(0) - a(2)} years old") -println(s"We have double the amount of ${n / 2.0} in apples.") -println(s"Power of 2: ${math.pow(2, 2)}") // Power of 2: 4.0 +println(s"My second daughter is ${a(0) - a(2)} years old") // => "My second daughter is 5 years old" +println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." +println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" // Formatting with interpolated strings (note the prefixed f) -println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // Power of 5: 25 -println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // Square root of 122 +println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" +println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" // Ignoring special characters. println(raw"New line feed: \n. Carriage return: \r.") -- cgit v1.2.3 From 775c7faa65e84b8030478f4476995935ac8c2813 Mon Sep 17 00:00:00 2001 From: "a.vandijk" Date: Sat, 16 Aug 2014 18:21:49 +0200 Subject: [ADDED] Output to additional println's. --- scala.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index eae39abb..6b398b4b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -354,11 +354,11 @@ println("ABCDEF".replace("C", "3")) // String interpolation val n = 45 -println(s"We have $n apples") +println(s"We have $n apples") // => "We have 45 apples" // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -println(s"My second daughter is ${a(0) - a(2)} years old") // => "My second daughter is 5 years old" +println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" @@ -367,10 +367,10 @@ println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" // Ignoring special characters. -println(raw"New line feed: \n. Carriage return: \r.") +println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." // Some characters need to be 'escaped', e.g. a double quote inside a string: -val a = "They stood outside the \"Rose and Crown\"" +val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" // Triple double-quotes let strings span multiple rows and contain quotes val html = """ -- cgit v1.2.3 From b249363a998d08aff750d2722370e648c59cf70f Mon Sep 17 00:00:00 2001 From: Dzianis Dashkevich Date: Tue, 19 Aug 2014 12:06:52 +0300 Subject: Make style fixes to conform to ruby style guide Made style fixes to conform to Ruby style guide. Added a reference to a community-driven Ruby coding style guide. --- ruby.html.markdown | 102 ++++++++++++++++++++++++++--------------------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 962853a2..3c67de2e 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -9,6 +9,7 @@ contributors: - ["Nick LaMuro", "https://github.com/NickLaMuro"] - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] --- @@ -35,7 +36,7 @@ You shouldn't either 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 -2 ** 5 #=> 32 +2**5 #=> 32 # Arithmetic is just syntactic sugar # for calling a method on an object @@ -78,14 +79,17 @@ false.class #=> FalseClass 'I am a string'.class #=> String "I am a string too".class #=> String -placeholder = "use string interpolation" +placeholder = 'use string interpolation' "I can #{placeholder} when using double quoted strings" #=> "I can use string interpolation when using double quoted strings" +# Prefer single quoted strings to double quoted ones where possible +# Double quoted strings perform additional inner calculations + # Combine strings, but not with numbers -"hello " + "world" #=> "hello world" -"hello " + 3 #=> TypeError: can't convert Fixnum into String -"hello " + 3.to_s #=> "hello 3" +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" # print to the output puts "I'm printing!" @@ -130,7 +134,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arrays can contain different types of items -[1, "hello", false] #=> [1, "hello", false] +[1, 'hello', false] #=> [1, "hello", false] # Arrays can be indexed # From the front @@ -157,7 +161,7 @@ array << 6 #=> [1, 2, 3, 4, 5, 6] # Hashes are Ruby's primary dictionary with keys/value pairs. # Hashes are denoted with curly braces: -hash = {'color' => 'green', 'number' => 5} +hash = { 'color' => 'green', 'number' => 5 } hash.keys #=> ['color', 'number'] @@ -170,7 +174,7 @@ hash['nothing here'] #=> nil # Since Ruby 1.9, there's a special syntax when using symbols as keys: -new_hash = { defcon: 3, action: true} +new_hash = { defcon: 3, action: true } new_hash.keys #=> [:defcon, :action] @@ -180,11 +184,11 @@ new_hash.keys #=> [:defcon, :action] # Control structures if true - "if statement" + 'if statement' elsif false - "else if, optional" + 'else if, optional' else - "else, also optional" + 'else, also optional' end for counter in 1..5 @@ -216,7 +220,7 @@ end #=> iteration 5 # You can also surround blocks in curly brackets: -(1..5).each {|counter| puts "iteration #{counter}"} +(1..5).each { |counter| puts "iteration #{counter}" } # The contents of data structures can also be iterated using each. array.each do |element| @@ -241,32 +245,30 @@ grade = 'B' case grade when 'A' - puts "Way to go kiddo" + puts 'Way to go kiddo' when 'B' - puts "Better luck next time" + puts 'Better luck next time' when 'C' - puts "You can do better" + puts 'You can do better' when 'D' - puts "Scraping through" + puts 'Scraping through' when 'F' - puts "You failed!" + puts 'You failed!' else - puts "Alternative grading system, eh?" + puts 'Alternative grading system, eh?' end - #=> "Better luck next time" # cases can also use ranges grade = 82 case grade - when 90..100 - puts "Hooray!" - when 80...90 - puts "OK job" - else - puts "You failed!" +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' end - #=> "OK job" @@ -284,23 +286,23 @@ double 3 #=> 6 double double 3 #=> 12 -def sum(x,y) +def sum(x, y) x + y end # Method arguments are separated by a comma sum 3, 4 #=> 7 -sum sum(3,4), 5 #=> 12 +sum sum(3, 4), 5 #=> 12 # yield # All methods have an implicit, optional block parameter # it can be called with the 'yield' keyword def surround - puts "{" + puts '{' yield - puts "}" + puts '}' end surround { puts 'hello world' } @@ -311,25 +313,25 @@ surround { puts 'hello world' } # You can pass a block to a function -# "&" marks a reference to a passed block +# "&" marks a reference to a passed block def guests(&block) - block.call "some_argument" + block.call 'some_argument' end - + # You can pass a list of arguments, which will be converted into an array -# That's what splat operator ("*") is for +# That's what splat operator ("*") is for def guests(*array) - array.each { |guest| puts "#{guest}" } + array.each { |guest| puts guest } end # Define a class with the class keyword class Human # A class variable. It is shared by all instances of this class. - @@species = "H. sapiens" + @@species = 'H. sapiens' # Basic initializer - def initialize(name, age=0) + def initialize(name, age = 0) # Assign the argument to the "name" instance variable for the instance @name = name # If no age given, we will fall back to the default in the arguments list. @@ -356,20 +358,19 @@ class Human # A class method uses self to distinguish from instance methods. # It can only be called on the class, not an instance. def self.say(msg) - puts "#{msg}" + puts msg end def species @@species end - end # Instantiate a class -jim = Human.new("Jim Halpert") +jim = Human.new('Jim Halpert') -dwight = Human.new("Dwight K. Schrute") +dwight = Human.new('Dwight K. Schrute') # Let's call a couple of methods jim.species #=> "H. sapiens" @@ -380,7 +381,7 @@ dwight.species #=> "H. sapiens" dwight.name #=> "Dwight K. Schrute" # Call the class method -Human.say("Hi") #=> "Hi" +Human.say('Hi') #=> "Hi" # Variable's scopes are defined by the way we name them. # Variables that start with $ have global scope @@ -399,7 +400,7 @@ defined? @@var #=> "class variable" Var = "I'm a constant" defined? Var #=> "constant" -# Class also is object in ruby. So class can have instance variables. +# Class is also an object in ruby. So class can have instance variables. # Class variable is shared among the class and all of its descendants. # base class @@ -415,7 +416,7 @@ class Human end end -# derived class +# derived class class Worker < Human end @@ -451,8 +452,8 @@ module ModuleExample end end -# Including modules binds the methods to the object instance -# Extending modules binds the methods to the class instance +# Including modules binds their methods to the class instances +# Extending modules binds their methods to the class itself class Person include ModuleExample @@ -467,7 +468,7 @@ Person.new.foo # => 'foo' Book.foo # => 'foo' Book.new.foo # => NoMethodError: undefined method `foo' -# Callbacks when including and extending a module are executed +# Callbacks are executed when including and extending a module module ConcernExample def self.included(base) @@ -500,9 +501,8 @@ Something.new.qux # => 'qux' ## Additional resources -- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. - [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) -- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. - - +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. -- cgit v1.2.3 From d7ead48d1fa7c6ffb32aeeb6f289bf859a6bbef8 Mon Sep 17 00:00:00 2001 From: James Baxter Date: Tue, 19 Aug 2014 12:06:02 +0100 Subject: Corrected the statement that rune is an alias for uint32 to say int32 --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 656b1051..f7bd8ee3 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -78,7 +78,7 @@ func learnTypes() { can include line breaks.` // Same string type. // Non-ASCII literal. Go source is UTF-8. - g := 'Σ' // rune type, an alias for uint32, holds a unicode code point. + g := 'Σ' // rune type, an alias for int32, holds a unicode code point. f := 3.14195 // float64, an IEEE-754 64-bit floating point number. c := 3 + 4i // complex128, represented internally with two float64's. -- cgit v1.2.3 From 4b5cbc91eb40d678c12d5bbb1d9fdbda9d22923d Mon Sep 17 00:00:00 2001 From: James Baxter Date: Tue, 19 Aug 2014 12:56:27 +0100 Subject: Fixed the statement that rune is an alias for uint32 in the translations --- de-de/go-de.html.markdown | 2 +- es-es/go-es.html.markdown | 2 +- ko-kr/go-kr.html.markdown | 2 +- pt-br/go-pt.html.markdown | 2 +- ru-ru/go-ru.html.markdown | 2 +- zh-cn/go-cn.html.markdown | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 8c2f58dd..ca27fdc7 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -79,7 +79,7 @@ func learnTypes() { Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ // nicht-ASCII Literal. Go Quelltext ist UTF-8 kompatibel. - g := 'Σ' // Ein Runen-Typ, alias uint32, gebraucht für unicode code points. + g := 'Σ' // Ein Runen-Typ, alias int32, gebraucht für unicode code points. f := 3.14195 // float64, eine IEEE-754 64-bit Dezimalzahl c := 3 + 4i // complex128, besteht intern aus zwei float64-er diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index e788e810..86de33ec 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -77,7 +77,7 @@ func learnTypes() { saltos de línea.` // mismo tipo cadena // Literal no ASCII. Los fuentes de Go son UTF-8. - g := 'Σ' // Tipo rune, un alias de uint32, alberga un punto unicode. + g := 'Σ' // Tipo rune, un alias de int32, alberga un punto unicode. f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit. c := 3 + 4i // complex128, representado internamente por dos float64. // Sintaxis Var con inicializadores. diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown index e4eaee56..3012c04f 100644 --- a/ko-kr/go-kr.html.markdown +++ b/ko-kr/go-kr.html.markdown @@ -79,7 +79,7 @@ func learnTypes() { 개행을 포함할 수 있다.` // 같은 string 타입 // non-ASCII 리터럴. Go 소스는 UTF-8로 작성해야 한다. - g := 'Σ' // 유니코드 코드 포인트를 담고 있고, uint32 타입의 가칭(alias)인 rune 타입 + g := 'Σ' // 유니코드 코드 포인트를 담고 있고, int32 타입의 가칭(alias)인 rune 타입 f := 3.14195 // float64, an IEEE-754 64-bit 부동소수 타입 c := 3 + 4i // complex128, 내부적으로는 두 개의 float64 타입으로 표현됨 diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown index 32c8fbdd..c7339831 100644 --- a/pt-br/go-pt.html.markdown +++ b/pt-br/go-pt.html.markdown @@ -75,7 +75,7 @@ func learnTypes() { pode incluir quebras de linha.` // mesmo tipo string // literal não-ASCII. A linguagem Go utiliza de raiz a codificação UTF-8. - g := 'Σ' // tipo rune, um alias para uint32, que contém um código unicode + g := 'Σ' // tipo rune, um alias para int32, que contém um código unicode f := 3.14195 // float64, número de vírgula flutuante de 64bit (IEEE-754) c := 3 + 4i // complex128, representado internamente com dois float64s diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index ffda01b7..5b9d8ebf 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -79,7 +79,7 @@ func learnTypes() { может содержать переносы строк` // Тоже тип данных string // Символ не из ASCII. Исходный код Go в кодировке UTF-8. - g := 'Σ' // тип rune, это алиас для типа uint32, содержит символ юникода. + g := 'Σ' // тип rune, это алиас для типа int32, содержит символ юникода. f := 3.14195 // float64, 64-х битное число с плавающей точкой (IEEE-754). c := 3 + 4i // complex128, внутри себя содержит два float64. diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 4a87dc21..9f6a8c15 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -68,7 +68,7 @@ func learnTypes() { can include line breaks.` // 同样是String类型 // 非ascii字符。Go使用UTF-8编码。 - g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码 + g := 'Σ' // rune类型,int32的别名,使用UTF-8编码 f := 3.14195 // float64类型,IEEE-754 64位浮点数 c := 3 + 4i // complex128类型,内部使用两个float64表示 -- cgit v1.2.3 From b33208ad676473b403d4f838b2c89bbae3056f51 Mon Sep 17 00:00:00 2001 From: Pierre-Arnaud Baciocchini Date: Tue, 19 Aug 2014 16:48:56 +0200 Subject: Added french translation for Swift --- fr-fr/swift-fr.html.markdown | 225 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 225 insertions(+) create mode 100644 fr-fr/swift-fr.html.markdown diff --git a/fr-fr/swift-fr.html.markdown b/fr-fr/swift-fr.html.markdown new file mode 100644 index 00000000..18628524 --- /dev/null +++ b/fr-fr/swift-fr.html.markdown @@ -0,0 +1,225 @@ +--- +language: swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] +translators: + - ["@prrrnd", "https://github.com/prrrnd"] +lang: fr-fr +--- + +Swift est un langage de programmation crée par Apple pour iOS et OS X. Swift a été introduit en 2014 à la conférence WWDC d'Apple. Il est construit avec le compilateur LLVM inclus dans la version bétâ de Xcode 6. + +Pour plus d'informations, en anglais, regardez le [guide d'Apple](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), qui inclus un tutoriel complet sur Swift. + +```js +// +// Bases +// + +println("Hello, world") +var myVariable = 42 +let myConstant = 3.1415926 +let explicitDouble: Double = 70 +let label = "du texte " + String(myVariable) // Cast +let piText = "Pi = \(myConstant)" // Interpolation +var optionalString: String? = "optional" // Peut être nil +optionalString = nil + + +// +// Tableaux et dictionnaires +// + +// Tableau +var shoppingList = ["poisson", "eau", "citrons"] +shoppingList[1] = "bouteille d'eau" +let tableauVide = [String]() + +// Dictionnaire +var occupations = [ + "Malcolm": "Capitaine", + "kaylee": "Mécanicien" +] +occupations["Jayne"] = "Secretaire" +let dicoVide = Dictionary() + + +// +// Contrôle et boucles +// + +// Boucle for (tableau) +let monTableau = [1, 1, 2, 3, 5] +for value in monTableau { + if value == 1 { + println("Un!") + } else { + println("Pas un!") + } +} + +// Boucle for (dictionnaire) +for (key, value) in dict { + println("\(key): \(value)") +} + +// Boucle for (interval) +for i in -1...1 { // [-1, 0, 1] + println(i) +} +// utilisez ..< pour exclure le dernier élement + +// Boucle while +var i = 1 +while i < 1000 { + i *= 2 +} + +// Boucle do-while +do { + println("bonjour") +} while 1 == 2 + +// Switch +let legume = "haricot" +switch legume { +case "haricot": + // ... +case "concombre", "patate": + // ... +default: // requis afin de couvrir toutes les possibilités + // ... +} + + +// +// Fonctions +// + +// Les fonctions sont de type primitif, ce qui veut dire qu'elles peuvent être incluses dans d'autres fonctions + +// Fonction +func direBonjour(name: String, day: String) -> String { + return "Bonjour \(name), on est \(day) aujourd'hui." +} +direBonjour("Bob", "mardi") + +// Fonction qui retourne plusieurs valeurs dans un tuple +func getPrix() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} + +// Arguments +func setup(nombres: Int...) {} + +// Passer et retourner des fonctions +func augmenter() -> (Int -> Int) { + func ajouterUn(nombre: Int) -> Int { + return 1 + nombre + } + return ajouterUn +} +var increment = augmenter() +increment(7) + + +// +// Closures +// +var nombres = [1, 2, 6] + +// Les fonctions sont des cas de closures spéciales ({}) + +// Exemple de closure. +// `->` sépare les arguments et le type de retour +// `in` sépare l'en-tête de closure de son corps +nombres.map({ + (nombre: Int) -> Int in + let resultat = 3 * nombre + return resultat + }) + +// Lorsque le type est connu, comme ci-dessus, on peut faire ceci +nombres = nombres.map({ nombre in 3 * nombre }) +//Ou cela +//nombres = nombres.map({ $0 * 3 }) + +print(nombres) // [3, 6, 18] + + +// +// Classes +// + +// Toutes les méthodes et propriétés d'une classe sont publiques. +// Si vous avez juste besoin de stocker des données dans un +// objet structuré, vous devez utiliser une structure + +// Une classe `Square` hérite d'une classe `Shape` +class Rect: Shape { + var longueurCote: Int = 1 + + // Custom getter and setter property + var perimeter: Int { + get { + return 4 * longueurCote + } + set { + longueurCote = newValue / 4 + } + } + + init(longueurCote: Int) { + super.init() + self.longueurCote = longueurCote + } + + func shrink() { + if longueurCote > 0 { + --longueurCote + } + } + + override func getArea() -> Int { + return longueurCote * longueurCote + } +} +var monCarre = new Square(longueurCote: 5) +print(monCarre.getArea()) // 25 +monCarre.shrink() +print(monCarre.longueurCote) // 4 + +// If you don't need a custom getter and setter, +// but still want to run code before and after getting or setting +// a property, you can use `willSet` and `didSet` + + +// +// Enumerations +// + +// Les énumerations peuvent être d'un type spécifique ou non. +// Elles peuvent contenir méthodes et classes + +enum Suit { + case Pic, Coeur, Carre, Trefle + func getIcon() -> String { + switch self { + case .Pic: return "♤" + case .Coeur: return "♡" + case .Carre: return "♢" + case .Trefle: return "♧" + } + } +} + + +// +// Autres +// + +// `protocol`: Similaire aux interfaces en Java +// `extension`s: Permet d'ajouter des fonctionnalités à un type existant +// Generics: Similaire à Java. Utilisez le mot clé `where` pour specifier les pré-requis du generic + +``` -- cgit v1.2.3 From e5a61a1db19f9099697791958a53c809d2050866 Mon Sep 17 00:00:00 2001 From: MrAkirah Date: Tue, 19 Aug 2014 21:30:31 +0100 Subject: Update ruby-fr.html.markdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @@species n'existe pas, remplacé @@espece --- fr-fr/ruby-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown index 3060bd75..75c8d0d3 100644 --- a/fr-fr/ruby-fr.html.markdown +++ b/fr-fr/ruby-fr.html.markdown @@ -336,8 +336,8 @@ class Humain puts "#{msg}" end - def species - @@species + def espece + @@espece end end -- cgit v1.2.3 From ddd4db06cabe4371b5cf6802b70995ac3b4a4db6 Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 02:01:40 +0200 Subject: Added French translation for Javascript --- fr-fr/javascript-fr.html.markdown | 508 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 508 insertions(+) create mode 100644 fr-fr/javascript-fr.html.markdown diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown new file mode 100644 index 00000000..598fb6af --- /dev/null +++ b/fr-fr/javascript-fr.html.markdown @@ -0,0 +1,508 @@ +--- +language: javascript +contributors: + - ['Adam Brenecki', 'http://adam.brenecki.id.au'] + - ['Ariel Krakowski', 'http://www.learneroo.com'] +filename: javascript-fr.js +translators: + - ['@nbrugneaux', 'https://nicolasbrugneaux.me'] +lang: fr-fr +--- + +JavaScript a été crée par Brendan Eich, travaillant alors a Netscape, en 1995. +Le langage avait à l'origine pour but d'être un langage de scripting simple +pour les sites web, complétant le Java pour des applications web complexes. Mais +son intégration très proche et simple des pages web, ainsi que le support natif +des navigateurs a rendu le JavaScript incontournable aujourd'hui tant bien dans +le front-end que dans le back-end. + +En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à +Node.JS, un projet qui offre un environnement indépendant dans lequel un +interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome, +peut être utilisé directement côté serveur pour exécuter des programmes écrits +en JavaScript. + +```js +// Les commentaires sont comme en C. Les commentaires en ligne commencent par 2 slashs, +/* et les commentaires sur plusieurs lignes commencent avec slash-étoile + et finissent avec étoile-slash */ + +// Toutes les expressions peuvent finir par ; +doStuff(); + +// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés +// lors de l’interprétation aux sauts de ligne, sauf exceptions +doStuff() + +// Parce que ces cas peuvent produire des effets inattendus, nous utiliserons +// des point-virgules dans ce guide. + +/////////////////////////////////// +// 1. Nombres, Chaines de caractères et Opérateurs + +// JavaScript a un seul type de nombre (qui est un 64-bit IEEE 754 double (décimaux)) +// Comme avec le Lua, ne paniquez pas à cause du manque d'int (entiers): les +// doubles ont un mantisse de 52 bits, ce qui est assez pour stocker des int jusqu'à +// 9 x 10¹⁵ exactement. +3; // = 3 +1.5; // = 1.5 + +// L'arithmétique de base fonctionne comme vous vous y attendriez +1 + 1; // = 2 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Ainsi que les divisions non-entières +5 / 2; // = 2.5 + +// Les opérations bits à bits fonctionnent aussi, quand vous effectuez une opération +// bits à bits , votre nombre décimal est converti en entier *jusqu'à* 32 bits. +1 << 2; // = 4 + +// Comme en mathématiques, la priorité est donnée aux parenthèses. +(1 + 3) * 2; // = 8 + +// Il existe 3 valeurs spéciales pour les nombres: +Infinity; // le résultat de 1/0 par exemple +-Infinity; // le résultat de -1/0 par exemple +NaN; // le résultat de 0/0 par exemple + +// Il existe également le type booléen. +true; // vrai +false; // faux + +// Les chaines de caractères (strings) sont crées avec ' ou ' indifféremment, la seule +// raison de choisir l'un ou l'autre est la consistance dans votre code. +'abc'; +'Hello, world'; + +// La négation utilise le symbole ! +!true; // = false +!false; // = true + +// L'égalité est === ou == +// === compare la valeur exacte 2 === '2' // = false +// == convertit la valeur pour comparer 2 === '2' // = true +// En général, il vaut mieux utiliser === pour ne pas faire d'erreurs. +1 === 1; // = true +2 === 1; // = false + +// L'inégalité est !== ou !=, basé sur le même principe qu'avant. +1 !== 1; // = false +2 !== 1; // = true + +// Plus de comparaisons: +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Les strings se concatènent avec + +'Hello ' + 'world!'; // = 'Hello world!' + +// et peuvent être comparées avec < et > +'a' < 'b'; // = true + +// Vous pouvez accéder les caractères dans une string avec charAt +'This is a string'.charAt(0); // = 'T' + +// .. ou utiliser substring pour avoir un plus gros morceau +'Hello world'.substring(0, 5); // = 'Hello' + +// la longueur, length, est une propriété, donc n'utilisez pas de () +'Hello'.length; // = 5 + +// Il y a également null et undefined +null; // utilisé pour une non-valeur +undefined; // utilisé pour une valeur actuellement non présente (cependant, + // undefined est aussi une valeur valide) + +// false, null, undefined, NaN, 0 and '' sont 'presque-faux' (falsy), tout le reste +// est 'presque-vrai' (truthy) +// Notez que 0 est falsy mais '0' est truthy, alors même que 0 == '0' (mais 0 !== '0') + + +/////////////////////////////////// +// 2. Variables, Tableaux et Objets + +// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est +// dynamique, donc pas besoin de spécifier le type. L'assignement utilise un seul =. +var someVar = 5; + +// si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict) +someOtherVar = 10; + +// ... mais la variable sera crée dans l’environnement global, et non l’environnement +// local dans lequel vous l'avez défini. + +// Les variables déclarées et non assignées sont undefined par défaut +var someThirdVar; +var someThirdVar = undefined; + +// ... sont deux déclarations identiques. + +// Il y a des raccourcis pour les opérations mathématiques: +someVar += 5; // équivalent pour someVar = someVar + 5; +someVar *= 10; // de même, someVar = someVar * 100; +someVar++; // = someVar += 1; +someVar--; // = someVar -= 1; + +// Les tableaux (Arrays) sont des listes ordonnées de valeurs, de tous types. +var myArray = ['Hello', 45, true]; + +// Leurs membres peuvent être accédés en utilisant les crochets +// Les indices commencent à 0. +myArray[1]; // = 45 + +// Les tableaux sont modifiables, ainsi que leurs longueurs +myArray.push( 'World' ); +myArray.length; // = 4 + +// Ajout/Modification à un index spécifique +myArray[3] = 'Hello'; + +// Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres +// langages: ils sont une liste non-ordonnée de paires clé-valeur. +var myObj = {key1: 'Hello', key2: 'World'}; + +// Les clés sont des strings, mais les ' ou " sont optionels si elles sont des +// noms valides en JavaScript. Les valeurs peuvent être de n'importe quel type. +var myObj = {myKey: 'myValue', 'my other key': 4}; + +// Les attributs d'objets peuvent être accédés avec les crochets +myObj['my other key']; // = 4 + +// .. ou avec un point si la clé est un identifiant valide. +myObj.myKey; // = 'myValue' + +// Les objets sont eux aussi modifiables. +myObj.myThirdKey = true; + +// Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Logique et structures de contrôle + +// La syntaxe de cette section est identique au Java. + +// Les si (if) fonctionnent comme vous vous y attendez. +var count = 1; +if (count === 3) { + // seulement quand count est 3 +} +else if (count === 4) { + // uniquement quand count est 4 +} +else { + // le reste du temps, si ni 3, ni 4. +} + +// De même pour while. +while (true) { + // Une boucle infinie ! +} + +// Les boucles do-while sont pareilles, mais sont exécutées au moins une fois. +var input +do { + input = getInput(); +} while (!isValid(input)) + +// La boucle for est la même qu'en C ou en Java: +// initialisation; condition pour continuer; itération +for (var i = 0; i < 5; i++){ + // sera exécutée 5 fois +} + +// && est le "et" logique, || est le "ou" logique +if (house.size === 'big' && house.colour === 'blue'){ + house.contains = 'bear'; +} +if (colour === 'red' || colour === 'blue'){ + // colour est soit 'red' soit 'blue' +} + +// Les raccourcis && et || sont pratiques pour instancier des valeurs par defaut. +var name = otherName || 'default'; + +// Ceci est l'équivalent de +var name = otherName; +if (!name){ + name = 'default'; +} + +// Le switch vérifie les égalités avec === +// utilisez un "break" à la fin de chaque cas +// ou les cas suivants seront eux aussi exécutés +grade = 'B'; +switch (grade) { + case 'A': + console.log('Great job'); + break; + case 'B': + console.log('OK job'); + break; + case 'C': + console.log('You can do better'); + break; + default: + console.log('Oy vey'); + break; +} + + +/////////////////////////////////// +// 4. Fonctions, Scope (Environnement) et Closures + +// Les fonctions sont déclarées avec le mot clé function +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction('foo'); // = 'FOO' + +// Les fonctions JavaScript sont des objets de première classe, donc peuvent +// être réassignées à d'autres variables et passées en tant que paramètres pour +// d'autres fonctions +function myFunction(){ + // ce code s'exécutera dans 5 secondes +} +setTimeout(myFunction, 5000); +// Note: setTimeout ne fait pas parti du langage, mais les navigateurs ainsi +// que Node.js le rendent disponible + +// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être +// anonymes +setTimeout(function(){ + // ce code s'exécutera dans 5 secondes +}, 5000); + +// Le Javascript crée uniquement un scope dans les fonctions, pas dans les +// autres blocs. +if (true){ + var i = 5; +} +i; // = 5 - et non undefined comme vous pourriez vous y attendre + +// Cela a mené à un style comment de fonctions anonymes immédiatement exécutée; +// ou "immediately-executing anonymous functions" +(function(){ + var temporary = 5; + // Nous pouvons accéder au scope global en assignant à l'objet global, + // qui dans les navigateurs est "window". Il est différent dans Node.js. + window.permanent = 10; +})(); +// Cela permet de ne pas avoir de fuites de variables qui polluent +// l’environnement global. +temporary; // raises ReferenceError +permanent; // = 10 + +// Une des particularité les plus puissantes de Javascript est le système de +// closures. Si une fonction est définie dans une autre fonction, alors la +// fonction interne aura accès aux variables de la fonction parente, même si +// celle-ci a déjà finie son exécution. +function sayHelloInFiveSeconds(name){ + var prompt = 'Hello, ' + name + '!'; + // Fonction interne + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout is asynchrone, donc la fonction sayHelloInFiveSeconds quittera + // immédiatement, et setTimeout appelera inner après. +} +sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec + +/////////////////////////////////// +// 5. Encore plus à propos des Objets; Constructeurs and Prototypes + +// Les objets peuvent contenir des fonctions. +var myObj = { + myFunc: function(){ + return 'Hello world!'; + } +}; +myObj.myFunc(); // = 'Hello world!' + +// Lorsqu'une fonction attachée à un objet est appelée, elle peut accéder à +// l'objet avec le mot clé this. +myObj = { + myString: 'Hello world!', + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = 'Hello world!' + +// LA valeur de "this" change de par l'endroit où la fonction est appelée, et +// non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle +// est appelée hors du contexte l'objet. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// A l'inverse, une fonction peut être attachée à un objet et y gagner l'accès +// au travers de "this" +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} + +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = 'HELLO WORLD!' + +// Nous pouvons aussi spécifier un contexte pour une fonction quand elle est +// appelée grâce à "call" ou "apply". +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, ' And Hello Moon!'); // = 'Hello World! And Hello Moon!' + +// 'apply' est presque identique, mais prend un tableau comme liste d’arguments. + +anotherFunc.apply(myObj, [' And Hello Sun!']); // = 'Hello World! And Hello Sun!' + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Mais, "call" and "apply" sont temporaires. Pour lier le contexte de façon +// permanente, nous pouvons utiliser "bind" +var boundFunc = anotherFunc.bind(myObj); +boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!' + +// "bind" peut aussi être utilisé pour créer une application partielle de la +// fonction (curry) +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est +// crée et mis à disposition de la fonction via "this". Ces fonctions sont +// communément appelées constructeurs. +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à +// une propriété que n'a pas l'objet, l'interpréteur regarder son prototype. + +// Quelque implémentations de JS vous laissent accéder au prototype avec la +// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard +// et ne fonctionne pas dans les navigateurs actuels. +var myObj = { + myString: 'Hello world!' +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 +myObj.myFunc(); // = 'hello world!' + +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Il n'y a pas de copie ici. Chacun des objets stocke une référence à son +// prototype. Cela veut dire que l'on peut le modifier et cela se répercutera +// partout. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Comme précédemment dit, __proto__ n'est pas standard et ne devrait pas être +// utilisé. Il y a deux autres moyen de créer un nouvel objet avec un prototype +// donné. + +// Le premier est Object.create, mais c'est assez récent et risque de ne pas +// fonctionner dans tous les navigateurs. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Le deuxième moyen, qui marche partout, fonctionne avec les constructeurs. +// Les constructeurs ont un propriété appelée prototype. Ce n'est *pas* le +// prototype du constructeur de la fonction elle-même, c'est le prototype que +// les nouveaux objets crées grâce à ce constructeur avec "new" auront. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Les types pré-définis tels que les strings ou nombres ont aussi des +// constructeurs +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// ... mais ils ne sont pas exactement équivalent. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // 0 est falsy, le code ne fonctionnera pas. +} +if (Number(0)){ + // Parce que Number(0) est truthy, le code fonctionnera +} + +// Cependant, vous pouvez ajouter des fonctionnalités aux types de bases grâce à +// cette particularité. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +'abc'.firstCharacter(); // = 'a' + +// C'est très souvent utilisé pour le "polyfilling", qui implémente des nouvelles +// fonctionnalités de JavaScript dans de plus anciens environnements, tels que +// les vieux navigateurs. + +//Par exemple, Object.create est assez récent, mais peut être implémenté grâce à +// ce polyfill +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){}; + Constructor.prototype = proto; + // then use it to create a new, appropriately-prototyped object + return new Constructor(); + } +} + +## Pour aller plus loin (en anglais) + +The [Mozilla Developer +Network](https://developer.mozilla.org/fr-FR/docs/Web/JavaScript) expose une +excellente documentation pour le Javascript dans les navigateurs. Et contient +également un wiki pour s'entraider. + +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +recouvre les principaux sujets vus ici. Le guide est délibérément uniquement +à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous +plutôt ici : +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +un guide pour vous éviter les faux-amis dans le JavaScript. + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire. + +En addition aux contributeurs de cet article, du contenu provient du +"Python tutorial" de Louie Dinh, et de [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +sur le réseau Mozilla. -- cgit v1.2.3 From 1d4e0929ff82d7205b09da2f30b37541464dc029 Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 02:03:01 +0200 Subject: Update javascript-fr.html.markdown --- fr-fr/javascript-fr.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 598fb6af..1dc4f8db 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -479,6 +479,7 @@ if (Object.create === undefined){ // don't overwrite it if it exists return new Constructor(); } } +``` ## Pour aller plus loin (en anglais) -- cgit v1.2.3 From a7a8c85257ee48b92913018a3c221a9703c6d59b Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Sun, 10 Aug 2014 20:02:31 -0700 Subject: In golang slices are dynamic, so a mention of append() for slice updates seems to be appropriate. --- go.html.markdown | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/go.html.markdown b/go.html.markdown index f7bd8ee3..390e36dc 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -101,6 +101,20 @@ can include line breaks.` // Same string type. var d2 [][]float64 // Declaration only, nothing allocated here. bs := []byte("a slice") // Type conversion syntax. + // Because they are dynamic, slices can be appended to on-demand. + // To append elements to a slice, built-in append() function is used. + // First argument is a slice to which we are appending. Commonly, + // the array variable is updated in place, as in example below. + s := []int{1, 2, 3} // Result is a slice of length 3. + s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] + // To append another slice, instead of list of atomic elements we can + // pass a reference to a slice or a slice literal like this, with a + // trailing elipsis, meaning take an array and unpack its elements, + // appending them to the slice. + s = append(s, []int{7, 8, 9}...) // Second argument is an array literal. + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] + p, q := learnMemory() // Declares p, q to be type pointer to int. fmt.Println(*p, *q) // * follows a pointer. This prints two ints. -- cgit v1.2.3 From 7000db24e040d712f963efa4dda70a9b3b99e3f8 Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Sun, 10 Aug 2014 20:04:49 -0700 Subject: Fixed indentation error created in previous commit. --- go.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 390e36dc..ddedd25e 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -107,13 +107,13 @@ can include line breaks.` // Same string type. // the array variable is updated in place, as in example below. s := []int{1, 2, 3} // Result is a slice of length 3. s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. - fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] - // To append another slice, instead of list of atomic elements we can + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] + // To append another slice, instead of list of atomic elements we can // pass a reference to a slice or a slice literal like this, with a // trailing elipsis, meaning take an array and unpack its elements, // appending them to the slice. s = append(s, []int{7, 8, 9}...) // Second argument is an array literal. - fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] p, q := learnMemory() // Declares p, q to be type pointer to int. fmt.Println(*p, *q) // * follows a pointer. This prints two ints. -- cgit v1.2.3 From 161e19baa96e3c9dbc5e8682cf3ef08bc6723a2e Mon Sep 17 00:00:00 2001 From: Sam Zaydel Date: Tue, 19 Aug 2014 20:43:18 -0700 Subject: Minor language change fixing mixed use of array and slice, where only slice is correct. --- go.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index ddedd25e..c85209e0 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -110,9 +110,9 @@ can include line breaks.` // Same string type. fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] // To append another slice, instead of list of atomic elements we can // pass a reference to a slice or a slice literal like this, with a - // trailing elipsis, meaning take an array and unpack its elements, - // appending them to the slice. - s = append(s, []int{7, 8, 9}...) // Second argument is an array literal. + // trailing elipsis, meaning take a slice and unpack its elements, + // appending them to slice s. + s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal. fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] p, q := learnMemory() // Declares p, q to be type pointer to int. -- cgit v1.2.3 From 12292eab583ce66a5ec7a2d60ff0f88a0aa2636b Mon Sep 17 00:00:00 2001 From: Pierre-Arnaud Baciocchini Date: Wed, 20 Aug 2014 07:45:07 +0200 Subject: [css/fr-fr] Added french translation of CSS --- fr-fr/css-fr.html.markdown | 223 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 fr-fr/css-fr.html.markdown diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown new file mode 100644 index 00000000..df45cf8e --- /dev/null +++ b/fr-fr/css-fr.html.markdown @@ -0,0 +1,223 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["@prrrnd", "https://github.com/prrrnd"] +lang: fr-fr +--- + +Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le developemnt des navigateurs, +des pages avec du contenu visuel sont arrivées. +CSS est le langage standard qui existe et permet de garder une séparation entre +le contenu (HTML) et le style d'une page web. + +En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents +sur un page HTML afin de leurs donner des propriétés visuelles différentes. + +Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parlons de CSS2.0 +qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateur. + +**NOTE:** Parce que le résultat du code CSS est un effet visuel, vous pouvez utiliser [dabblet](http://dabblet.com/) afin de +voir les résultats, comprendre, et vous familiariser avec le langage. +Cet article porte principalement sur la syntaxe et quelques astuces. + + +```css +/* Les commentaires sont entourés par slash-étoile, comme cette ligne! */ + +/* #################### + ## SELECTEURS + ####################*/ + +/* Généralement, la première déclaration en CSS est très simple */ +selecteur { propriete: valeur; /* autres proprietés...*/ } + +/* Le sélécteur sert à cibler un élément du HTML + +Vous pouvez cibler tous les éléments d'une page! */ +* { color:red; } + +/* +Voici un élément dans notre HTML: + +
+*/ + +/* Vous pouvez le cibler par une classe */ +.une-classe { } + +/* ou les deux */ +.une-classe.classe2 { } + +/* ou par son type */ +div { } + +/* ou son id */ +#unId { } + +/* ou par le fait qu'il a un attribut */ +[attr] { font-size:smaller; } + +/* ou que l'attribut a une valeur spécifique */ +[attr='valeur'] { font-size:smaller; } + +/* commence avec une valeur */ +[attr^='val'] { font-size:smaller; } + +/* termine avec une valeur */ +[attr$='eur'] { font-size:smaller; } + +/* contient une valeur */ +[attr~='leu'] { font-size:smaller; } + + +/* Ce qu'il faut bien comprendre, c'est que vous pouvez combiner ceci -- Il ne doit pas y avoir +d'espaces entre.*/ +div.une-classe[attr$='eu'] { } + +/* Vous pouvez aussi cibler un élément par son parent.*/ + +/* Un élément qui est en enfant direct */ +div.un-parent > .enfant {} + +/* Cela cible aussi les .enfants plus profond dans la structure HTML */ +div.un-parent .enfants {} + +/* Attention: le même sélécteur sans espace a un autre sens. */ +div.un-parent.classe {} + +/* Vous pouvez cibler un élément basé sur un enfant de même parent */ +.je-suis-avant + .cet-element { } + +/* ou n'importe quel enfant de même parent avec celui ci */ +.je-suis-tout-avant ~ .cet-element {} + +/* Il y a des pseudo-classes qui permettent de cibler un élément +basé sur le comportement, plus que la structure de la page */ + +/* élément avec le curseur au-dessus */ +:hover {} + +/* lien visité */ +:visited {} + +/* lien non visité */ +:link {} + +/* élément avec le focus */ +:focus {} + + +/* #################### + ## PROPRIETES + ####################*/ + +selecteur { + + /* Units */ + width: 50%; /* pourcentage */ + font-size: 2em; /* times current font-size */ + width: 200px; /* pixels */ + font-size: 20pt; /* points */ + width: 5cm; /* centimetres */ + width: 50mm; /* millimetres */ + width: 5in; /* pouces */ + + /* Couleurs */ + background-color: #F6E; /* court hex */ + background-color: #F262E2; /* long hex */ + background-color: tomato; /* couleur nommée */ + background-color: rgb(255, 255, 255); /* rouge, vert, bleu */ + background-color: rgb(10%, 20%, 50%); /* rouge, vert, bleu en pourcent */ + background-color: rgba(255, 0, 0, 0.3); /* rouge, vert, bleu avec transparence */ + + /* Images */ + background-image: url(/chemin-vers-image/image.jpg); + + /* Polices */ + font-family: Arial; + font-family: "Courier New"; /* Si espace, entre guillemets */ + font-family: "Courier New", Trebuchet, Arial; /* Si la première n'est pas trouvée, deuxième, etc... */ +} + +``` + +## Utilisation + +Le CSS s'écrit dans des fichiers `.css`. + +```xml + + + + + + + +
+
+ +``` + +## Priorités + +Comme on vient de le voir, un élément peut être ciblé par plus qu'un seul sélécteur +et une même propriété peut être définie plusieurs fois. +Dans ces cas, une des propriétés devient prioritaire. + +Voici du code CSS: + +```css +/*A*/ +p.classe1[attr='valeur'] + +/*B*/ +p.classe1 {} + +/*C*/ +p.classe2 {} + +/*D*/ +p {} + +/*E*/ +p { propriete: valeur !important; } + +``` + +et le code HTML: + +```xml +

+

+``` + +Les priorités de style sont: +Attention, les priorités s'appliquent aux **propriétés**, pas aux blocs entiers. + +* `E` a la priorité grâce à `!important`. +* `F` vient ensuite, car le code se trouve directement dans le HTML. +* `A` vient ensuite, car il est le plus spécifique. + plus spécifique veut dire, celui qui cible le plus l'élément +* `C` vient ensuite. Il est aussi spécifique que `B`, mais est écrit après. +* Puis `B` +* Et enfin `D`. + +## Compatibilité + +La plupart des fonctionnalités de CSS2 (et de plus en plus CSS3) sont compatibles +avec tous les navigateurs. Mais c'est important de vérifier la compatibilité. + +[QuirksMode CSS](http://www.quirksmode.org/css/) est une très bonne source pour cela. + +## En savoir plus (en anglais) + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) + -- cgit v1.2.3 From d46303a1239abe4430c3e0753c943f723545c49e Mon Sep 17 00:00:00 2001 From: Pierre-Arnaud Baciocchini Date: Wed, 20 Aug 2014 07:47:06 +0200 Subject: Fixed indentation --- fr-fr/css-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown index df45cf8e..17f1eab4 100644 --- a/fr-fr/css-fr.html.markdown +++ b/fr-fr/css-fr.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Mohammad Valipour", "https://github.com/mvalipour"] - ["Marco Scannadinari", "https://github.com/marcoms"] translators: - - ["@prrrnd", "https://github.com/prrrnd"] + - ["@prrrnd", "https://github.com/prrrnd"] lang: fr-fr --- -- cgit v1.2.3 From 8df21274b997b2c8f6913fd4694f141c2f5d68cc Mon Sep 17 00:00:00 2001 From: Pierre-Arnaud Baciocchini Date: Wed, 20 Aug 2014 07:49:13 +0200 Subject: Removed Swift fr --- fr-fr/swift-fr.html.markdown | 225 ------------------------------------------- 1 file changed, 225 deletions(-) delete mode 100644 fr-fr/swift-fr.html.markdown diff --git a/fr-fr/swift-fr.html.markdown b/fr-fr/swift-fr.html.markdown deleted file mode 100644 index 18628524..00000000 --- a/fr-fr/swift-fr.html.markdown +++ /dev/null @@ -1,225 +0,0 @@ ---- -language: swift -contributors: - - ["Grant Timmerman", "http://github.com/grant"] -translators: - - ["@prrrnd", "https://github.com/prrrnd"] -lang: fr-fr ---- - -Swift est un langage de programmation crée par Apple pour iOS et OS X. Swift a été introduit en 2014 à la conférence WWDC d'Apple. Il est construit avec le compilateur LLVM inclus dans la version bétâ de Xcode 6. - -Pour plus d'informations, en anglais, regardez le [guide d'Apple](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), qui inclus un tutoriel complet sur Swift. - -```js -// -// Bases -// - -println("Hello, world") -var myVariable = 42 -let myConstant = 3.1415926 -let explicitDouble: Double = 70 -let label = "du texte " + String(myVariable) // Cast -let piText = "Pi = \(myConstant)" // Interpolation -var optionalString: String? = "optional" // Peut être nil -optionalString = nil - - -// -// Tableaux et dictionnaires -// - -// Tableau -var shoppingList = ["poisson", "eau", "citrons"] -shoppingList[1] = "bouteille d'eau" -let tableauVide = [String]() - -// Dictionnaire -var occupations = [ - "Malcolm": "Capitaine", - "kaylee": "Mécanicien" -] -occupations["Jayne"] = "Secretaire" -let dicoVide = Dictionary() - - -// -// Contrôle et boucles -// - -// Boucle for (tableau) -let monTableau = [1, 1, 2, 3, 5] -for value in monTableau { - if value == 1 { - println("Un!") - } else { - println("Pas un!") - } -} - -// Boucle for (dictionnaire) -for (key, value) in dict { - println("\(key): \(value)") -} - -// Boucle for (interval) -for i in -1...1 { // [-1, 0, 1] - println(i) -} -// utilisez ..< pour exclure le dernier élement - -// Boucle while -var i = 1 -while i < 1000 { - i *= 2 -} - -// Boucle do-while -do { - println("bonjour") -} while 1 == 2 - -// Switch -let legume = "haricot" -switch legume { -case "haricot": - // ... -case "concombre", "patate": - // ... -default: // requis afin de couvrir toutes les possibilités - // ... -} - - -// -// Fonctions -// - -// Les fonctions sont de type primitif, ce qui veut dire qu'elles peuvent être incluses dans d'autres fonctions - -// Fonction -func direBonjour(name: String, day: String) -> String { - return "Bonjour \(name), on est \(day) aujourd'hui." -} -direBonjour("Bob", "mardi") - -// Fonction qui retourne plusieurs valeurs dans un tuple -func getPrix() -> (Double, Double, Double) { - return (3.59, 3.69, 3.79) -} - -// Arguments -func setup(nombres: Int...) {} - -// Passer et retourner des fonctions -func augmenter() -> (Int -> Int) { - func ajouterUn(nombre: Int) -> Int { - return 1 + nombre - } - return ajouterUn -} -var increment = augmenter() -increment(7) - - -// -// Closures -// -var nombres = [1, 2, 6] - -// Les fonctions sont des cas de closures spéciales ({}) - -// Exemple de closure. -// `->` sépare les arguments et le type de retour -// `in` sépare l'en-tête de closure de son corps -nombres.map({ - (nombre: Int) -> Int in - let resultat = 3 * nombre - return resultat - }) - -// Lorsque le type est connu, comme ci-dessus, on peut faire ceci -nombres = nombres.map({ nombre in 3 * nombre }) -//Ou cela -//nombres = nombres.map({ $0 * 3 }) - -print(nombres) // [3, 6, 18] - - -// -// Classes -// - -// Toutes les méthodes et propriétés d'une classe sont publiques. -// Si vous avez juste besoin de stocker des données dans un -// objet structuré, vous devez utiliser une structure - -// Une classe `Square` hérite d'une classe `Shape` -class Rect: Shape { - var longueurCote: Int = 1 - - // Custom getter and setter property - var perimeter: Int { - get { - return 4 * longueurCote - } - set { - longueurCote = newValue / 4 - } - } - - init(longueurCote: Int) { - super.init() - self.longueurCote = longueurCote - } - - func shrink() { - if longueurCote > 0 { - --longueurCote - } - } - - override func getArea() -> Int { - return longueurCote * longueurCote - } -} -var monCarre = new Square(longueurCote: 5) -print(monCarre.getArea()) // 25 -monCarre.shrink() -print(monCarre.longueurCote) // 4 - -// If you don't need a custom getter and setter, -// but still want to run code before and after getting or setting -// a property, you can use `willSet` and `didSet` - - -// -// Enumerations -// - -// Les énumerations peuvent être d'un type spécifique ou non. -// Elles peuvent contenir méthodes et classes - -enum Suit { - case Pic, Coeur, Carre, Trefle - func getIcon() -> String { - switch self { - case .Pic: return "♤" - case .Coeur: return "♡" - case .Carre: return "♢" - case .Trefle: return "♧" - } - } -} - - -// -// Autres -// - -// `protocol`: Similaire aux interfaces en Java -// `extension`s: Permet d'ajouter des fonctionnalités à un type existant -// Generics: Similaire à Java. Utilisez le mot clé `where` pour specifier les pré-requis du generic - -``` -- cgit v1.2.3 From 1421ef08f5aa7de56a413753d9017693d3b44187 Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 10:12:21 +0200 Subject: Updated the part that I forgot to translate. --- fr-fr/javascript-fr.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 1dc4f8db..55f7858c 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -37,6 +37,7 @@ doStuff() // Parce que ces cas peuvent produire des effets inattendus, nous utiliserons // des point-virgules dans ce guide. + /////////////////////////////////// // 1. Nombres, Chaines de caractères et Opérateurs @@ -182,6 +183,7 @@ myObj.myThirdKey = true; // Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined myObj.myFourthKey; // = undefined + /////////////////////////////////// // 3. Logique et structures de contrôle @@ -314,6 +316,7 @@ function sayHelloInFiveSeconds(name){ } sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec + /////////////////////////////////// // 5. Encore plus à propos des Objets; Constructeurs and Prototypes @@ -470,12 +473,12 @@ String.prototype.firstCharacter = function(){ //Par exemple, Object.create est assez récent, mais peut être implémenté grâce à // ce polyfill -if (Object.create === undefined){ // don't overwrite it if it exists +if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe déjà Object.create = function(proto){ - // make a temporary constructor with the right prototype + // créer un constructeur temporaire avec le bon prototype var Constructor = function(){}; Constructor.prototype = proto; - // then use it to create a new, appropriately-prototyped object + // puis on utilise "new" pour créer un object avec ce prototype return new Constructor(); } } -- cgit v1.2.3 From f6367016949df3576e9cce4b96148da1f867464c Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 12:10:15 +0200 Subject: =?UTF-8?q?Translatated=20strings=20to=20"chaines=20de=20caract?= =?UTF-8?q?=C3=A8res"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fr-fr/javascript-fr.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 55f7858c..9e69a038 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -73,9 +73,9 @@ NaN; // le résultat de 0/0 par exemple true; // vrai false; // faux -// Les chaines de caractères (strings) sont crées avec ' ou ' indifféremment, la seule +// Les chaines de caractères (strings) sont crées avec " ou ' indifféremment, la seule // raison de choisir l'un ou l'autre est la consistance dans votre code. -'abc'; +"abc"; 'Hello, world'; // La négation utilise le symbole ! @@ -99,10 +99,10 @@ false; // faux 2 <= 2; // = true 2 >= 2; // = true -// Les strings se concatènent avec + +// Les chaines de caractères se concatènent avec + 'Hello ' + 'world!'; // = 'Hello world!' -// et peuvent être comparées avec < et > +// et peuvent être comparées alphabétiquement avec < et > 'a' < 'b'; // = true // Vous pouvez accéder les caractères dans une string avec charAt @@ -475,10 +475,10 @@ String.prototype.firstCharacter = function(){ // ce polyfill if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe déjà Object.create = function(proto){ - // créer un constructeur temporaire avec le bon prototype + // on crée un constructeur temporaire avec le bon prototype var Constructor = function(){}; Constructor.prototype = proto; - // puis on utilise "new" pour créer un object avec ce prototype + // puis on utilise "new" pour créer un object avec ce même prototype return new Constructor(); } } -- cgit v1.2.3 From 7367cd9ae801bf0b8fdcef0ab57212e23057869b Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 19:08:18 +0200 Subject: Updated according to the review. --- fr-fr/javascript-fr.html.markdown | 64 +++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 26 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 9e69a038..21c8b5ae 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -11,10 +11,11 @@ lang: fr-fr JavaScript a été crée par Brendan Eich, travaillant alors a Netscape, en 1995. Le langage avait à l'origine pour but d'être un langage de scripting simple -pour les sites web, complétant le Java pour des applications web complexes. Mais -son intégration très proche et simple des pages web, ainsi que le support natif -des navigateurs a rendu le JavaScript incontournable aujourd'hui tant bien dans -le front-end que dans le back-end. +pour les sites web, complétant le Java (à ne pas confondre avec JavaScript) +pour des applications web complexes. Mais son intégration très proche et +simple des pages web, ainsi que le support natif des navigateurs a rendu +le JavaScript incontournable aujourd'hui tant bien dans le front-end que +dans le back-end. En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à Node.JS, un projet qui offre un environnement indépendant dans lequel un @@ -23,7 +24,7 @@ peut être utilisé directement côté serveur pour exécuter des programmes éc en JavaScript. ```js -// Les commentaires sont comme en C. Les commentaires en ligne commencent par 2 slashs, +// Les commentaires sont comme en C. Les commentaires mono-ligne commencent par 2 slashs, /* et les commentaires sur plusieurs lignes commencent avec slash-étoile et finissent avec étoile-slash */ @@ -42,7 +43,7 @@ doStuff() // 1. Nombres, Chaines de caractères et Opérateurs // JavaScript a un seul type de nombre (qui est un 64-bit IEEE 754 double (décimaux)) -// Comme avec le Lua, ne paniquez pas à cause du manque d'int (entiers): les +// Comme avec le Lua, ne paniquez pas à cause du manque d'int (entiers) : les // doubles ont un mantisse de 52 bits, ce qui est assez pour stocker des int jusqu'à // 9 x 10¹⁵ exactement. 3; // = 3 @@ -58,7 +59,7 @@ doStuff() 5 / 2; // = 2.5 // Les opérations bits à bits fonctionnent aussi, quand vous effectuez une opération -// bits à bits , votre nombre décimal est converti en entier *jusqu'à* 32 bits. +// bits à bits, votre nombre décimal est converti en entier *jusqu'à* 32 bits. 1 << 2; // = 4 // Comme en mathématiques, la priorité est donnée aux parenthèses. @@ -73,8 +74,8 @@ NaN; // le résultat de 0/0 par exemple true; // vrai false; // faux -// Les chaines de caractères (strings) sont crées avec " ou ' indifféremment, la seule -// raison de choisir l'un ou l'autre est la consistance dans votre code. +// Les chaines de caractères (strings) sont créees avec " ou ' indifféremment, la seule +// raison de choisir l'un ou l'autre est la cohérence dans votre code. "abc"; 'Hello, world'; @@ -85,7 +86,7 @@ false; // faux // L'égalité est === ou == // === compare la valeur exacte 2 === '2' // = false // == convertit la valeur pour comparer 2 === '2' // = true -// En général, il vaut mieux utiliser === pour ne pas faire d'erreurs. +// En général, il vaut mieux utiliser === pour ne pas faire d'erreur. 1 === 1; // = true 2 === 1; // = false @@ -93,7 +94,7 @@ false; // faux 1 !== 1; // = false 2 !== 1; // = true -// Plus de comparaisons: +// Plus de comparaisons : 1 < 10; // = true 1 > 10; // = false 2 <= 2; // = true @@ -108,7 +109,7 @@ false; // faux // Vous pouvez accéder les caractères dans une string avec charAt 'This is a string'.charAt(0); // = 'T' -// .. ou utiliser substring pour avoir un plus gros morceau +// ... ou utiliser substring pour avoir un plus gros morceau 'Hello world'.substring(0, 5); // = 'Hello' // la longueur, length, est une propriété, donc n'utilisez pas de () @@ -164,7 +165,7 @@ myArray.length; // = 4 myArray[3] = 'Hello'; // Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres -// langages: ils sont une liste non-ordonnée de paires clé-valeur. +// langages : ils sont une liste non-ordonnée de paires clé-valeur. var myObj = {key1: 'Hello', key2: 'World'}; // Les clés sont des strings, mais les ' ou " sont optionels si elles sont des @@ -187,8 +188,6 @@ myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Logique et structures de contrôle -// La syntaxe de cette section est identique au Java. - // Les si (if) fonctionnent comme vous vous y attendez. var count = 1; if (count === 3) { @@ -287,12 +286,14 @@ if (true){ } i; // = 5 - et non undefined comme vous pourriez vous y attendre -// Cela a mené à un style comment de fonctions anonymes immédiatement exécutée; +// Cela a mené à un style commun de fonctions anonymes immédiatement exécutée; // ou "immediately-executing anonymous functions" (function(){ var temporary = 5; // Nous pouvons accéder au scope global en assignant à l'objet global, - // qui dans les navigateurs est "window". Il est différent dans Node.js. + // qui dans les navigateurs est "window". Il est différent dans Node.js, + // le scope global sera en fait local au module dans lequel vous + // vous trouvez. http://nodejs.org/api/globals.html window.permanent = 10; })(); // Cela permet de ne pas avoir de fuites de variables qui polluent @@ -300,7 +301,7 @@ i; // = 5 - et non undefined comme vous pourriez vous y attendre temporary; // raises ReferenceError permanent; // = 10 -// Une des particularité les plus puissantes de Javascript est le système de +// Une des fonctionnalités les plus puissantes de Javascript est le système de // closures. Si une fonction est définie dans une autre fonction, alors la // fonction interne aura accès aux variables de la fonction parente, même si // celle-ci a déjà finie son exécution. @@ -338,7 +339,7 @@ myObj = { }; myObj.myFunc(); // = 'Hello world!' -// LA valeur de "this" change de par l'endroit où la fonction est appelée, et +// La valeur de "this" change de par l'endroit où la fonction est appelée, et // non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle // est appelée hors du contexte l'objet. var myFunc = myObj.myFunc; @@ -353,8 +354,9 @@ var myOtherFunc = function(){ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = 'HELLO WORLD!' -// Nous pouvons aussi spécifier un contexte pour une fonction quand elle est -// appelée grâce à "call" ou "apply". +// Le contexte correspond à la valeur de "this". +// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this, +// pour une fonction quand elle est appelée grâce à "call" ou "apply". var anotherFunc = function(s){ return this.myString + s; } @@ -368,8 +370,9 @@ Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// Mais, "call" and "apply" sont temporaires. Pour lier le contexte de façon -// permanente, nous pouvons utiliser "bind" +// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la +// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser +// "bind" pour garder une référence à la fonction avec ce "this". var boundFunc = anotherFunc.bind(myObj); boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!' @@ -389,11 +392,11 @@ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 // Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à -// une propriété que n'a pas l'objet, l'interpréteur regarder son prototype. +// une propriété que l'objet n'a pas, l'interpréteur va regarder son prototype. -// Quelque implémentations de JS vous laissent accéder au prototype avec la +// Quelques implémentations de JS vous laissent accéder au prototype avec la // propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard -// et ne fonctionne pas dans les navigateurs actuels. +// et ne fonctionne pas dans certains des navigateurs actuels. var myObj = { myString: 'Hello world!' }; @@ -413,12 +416,21 @@ myPrototype.__proto__ = { }; myObj.myBoolean; // = true + +// Pour obtenir le prototype il existe également Object.getPrototypeOf +Object.getPrototypeOf( myObj ) // = {meaningOfLife: 42, myFunc: function} + // Il n'y a pas de copie ici. Chacun des objets stocke une référence à son // prototype. Cela veut dire que l'on peut le modifier et cela se répercutera // partout. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 +// L'inverse n'est cependant pas vrai. Changer la propriété d'un objet ne change +// pas la chaine prototypale. +myObj.lonelyProperty = true; +myPrototype.lonelyProperty; // = undefined + // Comme précédemment dit, __proto__ n'est pas standard et ne devrait pas être // utilisé. Il y a deux autres moyen de créer un nouvel objet avec un prototype // donné. -- cgit v1.2.3 From 210d9eba8df66ac7298d4bdea386428fe1a1009f Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 19:13:53 +0200 Subject: better example. --- fr-fr/javascript-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 21c8b5ae..dd12d89f 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -428,8 +428,8 @@ myObj.meaningOfLife; // = 43 // L'inverse n'est cependant pas vrai. Changer la propriété d'un objet ne change // pas la chaine prototypale. -myObj.lonelyProperty = true; -myPrototype.lonelyProperty; // = undefined +myObj.meaningOfLife = 42; +myPrototype.meaningOfLife; // = 43 // Comme précédemment dit, __proto__ n'est pas standard et ne devrait pas être // utilisé. Il y a deux autres moyen de créer un nouvel objet avec un prototype -- cgit v1.2.3 From ffd5e7e149cf1da87abce5e56cdf32626eede22a Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 19:39:19 +0200 Subject: Typo --- fr-fr/javascript-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index dd12d89f..e15f70a3 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -9,7 +9,7 @@ translators: lang: fr-fr --- -JavaScript a été crée par Brendan Eich, travaillant alors a Netscape, en 1995. +JavaScript a été créé par Brendan Eich, travaillant alors a Netscape, en 1995. Le langage avait à l'origine pour but d'être un langage de scripting simple pour les sites web, complétant le Java (à ne pas confondre avec JavaScript) pour des applications web complexes. Mais son intégration très proche et -- cgit v1.2.3 From 1a9cf39190056d2d9fc4b42f57668aaba7ac5003 Mon Sep 17 00:00:00 2001 From: m90 Date: Wed, 20 Aug 2014 19:40:34 +0200 Subject: changes in regard to review --- de-de/coffeescript-de.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/de-de/coffeescript-de.html.markdown b/de-de/coffeescript-de.html.markdown index f8aeb502..bc447f90 100644 --- a/de-de/coffeescript-de.html.markdown +++ b/de-de/coffeescript-de.html.markdown @@ -9,8 +9,8 @@ filename: coffeescript-de.coffee lang: de-de --- -CoffeeScript ist eine kleine Sprache die eins zu eins nach JavaScript transpiliert wird, es gibt keinen Laufzeitinterpreter für sie. -Als Nachfolger von JavaScript konzipiert, gibt CoffeeScript sein Bestes lesbaren, gut formatierten und effizienten JavaScript-Code zu erzeugen der in allen Laufzeiten einwandfrei funktioniert. +CoffeeScript ist eine kleine Sprache, die eins zu eins nach JavaScript übersetzt wird - es findet keine Interpretation zur Laufzeit statt. +Als Nachfolger von JavaScript konzipiert, gibt CoffeeScript sein Bestes, lesbaren, gut formatierten und sauber laufenden JavaScript-Code zu erzeugen, der in jeder JavaScript-Laufzeit einwandfrei funktioniert. Auf [der CoffeeScript Website](http://coffeescript.org/) gibt es ein ausführliches Tutorial. @@ -20,11 +20,11 @@ Auf [der CoffeeScript Website](http://coffeescript.org/) gibt es ein ausführlic # Kommentare werden daher wie in Ruby und Python mit Hashes gekennzeichnet ### -Kommentarblöcke sehen aus wie diese und werden direkt nach '/ *s und '* /s -im erzeugten JavaScript transpiliert. +Kommentarblöcke sehen aus wie diese und werden direkt nach '/ *'s und '* /'s +im erzeugten JavaScript umgewandelt. -Vorweg: bevor du mit CoffeeScript anfängst solltest du einen guten Überblick -über die Eigenheiten von JavaScript an sich haben. +Vorweg: bevor du mit CoffeeScript anfängst, solltest du bereits einen guten +Überblick über die Sprache JavaScript haben. ### # Zuweisung: @@ -75,8 +75,8 @@ race = (winner, runners...) -> alert "Hab ich's nicht gesagt?" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Hab ich's nicht gesagt?"); } -# Collection-Mapping: -cubes = (math.cube num for num in list) +# Zuordnungen: +cubes = (math.cube num for num in list) #=>cubes = (function() { # var _i, _len, _results; # _results = []; -- cgit v1.2.3 From d15c9674a9005b544427c206424cc900bda48106 Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 20:57:40 +0200 Subject: Updated scope part. --- fr-fr/javascript-fr.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index e15f70a3..2e18d0be 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -135,8 +135,9 @@ var someVar = 5; // si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict) someOtherVar = 10; -// ... mais la variable sera crée dans l’environnement global, et non l’environnement -// local dans lequel vous l'avez défini. +// ... mais la variable aura une portée globale (plus communément trouvé en tant +// que "global scope" en anglais), et non pas une portée limitée à la fonction +// dans laquelle vous l'aviez définie. // Les variables déclarées et non assignées sont undefined par défaut var someThirdVar; @@ -279,8 +280,8 @@ setTimeout(function(){ // ce code s'exécutera dans 5 secondes }, 5000); -// Le Javascript crée uniquement un scope dans les fonctions, pas dans les -// autres blocs. +// Le Javascript crée uniquement un scope, une portée d'action limitée, pour +// les fonctions, et pas dans les autres blocs. if (true){ var i = 5; } -- cgit v1.2.3 From 1828ef068dd224a8402a4c786569de985f3793b2 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Thu, 21 Aug 2014 00:34:39 +0200 Subject: Make the text fit. --- perl6.html.markdown | 84 ++++++++++++++++++++++++++++------------------------- 1 file changed, 45 insertions(+), 39 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index fca863af..4ab90914 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -30,7 +30,7 @@ double paragraphs, and single notes. # In Perl 6, you declare a lexical variable using `my` my $variable; -# Perl 6 has 4 variable types : +# Perl 6 has 4 kinds of variables: ## * Scalars. They represent a single value. They start with a `$` @@ -56,7 +56,8 @@ my @array =
; # array of words, delimited by space. say @array[2]; # Array indices start at 0 -- This is the third element -say "Interpolate an array using [] : @array[]"; #=> Interpolate an array using [] : a b c +say "Interpolate an array using [] : @array[]"; +#=> Interpolate an array using [] : a b c ## * Hashes. Key-Value Pairs. # Hashes are actually arrays of Pairs (`Key => Value`), @@ -99,7 +100,7 @@ my &s = &say-hello; my &other-s = sub { say "Anonymous function !" } # A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" -sub as-many($head, *@rest) { # The `*@` slurpy will basically "take everything else". +sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else". # Note: you can have parameters *before* (like here) # a slurpy one, but not *after*. say @rest.join(' / ') ~ " !"; @@ -191,7 +192,7 @@ named-def(def => 15); #=> 15 # its right. When passed around, containers are marked as immutable. # Which means that, in a function, you'll get an error if you try to # mutate one of your arguments. -# If you really need to, you can ask for a mutable container using `is rw` : +# If you really need to, you can ask for a mutable container using `is rw`: sub mutate($n is rw) { $n++; say "\$n is now $n !"; @@ -199,7 +200,7 @@ sub mutate($n is rw) { # If what you want is a copy instead, use `is copy`. -# A sub itself returns a container, which means it can be marked as rw : +# A sub itself returns a container, which means it can be marked as rw: my $x = 42; sub mod() is rw { $x } mod() = 52; # in this case, the parentheses are mandatory @@ -210,7 +211,7 @@ say $x; #=> 52 ### Control Flow Structures # You don't need to put parenthesis around the condition, -# but that also means you always have to use brackets (`{ }`) for their body : +# but that also means you always have to use brackets (`{ }`) for their body: ## Conditionals @@ -246,7 +247,7 @@ my $a = $condition ?? $value-if-true !! $value-if-false; # blocks, etc), this means the powerful `when` is not only applicable along with # a `given`, but instead anywhere a `$_` exists. given "foo bar" { - when /foo/ { # You'll read about the smart-matching operator below -- just know `when` uses it. + when /foo/ { # Don't worry about smart matching -- just know `when` uses it. # This is equivalent to `if $_ ~~ /foo/`. say "Yay !"; } @@ -262,7 +263,7 @@ given "foo bar" { ## Looping constructs # - `loop` is an infinite loop if you don't pass it arguments, -# but can also be a c-style `for` : +# but can also be a c-style `for`: loop { say "This is an infinite loop !"; last; # last breaks out of the loop, like the `break` keyword in other languages @@ -270,8 +271,8 @@ loop { loop (my $i = 0; $i < 5; $i++) { next if $i == 3; # `next` skips to the next iteration, like `continue` - # in other languages. Note that you can also use postfix conditionals, - # loops, etc. + # in other languages. Note that you can also use postfix + # conditionals, loops, etc. say "This is a C-style for loop !"; } @@ -292,12 +293,12 @@ for @array { for @array { # You can... - next if $_ == 3; # Skip to the next iteration (like `continue` in C-like languages). + next if $_ == 3; # Skip to the next iteration (`continue` in C-like languages). redo if $_ == 4; # Re-do the iteration, keeping the same topic variable (`$_`). last if $_ == 5; # Or break out of a loop (like `break` in C-like languages). } -# Note - the "lambda" `->` syntax isn't reserved to `for` : +# Note - the "lambda" `->` syntax isn't reserved to `for`: if long-computation() -> $result { say "The result is $result"; } @@ -308,12 +309,12 @@ if long-computation() -> $result { ## Perl 6 operators are actually just funny-looking subroutines, in syntactic ## categories, like infix:<+> (addition) or prefix: (bool not). -## The categories are : -# - "prefix" : before (like `!` in `!True`). -# - "postfix" : after (like `++` in `$a++`). -# - "infix" : in between (like `*` in `4 * 3`). -# - "circumfix" : around (like `[`-`]` in `[1, 2]`). -# - "post-circumfix" : around, after another term (like `{`-`}` in `%hash{'key'}`) +## The categories are: +# - "prefix": before (like `!` in `!True`). +# - "postfix": after (like `++` in `$a++`). +# - "infix": in between (like `*` in `4 * 3`). +# - "circumfix": around (like `[`-`]` in `[1, 2]`). +# - "post-circumfix": around, after another term (like `{`-`}` in `%hash{'key'}`) ## The associativity and precedence list are explained below. @@ -334,7 +335,8 @@ if long-computation() -> $result { (1, 2) eqv (1, 3); # - `~~` is smart matching -# For a complete list of combinations, use this table : http://perlcabal.org/syn/S03.html#Smart_matching +# For a complete list of combinations, use this table: +# http://perlcabal.org/syn/S03.html#Smart_matching 'a' ~~ /a/; # true if matches regexp 'key' ~~ %hash; # true if key exists in hash $arg ~~ &bool-returning-function; # `True` if the function, passed `$arg` @@ -415,7 +417,7 @@ first-of-array(@tail); # Throws an error "Too many positional parameters passed" # (which means the array is too big). # You can also use a slurp ... -sub slurp-in-array(@ [$fst, *@rest]) { # you could decide to keep `*@rest` anonymous +sub slurp-in-array(@ [$fst, *@rest]) { # You could keep `*@rest` anonymous say $fst + @rest.elems; # `.elems` returns a list's length. # Here, `@rest` is `(3,)`, since `$fst` holds the `2`. } @@ -485,7 +487,7 @@ sub truthy-array(@array) { # You can also use the "whatever star" to create an anonymous function # (it'll stop at the furthest operator in the current expression) my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` -my @arrayplus3 = map(*+*+3, @array); # also works. Same as `-> $a, $b { $a + $b + 3 }` +my @arrayplus3 = map(*+*+3, @array); # Same as `-> $a, $b { $a + $b + 3 }` say (*/2)(4); #=> 2 # Immediatly execute the function Whatever created. say ((*+3)/5)(5); #=> 1.6 @@ -576,7 +578,7 @@ sub foo { bar(); # call `bar` in-place } sub bar { - say $*foo; # Perl 6 will look into the call stack instead, and find `foo`'s `$*a`, + say $*foo; # `$*a` will be looked in the call stack, and find `foo`'s, # even though the blocks aren't nested (they're call-nested). #=> 1 } @@ -589,8 +591,9 @@ sub bar { # but you have `$.` to get a public (immutable) accessor along with it. # (using `$.` is like using `$!` plus a `method` with the same name) -# (Perl 6's object model ("SixModel") is very flexible, and allows you to dynamically add methods, -# change semantics, etc -- This will not be covered here, and you should refer to the Synopsis) +# (Perl 6's object model ("SixModel") is very flexible, +# and allows you to dynamically add methods, change semantics, etc ... +# (this will not be covered here, and you should refer to the Synopsis). class A { has $.field; # `$.field` is immutable. @@ -685,7 +688,7 @@ class Item does PrintableVal { } ### Exceptions -# Exceptions are built on top of classes, usually in the package `X` (like `X::IO`). +# Exceptions are built on top of classes, in the package `X` (like `X::IO`). # Unlike many other languages, in Perl 6, you put the `CATCH` block *within* the # block to `try`. By default, a `try` has a `CATCH` block that catches # any exception (`CATCH { default {} }`). @@ -709,7 +712,7 @@ die X::AdHoc.new(payload => 'Error !'); # Packages are a way to reuse code. Packages are like "namespaces", and any # element of the six model (`module`, `role`, `class`, `grammar`, `subset` # and `enum`) are actually packages. (Packages are the lowest common denomitor) -# Packages play a big part in a language, especially as Perl is well-known for CPAN, +# Packages are important - especially as Perl is well-known for CPAN, # the Comprehensive Perl Archive Network. # You usually don't use packages directly: you use `class Package::Name::Here;`, # or if you only want to export variables/subs, you can use `module`: @@ -719,7 +722,7 @@ module Hello::World { # Bracketed form # ... declarations here ... } module Parse::Text; # file-scoped form -grammar Parse::Text::Grammar { # A grammar is a fine package, which you could `use` +grammar Parse::Text::Grammar { # A grammar is a package, which you could `use` } # NOTE for Perl 5 users: even though the `package` keyword exists, @@ -841,7 +844,7 @@ say "This code took " ~ (time - CHECK time) ~ "s to run"; # ... or clever organization: sub do-db-stuff { - ENTER $db.start-transaction; # create a new transaction everytime we enter the sub + ENTER $db.start-transaction; # New transaction everytime we enter the sub KEEP $db.commit; # commit the transaction if all went well UNDO $db.rollback; # or rollback if all hell broke loose } @@ -951,7 +954,7 @@ say 5!; #=> 120 sub infix:(Int $n, Block $r) { # infix in the middle for ^$n { $r(); # You need the explicit parentheses to call the function in `$r`, - # else you'd be referring at the variable itself, kind of like with `&r`. + # else you'd be referring at the variable itself, like with `&r`. } } 3 times -> { say "hello" }; #=> hello @@ -1004,8 +1007,9 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # of the element of the list to be passed to the operator), # or `Any` if there's none (examples below). # -# Otherwise, it pops an element from the list(s) one at a time, and applies the binary function -# to the last result (or the list's first element) and the popped element. +# Otherwise, it pops an element from the list(s) one at a time, and applies +# the binary function to the last result (or the list's first element) +# and the popped element. # # To sum a list, you could use the reduce meta-operator with `+`, i.e.: say [+] 1, 2, 3; #=> 6 @@ -1127,15 +1131,15 @@ for { .say if 'B' ff 'B' for ; #=> B B # because the right-hand-side was tested # directly (and returned `True`). - # "B"s are still printed since it matched that time + # "B"s are printed since it matched that time # (it just went back to `False` right away). .say if 'B' fff 'B' for ; #=> B C B - # because the right-hand-side wasn't tested until + # The right-hand-side wasn't tested until # `$_` became "C" # (and thus did not match instantly). # A flip-flop can change state as many times as needed: -for { +for { .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", #=> "print this printing again" } @@ -1190,8 +1194,8 @@ say so 'a' ~~ / a /; # More readable with some spaces! # a regexp. We're converting the result using `so`, but in fact, it's # returning a `Match` object. They know how to respond to list indexing, # hash indexing, and return the matched string. -# The results of the match are also available as `$/` (implicitly lexically-scoped). -# You can also use the capture variables (`$0`, `$1`, ... - starting at 0, not 1 !). +# The results of the match are available as `$/` (implicitly lexically-scoped). +# You can also use the capture variables (`$0`, `$1`, ... starting at 0, not 1 !). # # You can also note that `~~` does not perform start/end checking # (meaning the regexp can be matched with just one char of the string), @@ -1233,7 +1237,7 @@ so 'abbbbc' ~~ / a b+ c /; # `True`, matched 4 "b"s so 'ac' ~~ / a b* c /; # `True`, they're all optional. so 'abc' ~~ / a b* c /; # `True` so 'abbbbc' ~~ / a b* c /; # `True` -so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, but can't be something else. +so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, not replaceable. # - `**` - "Quantify It Yourself". # If you squint hard enough, you might understand @@ -1255,7 +1259,7 @@ so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; # But this does not go far enough, because we can't actually get back what # we matched. # Capture: We can actually *capture* the results of the regexp, using parentheses. -so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (we keep `so` here and use `$/` below) +so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below) # So, starting with the grouping explanations. # As we said before, our `Match` object is available as `$/`: @@ -1308,7 +1312,7 @@ sub MAIN($name) { say "Hello, you !" } # And since it's a regular Perl 6 sub, you can haz multi-dispatch: # (using a "Bool" for the named argument so that we get `--replace` # instead of `--replace=1`) -subset File of Str where *.IO.d; # convert to IO object, then check the file exists +subset File of Str where *.IO.d; # convert to IO object to check the file exists multi MAIN('add', $key, $value, Bool :$replace) { ... } multi MAIN('remove', $key) { ... } @@ -1325,7 +1329,9 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name ``` If you want to go further, you can: + - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This is probably the greatest source of Perl 6 information, snippets and such. - Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful. - Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize). - Read the [Synopses](perlcabal.org/syn). They explain it from an implementor point-of-view, but it's still very interesting. + -- cgit v1.2.3 From 98ce82761f135f8e4dbabeb84e53fde44822f0d3 Mon Sep 17 00:00:00 2001 From: Frederik Ring Date: Thu, 21 Aug 2014 13:53:07 +0200 Subject: change array comprehension title and add translator --- de-de/coffeescript-de.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/de-de/coffeescript-de.html.markdown b/de-de/coffeescript-de.html.markdown index bc447f90..98a452ba 100644 --- a/de-de/coffeescript-de.html.markdown +++ b/de-de/coffeescript-de.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Xavier Yao", "http://github.com/xavieryao"] translators: - ["Frederik Ring", "https://github.com/m90"] + - ["Philipp Fischbeck", "https://github.com/PFischbeck"] filename: coffeescript-de.coffee lang: de-de --- @@ -75,7 +76,7 @@ race = (winner, runners...) -> alert "Hab ich's nicht gesagt?" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Hab ich's nicht gesagt?"); } -# Zuordnungen: +# Listen-Abstraktion: cubes = (math.cube num for num in list) #=>cubes = (function() { # var _i, _len, _results; -- cgit v1.2.3 From 83b63aab543c2c7ece74f514ef12b1e068f463e4 Mon Sep 17 00:00:00 2001 From: Louie Dinh Date: Thu, 21 Aug 2014 15:38:50 -0700 Subject: Fix a long line. --- python3.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index b494dc1e..f6babaff 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -93,7 +93,9 @@ not False # => True "{} 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" +"{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" -- cgit v1.2.3 From 7bfbec395acc3ddd61b9cc1d7c4b0ee3877f250b Mon Sep 17 00:00:00 2001 From: Samuel Marks Date: Sat, 23 Aug 2014 16:54:13 +1000 Subject: -ne not equal --- bash.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 061d35b0..57fb5c55 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -73,9 +73,9 @@ echo Hello, $NAME! # use 'man test' for more info about conditionals if [ $NAME -ne $USER ] then - echo "Your name is your username" -else echo "Your name isn't your username" +else + echo "Your name is your username" fi # There is also conditional execution -- cgit v1.2.3 From 328a4f1babe167e94858b92faaa9caa19aa8aade Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sat, 23 Aug 2014 22:48:10 -0500 Subject: - add more examples; update examples - now runs in the Xcode 6 b6 playground - add MARK sections --- swift.html.markdown | 206 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 135 insertions(+), 71 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index a47b085a..5ba160b8 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -2,6 +2,7 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] filename: learnswift.swift --- @@ -11,21 +12,34 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre ```js // -// Basics +// MARK: Basics // println("Hello, world") + var myVariable = 42 +//let fƒ∆ = "value" // unicode in variable names let myConstant = 3.1415926 +let convenience = "keyword" // contextual variable name +let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon +let `class` = "keyword" // backticks allow keywords to be used as variable names let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 let label = "some text " + String(myVariable) // Casting let piText = "Pi = \(myConstant)" // String interpolation var optionalString: String? = "optional" // Can be nil optionalString = nil +/* +Comment here + /* + Nested comment here + */ +*/ // -// Arrays and Dictionaries +// MARK: Collections // // Array @@ -35,65 +49,66 @@ let emptyArray = [String]() // Dictionary var occupations = [ - "Malcolm": "Captain", - "kaylee": "Mechanic" + "Malcolm": "Captain", + "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" let emptyDictionary = Dictionary() // -// Control Flow +// MARK: Control Flow // // for loop (array) let myArray = [1, 1, 2, 3, 5] for value in myArray { - if value == 1 { - println("One!") - } else { - println("Not one!") - } + if value == 1 { + println("One!") + } else { + println("Not one!") + } } // for loop (dictionary) +var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + println("\(key): \(value)") } // for loop (range) for i in -1...1 { // [-1, 0, 1] - println(i) + println(i) } // use ..< to exclude the last number // while loop var i = 1 while i < 1000 { - i *= 2 + i *= 2 } // do-while loop do { - println("hello") + println("hello") } while 1 == 2 // Switch let vegetable = "red pepper" switch vegetable { case "celery": - let vegetableComment = "Add some raisins and make ants on a log." + let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": - let vegetableComment = "That would make a good tea sandwich." + let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): - let vegetableComment = "Is it a spicy \(x)?" + let vegetableComment = "Is it a spicy \(x)?" default: // required (in order to cover all possible input) - let vegetableComment = "Everything tastes good in soup." + let vegetableComment = "Everything tastes good in soup." } // -// Functions +// MARK: Functions // // Functions are a first-class type, meaning they can be nested @@ -101,31 +116,31 @@ default: // required (in order to cover all possible input) // Function func greet(name: String, day: String) -> String { - return "Hello \(name), today is \(day)." + return "Hello \(name), today is \(day)." } greet("Bob", "Tuesday") // Function that returns multiple items in a tuple func getGasPrices() -> (Double, Double, Double) { - return (3.59, 3.69, 3.79) + return (3.59, 3.69, 3.79) } -// Args +// Variadic Args func setup(numbers: Int...) {} // Passing and returning functions func makeIncrementer() -> (Int -> Int) { - func addOne(number: Int) -> Int { - return 1 + number - } - return addOne + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne } var increment = makeIncrementer() increment(7) // -// Closures +// MARK: Closures // var numbers = [1, 2, 6] @@ -135,93 +150,142 @@ var numbers = [1, 2, 6] // `->` separates the arguments and return type // `in` separates the closure header from the closure body numbers.map({ - (number: Int) -> Int in - let result = 3 * number - return result - }) + (number: Int) -> Int in + let result = 3 * number + return result +}) // When the type is known, like above, we can do this numbers = numbers.map({ number in 3 * number }) -//Or even this +// Or even this //numbers = numbers.map({ $0 * 3 }) print(numbers) // [3, 6, 18] +// Trailing closure +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super shorthand, since the < operator infers the types + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] // -// Classes +// MARK: Classes // +class Shape { + func getArea() -> Int { + return 0; + } +} + // All methods and properties of a class are public. // If you just need to store data in a // structured object, you should use a `struct` // A simple class `Square` extends `Shape` class Rect: Shape { - var sideLength: Int = 1 - - // Custom getter and setter property - var perimeter: Int { - get { - return 4 * sideLength + var sideLength: Int = 1 + + // Custom getter and setter property + var perimeter: Int { + get { + return 4 * sideLength + } + set { + sideLength = newValue / 4 + } } - set { - sideLength = newValue / 4 + + // If you don't need a custom getter and setter, + // but still want to run code before and after getting or setting + // a property, you can use `willSet` and `didSet` + var identifier: String = "defaultID" { + willSet(someIdentifier) { + print(someIdentifier) + } } - } - - init(sideLength: Int) { - super.init() - self.sideLength = sideLength - } - - func shrink() { - if sideLength > 0 { - --sideLength + + init(sideLength: Int) { + super.init() + self.sideLength = sideLength + } + + func shrink() { + if sideLength > 0 { + --sideLength + } } - } + + override func getArea() -> Int { + return sideLength * sideLength + } +} - override func getArea() -> Int { - return sideLength * sideLength - } +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } } -var mySquare = new Square(sideLength: 5) + +var mySquare = Square() print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 -// If you don't need a custom getter and setter, -// but still want to run code before and after getting or setting -// a property, you can use `willSet` and `didSet` - // -// Enums +// MARK: Enums // // Enums can optionally be of a specific type or on their own. // They can contain methods like classes. enum Suit { - case Spades, Hearts, Diamonds, Clubs - func getIcon() -> String { - switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } } - } } // -// Other +// MARK: Other // // `protocol`: Similar to Java interfaces. -// `extension`s: Add extra functionality to an already created type +protocol ShapeGenerator { + func buildShape() -> Shape +} + +// `extension`s: Add extra functionality to an already existing type +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +println("Square: \(mySquare)") + // Generics: Similar to Java. Use the `where` keyword to specify the // requirements of the generics. +func findIndex(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} + ``` -- cgit v1.2.3 From 6b34ef65a3aea7af638145be83c1d3699caa353b Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 00:48:54 -0500 Subject: - more examples - add custom operator example --- swift.html.markdown | 54 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 5ba160b8..6ce60cf5 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -26,9 +26,9 @@ let `class` = "keyword" // backticks allow keywords to be used as variable names let explicitDouble: Double = 70 let intValue = 0007 // 7 let largeIntValue = 77_000 // 77000 -let label = "some text " + String(myVariable) // Casting -let piText = "Pi = \(myConstant)" // String interpolation -var optionalString: String? = "optional" // Can be nil +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(myConstant), Pi 2 = \(myConstant * 2)" // String interpolation +var optionalString: String? = "optional" // Can be nil optionalString = nil /* @@ -114,7 +114,17 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function +// Function with Swift docs +/** + A greet operation + + - A bullet in docs + - Another bullet in the docs + + :param: name A name + :param: day A day + :returns: A string containing the name and day value. +*/ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } @@ -237,6 +247,11 @@ print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 +// compare instances, not the same as == which compares objects (equal to) +if mySquare === mySquare { + println("Yep its mySquare") +} + // // MARK: Enums @@ -276,6 +291,20 @@ extension Square: Printable { println("Square: \(mySquare)") +// You can also extend built-in types +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +println(7.customProperty) // "This is 7" +println(14.multiplyBy(2)) // 42 + // Generics: Similar to Java. Use the `where` keyword to specify the // requirements of the generics. @@ -288,4 +317,21 @@ func findIndex(array: [T], valueToFind: T) -> Int? { return nil } + +// Operators: +// Custom operators can start with the characters: +// / = - + * % < > ! & | ^ . ~ +// or +// Unicode math, symbol, arrow, dingbat, and line/box drawing characters. +prefix operator !!! {} + +// An operator that triples the side length when used +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +let bigSquare = !!!mySquare +println(bigSquare.sideLength) + ``` -- cgit v1.2.3 From 2a5a4ebf64593009002053514deb057f37d7b693 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 14:37:09 -0500 Subject: - add landmark notes --- swift.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index 6ce60cf5..600eedcf 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -15,6 +15,11 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre // MARK: Basics // +// Xcode supports landmarks to annotate your code and lists them in the jump bar +// MARK: Section mark +// TODO: Do something soon +// FIXME Fix this code + println("Hello, world") var myVariable = 42 @@ -114,7 +119,7 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function with Swift docs +// Function with Swift function docs /** A greet operation -- cgit v1.2.3 From 53696bd547736eafd3233e9626838610b696a1d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20Ferrero?= Date: Sun, 24 Aug 2014 22:42:11 +0200 Subject: Update perl-es.html.markdown Typos, passive form eliminated --- es-es/perl-es.html.markdown | 106 ++++++++++++++++++++------------------------ 1 file changed, 49 insertions(+), 57 deletions(-) diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown index 4f0c26c1..fecaf5c4 100644 --- a/es-es/perl-es.html.markdown +++ b/es-es/perl-es.html.markdown @@ -7,23 +7,24 @@ contributors: - ["Korjavin Ivan", "http://github.com/korjavin"] translators: - ["Francisco Gomez", "http://github.com/frncscgmz"] + - ["Joaquín Ferrero", "http://github.com/joaquinferrero"] 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 es un lenguaje de programación altamente capaz, rico en características, con más 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 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala. ```perl -# Comentarios de una sola linea con un carácter hash. +# Comentarios de una sola línea 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. +# Las variables comienzan con el símbolo $ +# Un nombre de variable válido empieza con una letra o un guión bajo, +# seguido por cualquier número de letras, números o guiones bajos -### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes. +### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes ## Escalares # Un escalar representa un solo valor: @@ -31,7 +32,7 @@ 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. +# de punto flotante; Perl automáticamente los convertirá como sea requerido ## Arreglos # Un arreglo representa una lista de valores: @@ -39,91 +40,86 @@ 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: - +# 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. - +# Puede usar un espacio en blanco y el operador "=>" para asignarlos más 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. +# Los escalares, arreglos y hashes están más documentados en perldata (perldoc perldata) -#### Estructuras condicionales y de ciclos +# Los tipos de datos más complejos se pueden construir utilizando +# referencias, las cuales le permiten construir listas y hashes dentro +# de listas y hashes -# Perl tiene la mayoría de las estructuras condicionales y de ciclos mas comunes. +#### Estructuras condicionales y de ciclos +# Perl tiene la mayoría de las estructuras condicionales y de ciclos más 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)" + ...; +} + +# Esto se ofrece como una versión más fácil de leer que "if (!condición)" -# La post condición al modo Perl +# La postcondición al modo Perl: print "Yow!" if $zippy; print "No tenemos bananas" unless $bananas; # while - while ( condicion ) { - ... - } - +while ( condicion ) { + ...; +} # for y foreach for ($i = 0; $i <= $max; $i++) { - ... - } + ...; +} foreach (@array) { - print "Este elemento es $_\n"; - } + 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. +# El soporte de expresiones regulares en Perl es muy amplio y profundo, y +# está sujeto a una extensa documentación en perlrequick, perlretut, entre otros. # Sin embargo, resumiendo: -# Pareo simple +# Coincidencia 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 +$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 +#### Archivos y E/S -# Puedes abrir un archivo para obtener datos o escribirlos utilizando la -# función "open()". +# Puede 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. +# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>". +# En contexto escalar, leer una sola línea desde el gestor de archivo, y +# en contexto de lista, leer el archivo completo en donde asigna +# cada línea a un elemento de la lista my $linea = <$entrada>; my @lineas = <$entrada>; @@ -131,30 +127,26 @@ 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: - +# 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. +Los módulos en Perl proveen de una gama de funciones que le pueden ayudar a evitar reinventar la rueda. Éstas se pueden descargar desde CPAN ( http://www.cpan.org/ ). Algunos de los módulos más 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. +perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos de CPAN que puede usar. #### Material de Lectura - [perl-tutorial](http://perl-tutorial.org/) - - [Aprende en www.perl.com](http://www.perl.org/learn.html) + - [Learn Perl](http://www.perl.org/learn.html) - [perldoc](http://perldoc.perl.org/) - - y perl incorporado: `perldoc perlintro` + - y en su propio perl: `perldoc perlintro` -- cgit v1.2.3 From 5f15d684efd831a6b048f2d42ea66f2494728d7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20Ferrero?= Date: Sun, 24 Aug 2014 22:56:09 +0200 Subject: Update perl-es.html.markdown Perl syntax errors. --- es-es/perl-es.html.markdown | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown index fecaf5c4..644182ff 100644 --- a/es-es/perl-es.html.markdown +++ b/es-es/perl-es.html.markdown @@ -36,19 +36,19 @@ my $respuesta = 42; ## Arreglos # Un arreglo representa una lista de valores: -my @animales = {"camello","llama","buho"}; -my @numeros = {23,42,69}; -my @mixto = {"camello",42,1.23}; +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"}; +my %color_fruta = ("manzana","rojo","banana","amarillo"); # Puede usar un espacio en blanco y el operador "=>" para asignarlos más fácilmente my %color_fruta = ( manzana => "rojo", banana => "amarillo", - ); +); # Los escalares, arreglos y hashes están más documentados en perldata (perldoc perldata) @@ -87,6 +87,10 @@ for ($i = 0; $i <= $max; $i++) { ...; } +for $i (0 .. $max) { + ...; +} + foreach (@array) { print "Este elemento es $_\n"; } -- cgit v1.2.3 From b50d4443cdca87e3342e2364c9e6afd2d7fce7d2 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 18:33:16 -0500 Subject: - add more examples; add book link - add link to official Swift book from Apple - add examples of access control and structures - update protocols --- swift.html.markdown | 95 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 81 insertions(+), 14 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 600eedcf..f8fa31fe 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -8,6 +8,8 @@ filename: learnswift.swift Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta. +The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. + See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. ```js @@ -23,7 +25,7 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre println("Hello, world") var myVariable = 42 -//let fƒ∆ = "value" // unicode in variable names +let øπΩ = "value" // unicode variable names let myConstant = 3.1415926 let convenience = "keyword" // contextual variable name let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon @@ -39,7 +41,7 @@ optionalString = nil /* Comment here /* - Nested comment here + Nested comments are also supported */ */ @@ -119,7 +121,7 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function with Swift function docs +// Function with Swift header docs (format as reStructedText) /** A greet operation @@ -188,12 +190,34 @@ numbers = sorted(numbers, < ) print(numbers) // [3, 6, 18] +// +// MARK: Structures +// + +// Structures and classes have very similar capabilites +struct NamesTable { + let names: [String] + + // Custom subscript + subscript(index: Int) -> String { + return names[index] + } +} + +// Structures have an auto-generated (implicit) designated initializer +let namesTable = NamesTable(names: ["Me", "Them"]) +//let name = namesTable[2] +//println("Name is \(name)") // Name is Them + // // MARK: Classes // -class Shape { - func getArea() -> Int { +// Classes, structures and its members have three levels of access control +// They are: internal (default), public, private + +public class Shape { + public func getArea() -> Int { return 0; } } @@ -203,23 +227,29 @@ class Shape { // structured object, you should use a `struct` // A simple class `Square` extends `Shape` -class Rect: Shape { +internal class Rect: Shape { var sideLength: Int = 1 // Custom getter and setter property - var perimeter: Int { + private var perimeter: Int { get { return 4 * sideLength } set { + // `newValue` is an implicit variable available to setters sideLength = newValue / 4 } } + + // Lazily load a property + // subShape remains nil (uninitialized) until getter called + lazy var subShape = Rect(sideLength: 4) // If you don't need a custom getter and setter, // but still want to run code before and after getting or setting // a property, you can use `willSet` and `didSet` var identifier: String = "defaultID" { + // the `willSet` arg will be the variable name for the new value willSet(someIdentifier) { print(someIdentifier) } @@ -254,7 +284,7 @@ print(mySquare.sideLength) // 4 // compare instances, not the same as == which compares objects (equal to) if mySquare === mySquare { - println("Yep its mySquare") + println("Yep, it's mySquare") } @@ -279,15 +309,47 @@ enum Suit { // -// MARK: Other +// MARK: Protocols // -// `protocol`: Similar to Java interfaces. +// `protocol`s can require that conforming types have specific +// instance properties, instance methods, type methods, +// operators, and subscripts. + protocol ShapeGenerator { + var enabled: Bool { get set } func buildShape() -> Shape } +/* +// Protocols declared with @objc allow optional functions, +// which allow you to check for conformance +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + if let allow = self.delegate?.canReshape?() { + // test for delegate then for method + self.delegate?.reshaped?() + } + } +} +*/ + +// +// MARK: Other +// + // `extension`s: Add extra functionality to an already existing type + +// Square now "conforms" to the `Printable` protocol extension Square: Printable { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" @@ -321,7 +383,8 @@ func findIndex(array: [T], valueToFind: T) -> Int? { } return nil } - +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +println(foundAtIndex == 2) // true // Operators: // Custom operators can start with the characters: @@ -330,13 +393,17 @@ func findIndex(array: [T], valueToFind: T) -> Int? { // Unicode math, symbol, arrow, dingbat, and line/box drawing characters. prefix operator !!! {} -// An operator that triples the side length when used +// A prefix operator that triples the side length when used prefix func !!! (inout shape: Square) -> Square { shape.sideLength *= 3 return shape } -let bigSquare = !!!mySquare -println(bigSquare.sideLength) +// current value +println(mySquare.sideLength) // 4 + +// change side length using custom !!! operator, increases size by 3 +!!!mySquare +println(mySquare.sideLength) // 12 ``` -- cgit v1.2.3 From 3771906a8c93eeca9333189db5cf3374c69e085a Mon Sep 17 00:00:00 2001 From: Michael Bock Date: Mon, 25 Aug 2014 00:13:59 -0700 Subject: Fix typo in scala "less then" -> "less than" --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 6b398b4b..379c092c 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -243,7 +243,7 @@ i // Show the value of i. Note that while is a loop in the classical sense - // A do while loop do { - println("x is still less then 10"); + println("x is still less than 10"); x += 1 } while (x < 10) -- cgit v1.2.3 From 54bd312f8de72d4ca109fb12351b44203a482d23 Mon Sep 17 00:00:00 2001 From: "Janne R." Date: Tue, 26 Aug 2014 20:48:35 +0300 Subject: Use preferred shorthand syntax for dictionary type --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index a47b085a..a0ea8519 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -39,7 +39,7 @@ var occupations = [ "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" -let emptyDictionary = Dictionary() +let emptyDictionary = [String: Float]() // -- cgit v1.2.3 From 013112b9b338d5f05d33e6d1d85e39e7f061285d Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Wed, 27 Aug 2014 12:38:23 +0200 Subject: Clarifications about *+* and ... with a sub mrf++ --- perl6.html.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 4ab90914..fe5b197c 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -488,6 +488,7 @@ sub truthy-array(@array) { # (it'll stop at the furthest operator in the current expression) my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` my @arrayplus3 = map(*+*+3, @array); # Same as `-> $a, $b { $a + $b + 3 }` + # also `sub ($a, $b) { $a + $b + 3 }` say (*/2)(4); #=> 2 # Immediatly execute the function Whatever created. say ((*+3)/5)(5); #=> 1.6 @@ -496,7 +497,8 @@ say ((*+3)/5)(5); #=> 1.6 # But if you need to have more than one argument (`$_`) # in a block (without wanting to resort to `-> {}`), # you can also use the implicit argument syntax, `$^` : -map({ $^a + $^b + 3 }, @array); # same as the above +map({ $^a + $^b + 3 }, @array); # equivalent to following: +map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) # Note : those are sorted lexicographically. # `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` @@ -1072,6 +1074,11 @@ my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above) my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers, # computed using a closure! my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above) +my @fib = 1, 1, { $^a + $^b } ... *; #(... also equivalent to the above) +# $a and $b will always take the previous values, meaning here +# they'll start with $a = 1 and $b = 1 (values we set by hand). +# then $a = 1 and $b = 2 (result from previous $a+$b), and so on. + say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55 # (using a range as the index) # Note : as for ranges, once reified, elements aren't re-calculated. -- cgit v1.2.3 From 0d022b14c0d11314d29211b862ac65095ceba26c Mon Sep 17 00:00:00 2001 From: Philippe Date: Wed, 27 Aug 2014 15:41:12 +0200 Subject: Added section on Modules Indented comments and edited the Interfaces part. Still missing indexers and Generics. --- typescript.html.markdown | 50 ++++++++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 8209fedb..74e98d14 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -18,7 +18,7 @@ var isDone: boolean = false; var lines: number = 42; var name: string = "Anders"; -//When it's impossible to know, there is the "Any" type +//..When it's impossible to know, there is the "Any" type var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean @@ -50,40 +50,32 @@ interface Person { name: string; //Optional properties, marked with a "?" age?: number; -} -//Object that implements the "Person" interface -var p : Person = { name: "Bobby" }; //Can be treated as a Person since it has the name and age properties -//Objects that have the optional property: -var validPerson : Person = { name: "Bobby", age: 42 }; -var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number - -//Interfaces can also define method signatures: -interface PersonWhoCanTalk { - sayHello(otherPersonsName: string): void; + //And of course functions + move(): void; } -//And also indexers, both with number and string -interface PersonWhoCanBeIndexed { - [index: number]: string; -} -//TODO +//..Object that implements the "Person" interface +var p : Person = { name: "Bobby", move : () => {} }; //Can be treated as a Person since it has the name and age properties +//..Objects that have the optional property: +var validPerson : Person = { name: "Bobby", age: 42, move: () => {} }; +var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number -//Interfaces can also describe a function type +//..Interfaces can also describe a function type interface SearchFunc { (source: string, subString: string): boolean; } -//Only the parameters' types are important, names are not important. +//..Only the parameters' types are important, names are not important. var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { return src.search(sub) != -1; } -//Classes +//Classes - members are public by default class Point { //Properties x: number; - //Constructor - the public/private keywords are shortcuts to generate the code for a property and its initialization + //Constructor - the public/private keywords in this context are shortcuts to generate the code for a property //Equivalent to "x" in this case //Default values are also supported constructor(x: number, public y: number = 0) { @@ -113,7 +105,23 @@ class Point3D extends Point { } } -//Modules +//Modules, "." can be used as separators for sub modules +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +//..Local alias for rreferencing a module +import G = Geometry; + +var s2 = new G.Square(10); //Generics -- cgit v1.2.3 From bfa04112e8e788bea9dc53cdef1659961c7882cb Mon Sep 17 00:00:00 2001 From: Philippe Date: Wed, 27 Aug 2014 16:14:57 +0200 Subject: Added filename in header --- typescript.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/typescript.html.markdown b/typescript.html.markdown index 74e98d14..fd22cbef 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -2,6 +2,7 @@ language: TypeScript contributors: - ["Philippe Vlérick", "https://github.com/pvlerick"]] +filename: learntypescript.ts --- TypeScript is a language that aims at easing development of large scale applications written in JavaScript. -- cgit v1.2.3 From c9400c2a7d5262651884fffecda83ace1bfc4d97 Mon Sep 17 00:00:00 2001 From: Assaf Gelber Date: Thu, 28 Aug 2014 14:00:25 +0300 Subject: Change swift class name to Square --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index a0ea8519..6d98b067 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -157,7 +157,7 @@ print(numbers) // [3, 6, 18] // structured object, you should use a `struct` // A simple class `Square` extends `Shape` -class Rect: Shape { +class Square: Shape { var sideLength: Int = 1 // Custom getter and setter property -- cgit v1.2.3 From 2c56f7bed41f7b7e26989374020d68f1f0f9ebe5 Mon Sep 17 00:00:00 2001 From: Philippe Date: Sun, 31 Aug 2014 17:57:44 +0200 Subject: Generics added And a few typos corrected, ready for pull request --- typescript.html.markdown | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index fd22cbef..3ba1300d 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -41,7 +41,7 @@ function bigHorribleAlert(): void { //Functions are first class citizens, support the lambda "fat arrow" syntax and use type inference //All examples are equivalent, the same signature will be infered by the compiler, and same JavaScript will be emitted var f1 = function(i: number) : number { return i * i; } -var f2 = function(i: number) { return i * i; } //Return type infered #TODO bug! +var f2 = function(i: number) { return i * i; } //Return type infered var f3 = (i : number) : number => { return i * i; } var f4 = (i: number) => { return i * i; } //Return type infered var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed @@ -119,12 +119,30 @@ module Geometry { var s1 = new Geometry.Square(5); -//..Local alias for rreferencing a module +//..Local alias for referencing a module import G = Geometry; var s2 = new G.Square(10); //Generics +//..Classes +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +//..Interfaces +interface Pair { + item1: T; + item2: T; +} + +//..And functions +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); //Including references to a definition file: /// -- cgit v1.2.3 From 199e2e8726fd913b4accc9e94c386c0cb26fb447 Mon Sep 17 00:00:00 2001 From: Fredrik Dyrkell Date: Sun, 31 Aug 2014 23:26:56 +0200 Subject: Learn Purescript in Y minutes --- purescript.html.markdown | 195 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 purescript.html.markdown diff --git a/purescript.html.markdown b/purescript.html.markdown new file mode 100644 index 00000000..6bff7545 --- /dev/null +++ b/purescript.html.markdown @@ -0,0 +1,195 @@ +--- +language: purescript +contributors: + - ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"] +--- + +PureScript is a small strongly, statically typed language compiling to Javascript. + +* Learn more at [http://www.purescript.org/](http://www.purescript.org/) +* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/) +* Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/) + +```haskell + +-- +-- 1. Primitive datatypes that corresponds to their Javascript +-- equivalents at runtime. + +-- Numbers +1 + 7*5 :: Number -- 36 +-- Types are inferred, so the following works fine +9 / 2.5 + 4.4 -- 8 +-- Hexadecimal literals +0xff + 1 -- 256 +-- Unary negation +6 * -3 -- -18 +6 * negate 3 -- -18 +-- Modulus +3 % 2 -- 1 +4 % 2 -- 0 +-- Inspect the type of an expression in psci +:t 9 / 2.5 + 4.4 -- Prim.Number + +-- Booleans +true :: Boolean -- true +false :: Boolean -- false +-- Negation +not true --false +23 == 23 -- true +1 /= 4 -- true +1 >= 4 -- false +-- Comparisions < <= > >= +-- are defined in terms of compare +compare 1 2 -- LT +compare 2 2 -- EQ +compare 3 2 -- GT +-- Conjunction and Disjunction +true && (9 >= 19 || 1 < 2) -- true + +-- Strings +"Hellow" :: String -- "Hellow" +-- Multiline string +"Hellow\ +\orld" -- "Helloworld" +-- Concatenate +"such " ++ "amaze" -- "such amaze" + +-- +-- 2. Arrays are Javascript arrays, but must be homogeneous + +[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8] +[true, true, false] :: [Boolean] -- [true,true,false] +-- [1,2, true, "false"] won't work +-- `Cannot unify Prim.Number with Prim.Boolean` +-- Cons (prepend) +1 : [2,4,3] -- [1,2,4,3] + +-- Requires purescript-arrays (Data.Array) +-- and purescript-maybe (Data.Maybe) + +-- Safe access return Maybe a +head [1,2,3] -- Just (1) +tail [3,2,1] -- Just ([2,1]) +init [1,2,3] -- Just ([1,2]) +last [3,2,1] -- Just (1) +-- Random access - indexing +[3,4,5,6,7] !! 2 -- Just (5) +-- Range +1..5 -- [1,2,3,4,5] +length [2,2,2] -- 3 +drop 3 [5,4,3,2,1] -- [2,1] +take 3 [5,4,3,2,1] -- [5,4,3] +append [1,2,3] [4,5,6] -- [1,2,3,4,5,6] + +-- +-- 3. Records are Javascript objects, with zero or more fields, which +-- can have different types +let book = {title: "Foucault's pendulum", author: "Umberto Eco"} +-- Access properties +book.title -- "Foucault's pendulum" + +getTitle b = b.title +-- Works on all records with a title (but doesn't require any other field) +getTitle book -- "Foucault's pendulum" +getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco" +-- Update a record +changeTitle b t = b {title = t} +changeTitle book "Ill nome della rosa" -- {title: "Ill nome della + -- rosa", author: "Umberto Eco"} + +-- +-- 4. Functions +sumOfSquares x y = x*x+y*y +sumOfSquares 3 4 -- 25 +-- In psci you have to write `let` in front of the function to get a +-- top level binding +mod x y = x % y +mod 3 2 -- 1 +-- Infix application of function +3 `mod` 2 -- 1 + +-- function application have higher precedence than all other +-- operators +sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025 + +-- Conditional +abs' n = if n>=0 then n else -n +abs' (-3) -- 3 + +-- Guarded equations +abs n | n >= 0 = n + | otherwise = -n + +-- Pattern matching + +-- Note the type signature, input is an array of numbers The pattern +-- matching destructures and binds the array into parts +first :: [Number] -> Number +first (x:_) = x +first [3,4,5] -- 3 +second :: [Number] -> Number +second (_:y:_) = y +second [3,4,5] -- 4 +sumTwo :: [Number] -> [Number] +sumTwo (x:y:rest) = (x+y) : rest +sumTwo [2,3,4,5,6] -- [5,4,5,6] + +-- sumTwo doesn't handle when the array is empty or just have one +-- element in which case you get an error +sumTwo [1] -- Failed pattern match + +-- Complementing patterns to match +-- Good ol' Fibonacci +fib 1 = 1 +fib 2 = 2 +fib x = fib (x-1) + fib (x-2) +fib 10 -- 89 + +-- Use underscore to match any, where you don't care about the binding name +isZero 0 = true +isZero _ = false + +-- Pattern matching on records +ecoTitle {author = "Umberto Eco", title = t} = Just t +ecoTitle _ = Nothing + +ecoTitle book -- Just ("Foucault's pendulum") +ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing +-- ecoTitle requires both field to type check: +ecoTitle {title: "The Quantum Thief"} -- Object does not have property author + +-- Lambda expressions +(\x -> x*x) 3 -- 9 +(\x y -> x*x + y*y) 4 5 -- 41 +sqr = \x -> x*x + +-- Currying +add x y = x + y -- is equivalent with +add = \x -> (\y -> x+y) +add3 = add 3 +:t add3 -- Prim.Number -> Prim.Number + +-- Forward and backward function composition +-- drop 3 followed by taking 5 +(drop 3 >>> take 5) (1..20) -- [4,5,6,7,8] +-- take 5 followed by dropping 3 +(drop 3 <<< take 5) (1..20) -- [4,5] + +-- Operations using higher order functions +even x = x % 2 == 0 +filter even (1..10) -- [2,4,6,8,10] +map (\x -> x+11) (1..5) -- [12,13,14,15,16] + +-- Requires purescript-foldable-traversabe (Data.Foldable) + +foldr (+) 0 (1..10) -- 55 +sum (1..10) -- 55 +product (1..10) -- 3628800 + +-- Testing with predicate +any even [1,2,3] -- true +all even [1,2,3] -- false + +``` + -- cgit v1.2.3 From ef37db634aa8fc1b21a1542c176339f250678cb2 Mon Sep 17 00:00:00 2001 From: Philippe Date: Mon, 1 Sep 2014 10:51:43 +0200 Subject: Fixed errors and typos After review from from Nami-Doc --- typescript.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 3ba1300d..8173aac8 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -1,13 +1,13 @@ --- language: TypeScript contributors: - - ["Philippe Vlérick", "https://github.com/pvlerick"]] + - ["Philippe Vlérick", "https://github.com/pvlerick"] filename: learntypescript.ts --- TypeScript is a language that aims at easing development of large scale applications written in JavaScript. TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. -It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emitts JavaScript. +It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. This article will focus only on TypeScript extra syntax, as oposed to [JavaScript] (../javascript/). @@ -46,7 +46,7 @@ var f3 = (i : number) : number => { return i * i; } var f4 = (i: number) => { return i * i; } //Return type infered var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed -//Interfaces are structural, anything that has the properties is compliant with the interface (duck typing) +//Interfaces are structural, anything that has the properties is compliant with the interface interface Person { name: string; //Optional properties, marked with a "?" @@ -76,8 +76,9 @@ class Point { //Properties x: number; - //Constructor - the public/private keywords in this context are shortcuts to generate the code for a property - //Equivalent to "x" in this case + //Constructor - the public/private keywords in this context will generate the boiler plate code + // for the property and the initialization in the constructor. + // In this example, "y" will be defined just like "x" is, but with less code //Default values are also supported constructor(x: number, public y: number = 0) { this.x = x; @@ -106,7 +107,7 @@ class Point3D extends Point { } } -//Modules, "." can be used as separators for sub modules +//Modules, "." can be used as separator for sub modules module Geometry { export class Square { constructor(public sideLength: number = 0) { -- cgit v1.2.3 From 12c9653b03271abbd13906058ece129c13f9c055 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 1 Sep 2014 11:01:30 -0500 Subject: Fix arrow => array java typo. --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 3484aee5..dffc3828 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -101,7 +101,7 @@ public class LearnJava { // Arrays //The array size must be decided upon instantiation - //The following formats work for declaring an arrow + //The following formats work for declaring an array // [] = new []; // [] = new []; int [] intArray = new int[10]; -- cgit v1.2.3 From 29e602675c6ec91c719bd072e70c81f3c067e5ce Mon Sep 17 00:00:00 2001 From: boston Date: Tue, 2 Sep 2014 11:41:31 +0600 Subject: =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BE=D0=BA=20=D1=80?= =?UTF-8?q?=D1=83=D1=81=D1=81=D0=BA=D0=BE=D0=B3=D0=BE=20=D1=8F=D0=B7=D1=8B?= =?UTF-8?q?=D0=BA=D0=B0=20/=20Typo=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Исправлены синтаксические и пунктуационные ошибки русского языка --- ru-ru/go-ru.html.markdown | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 5b9d8ebf..44a22b45 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -13,11 +13,11 @@ lang: ru-ru --- Go - это язык общего назначения, целью которого является удобство, простота, -конкуррентность. Это не тренд в компьютерных науках, а новейший и быстрый +конкурентность. Это не тренд в компьютерных науках, а новейший и быстрый способ решать насущные проблемы. Концепции Go схожи с другими императивными статически типизированными языками. -Быстро компилируется и быстро исполняется, имеет легкие в понимании конструкции +Быстро компилируется и быстро исполняется, имеет лёгкие в понимании конструкции для создания масштабируемых и многопоточных программ. Может похвастаться отличной стандартной библиотекой и большим комьюнити, полным @@ -57,7 +57,7 @@ func main() { func beyondHello() { var x int // Переменные должны быть объявлены до их использования. x = 3 // Присвоение значения переменной. - // Краткое определение := позволяет объявить перменную с автоматической + // Краткое определение := позволяет объявить переменную с автоматической // подстановкой типа из значения. y := 4 sum, prod := learnMultiple(x, y) // Функция возвращает два значения. @@ -70,7 +70,7 @@ func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Возврат двух значений. } -// Некотрые встроенные типы и литералы. +// Некоторые встроенные типы и литералы. func learnTypes() { // Краткое определение переменной говорит само за себя. s := "Learn Go!" // Тип string. @@ -97,7 +97,7 @@ func learnTypes() { // Слайсы (slices) имеют динамическую длину. И массивы, и слайсы имеют свои // преимущества, но слайсы используются гораздо чаще. - s3 := []int{4, 5, 9} // Сравните с a3. Тут нет троеточия. + s3 := []int{4, 5, 9} // Сравните с a3, тут нет троеточия. s4 := make([]int, 4) // Выделение памяти для слайса из 4-х int (нули). var d2 [][]float64 // Только объявление, память не выделяется. bs := []byte("a slice") // Синтаксис приведения типов. @@ -113,7 +113,7 @@ func learnTypes() { delete(m, "three") // Встроенная функция, удаляет элемент из map-а. // Неиспользуемые переменные в Go являются ошибкой. - // Нижнее подчеркивание позволяет игнорировать такие переменные. + // Нижнее подчёркивание позволяет игнорировать такие переменные. _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs // Вывод считается использованием переменной. fmt.Println(s, c, a4, s3, d2, m) @@ -121,16 +121,16 @@ func learnTypes() { learnFlowControl() // Идем дальше. } -// У Go есть полноценный сборщик мусора. В нем есть указатели но нет арифметики +// У Go есть полноценный сборщик мусора. В нем есть указатели, но нет арифметики // указателей. Вы можете допустить ошибку с указателем на nil, но не с // инкрементацией указателя. func learnMemory() (p, q *int) { // Именованные возвращаемые значения p и q являются указателями на int. p = new(int) // Встроенная функция new выделяет память. - // Выделенный int проинициализирован нулем, p больше не содержит nil. + // Выделенный int проинициализирован нулём, p больше не содержит nil. s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов. s[3] = 7 // Присвоить значение одному из них. - r := -2 // Определить еще одну локальную переменную. + r := -2 // Определить ещё одну локальную переменную. return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной. } @@ -139,7 +139,7 @@ func expensiveComputation() float64 { } func learnFlowControl() { - // If-ы всегда требуют наличине фигурных скобок, но не круглых. + // If-ы всегда требуют наличие фигурных скобок, но не круглых. if true { fmt.Println("told ya") } @@ -178,7 +178,7 @@ func learnFlowControl() { } // Функции являются замыканиями. xBig := func() bool { - return x > 10000 // Ссылается на x, объявленый выше switch. + return x > 10000 // Ссылается на x, объявленный выше switch. } fmt.Println("xBig:", xBig()) // true (т.к. мы присвоили x = e^10). x = 1.3e3 // Тут х == 1300 @@ -189,7 +189,7 @@ func learnFlowControl() { love: learnDefer() // Быстрый обзор важного ключевого слова. - learnInterfaces() // О! Интерфейсы, идем далее. + learnInterfaces() // О! Интерфейсы, идём далее. } func learnDefer() (ok bool) { @@ -214,7 +214,7 @@ type pair struct { // Объявление метода для типа pair. Теперь pair реализует интерфейс Stringer. func (p pair) String() string { // p в данном случае называют receiver-ом. - // Sprintf – еще одна функция из пакета fmt. + // Sprintf – ещё одна функция из пакета fmt. // Обращение к полям p через точку. return fmt.Sprintf("(%d, %d)", p.x, p.y) } @@ -234,7 +234,7 @@ func learnInterfaces() { fmt.Println(p) // Вывод такой же, что и выше. Println вызывает метод String. fmt.Println(i) // Вывод такой же, что и выше. - learnVariadicParams("Учиться", "учиться", "и еще раз учиться!") + learnVariadicParams("Учиться", "учиться", "и ещё раз учиться!") } // Функции могут иметь варьируемое количество параметров. @@ -263,22 +263,22 @@ func learnErrorHandling() { // выведет "strconv.ParseInt: parsing "non-int": invalid syntax" fmt.Println(err) } - // Мы еще обратимся к интерфейсам чуть позже, а пока... + // Мы ещё обратимся к интерфейсам чуть позже, а пока... learnConcurrency() } -// c – это тип данных channel (канал), объект для конкуррентного взаимодействия. +// c – это тип данных channel (канал), объект для конкурентного взаимодействия. func inc(i int, c chan int) { c <- i + 1 // когда channel слева, <- являтся оператором "отправки". } -// Будем использовать функцию inc для конкуррентной инкрементации чисел. +// Будем использовать функцию inc для конкурентной инкрементации чисел. func learnConcurrency() { // Тот же make, что и в случае со slice. Он предназначен для выделения // памяти и инициализации типов slice, map и channel. c := make(chan int) - // Старт трех конкуррентных goroutine. Числа будут инкрементированы - // конкуррентно и, может быть параллельно, если машина правильно + // Старт трех конкурентных goroutine. Числа будут инкрементированы + // конкурентно и, может быть параллельно, если машина правильно // сконфигурирована и позволяет это делать. Все они будут отправлены в один // и тот же канал. go inc(0, c) // go начинает новую горутину. @@ -291,7 +291,7 @@ func learnConcurrency() { cs := make(chan string) // другой канал, содержит строки. cc := make(chan chan string) // канал каналов со строками. go func() { c <- 84 }() // пуск новой горутины для отправки значения - go func() { cs <- "wordy" }() // еще раз, теперь для cs + go func() { cs <- "wordy" }() // ещё раз, теперь для cs // Select тоже что и switch, но работает с каналами. Он случайно выбирает // готовый для взаимодействия канал. select { @@ -327,7 +327,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { Основа всех основ в Go это [официальный веб сайт](http://golang.org/). Там можно пройти туториал, поиграться с интерактивной средой Go и почитать -объемную документацию. +объёмную документацию. Для живого ознакомления рекомендуется почитать исходные коды [стандартной библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированная, она -- cgit v1.2.3 From d4286056d3e48dc3a44bc51adb1a1b6da80c990c Mon Sep 17 00:00:00 2001 From: kaernyk Date: Tue, 2 Sep 2014 18:24:41 -0400 Subject: Create LearnTmux.txt Quick write-up of using tmux --- LearnTmux.txt | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 LearnTmux.txt diff --git a/LearnTmux.txt b/LearnTmux.txt new file mode 100644 index 00000000..a86e36f4 --- /dev/null +++ b/LearnTmux.txt @@ -0,0 +1,61 @@ +--- +category: tool +tool: tmux +contributors: + - ["kaernyk", "http://github.com/kaernyk"] +filename: LearnTmux.txt +--- + + tmux is a terminal multiplexer: it enables a number of terminals to be +created, accessed, and controlled from a single screen. tmux may be detached +from a screen and continue running in the background, then later reattached. + + This will be a quick walkthough detailing the basic method of controlling tmux +for users to get acclimated quickly. Once you feel comfortable manipulating +tmux to suit your needs, I strongly suggest you read the man pages. + + +### Session Management +```bash + tmux new Create new session + -s "Session" Create named session + -n "Window" Create named Window + -c "/dir" Start in target directory + + ex: tmux new -c "~/Documents" -s "" -n "" + ----------------------------------------------------------------------------- + C^b d Detach current session + C^b D Select session to detach + ----------------------------------------------------------------------------- + tmux attach Attach last/available session + -t "#" Attach target session + -d Detach the session from other instances + ----------------------------------------------------------------------------- + tmux ls List open sessions + C^b s Select new session for attached client interactively + ----------------------------------------------------------------------------- + kill-session Kill current session + -t "#" Kill target session + -a Kill all sessions + -a -t "#" Kill all sessions but the target + ----------------------------------------------------------------------------- +``` + +### Window Management +```bash + ----------------------------------------------------------------------------- + C^b c Create another window + C^b " Split Horizontally + C^b % Split Vertically + ----------------------------------------------------------------------------- + C^b q Briefly display pane indexes + C^b w Choose current window interactively + ----------------------------------------------------------------------------- + + Detaching Windows + + ----------------------------------------------------------------------------- + + Killing Windows + +``` -- cgit v1.2.3 From fd2cf1606fb13ce506e0fdee0123269cf6023522 Mon Sep 17 00:00:00 2001 From: kaernyk Date: Tue, 2 Sep 2014 18:52:29 -0400 Subject: Update LearnTmux.txt clean up in prep for markdown --- LearnTmux.txt | 84 ++++++++++++++++++++++++++++++++--------------------------- 1 file changed, 46 insertions(+), 38 deletions(-) diff --git a/LearnTmux.txt b/LearnTmux.txt index a86e36f4..e73d1485 100644 --- a/LearnTmux.txt +++ b/LearnTmux.txt @@ -15,47 +15,55 @@ for users to get acclimated quickly. Once you feel comfortable manipulating tmux to suit your needs, I strongly suggest you read the man pages. -### Session Management -```bash - tmux new Create new session - -s "Session" Create named session - -n "Window" Create named Window - -c "/dir" Start in target directory - - ex: tmux new -c "~/Documents" -s "" -n "" - ----------------------------------------------------------------------------- - C^b d Detach current session - C^b D Select session to detach - ----------------------------------------------------------------------------- - tmux attach Attach last/available session - -t "#" Attach target session - -d Detach the session from other instances - ----------------------------------------------------------------------------- - tmux ls List open sessions - C^b s Select new session for attached client interactively - ----------------------------------------------------------------------------- - kill-session Kill current session - -t "#" Kill target session - -a Kill all sessions - -a -t "#" Kill all sessions but the target - ----------------------------------------------------------------------------- + ``` +# Session Management + + tmux new Create new session + -s "Session" Create named session + -n "Window" Create named Window + -c "/dir" Start in target directory + ex: $ tmux new -c "~/" -s "Name" -n "Name" + + C^b $ Rename current session + + C^b d Detach current session + C^b D Select session to detach + + tmux attach Attach last/available session + -t "#" Attach target session + -d Detach the session from other instances + tmux ls List open sessions + C^b s Select new session for attached client interactively + + kill-session Kill current session + -t "#" Kill target session + -a Kill all sessions + -a -t "#" Kill all sessions but the target + -### Window Management -```bash - ----------------------------------------------------------------------------- - C^b c Create another window - C^b " Split Horizontally - C^b % Split Vertically - ----------------------------------------------------------------------------- - C^b q Briefly display pane indexes - C^b w Choose current window interactively - ----------------------------------------------------------------------------- +# Window Management - Detaching Windows + C^b c Create another window + C^b " Split Horizontally + C^b % Split Vertically + + exit or C^b x Kill the current pane + + C^b q Briefly display pane indexes + C^# Choose current window by # + C^b w Choose current window interactively + C^b n Change to next window + C^b p Change to previous window + C^b Up, Right Change to pane in selected direction + Down, left - ----------------------------------------------------------------------------- - - Killing Windows + C^b { Swap current/previous pane + C^b } Swap current/next pane + + C^b C-Up, Right Resize in steps of one cell + Down, left + C^b M-Up, Right resize in steps of five cells + Down, left ``` -- cgit v1.2.3 From 7d52148acf1ca5228e7882769345bc4da36c787f Mon Sep 17 00:00:00 2001 From: Ben Eysenbach Date: Wed, 3 Sep 2014 20:33:55 -0400 Subject: Matlab syntax error --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index d9a82890..9dae8ef2 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -85,7 +85,7 @@ load myFile.mat y % no parentheses, and spaces instead of commas % 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 ] +A( A > 5 ) % returns a vector containing the elements in A for which condition is true % Strings -- cgit v1.2.3 From c0c77e850c051a28afafcd1e71710c4eebebcccc Mon Sep 17 00:00:00 2001 From: Ben Eysenbach Date: Wed, 3 Sep 2014 22:46:50 -0400 Subject: Clarified C Octal Character This fixes issue #658 --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 8e170300..79b7aec7 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -573,7 +573,7 @@ typedef void (*my_fnp_type)(char *); '\''; // single quote '\"'; // double quote '\xhh'; // hexadecimal number. Example: '\xb' = vertical tab character -'\ooo'; // octal number. Example: '\013' = vertical tab character +'\0oo'; // octal number. Example: '\013' = vertical tab character //print formatting: "%d"; // integer -- cgit v1.2.3 From 4347222876022e98d6ce8f0e1f6ab9a60159c653 Mon Sep 17 00:00:00 2001 From: kaernyk Date: Thu, 4 Sep 2014 14:30:25 -0400 Subject: Update LearnTmux.txt --- LearnTmux.txt | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/LearnTmux.txt b/LearnTmux.txt index e73d1485..3396989f 100644 --- a/LearnTmux.txt +++ b/LearnTmux.txt @@ -23,16 +23,15 @@ tmux to suit your needs, I strongly suggest you read the man pages. -s "Session" Create named session -n "Window" Create named Window -c "/dir" Start in target directory - ex: $ tmux new -c "~/" -s "Name" -n "Name" - + C^b $ Rename current session - C^b d Detach current session C^b D Select session to detach tmux attach Attach last/available session -t "#" Attach target session -d Detach the session from other instances + tmux ls List open sessions C^b s Select new session for attached client interactively @@ -48,8 +47,6 @@ tmux to suit your needs, I strongly suggest you read the man pages. C^b " Split Horizontally C^b % Split Vertically - exit or C^b x Kill the current pane - C^b q Briefly display pane indexes C^# Choose current window by # C^b w Choose current window interactively @@ -57,13 +54,18 @@ tmux to suit your needs, I strongly suggest you read the man pages. C^b p Change to previous window C^b Up, Right Change to pane in selected direction Down, left - - C^b { Swap current/previous pane - C^b } Swap current/next pane - + C^b { Swap current/previous window + C^b } Swap current/next window C^b C-Up, Right Resize in steps of one cell Down, left - C^b M-Up, Right resize in steps of five cells Down, left + C^b M-(1-5) 1 - Tile vertically + 2 - Tile horizontally + 3 - Tile Vertically /w large horizontal + 4 - Tile horizontally /w large vertical + 5 - Tile all windows evenly + + exit or C^b x Kill the current window + ``` -- cgit v1.2.3 From 9f791e1e66c1ff2e42d7fa9ac5ad42e36037176e Mon Sep 17 00:00:00 2001 From: kaernyk Date: Thu, 4 Sep 2014 14:45:44 -0400 Subject: re-order commands I'm trying to perfect the order so that learning how to use tmux can be reasonably accomplished in one sitting. I feel like I may be leaving out some things that power users would be interested in, but for the sake of someone attempting to find out if they enjoy using tmux I believe it is in decent shape. --- LearnTmux.txt | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/LearnTmux.txt b/LearnTmux.txt index 3396989f..eaf3fd25 100644 --- a/LearnTmux.txt +++ b/LearnTmux.txt @@ -6,13 +6,13 @@ contributors: filename: LearnTmux.txt --- + tmux is a terminal multiplexer: it enables a number of terminals to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached. - This will be a quick walkthough detailing the basic method of controlling tmux -for users to get acclimated quickly. Once you feel comfortable manipulating -tmux to suit your needs, I strongly suggest you read the man pages. + Once you feel comfortable manipulating tmux to suit your needs, I strongly +suggest you read the man pages. @@ -46,26 +46,26 @@ tmux to suit your needs, I strongly suggest you read the man pages. C^b c Create another window C^b " Split Horizontally C^b % Split Vertically - + C^b M-(1-5) 1) Tile vertically + 2) Tile horizontally + 3) Tile Vertically /w large horizontal + 4) Tile horizontally /w large vertical + 5) Tile all windows evenly + C^b q Briefly display pane indexes C^# Choose current window by # C^b w Choose current window interactively C^b n Change to next window C^b p Change to previous window C^b Up, Right Change to pane in selected direction - Down, left + Down, left C^b { Swap current/previous window C^b } Swap current/next window + C^b C-Up, Right Resize in steps of one cell Down, left C^b M-Up, Right resize in steps of five cells Down, left - C^b M-(1-5) 1 - Tile vertically - 2 - Tile horizontally - 3 - Tile Vertically /w large horizontal - 4 - Tile horizontally /w large vertical - 5 - Tile all windows evenly - + exit or C^b x Kill the current window - ``` -- cgit v1.2.3 From 0833c79b34c36cf4121055f0bf929a5526d0d5ea Mon Sep 17 00:00:00 2001 From: kaernyk Date: Fri, 5 Sep 2014 07:48:24 -0400 Subject: Massive re-write I wanted to show a lot more than I had previously, though this may have gotten a little out of hand for a casual glance in comparison to the previous version. I feel that a majority of the available tools/features that tmux has to offer should be noticeable during a quick skim, and the bulk of the information is still digestible over a short period of time. --- LearnTmux.txt | 241 ++++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 185 insertions(+), 56 deletions(-) diff --git a/LearnTmux.txt b/LearnTmux.txt index eaf3fd25..65ead04f 100644 --- a/LearnTmux.txt +++ b/LearnTmux.txt @@ -6,66 +6,195 @@ contributors: filename: LearnTmux.txt --- +```bash +# tmux is a terminal multiplexer: it enables a number of terminals to be +# created, accessed, and controlled from a single screen. tmux may be detached +# from a screen and continue running in the background, then later reattached. - tmux is a terminal multiplexer: it enables a number of terminals to be -created, accessed, and controlled from a single screen. tmux may be detached -from a screen and continue running in the background, then later reattached. +# Once you feel comfortable manipulating tmux to suit your needs, I strongly +# suggest you read the man pages, as there are TONS of features I’m not going +# to go over. - Once you feel comfortable manipulating tmux to suit your needs, I strongly -suggest you read the man pages. +# We’ll start of with managing tmux from a terminal, then introduce you to the +# keybinds: - -``` -# Session Management - - tmux new Create new session - -s "Session" Create named session - -n "Window" Create named Window - -c "/dir" Start in target directory - - C^b $ Rename current session - C^b d Detach current session - C^b D Select session to detach + tmux | tmux new # Create an unamed session + -s "Session" # Create named session + -n "Window" # Create named Window + -c "/dir" # Start in target directory - tmux attach Attach last/available session - -t "#" Attach target session - -d Detach the session from other instances + tmux attach # Attach last/available session + -t "#" # Attach target session + -d # Detach the session from other instances - tmux ls List open sessions - C^b s Select new session for attached client interactively - - kill-session Kill current session - -t "#" Kill target session - -a Kill all sessions - -a -t "#" Kill all sessions but the target - - -# Window Management - - C^b c Create another window - C^b " Split Horizontally - C^b % Split Vertically - C^b M-(1-5) 1) Tile vertically - 2) Tile horizontally - 3) Tile Vertically /w large horizontal - 4) Tile horizontally /w large vertical - 5) Tile all windows evenly - - C^b q Briefly display pane indexes - C^# Choose current window by # - C^b w Choose current window interactively - C^b n Change to next window - C^b p Change to previous window - C^b Up, Right Change to pane in selected direction - Down, left - C^b { Swap current/previous window - C^b } Swap current/next window - - C^b C-Up, Right Resize in steps of one cell - Down, left - C^b M-Up, Right resize in steps of five cells - Down, left - - exit or C^b x Kill the current window + tmux ls # List open sessions + + kill-session # Kill current session + -t "#" # Kill target session + -a # Kill all sessions + -a -t "#" # Kill all sessions but the target + + + +## Key Bindings + +# The method of controlling an attached tmux session is fairly simple, but +# there are two keys we will see repeated throughout this write-up (as well as +# the man pages). + + (C-b) == Ctrl + b THEN ? to list all keybinds + +# The default keybinds are as follows: + + C-b # Send the prefix key (C-b) through to the application. + C-o # Rotate the panes in the current window forwards. + C-z # Suspend the tmux client. + ? # List all key bindings. + : # Enter the tmux command prompt. + r # Force redraw of the attached client. + + c # Create a new window. + $ # Rename the current session. + , # Rename the current window. + + ! # Break the current pane out of the window. + % # Split the current pane into two, left and right. + " # Split the current pane into two, top and bottom. + + n # Change to the next window. + p # Change to the previous window. + { # Swap the current pane with the previous pane. + } # Swap the current pane with the next pane. + + s # Select a new session for the attached client interactively. + w # Choose the current window interactively. + 0 to 9 # Select windows 0 to 9. + + d # Detach the current client. + D # Choose a client to detach. + + & # Kill the current window. + x # Kill the current pane. + + Up, Down # Change to the pane above, below, left, or right. + Left, Right + + M-1 to M-5 # Arrange panes: + # 1) even-horizontal + # 2) even-vertical + # 3) main-horizontal + # 4) main-vertical + # 5) tiled. + + C-Up, C-Down # Resize the current pane in steps of one cell. + C-Left, C-Right + + M-Up, M-Down # Resize the current pane in steps of five cells. + M-Left, M-Right +``` + + +### Configuring ~/.tmux.conf + + tmux.conf can be used to set options automatically on start up, much +like how .vimrc or init.el are used. + +```bash +# Example tmux.conf +# http://dev.gentoo.org/~wired/conf/tmux.conf +# http://wiki.gentoo.org/wiki/Tmux +# https://wiki.archlinux.org/index.php/Tmux + +### Keybinds +########################################################################### + +## Prefix Adjustment +unbind-key C-b +set-option -g prefix ` +#set option -g prefix C-a + +bind-key C-a last-window +bind-key ` last-window +bind-key a send-prefix +bind-key F11 set-option -g prefix C-a +bind-key F12 set-option -g prefix ` + +## Index Start +set -g base-index 1 + +## Window Cycle/Swap +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + + +### Theme +########################################################################### + +## Statusbar Color Palatte +#set-option -g status-justify centre +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + + + +## Pane Border Color Palette +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + + +## Message Color Palette +set-option -g message-fg black +set-option -g message-bg green + + +#setw -g mode-bg black + + +## Window Status Color Palette +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +## Window Interface Adjustments +set-option -g status-utf8 on +setw -g mode-keys vi +setw -g mode-mouse on +setw -g monitor-activity on + +set-option -g mouse-select-pane on +set-option -g status-keys vi +set-option -g bell-action any +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) +set-option -g visual-bell off + + +## Statusbar Adjustments +set -g status-left ' #[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default] ' +set -g status-interval 5 +#set -g status-right ' #[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default] ' +set -g status-right ' #[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default] ' + + +### Misc +########################################################################### +set -g history-limit 4096 +bind r source-file ~/.tmux.conf ``` -- cgit v1.2.3 From 0846eaa0e71cdcd651edf1c58b459520be844567 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Fri, 5 Sep 2014 15:05:13 +0200 Subject: EDOUBLEDSPACE My *fake* ocd kicked in --- go.html.markdown | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index c85209e0..bedc3042 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -12,7 +12,7 @@ contributors: - ["Alexej Friesen", "https://github.com/heyalexej"] --- -Go was created out of the need to get work done. It's not the latest trend +Go was created out of the need to get work done. It's not the latest trend in computer science, but it is the newest fastest way to solve real-world problems. @@ -26,7 +26,7 @@ Go comes with a great standard library and an enthusiastic community. ```go // Single line comment /* Multi- - line comment */ + line comment */ // A package clause starts every source file. // Main is a special name declaring an executable rather than a library. @@ -41,8 +41,8 @@ import ( "strconv" // String conversions. ) -// A function definition. Main is special. It is the entry point for the -// executable program. Love it or hate it, Go uses brace brackets. +// A function definition. Main is special. It is the entry point for the +// executable program. Love it or hate it, Go uses brace brackets. func main() { // Println outputs a line to stdout. // Qualify it with the package name, fmt. @@ -77,7 +77,7 @@ func learnTypes() { s2 := `A "raw" string literal can include line breaks.` // Same string type. - // Non-ASCII literal. Go source is UTF-8. + // Non-ASCII literal. Go source is UTF-8. g := 'Σ' // rune type, an alias for int32, holds a unicode code point. f := 3.14195 // float64, an IEEE-754 64-bit floating point number. @@ -94,9 +94,9 @@ can include line breaks.` // Same string type. var a4 [4]int // An array of 4 ints, initialized to all 0. a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown. - // Slices have dynamic size. Arrays and slices each have advantages + // Slices have dynamic size. Arrays and slices each have advantages // but use cases for slices are much more common. - s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. + s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0. var d2 [][]float64 // Declaration only, nothing allocated here. bs := []byte("a slice") // Type conversion syntax. @@ -116,7 +116,7 @@ can include line breaks.` // Same string type. fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] p, q := learnMemory() // Declares p, q to be type pointer to int. - fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. // Maps are a dynamically growable associative array type, like the // hash or dictionary types of some other languages. @@ -142,7 +142,7 @@ func learnNamedReturns(x, y int) (z int) { return // z is implicit here, because we named it earlier. } -// Go is fully garbage collected. It has pointers but no pointer arithmetic. +// Go is fully garbage collected. It has pointers but no pointer arithmetic. // You can make a mistake with a nil pointer, but not by incrementing a pointer. func learnMemory() (p, q *int) { // Named return values p and q have type pointer to int. @@ -220,7 +220,7 @@ func learnFlowControl() { func(a, b int) int { return (a + b) * 2 }(10, 2)) // Called with args 10 and 2 - // => Add + double two numbers: 24 + // => Add + double two numbers: 24 // When you need it, you'll love it. goto love @@ -267,7 +267,7 @@ type pair struct { x, y int } -// Define a method on type pair. Pair now implements Stringer. +// Define a method on type pair. Pair now implements Stringer. func (p pair) String() string { // p is called the "receiver" // Sprintf is another public function in package fmt. // Dot syntax references fields of p. @@ -275,13 +275,13 @@ func (p pair) String() string { // p is called the "receiver" } func learnInterfaces() { - // Brace syntax is a "struct literal." It evaluates to an initialized - // struct. The := syntax declares and initializes p to this struct. + // Brace syntax is a "struct literal". It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. p := pair{3, 4} fmt.Println(p.String()) // Call String method of p, of type pair. var i Stringer // Declare i of interface type Stringer. i = p // Valid because pair implements Stringer - // Call String method of i, of type Stringer. Output same as above. + // Call String method of i, of type Stringer. Output same as above. fmt.Println(i.String()) // Functions in the fmt package call the String method to ask an object @@ -319,7 +319,7 @@ func learnErrorHandling() { // prints 'strconv.ParseInt: parsing "non-int": invalid syntax' fmt.Println(err) } - // We'll revisit interfaces a little later. Meanwhile, + // We'll revisit interfaces a little later. Meanwhile, learnConcurrency() } @@ -330,12 +330,12 @@ func inc(i int, c chan int) { // We'll use inc to increment some numbers concurrently. func learnConcurrency() { - // Same make function used earlier to make a slice. Make allocates and + // Same make function used earlier to make a slice. Make allocates and // initializes slices, maps, and channels. c := make(chan int) - // Start three concurrent goroutines. Numbers will be incremented + // Start three concurrent goroutines. Numbers will be incremented // concurrently, perhaps in parallel if the machine is capable and - // properly configured. All three send to the same channel. + // properly configured. All three send to the same channel. go inc(0, c) // go is a statement that starts a new goroutine. go inc(10, c) go inc(-805, c) @@ -348,7 +348,7 @@ func learnConcurrency() { go func() { c <- 84 }() // Start a new goroutine just to send a value. go func() { cs <- "wordy" }() // Again, for cs this time. // Select has syntax like a switch statement but each case involves - // a channel operation. It selects a case at random out of the cases + // a channel operation. It selects a case at random out of the cases // that are ready to communicate. select { case i := <-c: // The value received can be assigned to a variable, @@ -358,7 +358,7 @@ func learnConcurrency() { case <-ccs: // Empty channel, not ready for communication. fmt.Println("didn't happen.") } - // At this point a value was taken from either c or cs. One of the two + // At this point a value was taken from either c or cs. One of the two // goroutines started above has completed, the other will remain blocked. learnWebProgramming() // Go does it. You want to do it too. @@ -397,15 +397,15 @@ func requestServer() { The root of all things Go is the [official Go web site](http://golang.org/). There you can follow the tutorial, play interactively, and read lots. -The language definition itself is highly recommended. It's easy to read +The language definition itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://play.golang.org](https://play.golang.org) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. On the reading list for students of Go is the [source code to the standard -library](http://golang.org/src/pkg/). Comprehensively documented, it +library](http://golang.org/src/pkg/). Comprehensively documented, it demonstrates the best of readable and understandable Go, Go style, and Go -idioms. Or you can click on a function name in [the +idioms. Or you can click on a function name in [the documentation](http://golang.org/pkg/) and the source code comes up! Another great resource to learn Go is [Go by example](https://gobyexample.com/). -- cgit v1.2.3 From c040acba1a8c389d1e4da7332eb4ba2cc58d7edb Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 5 Sep 2014 22:56:25 +0200 Subject: Added compojure --- compojure.html.markdown | 225 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 225 insertions(+) create mode 100644 compojure.html.markdown diff --git a/compojure.html.markdown b/compojure.html.markdown new file mode 100644 index 00000000..56f43cb7 --- /dev/null +++ b/compojure.html.markdown @@ -0,0 +1,225 @@ +--- +category: tool +tool: compojure +contributors: + - ["Adam Bard", "http://adambard.com/"] +filename: learncompojure.clj +--- + +## Getting Started with Compojure + +Compojure is a DSL for *quickly* creating *performant* web applications +in Clojure with minimal effort: + +```clojure +(ns myapp.core + (:require [compojure.core :refer :all] + [org.httpkit.server :refer [run-server]])) ; httpkit is a server + +(defroutes myapp + (GET "/" [] "Hello World")) + +(defn -main [] + (run-server myapp {:port 5000})) +``` + +Create a project with [Leiningen](http://leiningen.org/): + +``` +lein new myapp +``` + +Add your dependencies: + +``` +[compojure "1.1.8"] +[http-kit "2.1.16"] +``` + +And run: + +``` +lein run -m myapp.core +``` + +View at: + +Compojure apps will run on any ring-compatible server, but we recommend +[http-kit](http://http-kit.org/) for its performance and +[massive concurrency](http://http-kit.org/600k-concurrent-connection-http-kit.html). + +### Routes + +In compojure, each route is an HTTP method paired with a URL-matching pattern, +an argument list, and a body. + +```clojure +(defroutes myapp + (GET "/" [] "Show something") + (POST "/" [] "Create something") + (PUT "/" [] "Replace something") + (PATCH "/" [] "Modify Something") + (DELETE "/" [] "Annihilate something") + (OPTIONS "/" [] "Appease something") + (HEAD "/" [] "Preview something")) +``` + +Compojure route definitions are just functions which +[accept request maps and return response maps](https://github.com/mmcgrana/ring/blob/master/SPEC): + +```clojure +(myapp {:uri "/" :request-method :post}) +; => {:status 200 +; :headers {"Content-Type" "text/html; charset=utf-8} +; :body "Create Something"} +``` + +The body may be a function, which must accept the request as a parameter: + +```clojure +(defroutes myapp + (GET "/" [] (fn [req] "Do something with req"))) +``` + +Route patterns may include named parameters, + +```clojure +(defroutes myapp + (GET "/hello/:name" [name] (str "Hello " name))) +``` + +You can match entire paths with * + +```clojure +(defroutes myapp + (GET "/file/*.*" [*] (str *))) +``` + +Handlers may utilize query parameters: + +```clojure +(defroutes myapp + (GET "/posts" [] + (fn [req] + (let [title (get (:params req) "title") + author (get (:params req) "title")] + " Do something with title and author")))) +``` + +Or, for POST and PUT requests, form parameters + +```clojure +(defroutes myapp + (POST "/posts" [] + (fn [req] + (let [title (get (:params req) "title") + author (get (:params req) "title")] + "Do something with title and author")))) +``` + + +### Return values + +The return value of a route block determines at least the response body +passed on to the HTTP client, or at least the next middleware in the +ring stack. Most commonly, this is a string, as in the above examples. +But, you may also return a [response body](https://github.com/mmcgrana/ring/blob/master/SPEC): + +```clojure +(defroutes myapp + (GET "/" [] + {:status 200 :body "Hello World"}) + (GET "/is-403" [] + {:status 403 :body ""}) + (GET "/is-json" [] + {:status 200 :headers {"Content-Type" "application/json"} :body "{}"})) +``` + +### Static Files + +To serve up static files, use `compojure.route.resources`. +Resources will be served from your project's `resources/` folder. + +```clojure +(require '[compojure.route :as route]) + +(defroutes myapp + (GET "/") + (route/resources "/")) ; Serve static resources at the root path + +(myapp {:uri "/js/script.js" :request-method :get}) +; => Contents of resources/public/js/script.js +``` + +### Views / Templates + +To use templating with Compojure, you'll need a template library. Here are a few: + +#### [Stencil](https://github.com/davidsantiago/stencil) + +[Stencil](https://github.com/davidsantiago/stencil) is a [Mustache](http://mustache.github.com/) template library: + +```clojure +(require '[stencil.core :refer [render-string]]) + +(defroutes myapp + (GET "/hello/:name" [name] + (render-string "Hello {{name}}" {:name name}))) +``` + +You can easily read in templates from your resources directory. Here's a helper function + +```clojure +(require 'clojure.java.io) + +(defn read-template [filename] + (slurp (clojure.java.io/resource filename))) + +(defroutes myapp + (GET "/hello/:name" [name] + (render-string (read-template "templates/hello.html") {:name name}))) +``` + +#### [Selmer](https://github.com/yogthos/Selmer) + +[Selmer](https://github.com/yogthos/Selmer) is a Django and Jinja2-inspired templating language: + +```clojure +(require '[selmer.parser :refer [render-file]]) + +(defroutes myapp + (GET "/hello/:name" [name] + (render-file "templates/hello.html" {:name name}))) +``` + +#### [Hiccup](https://github.com/weavejester/hiccup) + +[Hiccup](https://github.com/weavejester/hiccup) is a library for representing HTML as Clojure code + +```clojure +(require '[hiccup.core :as hiccup]) + +(defroutes myapp + (GET "/hello/:name" [name] + (hiccup/html + [:html + [:body + [:h1 {:class "title"} + (str "Hello " name)]]]))) +``` + +#### [Markdown](https://github.com/yogthos/markdown-clj) + +[Markdown-clj](https://github.com/yogthos/markdown-clj) is a Markdown implementation. + +```clojure +(require '[markdown.core :refer [md-to-html-string]]) + +(defroutes myapp + (GET "/hello/:name" [name] + (md-to-html-string "## Hello, world"))) +``` + +Further reading: + +[Clojure for the Brave and True](http://www.braveclojure.com/) -- cgit v1.2.3 From fc84512fa651d89b0e6acbd248e0b078706e7268 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 5 Sep 2014 22:58:40 +0200 Subject: Fix learntmux --- LearnTmux.txt | 71 ------------------------------------------------- learntmux.html.markdown | 71 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 71 deletions(-) delete mode 100644 LearnTmux.txt create mode 100644 learntmux.html.markdown diff --git a/LearnTmux.txt b/LearnTmux.txt deleted file mode 100644 index eaf3fd25..00000000 --- a/LearnTmux.txt +++ /dev/null @@ -1,71 +0,0 @@ ---- -category: tool -tool: tmux -contributors: - - ["kaernyk", "http://github.com/kaernyk"] -filename: LearnTmux.txt ---- - - - tmux is a terminal multiplexer: it enables a number of terminals to be -created, accessed, and controlled from a single screen. tmux may be detached -from a screen and continue running in the background, then later reattached. - - Once you feel comfortable manipulating tmux to suit your needs, I strongly -suggest you read the man pages. - - - -``` -# Session Management - - tmux new Create new session - -s "Session" Create named session - -n "Window" Create named Window - -c "/dir" Start in target directory - - C^b $ Rename current session - C^b d Detach current session - C^b D Select session to detach - - tmux attach Attach last/available session - -t "#" Attach target session - -d Detach the session from other instances - - tmux ls List open sessions - C^b s Select new session for attached client interactively - - kill-session Kill current session - -t "#" Kill target session - -a Kill all sessions - -a -t "#" Kill all sessions but the target - - -# Window Management - - C^b c Create another window - C^b " Split Horizontally - C^b % Split Vertically - C^b M-(1-5) 1) Tile vertically - 2) Tile horizontally - 3) Tile Vertically /w large horizontal - 4) Tile horizontally /w large vertical - 5) Tile all windows evenly - - C^b q Briefly display pane indexes - C^# Choose current window by # - C^b w Choose current window interactively - C^b n Change to next window - C^b p Change to previous window - C^b Up, Right Change to pane in selected direction - Down, left - C^b { Swap current/previous window - C^b } Swap current/next window - - C^b C-Up, Right Resize in steps of one cell - Down, left - C^b M-Up, Right resize in steps of five cells - Down, left - - exit or C^b x Kill the current window -``` diff --git a/learntmux.html.markdown b/learntmux.html.markdown new file mode 100644 index 00000000..eaf3fd25 --- /dev/null +++ b/learntmux.html.markdown @@ -0,0 +1,71 @@ +--- +category: tool +tool: tmux +contributors: + - ["kaernyk", "http://github.com/kaernyk"] +filename: LearnTmux.txt +--- + + + tmux is a terminal multiplexer: it enables a number of terminals to be +created, accessed, and controlled from a single screen. tmux may be detached +from a screen and continue running in the background, then later reattached. + + Once you feel comfortable manipulating tmux to suit your needs, I strongly +suggest you read the man pages. + + + +``` +# Session Management + + tmux new Create new session + -s "Session" Create named session + -n "Window" Create named Window + -c "/dir" Start in target directory + + C^b $ Rename current session + C^b d Detach current session + C^b D Select session to detach + + tmux attach Attach last/available session + -t "#" Attach target session + -d Detach the session from other instances + + tmux ls List open sessions + C^b s Select new session for attached client interactively + + kill-session Kill current session + -t "#" Kill target session + -a Kill all sessions + -a -t "#" Kill all sessions but the target + + +# Window Management + + C^b c Create another window + C^b " Split Horizontally + C^b % Split Vertically + C^b M-(1-5) 1) Tile vertically + 2) Tile horizontally + 3) Tile Vertically /w large horizontal + 4) Tile horizontally /w large vertical + 5) Tile all windows evenly + + C^b q Briefly display pane indexes + C^# Choose current window by # + C^b w Choose current window interactively + C^b n Change to next window + C^b p Change to previous window + C^b Up, Right Change to pane in selected direction + Down, left + C^b { Swap current/previous window + C^b } Swap current/next window + + C^b C-Up, Right Resize in steps of one cell + Down, left + C^b M-Up, Right resize in steps of five cells + Down, left + + exit or C^b x Kill the current window +``` -- cgit v1.2.3 From cd7ed4f9f9590f82acf953bba8d6032e1f62fa0c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 5 Sep 2014 20:47:18 -0500 Subject: Couple changes to C to close https://github.com/adambard/learnxinyminutes-docs/pull/594 --- c.html.markdown | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 79b7aec7..cbb6d289 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -4,6 +4,7 @@ filename: learnc.c contributors: - ["Adam Bard", "http://adambard.com/"] - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] + - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] --- @@ -175,6 +176,9 @@ int main() { i2 * i1; // => 2 i1 / i2; // => 0 (0.5, but truncated towards 0) + // You need to cast at least one integer to float to get a floating-point result + (float)i1 / i2 // => 0.5f + i1 / (double)i2 // => 0.5 // Same with double f1 / f2; // => 0.5, plus or minus epsilon // Floating-point numbers and calculations are not exact @@ -194,9 +198,11 @@ int main() { 2 >= 2; // => 1 // C is not Python - comparisons don't chain. - // WRONG: - //int between_0_and_2 = 0 < a < 2; - // Correct: + // Warning: The line below will compile, but it means `(0 < a) < 2`. + // This expression is always true, because (0 < a) could be either 1 or 0. + // In this case it's 1, because (0 < 1). + int between_0_and_2 = 0 < a < 2; + // Instead use: int between_0_and_2 = 0 < a && a < 2; // Logic works on ints -- cgit v1.2.3 From 64c1ee391f4e03f363fd829ce658fc881bcffb6f Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 5 Sep 2014 20:48:42 -0500 Subject: Add lua-cn filename to close https://github.com/adambard/learnxinyminutes-docs/pull/610/files --- zh-cn/lua-cn.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 95a94c76..3ba098ec 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -9,6 +9,7 @@ contributors: - ["Amr Tamimi", "https://amrtamimi.com"] translators: - ["Jakukyo Friel", "http://weakish.github.io"] +filename: lua-cn.lua --- ```lua -- cgit v1.2.3 From eefa3add633ef1e80fb7403eec7854da1077188b Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 5 Sep 2014 20:51:48 -0500 Subject: Add traditional for loop bash example to close https://github.com/adambard/learnxinyminutes-docs/pull/654 --- bash.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 57fb5c55..dc7d32b6 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Denis Arh", "https://github.com/darh"] - ["akirahirose", "https://twitter.com/akirahirose"] - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] filename: LearnBash.sh --- @@ -140,6 +141,12 @@ do echo "$VARIABLE" done +# Or write it the "traditional for loop" way: +for ((a=1; a <= 3; a++)) +do + echo $a +done + # They can also be used to act on files.. # This will run the command 'cat' on file1 and file2 for VARIABLE in file1 file2 -- cgit v1.2.3 From b35ccf01af17b52447c98d7101ee932e7f089c52 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 5 Sep 2014 20:59:37 -0500 Subject: Add FZSS's GitHub profile link to close https://github.com/adambard/learnxinyminutes-docs/pull/666 --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 975ebcb5..f1166a04 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -3,7 +3,7 @@ language: Markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - - ["Fangzhou Chen"] + - ["Fangzhou Chen","https://github.com/FZSS"] filename: learnmarkdown-cn.md lang: zh-cn --- -- cgit v1.2.3 From 291f6f6b22acf7962a180e6e12234aebcb20c5bd Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 5 Sep 2014 21:02:38 -0500 Subject: Fix "initialized" typo. --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 758c9ff4..b4c6afff 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -92,7 +92,7 @@ can include line breaks.` // Same string type. // Arrays have size fixed at compile time. var a4 [4]int // An array of 4 ints, initialized to all 0. - a3 := [...]int{3, 1, 5} // An array initialzed with a fixed size of three + a3 := [...]int{3, 1, 5} // An array initialized with a fixed size of three // elements, with values 3, 1, and 5. // Slices have dynamic size. Arrays and slices each have advantages -- cgit v1.2.3 From e97b3d6a0ff0715b18ac1f0195a064759002975d Mon Sep 17 00:00:00 2001 From: kaernyk Date: Fri, 5 Sep 2014 22:06:10 -0400 Subject: Update and rename learntmux.html.markdown to tmux.html.markdown Fixed some spelling, grammar, and punctuation issues Line 48: Added additional items to the list of keybinds for power users Line 104: Created section on configuring ~/.tmux.conf & added additional comments Line 203: Added section including external resources --- learntmux.html.markdown | 71 ---------------- tmux.html.markdown | 209 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 209 insertions(+), 71 deletions(-) delete mode 100644 learntmux.html.markdown create mode 100644 tmux.html.markdown diff --git a/learntmux.html.markdown b/learntmux.html.markdown deleted file mode 100644 index eaf3fd25..00000000 --- a/learntmux.html.markdown +++ /dev/null @@ -1,71 +0,0 @@ ---- -category: tool -tool: tmux -contributors: - - ["kaernyk", "http://github.com/kaernyk"] -filename: LearnTmux.txt ---- - - - tmux is a terminal multiplexer: it enables a number of terminals to be -created, accessed, and controlled from a single screen. tmux may be detached -from a screen and continue running in the background, then later reattached. - - Once you feel comfortable manipulating tmux to suit your needs, I strongly -suggest you read the man pages. - - - -``` -# Session Management - - tmux new Create new session - -s "Session" Create named session - -n "Window" Create named Window - -c "/dir" Start in target directory - - C^b $ Rename current session - C^b d Detach current session - C^b D Select session to detach - - tmux attach Attach last/available session - -t "#" Attach target session - -d Detach the session from other instances - - tmux ls List open sessions - C^b s Select new session for attached client interactively - - kill-session Kill current session - -t "#" Kill target session - -a Kill all sessions - -a -t "#" Kill all sessions but the target - - -# Window Management - - C^b c Create another window - C^b " Split Horizontally - C^b % Split Vertically - C^b M-(1-5) 1) Tile vertically - 2) Tile horizontally - 3) Tile Vertically /w large horizontal - 4) Tile horizontally /w large vertical - 5) Tile all windows evenly - - C^b q Briefly display pane indexes - C^# Choose current window by # - C^b w Choose current window interactively - C^b n Change to next window - C^b p Change to previous window - C^b Up, Right Change to pane in selected direction - Down, left - C^b { Swap current/previous window - C^b } Swap current/next window - - C^b C-Up, Right Resize in steps of one cell - Down, left - C^b M-Up, Right resize in steps of five cells - Down, left - - exit or C^b x Kill the current window -``` diff --git a/tmux.html.markdown b/tmux.html.markdown new file mode 100644 index 00000000..53606bbe --- /dev/null +++ b/tmux.html.markdown @@ -0,0 +1,209 @@ +--- +category: tool +tool: tmux +contributors: + - ["kaernyk", "http://github.com/kaernyk"] +filename: LearnTmux.txt +--- + + + +tmux is a terminal multiplexer: it enables a number of terminals to be +created, accessed, and controlled from a single screen. tmux may be detached +from a screen and continue running in the background, then later reattached. + +```bash +# We’ll start off with managing tmux from a terminal: + + tmux | tmux new # Create an unamed session + -s "Session" # Create named session + -n "Window" # Create named Window + -c "/dir" # Start in target directory + + tmux attach # Attach last/available session + -t "#" # Attach target session + -d # Detach the session from other instances + + tmux ls # List open sessions + + kill-session # Kill current session + -t "#" # Kill target session + -a # Kill all sessions + -a -t "#" # Kill all sessions but the target + + + +## Key Bindings + +# The method of controlling an attached tmux session is fairly simple, but +# there are two keys we will see repeated throughout this write-up (as well as +# the man pages). + + (C-b) == Ctrl + b + +# This combination is the default prefix key that is to be used in conjunction +# with a keybind to produce the stated effect. + + +# The default keybinds are as follows: + + C-b # Send the prefix key (C-b) through to the application. + C-o # Rotate the panes in the current window forwards. + C-z # Suspend the tmux client. + ? # List all key bindings. + : # Enter the tmux command prompt. + r # Force redraw of the attached client. + + c # Create a new window. + $ # Rename the current session. + , # Rename the current window. + + ! # Break the current pane out of the window. + % # Split the current pane into two, left and right. + " # Split the current pane into two, top and bottom. + + n # Change to the next window. + p # Change to the previous window. + { # Swap the current pane with the previous pane. + } # Swap the current pane with the next pane. + + s # Select a new session for the attached client interactively. + w # Choose the current window interactively. + 0 to 9 # Select windows 0 to 9. + + d # Detach the current client. + D # Choose a client to detach. + + & # Kill the current window. + x # Kill the current pane. + + Up, Down # Change to the pane above, below, left, or right. + Left, Right + + M-1 to M-5 # Arrange panes: + # 1) even-horizontal + # 2) even-vertical + # 3) main-horizontal + # 4) main-vertical + # 5) tiled. + + C-Up, C-Down # Resize the current pane in steps of one cell. + C-Left, C-Right + + M-Up, M-Down # Resize the current pane in steps of five cells. + M-Left, M-Right +``` + + +### Configuring ~/.tmux.conf + + tmux.conf can be used to set options automatically on start up, much +like how .vimrc or init.el are used. + +```bash +# Example tmux.conf +# 2014.9 + +### Keybinds +########################################################################### + +## Prefix Adjustment + +# Unbind C-b as the default prefix +unbind-key C-b + +# Set ` as the default prefix +set-option -g prefix ` +#set option -g prefix C-a + +# Return to previous window when prefix is pressed twice +bind-key C-a last-window +bind-key ` last-window +bind-key a send-prefix + +# Allow swapping C-a and ` using F11/F12 +bind-key F11 set-option -g prefix C-a +bind-key F12 set-option -g prefix ` + +## Index Start +set -g base-index 1 + +## Window Cycle/Swap +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + + +### Theme +########################################################################### + +## Statusbar Color Palatte +#set-option -g status-justify centre +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +## Pane Border Color Palette +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +## Message Color Palette +set-option -g message-fg black +set-option -g message-bg green + +#setw -g mode-bg black + +## Window Status Color Palette +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +## Window Interface Adjustments +set-option -g status-utf8 on +setw -g mode-keys vi +setw -g mode-mouse on +setw -g monitor-activity on + +set-option -g mouse-select-pane on +set-option -g status-keys vi +set-option -g bell-action any +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) +set-option -g visual-bell off + +## Statusbar Adjustments +set -g status-left ' #[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default] ' +set -g status-interval 5 +#set -g status-right ' #[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default] ' + +## Show performance counters in statusbar +#set -g status-right ' #[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default] ' + + +### Misc +########################################################################### +set -g history-limit 4096 +bind r source-file ~/.tmux.conf +``` + +### External Resources + +Tmux | Home
+Manual page
+Display CPU/MEM % in statusbar
+Archlinux Wiki
+Gentoo Wiki
-- cgit v1.2.3 From 29581e5c1307e43f752e08b6fdd66cde54448424 Mon Sep 17 00:00:00 2001 From: kaernyk Date: Fri, 5 Sep 2014 23:11:58 -0400 Subject: Update tmux.html.markdown Corrected page structure/style to conform to other tutorials ``` Line 18: Removed "tmux" as it has other purposes as well as quickly starting a blank session that will not be covered Line 45: Added Meta/Alt explanation Line 126: Moved 'bind-key C-a send-prefix" to the group that requires it Line 184: Added comment Line 186: Added comment pointing to resource required (if enabled) - Removed 'set-option -g status-justify centre' ``` --- tmux.html.markdown | 200 ++++++++++++++++++++++++++--------------------------- 1 file changed, 97 insertions(+), 103 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 53606bbe..7127d3b9 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -12,10 +12,11 @@ tmux is a terminal multiplexer: it enables a number of terminals to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached. + ```bash # We’ll start off with managing tmux from a terminal: - tmux | tmux new # Create an unamed session + tmux new # Create a new session -s "Session" # Create named session -n "Window" # Create named Window -c "/dir" # Start in target directory @@ -40,9 +41,10 @@ from a screen and continue running in the background, then later reattached. # the man pages). (C-b) == Ctrl + b - -# This combination is the default prefix key that is to be used in conjunction -# with a keybind to produce the stated effect. + + (M-1) == Alt + b + -or- + Meta + b # The default keybinds are as follows: @@ -92,7 +94,6 @@ from a screen and continue running in the background, then later reattached. M-Up, M-Down # Resize the current pane in steps of five cells. M-Left, M-Right -``` ### Configuring ~/.tmux.conf @@ -100,104 +101,97 @@ from a screen and continue running in the background, then later reattached. tmux.conf can be used to set options automatically on start up, much like how .vimrc or init.el are used. -```bash -# Example tmux.conf -# 2014.9 - -### Keybinds -########################################################################### - -## Prefix Adjustment - -# Unbind C-b as the default prefix -unbind-key C-b - -# Set ` as the default prefix -set-option -g prefix ` -#set option -g prefix C-a - -# Return to previous window when prefix is pressed twice -bind-key C-a last-window -bind-key ` last-window -bind-key a send-prefix - -# Allow swapping C-a and ` using F11/F12 -bind-key F11 set-option -g prefix C-a -bind-key F12 set-option -g prefix ` - -## Index Start -set -g base-index 1 - -## Window Cycle/Swap -bind e previous-window -bind f next-window -bind E swap-window -t -1 -bind F swap-window -t +1 - - -### Theme -########################################################################### - -## Statusbar Color Palatte -#set-option -g status-justify centre -set-option -g status-justify left -set-option -g status-bg black -set-option -g status-fg white -set-option -g status-left-length 40 -set-option -g status-right-length 80 - -## Pane Border Color Palette -set-option -g pane-active-border-fg green -set-option -g pane-active-border-bg black -set-option -g pane-border-fg white -set-option -g pane-border-bg black - -## Message Color Palette -set-option -g message-fg black -set-option -g message-bg green - -#setw -g mode-bg black - -## Window Status Color Palette -setw -g window-status-bg black -setw -g window-status-current-fg green -setw -g window-status-bell-attr default -setw -g window-status-bell-fg red -setw -g window-status-content-attr default -setw -g window-status-content-fg yellow -setw -g window-status-activity-attr default -setw -g window-status-activity-fg yellow - - -### UI -########################################################################### - -## Window Interface Adjustments -set-option -g status-utf8 on -setw -g mode-keys vi -setw -g mode-mouse on -setw -g monitor-activity on - -set-option -g mouse-select-pane on -set-option -g status-keys vi -set-option -g bell-action any -set-option -g set-titles on -set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) -set-option -g visual-bell off - -## Statusbar Adjustments -set -g status-left ' #[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default] ' -set -g status-interval 5 -#set -g status-right ' #[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default] ' - -## Show performance counters in statusbar -#set -g status-right ' #[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default] ' - - -### Misc -########################################################################### -set -g history-limit 4096 -bind r source-file ~/.tmux.conf +``` + # Example tmux.conf + # 2014.9 + + ## Prefix Adjustment + + # Unbind C-b as the default prefix + unbind-key C-b + + # Set ` as the default prefix + set-option -g prefix ` + + # Set C-a as the default prefix + #set option -g prefix C-a + + # Return to previous window when prefix is pressed twice + bind-key C-a last-window + bind-key ` last-window + + # Allow swapping C-a and ` using F11/F12 + bind-key F11 set-option -g prefix C-a + bind-key F12 set-option -g prefix ` + bind-key C-a send-prefix + + ## Index Start + set -g base-index 1 + + ## Window Cycle/Swap + bind e previous-window + bind f next-window + bind E swap-window -t -1 + bind F swap-window -t +1 + + ## Statusbar Color Palatte + set-option -g status-justify left + set-option -g status-bg black + set-option -g status-fg white + set-option -g status-left-length 40 + set-option -g status-right-length 80 + + ## Pane Border Color Palette + set-option -g pane-active-border-fg green + set-option -g pane-active-border-bg black + set-option -g pane-border-fg white + set-option -g pane-border-bg black + + ## Message Color Palette + set-option -g message-fg black + set-option -g message-bg green + + #setw -g mode-bg black + + ## Window Status Color Palette + setw -g window-status-bg black + setw -g window-status-current-fg green + setw -g window-status-bell-attr default + setw -g window-status-bell-fg red + setw -g window-status-content-attr default + setw -g window-status-content-fg yellow + setw -g window-status-activity-attr default + setw -g window-status-activity-fg yellow + + ## Window Interface Adjustments + set-option -g status-utf8 on + setw -g mode-keys vi + setw -g mode-mouse on + setw -g monitor-activity on + + set-option -g mouse-select-pane on + set-option -g status-keys vi + set-option -g bell-action any + set-option -g set-titles on + set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + set-option -g visual-bell off + + ## Statusbar Adjustments + set -g status-left ' #[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default] ' + set -g status-interval 5 + + # Statusbar with right-aligned Date / Time + set -g status-right ' #[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default] ' + + ## Show performance counters in statusbar + # Requires https://github.com/thewtex/tmux-mem-cpu-load/ + #set -g status-right ' #[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default] ' + + ## Scrollback/History limit + set -g history-limit 4096 + + bind r source-file ~/.tmux.conf +``` ``` ### External Resources -- cgit v1.2.3 From 408a4689f240e15d2b7e7517949d7c5682da6e8a Mon Sep 17 00:00:00 2001 From: kaernyk Date: Fri, 5 Sep 2014 23:20:51 -0400 Subject: fix code block example tmux.conf was not nested as I previously thought. I combined the blocks and fixed the issue --- tmux.html.markdown | 183 +++++++++++++++++++++++++++-------------------------- 1 file changed, 92 insertions(+), 91 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 7127d3b9..b9257edc 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -96,102 +96,103 @@ from a screen and continue running in the background, then later reattached. M-Left, M-Right + + ### Configuring ~/.tmux.conf tmux.conf can be used to set options automatically on start up, much like how .vimrc or init.el are used. -``` - # Example tmux.conf - # 2014.9 - - ## Prefix Adjustment - - # Unbind C-b as the default prefix - unbind-key C-b - - # Set ` as the default prefix - set-option -g prefix ` - - # Set C-a as the default prefix - #set option -g prefix C-a - - # Return to previous window when prefix is pressed twice - bind-key C-a last-window - bind-key ` last-window - - # Allow swapping C-a and ` using F11/F12 - bind-key F11 set-option -g prefix C-a - bind-key F12 set-option -g prefix ` - bind-key C-a send-prefix - - ## Index Start - set -g base-index 1 - - ## Window Cycle/Swap - bind e previous-window - bind f next-window - bind E swap-window -t -1 - bind F swap-window -t +1 - - ## Statusbar Color Palatte - set-option -g status-justify left - set-option -g status-bg black - set-option -g status-fg white - set-option -g status-left-length 40 - set-option -g status-right-length 80 - - ## Pane Border Color Palette - set-option -g pane-active-border-fg green - set-option -g pane-active-border-bg black - set-option -g pane-border-fg white - set-option -g pane-border-bg black - - ## Message Color Palette - set-option -g message-fg black - set-option -g message-bg green - - #setw -g mode-bg black - - ## Window Status Color Palette - setw -g window-status-bg black - setw -g window-status-current-fg green - setw -g window-status-bell-attr default - setw -g window-status-bell-fg red - setw -g window-status-content-attr default - setw -g window-status-content-fg yellow - setw -g window-status-activity-attr default - setw -g window-status-activity-fg yellow - - ## Window Interface Adjustments - set-option -g status-utf8 on - setw -g mode-keys vi - setw -g mode-mouse on - setw -g monitor-activity on - - set-option -g mouse-select-pane on - set-option -g status-keys vi - set-option -g bell-action any - set-option -g set-titles on - set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) - set-option -g visual-bell off - - ## Statusbar Adjustments - set -g status-left ' #[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default] ' - set -g status-interval 5 - - # Statusbar with right-aligned Date / Time - set -g status-right ' #[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default] ' - - ## Show performance counters in statusbar - # Requires https://github.com/thewtex/tmux-mem-cpu-load/ - #set -g status-right ' #[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default] ' - - ## Scrollback/History limit - set -g history-limit 4096 - - bind r source-file ~/.tmux.conf -``` + +# Example tmux.conf +# 2014.9 + +## Prefix Adjustment + +# Unbind C-b as the default prefix +unbind-key C-b + +# Set ` as the default prefix +set-option -g prefix ` + +# Set C-a as the default prefix +#set option -g prefix C-a + +# Return to previous window when prefix is pressed twice +bind-key C-a last-window +bind-key ` last-window + +# Allow swapping C-a and ` using F11/F12 +bind-key F11 set-option -g prefix C-a +bind-key F12 set-option -g prefix ` +bind-key C-a send-prefix + +## Index Start +set -g base-index 1 + +## Window Cycle/Swap +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +## Statusbar Color Palatte +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +## Pane Border Color Palette +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +## Message Color Palette +set-option -g message-fg black +set-option -g message-bg green + +#setw -g mode-bg black + +## Window Status Color Palette +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + +## Window Interface Adjustments +set-option -g status-utf8 on +setw -g mode-keys vi +setw -g mode-mouse on +setw -g monitor-activity on + +set-option -g mouse-select-pane on +set-option -g status-keys vi +set-option -g bell-action any +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) +set-option -g visual-bell off + +## Statusbar Adjustments +set -g status-left ' #[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default] ' +set -g status-interval 5 + +# Statusbar with right-aligned Date / Time +set -g status-right ' #[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default] ' + +## Show performance counters in statusbar +# Requires https://github.com/thewtex/tmux-mem-cpu-load/ +#set -g status-right ' #[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default] ' + +## Scrollback/History limit +set -g history-limit 4096 + +bind r source-file ~/.tmux.conf ``` ### External Resources -- cgit v1.2.3 From 014262f5c62ae1904b5e70135aca8c56540abc78 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 6 Sep 2014 10:18:31 +0200 Subject: Updated compojure per weavejester's suggestions --- compojure.html.markdown | 60 ++++++++++++++++++++++++++++--------------------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/compojure.html.markdown b/compojure.html.markdown index 56f43cb7..1644dfb7 100644 --- a/compojure.html.markdown +++ b/compojure.html.markdown @@ -81,18 +81,26 @@ The body may be a function, which must accept the request as a parameter: (GET "/" [] (fn [req] "Do something with req"))) ``` -Route patterns may include named parameters, +Or, you can just use the request directly: + +```clojure +(defroutes myapp + (GET "/" req "Do something with req")) +``` + +Route patterns may include named parameters: ```clojure (defroutes myapp (GET "/hello/:name" [name] (str "Hello " name))) ``` -You can match entire paths with * +You can adjust what each parameter matches by supplying a regex: ```clojure (defroutes myapp - (GET "/file/*.*" [*] (str *))) + (GET ["/file/:name.:ext" :name #".*", :ext #".*"] [name ext] + (str "File: " name ext)) ``` Handlers may utilize query parameters: @@ -100,10 +108,10 @@ Handlers may utilize query parameters: ```clojure (defroutes myapp (GET "/posts" [] - (fn [req] - (let [title (get (:params req) "title") - author (get (:params req) "title")] - " Do something with title and author")))) + (fn [req] + (let [title (get (:params req) "title") + author (get (:params req) "title")] + " Do something with title and author")))) ``` Or, for POST and PUT requests, form parameters @@ -111,10 +119,10 @@ Or, for POST and PUT requests, form parameters ```clojure (defroutes myapp (POST "/posts" [] - (fn [req] - (let [title (get (:params req) "title") - author (get (:params req) "title")] - "Do something with title and author")))) + (fn [req] + (let [title (get (:params req) "title") + author (get (:params req) "title")] + "Do something with title and author")))) ``` @@ -123,16 +131,16 @@ Or, for POST and PUT requests, form parameters The return value of a route block determines at least the response body passed on to the HTTP client, or at least the next middleware in the ring stack. Most commonly, this is a string, as in the above examples. -But, you may also return a [response body](https://github.com/mmcgrana/ring/blob/master/SPEC): +But, you may also return a [response map](https://github.com/mmcgrana/ring/blob/master/SPEC): ```clojure (defroutes myapp (GET "/" [] - {:status 200 :body "Hello World"}) + {:status 200 :body "Hello World"}) (GET "/is-403" [] - {:status 403 :body ""}) + {:status 403 :body ""}) (GET "/is-json" [] - {:status 200 :headers {"Content-Type" "application/json"} :body "{}"})) + {:status 200 :headers {"Content-Type" "application/json"} :body "{}"})) ``` ### Static Files @@ -164,7 +172,7 @@ To use templating with Compojure, you'll need a template library. Here are a few (defroutes myapp (GET "/hello/:name" [name] - (render-string "Hello {{name}}" {:name name}))) + (render-string "Hello {{name}}" {:name name}))) ``` You can easily read in templates from your resources directory. Here's a helper function @@ -177,7 +185,7 @@ You can easily read in templates from your resources directory. Here's a helper (defroutes myapp (GET "/hello/:name" [name] - (render-string (read-template "templates/hello.html") {:name name}))) + (render-string (read-template "templates/hello.html") {:name name}))) ``` #### [Selmer](https://github.com/yogthos/Selmer) @@ -189,7 +197,7 @@ You can easily read in templates from your resources directory. Here's a helper (defroutes myapp (GET "/hello/:name" [name] - (render-file "templates/hello.html" {:name name}))) + (render-file "templates/hello.html" {:name name}))) ``` #### [Hiccup](https://github.com/weavejester/hiccup) @@ -201,11 +209,11 @@ You can easily read in templates from your resources directory. Here's a helper (defroutes myapp (GET "/hello/:name" [name] - (hiccup/html - [:html - [:body - [:h1 {:class "title"} - (str "Hello " name)]]]))) + (hiccup/html + [:html + [:body + [:h1 {:class "title"} + (str "Hello " name)]]]))) ``` #### [Markdown](https://github.com/yogthos/markdown-clj) @@ -217,9 +225,11 @@ You can easily read in templates from your resources directory. Here's a helper (defroutes myapp (GET "/hello/:name" [name] - (md-to-html-string "## Hello, world"))) + (md-to-html-string "## Hello, world"))) ``` Further reading: -[Clojure for the Brave and True](http://www.braveclojure.com/) +* [Official Compojure Documentation](https://github.com/weavejester/compojure/wiki) + +* [Clojure for the Brave and True](http://www.braveclojure.com/) -- cgit v1.2.3 From c0d8a18b08d114dd0142a09f6787c7221b423802 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 6 Sep 2014 10:28:58 +0200 Subject: Made beginning easier --- compojure.html.markdown | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/compojure.html.markdown b/compojure.html.markdown index 1644dfb7..96555273 100644 --- a/compojure.html.markdown +++ b/compojure.html.markdown @@ -23,20 +23,22 @@ in Clojure with minimal effort: (run-server myapp {:port 5000})) ``` -Create a project with [Leiningen](http://leiningen.org/): +**Step 1:** Create a project with [Leiningen](http://leiningen.org/): ``` lein new myapp ``` -Add your dependencies: +**Step 2:** Put the above code in `src/myapp/core.clj` + +**Step 3:** Add some dependencies to `project.clj`: ``` [compojure "1.1.8"] [http-kit "2.1.16"] ``` -And run: +**Step 4:** Run: ``` lein run -m myapp.core -- cgit v1.2.3 From 9a909d6a4a1083a97b54c50de2fb390e76f879c0 Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Sun, 7 Sep 2014 02:39:31 -0400 Subject: Added Boolean operators and lowered line lengths Added Bool operators and and or, and lowered some line lengths. Also shifted some notes above the code lines to keep with same style and help readability. Also added a note on list comprehension. Also added adding to dictionary. --- python3.html.markdown | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index f6babaff..c3e2ede5 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -61,6 +61,17 @@ False not True # => False not False # => True +# Boolean Operators +# Note "and" and "or" are case-sensitive +True and False #=> False +False or True #=> True + +# Note with ints +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False #only 1 == True #=> True + # Equality is == 1 == 1 # => True 2 == 1 # => False @@ -127,7 +138,8 @@ bool({}) #=> False # 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 +# No need to declare variables before assigning to them. +# Convention is to use lower_case_with_underscores some_var = 5 some_var # => 5 @@ -176,7 +188,8 @@ li[::-1] # => [3, 4, 2, 1] del li[2] # li is now [1, 2, 3] # You can add lists -li + other_li # => [1, 2, 3, 4, 5, 6] - Note: values for li and for other_li are not modified. +# 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] @@ -215,14 +228,17 @@ 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. -list(filled_dict.keys()) # => ["three", "two", "one"] +# 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. -list(filled_dict.values()) # => [3, 2, 1] # 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 @@ -242,6 +258,10 @@ filled_dict.get("four", 4) # => 4 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 @@ -458,6 +478,7 @@ 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] -- cgit v1.2.3 From 62f4c0de22452177d96ba24ce0cf8cce119af47b Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Sun, 7 Sep 2014 19:22:01 -0400 Subject: [python/en] Added Bool operators Bool operators --- python.html.markdown | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 9057dde2..6b2a40de 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -57,9 +57,17 @@ to Python 2.x. Look for another tour of Python 3 soon! # Enforce precedence with parentheses (1 + 3) * 2 # => 8 -# Boolean values are primitives -True -False +# Boolean Operators ++# Note "and" and "or" are case-sensitive ++True and False #=> False ++False or True #=> True ++ ++# Note with ints ++0 and 2 #=> 0 ++-5 or 0 #=> -5 ++0 == False #=> True ++2 == True #=> False +1 == True #=> True # negate with not not True # => False -- cgit v1.2.3 From 820eebcd3362841721a981f91695b64af8f50b94 Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Sun, 7 Sep 2014 19:23:07 -0400 Subject: [python3/en] Bool operators Bool operators --- python3.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index c3e2ede5..a94f4eae 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -66,11 +66,12 @@ not False # => True True and False #=> False False or True #=> True -# Note with ints +# Note using Bool operators with ints 0 and 2 #=> 0 -5 or 0 #=> -5 0 == False #=> True -2 == True #=> False #only 1 == True #=> True +2 == True #=> False +1 == True #=> True # Equality is == 1 == 1 # => True -- cgit v1.2.3 From 81b4f49e999a6ec41bd1f79d77208d2db0a29871 Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Sun, 7 Sep 2014 19:32:46 -0400 Subject: [python/en] Added Bool operators Modified Bool operators --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 6b2a40de..390c7b76 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -62,7 +62,7 @@ to Python 2.x. Look for another tour of Python 3 soon! +True and False #=> False +False or True #=> True + -+# Note with ints ++# Note using Bool operators with ints +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True -- cgit v1.2.3 From eab554a7a7f2869ff7dac9f54acce9a7ed55cfa4 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 8 Sep 2014 13:08:28 +0200 Subject: Review docs for added rouge lexers and update those with new highlighters --- coffeescript.html.markdown | 2 +- common-lisp.html.markdown | 2 +- es-es/markdown-es.html.markdown | 2 +- fr-fr/objective-c-fr.html.markdown | 2 +- ja-jp/r-jp.html.markdown | 4 ++-- markdown.html.markdown | 2 +- objective-c.html.markdown | 2 +- pt-br/markdown-pt.html.markdown | 2 +- r.html.markdown | 2 +- ru-ru/objective-c-ru.html.markdown | 2 +- scala.html.markdown | 2 +- swift.html.markdown | 2 +- tr-tr/objective-c-tr.html.markdown | 2 +- typescript.html.markdown | 2 +- vi-vn/objective-c-vi.html.markdown | 2 +- zh-cn/common-lisp-cn.html.markdown | 2 +- zh-cn/markdown-cn.html.markdown | 2 +- zh-cn/r-cn.html.markdown | 2 +- zh-cn/scala-cn.html.markdown | 2 +- zh-cn/swift-cn.html.markdown | 2 +- 20 files changed, 21 insertions(+), 21 deletions(-) diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index d96eed39..6af692b9 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -11,7 +11,7 @@ As one of the succeeders of JavaScript, CoffeeScript tries its best to output re See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript. -``` coffeescript +```coffeescript # CoffeeScript is a hipster language. # It goes with the trends of many modern languages. # So comments are like Ruby and Python, they use number symbols. diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 8de81549..08134e35 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -17,7 +17,7 @@ Another popular and recent book is -```scheme +```common_lisp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; 0. Syntax diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index 3865126c..d90e3eb5 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -14,7 +14,7 @@ fácilmente a HTML (y, actualmente, otros formatos también). ¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! -``` +```markdown - + *This text is in italics.* _And so is this text._ @@ -52,7 +52,7 @@ __And so is this text.__ *__And this!__* +Github, we also have strikethrough: --> ~~This text is rendered with strikethrough.~~ @@ -201,11 +201,11 @@ can be anything so long as they are unique. --> -![This is hover-text (alt text) for my image](http://imgur.com/myimage.jpg "An optional title") +![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") -![This is the hover-text.][myimage] +![This is the alt-attribute.][myimage] [myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" -- cgit v1.2.3 From 9e76a70a6edd5ca3c33213730acdb795881ea422 Mon Sep 17 00:00:00 2001 From: kaernyk Date: Wed, 10 Sep 2014 12:42:05 -0400 Subject: Improve formatting I noticed that quite a bit of the text was not wrapped appropriately and was ruining the display. I have since reduced all lines possible to wrap at/before 72 columns --- tmux.html.markdown | 81 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 42 insertions(+), 39 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 516bee4d..8d7aa752 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -8,14 +8,16 @@ filename: LearnTmux.txt -tmux is a terminal multiplexer: it enables a number of terminals to be -created, accessed, and controlled from a single screen. tmux may be detached -from a screen and continue running in the background, then later reattached. +tmux is a terminal multiplexer: it enables a number of terminals +to be created, accessed, and controlled from a single screen. tmux +may be detached from a screen and continue running in the background +then later reattached. ``` tmux [command] # Run a command - # 'tmux' with no commands will create a new session + # 'tmux' with no commands will create a new + session new # Create a new session -s "Session" # Create named session @@ -52,42 +54,41 @@ from a screen and continue running in the background, then later reattached. ## Key Bindings -# The method of controlling an attached tmux session is via key combinations -# called 'Prefix' keys. - ------------------------------------------------------------------------------- +# The method of controlling an attached tmux session is via key +# combinations called 'Prefix' keys. +---------------------------------------------------------------------- (C-b) = Ctrl + b # 'Prefix' combination required to use keybinds (M-1) = Meta + 1 -or- Alt + 1 +---------------------------------------------------------------------- ------------------------------------------------------------------------------- - - ? # List all key bindings. - : # Enter the tmux command prompt. - r # Force redraw of the attached client. - c # Create a new window. + ? # List all key bindings + : # Enter the tmux command prompt + r # Force redraw of the attached client + c # Create a new window ! # Break the current pane out of the window. - % # Split the current pane into two, left and right. - " # Split the current pane into two, top and bottom. + % # Split the current pane into two, left and right + " # Split the current pane into two, top and bottom - n # Change to the next window. - p # Change to the previous window. - { # Swap the current pane with the previous pane. - } # Swap the current pane with the next pane. + n # Change to the next window + p # Change to the previous window + { # Swap the current pane with the previous pane + } # Swap the current pane with the next pane - s # Select a new session for the attached client interactively. - w # Choose the current window interactively. - 0 to 9 # Select windows 0 to 9. + s # Select a new session for the attached client + interactively + w # Choose the current window interactively + 0 to 9 # Select windows 0 to 9 - d # Detach the current client. - D # Choose a client to detach. + d # Detach the current client + D # Choose a client to detach - & # Kill the current window. - x # Kill the current pane. + & # Kill the current window + x # Kill the current pane - Up, Down # Change to the pane above, below, left, or right. + Up, Down # Change to the pane above, below, left, or right Left, Right M-1 to M-5 # Arrange panes: @@ -95,12 +96,12 @@ from a screen and continue running in the background, then later reattached. # 2) even-vertical # 3) main-horizontal # 4) main-vertical - # 5) tiled. + # 5) tiled - C-Up, C-Down # Resize the current pane in steps of one cell. + C-Up, C-Down # Resize the current pane in steps of one cell C-Left, C-Right - M-Up, M-Down # Resize the current pane in steps of five cells. + M-Up, M-Down # Resize the current pane in steps of five cells M-Left, M-Right @@ -115,7 +116,7 @@ like how .vimrc or init.el are used. ### Keybinds -########################################################################### +###################################################################### # Unbind C-b as the default prefix unbind-key C-befix C-a @@ -155,7 +156,7 @@ bind l select-pane -R ### Theme -########################################################################### +##################################################################### # Statusbar Color Palette set-option -g status-justify left @@ -186,7 +187,7 @@ setw -g window-status-activity-fg yellow ### UI -########################################################################### +###################################################################### # Statusbar set-option -g status-utf8 on @@ -209,22 +210,24 @@ set -g mouse-select-window on # Automatically set window titles set-option -g set-titles on -set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# window number,program name,active (or not) +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # Statusbar Adjustments -set -g status-left '#[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default] ' +set -g status-left '#[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default]' set -g status-interval 3 # Statusbar with right-aligned Date / Time -#set -g status-right ' #[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default] ' +#set -g status-right '#[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default]' # Show performance counters in statusbar # Requires https://github.com/thewtex/tmux-mem-cpu-load/ -#set -g status-right ' #[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default] ' +#set -g status-right '#[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default]' ### Misc -########################################################################### +###################################################################### # Scrollback/History limit set -g history-limit 4096 -- cgit v1.2.3 From 34e239526d5a130167d3cd442eadeab2f08356b3 Mon Sep 17 00:00:00 2001 From: m90 Date: Wed, 10 Sep 2014 20:17:16 +0200 Subject: add german translation of markdown tutorial --- de-de/markdown-de.html.markdown | 254 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 254 insertions(+) create mode 100644 de-de/markdown-de.html.markdown diff --git a/de-de/markdown-de.html.markdown b/de-de/markdown-de.html.markdown new file mode 100644 index 00000000..bf07215e --- /dev/null +++ b/de-de/markdown-de.html.markdown @@ -0,0 +1,254 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators : + - ["Frederik Ring", "https://github.com/m90"] +filename: markdown-de.md +lang: de-de +--- + +Markdown wurde im Jahr 2004 von John Gruber kreiert. Ziel ist und war eine leicht +zu lesende und zu schreibende Syntax für jegliche Dokumente, die möglichst +reibungslos nach HTML (und anderen Formaten) konvertiert werden kann. + +```markdown + + + + + + +# Das ist eine

+## Das ist eine

+### Das ist eine

+#### Das ist eine

+##### Das ist eine

+###### Das ist eine
+ + +Das ist eine h1 +============= + +Das ist eine h2 +------------- + + + + +*Dieser Text ist kursiv.* +_Genau wie dieser._ + +**Dieser Text ist fett.** +__Genau wie dieser.__ + +***Dieser Text ist beides*** +**_Dieser auch!_** +*__Und dieser genau so!__* + + + +~~Dieser Text wird durchgestrichen dargestellt.~~ + + + +Das ist ein Absatz. Ich kann immer noch nicht glauben wie viel Spaß das macht !?! + +Jetzt bin ich schon bei Absatz 2. +Hier ist dann immer noch Absatz 2! + + +Jetzt ist das dann Nummer drei! + + + +Ich höre mit zwei Leerzeichen auf (markiere mich, und du siehst es). + +Über mir ist wohl ein
! + + + +> Das ist ein Zitat. Du kannst Zeilenumbrüche +> entweder manuell hinzufügen und ein `>` vor jeder Zeile einfügen, oder du kannst deine Zeilen einfach immer länger und länger werden lassen, die Umbrüche werden dann automatisch erzeugt. +> Solange sie mit einem `>` beginnen macht das keinen Unterschied. + +> Auch möglich ist den Text +>> mehrstufig einzurücken. +> Nicht schlecht, oder? + + + + +* Punkt auf der Liste +* Punkt auf der Liste +* Anderer Punkt auf der Liste + +oder + ++ Punkt auf der Liste ++ Punkt auf der Liste ++ Noch ein Punkt auf der Liste + +oder + +- Punkt auf der Liste +- Punkt auf der Liste +- Ein letzter Punkt auf der Liste + + + +1. Punkt eins +2. Punkt zwei +3. Punkt drei + + + +1. Punkt eins +1. Punkt zwei +1. Punkt drei + + + + +1. Punkt eins +2. Punkt zwei +3. Punkt drei + * Unterpunkt + * Unterpunkt +4. Punkt vier + + + + + Das ist Quellcode + Das hier auch + + + + my_array.each do |item| + puts item + end + + + +Hermann hatte nicht die leiseste Ahnung was dieses `go_to()` bedeuten könnte! + + + +\`\`\`ruby +def foobar + puts "Hallo Welt!" +end +\`\`\` + +<-- der obige Block muss nicht extra eingerückt werden, ausserdem fügt Github +Syntax-Highlighting für die nach dem ``` angegebene Sprache hinzu --> + + + + +*** +--- +- - - +**************** + + + + +[Klick mich!](http://test.de/) + + + +[Klick mich!](http://test.at/ "Link zu Test.at") + + + +[Zu meiner Musiksammlung](/music/). + + + +[Klick mich][link1] um mehr über mich herauszufinden! +[Hier kannst du auch mal draufklicken][foobar] wenn es dich interessiert. + +[link1]: http://test.de/ "Wahnsinn!" +[foobar]: http://foobar.ch/ "Erstaunlich!" + + + + + +[Das][] ist ein Link. + +[das]: http://dasisteinlink.at/ + + + + + + +![Das ist das alt-Attribut für mein Bild](http://imgur.com/myimage.jpg "Hier noch ein title-Attribut") + + + +![Das ist das alt-Attribut][meinbild] + +[meinbild]: relative/urls/gehen/auch.jpg "hier wäre noch Platz für einen title" + + + + + ist das selbe wie +[http://testwebseite.de/](http://testwebseite.de/) + + + + + + + +Ich würde *diesen Teil gerne mit Sternen umschliessen*, doch ohne daß er kursiv +wird. Also mache ich folgendes: \*Ich umschliesse diesen Text mit Sternen\*! + + + + +| Spalte1 | Spalte2 | Spalte3 | +| :----------- | :------: | ------------: | +| linksbündig | mittig | rechtsbündig | +| blah | blah | blah | + + + +Spalte1 | Spalte2 | Spalte3 +:-- | :-: | --: +Ganz schön häßlich | vielleicht doch lieber | wieder aufhören + + + +``` + +Mehr Informationen gibt es in [John Gruber's offiziellem Blog-Post](http://daringfireball.net/projects/markdown/syntax) +und bei Adam Pritchards [grandiosem Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). +Infos zu Github Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown). \ No newline at end of file -- cgit v1.2.3 From a05547486450bb8918bce322da2c2a8402989ba2 Mon Sep 17 00:00:00 2001 From: Steven Basart Date: Wed, 10 Sep 2014 18:04:18 -0400 Subject: Created c++ tutorial c++ --- c++.html.markdown | 349 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 349 insertions(+) create mode 100644 c++.html.markdown diff --git a/c++.html.markdown b/c++.html.markdown new file mode 100644 index 00000000..8cf72e47 --- /dev/null +++ b/c++.html.markdown @@ -0,0 +1,349 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] +lang: en +--- + +I am writing this to highlight the differences and +additions that C++ has with respect to C. My +suggestion would be to follow the C tutorial first +then look here for the additions and differences. + +```c++ +/////////////////////////////////////// +// C++ differences +/////////////////////////////////////// + + +//In C++ +//cannot use void main() +int main() { //or int main(int argc, char **argv) + //cannot end with return; + return 0; + //Can also end without return statement +} + +//In C++ +/* + //This could lead to compiler errors and is discouraged + //#if 0 #endif pairs are encouraged instead +*/ + +//In C++ +sizeof(10) //Typically 4 +sizeof('c') == 1 + +//In C +sizeof('c') == sizeof(10) //true chars are passed as ints + + +//In C++ strict prototyping +void func(); //function which accepts no arguments + +//In C +void func(); //function which may accept arguments + + +//In C++ +for(int i = 0; i < 10; i++) {;} +//In C must int i must be declared before + + +//C++ Supports Function overloading +//Provided each function takes different +//parameters + +void printing(char const *myString) +{printf("String %s\n",myString);} //Hello + +void printing(int myInt) +{printf("My int is %d",myInt);} //15 + +int main () +{ + printing("Hello"); + printing(15); +} + + + +//C++ Default Function Arguments +void two_ints(int a = 1, int b = 4); + +int main() +{ + two_ints(); // arguments: 1, 4 + two_ints(20); // arguments: 20, 4 + two_ints(20, 5); // arguments: 20, 5 +} + + +//C++ added the nullptr which is different from 0 +int *ip = nullptr; // OK +int value = nullptr; // error: value is no pointer + + +/////////////////////////////////////// +// C++ Additions ontop of C +/////////////////////////////////////// + + +/////////////////////////////////////// +// C++ Namespace +/////////////////////////////////////// + +//Namespaces allow you to define your own +//functions and variables for use + +// Use '::' to change variable (or function) scope +// Putting '::' before a function or variable will +// reference a global scope + +// This allows you to make normal c library calls +// std is for standard library +using namespace std; + +#include + +int counter = 50; // global variable + +int main() +{ + for (int counter = 1; // this refers to the + counter < 2; // local variable + counter++) + { + printf("Global var %d local var %d\n", + ::counter, // global variable + counter); // local variable + // => Global var 50 local var 1 + } +} + +// Namespaces can be nested + + +namespace myFirstNameSpace +{ + namespace myInnerSoul + { + cos(int x) + { + printf("My inner soul was made to program."); + } + } +} + +namespace anotherNameSpace +{ + cos(int x) {;} //does nothing +} + +int main() +{ + //Specify the full path because main is outside of both namespaces. + //Will print out My inner soul was made to program. + myFirstNameSpace::myInnerSoul::cos(60); +} + + +/////////////////////////////////////// +// C++ Strings +/////////////////////////////////////// + +//Strings in C++ are Objects and have many functions +myString = "Hello"; +myOtherString = " World"; + +myString + myOtherString; // => "Hello World" + +myString + ' You'; // => "Hello You" + +myString != myOtherString; //True + +//An example of a string method +myString.append(" Dog"); // => "Hello Dog" + + +/////////////////////////////////////// +// C++ Input Output +/////////////////////////////////////// + +//C++ input and output streams +//cin, cout, cerr, << is insertion and >> is extraction operator +#include + +using namespace std; + +int main() +{ + + int myInt; + + //Prints to stdout (or terminal/screen) + cout << "Enter your fav number:\n" + //Takes in input + cin >> myInt; + + //cout can also be formatted + cout << "Your fav number is " << myInt << "\n" + //Your fav number is ## + + cerr << "Used for error messages" +} + + +/////////////////////////////////////// +// C++ Classes +/////////////////////////////////////// + + +//First example of classes +#include + +//define a class +class Doggie +{ + std::string name; + int weight; + + // These are only the declarations + //Can also have private and protected + public: + //The public methods (can also include variables) + + // Default constructor + Doggie(); + + void setName(std::string dogsName); + void setWeight(int dogsWeight); + void printDog(); + + //Can define functions within class declaration too + void dogBark() {std::cout << "Bark Bark\n"} + + //Destructors are methods that free the allocated space + ~doggieDestructor(); + //if no destructor compiler defines the trivial destructor + +//Classes are similar to structs and must close the } with ; +}; + +// This is the implementation of the class methods +// Also called the definition +void Doggie::Doggie () { + std::cout << "A doggie is born. Woof!\n"; +} + +void Doggie::setName (std::string doggie_name) { + name = doggie_name; +} + +void Doggie::setWeight (int doggie_weight) { + weight = doggie_weight; +} + +void Doggie::printDog () { + std::cout << "Dog is " << name << " weighs" << weight << "\n"; +} + +void Doggie::~doggieDestructor () { + delete[] name; + delete weight; +} + +int main () { + Doggie deedee; // prints out a doggie is born. Woof! + deedee.setName ("Barkley"); + deedee.setWeight(1000000); + deedee.printDog; + //prints => Dog is Barkley weighs 1000000 + return 0; +} + + +//C++ Class inheritance + +class German_Sheperd +{ + //This class now inherits everything public and protected from Doggie class + Doggie d_dog; + + //Good practice to put d_ in front of datatypes in classes + std::string d_type; + + public: + void dogType() {d_type = "German Sheperd";} +}; + + + +/////////////////////////////////////// +// C++ Exception Handling +/////////////////////////////////////// + +try { + throw 12.25; // throws a double no handler declared +} catch (int errorNum) +{ + std::cout << "I caught an int " << errorNum << "\n"; +//default catcher +} catch (...) +{ + std::cout << "I got an error. Not sure what but I can pass it up."; + throw; +} + + +/////////////////////////////////////// +// C++ Operator Overloading +/////////////////////////////////////// + +// In C++ you can overload operators such as +, -, new, etc. + +#include +using namespace std; + +class Vector { + public: + double x,y; + Vector () {}; + Vector (double a, double b) : x(a), y(b) {} + Vector operator + (const CVector&); + Vector operator += (const CVector&); +}; + +Vector Vector::operator+ (const Vector& rhs) +{ + Vector temp; + temp.x = x + rhs.x; + temp.y = y + rhs.y; + return temp; +} + +Vector Vector::operator+= (const Vector& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Vector up (0,1); + Vector right (1,0); + Vector result; + // This calls the Vector + operator + // Vector up calls the + (function) with right as its paramater + result = up + right; + // prints out => Result is upright (1,1) + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +``` +Futher Reading + +for more resources see: http://www.icce.rug.nl/documents/cplusplus/ +for other reference material: http://www.cplusplus.com/doc/tutorial/ -- cgit v1.2.3 From d1929e23924855589df130deec551b6fc3dd95d5 Mon Sep 17 00:00:00 2001 From: m90 Date: Thu, 11 Sep 2014 12:13:54 +0200 Subject: rephrase intro --- de-de/markdown-de.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/de-de/markdown-de.html.markdown b/de-de/markdown-de.html.markdown index bf07215e..7bfd3f41 100644 --- a/de-de/markdown-de.html.markdown +++ b/de-de/markdown-de.html.markdown @@ -8,9 +8,10 @@ filename: markdown-de.md lang: de-de --- -Markdown wurde im Jahr 2004 von John Gruber kreiert. Ziel ist und war eine leicht -zu lesende und zu schreibende Syntax für jegliche Dokumente, die möglichst -reibungslos nach HTML (und anderen Formaten) konvertiert werden kann. +Markdown wurde im Jahr 2004 von John Gruber kreiert. Ziel ist und war eine +Syntax, in der sich Dokumente leicht schreiben *und* lesen lassen. Ausserdem +sollte Markdown sich leicht nach HTML (und in andere Formate) konvertieren +lassen. ```markdown - + -Das ist ein Absatz. Ich kann immer noch nicht glauben wie viel Spaß das macht !?! +Das ist ein Absatz. Ich kann immer noch nicht glauben, wie viel Spaß das macht !?! Jetzt bin ich schon bei Absatz 2. Hier ist dann immer noch Absatz 2! @@ -82,9 +82,9 @@ Ich höre mit zwei Leerzeichen auf (markiere mich, und du siehst es). > Das ist ein Zitat. Du kannst Zeilenumbrüche > entweder manuell hinzufügen und ein `>` vor jeder Zeile einfügen, oder du kannst deine Zeilen einfach immer länger und länger werden lassen, die Umbrüche werden dann automatisch erzeugt. -> Solange sie mit einem `>` beginnen macht das keinen Unterschied. +> Solange sie mit einem `>` beginnen, macht das keinen Unterschied. -> Auch möglich ist den Text +> Auch möglich ist es, den Text >> mehrstufig einzurücken. > Nicht schlecht, oder? @@ -145,10 +145,10 @@ indem du eine Zeile mit vier Leerzeichen oder einem Tabulator einrückst --> -Hermann hatte nicht die leiseste Ahnung was dieses `go_to()` bedeuten könnte! +Hermann hatte nicht die leiseste Ahnung, was dieses `go_to()` bedeuten könnte! - + \`\`\`ruby def foobar @@ -156,12 +156,12 @@ def foobar end \`\`\` -<-- der obige Block muss nicht extra eingerückt werden, ausserdem fügt Github +<-- der obige Block muss nicht extra eingerückt werden, außerdem fügt Github Syntax-Highlighting für die nach dem ``` angegebene Sprache hinzu --> +erzeugen (egal ob mit oder ohne Leerzeichen dazwischen)--> *** --- @@ -185,15 +185,15 @@ einer mit runden Klammern () umschlossenen URL. --> -[Klick mich][link1] um mehr über mich herauszufinden! -[Hier kannst du auch mal draufklicken][foobar] wenn es dich interessiert. +[Klick mich][link1], um mehr über mich herauszufinden! +[Hier kannst du auch mal draufklicken][foobar], wenn es dich interessiert. [link1]: http://test.de/ "Wahnsinn!" [foobar]: http://foobar.ch/ "Erstaunlich!" @@ -205,7 +205,7 @@ es dokumentweit eindeutig ist. --> - ![Das ist das alt-Attribut für mein Bild](http://imgur.com/myimage.jpg "Hier noch ein title-Attribut") @@ -228,8 +228,8 @@ voranstellt! --> -Ich würde *diesen Teil gerne mit Sternen umschliessen*, doch ohne daß er kursiv -wird. Also mache ich folgendes: \*Ich umschliesse diesen Text mit Sternen\*! +Ich würde *diesen Teil gerne mit Sternen umschließen*, doch ohne dass er kursiv +wird. Also mache ich folgendes: \*Ich umschließe diesen Text mit Sternen\*! Spalte1 | Spalte2 | Spalte3 :-- | :-: | --: -Ganz schön häßlich | vielleicht doch lieber | wieder aufhören +Ganz schön hässlich | vielleicht doch lieber | wieder aufhören -- cgit v1.2.3 From b71bd349bba0755be3dafd836b31ca3792131e99 Mon Sep 17 00:00:00 2001 From: m90 Date: Fri, 12 Sep 2014 09:16:09 +0200 Subject: add credit --- de-de/markdown-de.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/de-de/markdown-de.html.markdown b/de-de/markdown-de.html.markdown index 85eb853a..6a90980b 100644 --- a/de-de/markdown-de.html.markdown +++ b/de-de/markdown-de.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators : - ["Frederik Ring", "https://github.com/m90"] + - ["Philipp Fischbeck", "https://github.com/PFischbeck"] filename: markdown-de.md lang: de-de --- -- cgit v1.2.3 From 55c269cc3c6a5678bbff3effc587edb7a1cd6e8a Mon Sep 17 00:00:00 2001 From: Daniil Baturin Date: Fri, 12 Sep 2014 18:39:15 +0700 Subject: F# is also related to the ML family. --- ocaml.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index 7f4e0a9d..8638a291 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -8,8 +8,10 @@ OCaml is a strictly evaluated functional language with some imperative features. Along with StandardML and its dialects it belongs to ML language family. -Just like StandardML, there are both a compiler and an interpreter -for OCaml. The interpreter binary is normally called "ocaml" and +F# is also heavily influenced by OCaml. + +Just like StandardML, OCaml features both an interpreter that can be +used interactively and a compiler. The interpreter binary is normally called "ocaml" and the compiler is "ocamlopt". There is also a bytecode compiler, "ocamlc", but there are few reasons to use it. -- cgit v1.2.3 From d9110cf7bc8a3dcf84207ea509340dbae868a44a Mon Sep 17 00:00:00 2001 From: Daniil Baturin Date: Fri, 12 Sep 2014 19:34:50 +0700 Subject: An overly simplified explanation of currying in OCaml tutorial. --- ocaml.html.markdown | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index 8638a291..fd5b9b2e 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -31,7 +31,7 @@ val a : int = 99 ``` For a source file you can use "ocamlc -i /path/to/file.ml" command -to print all names and signatures. +to print all names and type signatures. ``` $ cat sigtest.ml @@ -47,7 +47,13 @@ val a : int ``` Note that type signatures of functions of multiple arguments are -written in curried form. +written in curried form. A function that takes multiple arguments can be +represented as a composition of functions that take only one argument. +The "f(x,y) = x + y" function from the example above applied to +arguments 2 and 3 is equivalent to the "f0(y) = 2 + y" function applied to 3. +Hence the "int -> int -> int" signature, which can be read as +"(int -> int) -> int". + ```ocaml (*** Comments ***) -- cgit v1.2.3 From 962d58d013fa245c6b61863d2d14420c4c563743 Mon Sep 17 00:00:00 2001 From: Daniil Baturin Date: Fri, 12 Sep 2014 19:35:56 +0700 Subject: Remove stray argument from the alternative matching syntax in OCaml tutorial. It wouldn't cause a syntax error, but wouldn't give intended result either. --- ocaml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index fd5b9b2e..1732f7be 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -297,7 +297,7 @@ let is_zero x = ;; (* Alternatively, you can use the "function" keyword. *) -let is_one x = function +let is_one = function | 1 -> true | _ -> false ;; -- cgit v1.2.3 From 3995be4f4bf518e2c3436632ec100c14bb47bda1 Mon Sep 17 00:00:00 2001 From: Daniil Baturin Date: Fri, 12 Sep 2014 19:42:50 +0700 Subject: Break some long lines in OCaml tutorial to avoid horizontal scrolling. --- ocaml.html.markdown | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index 1732f7be..41bc4ff2 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -81,7 +81,8 @@ let foo = 1 ;; let foo' = foo * 2 ;; (* Since OCaml compiler infers types automatically, you normally don't need to - specify argument types explicitly. However, you can do it if you want or need to. *) + specify argument types explicitly. However, you can do it if + you want or need to. *) let inc_int (x: int) = x + 1 ;; (* You need to mark recursive function definitions as such with "rec" keyword. *) @@ -285,8 +286,8 @@ let l = Cons (1, EmptyList) ;; languages, but offers a lot more expressive power. Even though it may look complicated, it really boils down to matching - an argument against an exact value, a predicate, or a type constructor. The type system - is what makes it so powerful. *) + an argument against an exact value, a predicate, or a type constructor. + The type system is what makes it so powerful. *) (** Matching exact values. **) @@ -328,8 +329,8 @@ say (Cat "Fluffy") ;; (* "Fluffy says meow". *) (* Recursive types can be traversed with pattern matching easily. Let's see how we can traverse a datastructure of the built-in list type. - Even though the built-in cons ("::") looks like an infix operator, it's actually - a type constructor and can be matched like any other. *) + Even though the built-in cons ("::") looks like an infix operator, + it's actually a type constructor and can be matched like any other. *) let rec sum_list l = match l with | [] -> 0 -- cgit v1.2.3 From 2d01fb3c0597cfc692e3edfebcfc81bf2e3e3ee9 Mon Sep 17 00:00:00 2001 From: Daniil Baturin Date: Fri, 12 Sep 2014 19:46:41 +0700 Subject: Minor formatting and punctuation fix in the OCaml tutorial. --- ocaml.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index 41bc4ff2..0107fd35 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -10,10 +10,10 @@ features. Along with StandardML and its dialects it belongs to ML language family. F# is also heavily influenced by OCaml. -Just like StandardML, OCaml features both an interpreter that can be -used interactively and a compiler. The interpreter binary is normally called "ocaml" and -the compiler is "ocamlopt". There is also a bytecode compiler, "ocamlc", -but there are few reasons to use it. +Just like StandardML, OCaml features both an interpreter, that can be +used interactively, and a compiler. +The interpreter binary is normally called "ocaml" and the compiler is "ocamlopt". +There is also a bytecode compiler, "ocamlc", but there are few reasons to use it. It is strongly and statically typed, but instead of using manually written type annotations, it infers types of expressions using Hindley-Milner algorithm. -- cgit v1.2.3 From d855f4a156a95fe8eaf8d7946db6aed55ebabf66 Mon Sep 17 00:00:00 2001 From: Matthias Nehlsen Date: Fri, 12 Sep 2014 19:33:03 +0200 Subject: Update compojure.html.markdown I think you meant different parameters for title and author --- compojure.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compojure.html.markdown b/compojure.html.markdown index 444c8c58..c5b03498 100644 --- a/compojure.html.markdown +++ b/compojure.html.markdown @@ -156,7 +156,7 @@ Now, your handlers may utilize query parameters: (defroutes myapp (GET "/posts" req (let [title (get (:params req) "title") - author (get (:params req) "title")] + author (get (:params req) "author")] (str "Title: " title ", Author: " author)))) ``` @@ -166,7 +166,7 @@ Or, for POST and PUT requests, form parameters as well (defroutes myapp (POST "/posts" req (let [title (get (:params req) "title") - author (get (:params req) "title")] + author (get (:params req) "author")] (str "Title: " title ", Author: " author)))) ``` -- cgit v1.2.3 From 166fb997a0793067b7aa09091a1c9f76229ea6de Mon Sep 17 00:00:00 2001 From: Daniil Baturin Date: Sat, 13 Sep 2014 00:36:15 +0700 Subject: Remove the signature explanation by grouping to avoid confusion with signature syntax for function types. --- ocaml.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index 0107fd35..5be9510b 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -51,8 +51,7 @@ written in curried form. A function that takes multiple arguments can be represented as a composition of functions that take only one argument. The "f(x,y) = x + y" function from the example above applied to arguments 2 and 3 is equivalent to the "f0(y) = 2 + y" function applied to 3. -Hence the "int -> int -> int" signature, which can be read as -"(int -> int) -> int". +Hence the "int -> int -> int" signature. ```ocaml -- cgit v1.2.3 From c67cd5bb4be6f972104a82f27fa75f18e0677de9 Mon Sep 17 00:00:00 2001 From: Matthias Nehlsen Date: Fri, 12 Sep 2014 19:36:53 +0200 Subject: Update compojure.html.markdown While I'm at it... great work, by the way. The article about Compojure is really helpful. Thanks for that --- compojure.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compojure.html.markdown b/compojure.html.markdown index 444c8c58..af97a147 100644 --- a/compojure.html.markdown +++ b/compojure.html.markdown @@ -173,7 +173,7 @@ Or, for POST and PUT requests, form parameters as well ### Return values -The return value of a route block determines at least the response body +The return value of a route block determines the response body passed on to the HTTP client, or at least the next middleware in the ring stack. Most commonly, this is a string, as in the above examples. But, you may also return a [response map](https://github.com/mmcgrana/ring/blob/master/SPEC): -- cgit v1.2.3 From 807a958c78c44a83172724766d446eadb24f8cc5 Mon Sep 17 00:00:00 2001 From: Daniil Baturin Date: Sat, 13 Sep 2014 00:46:46 +0700 Subject: Some information about the need for type annotations in OCaml tutorial. --- ocaml.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index 5be9510b..bb9a1a75 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -82,7 +82,13 @@ let foo' = foo * 2 ;; (* Since OCaml compiler infers types automatically, you normally don't need to specify argument types explicitly. However, you can do it if you want or need to. *) -let inc_int (x: int) = x + 1 ;; +let inc_int (x: int) : int = x + 1 ;; + +(* One of the cases when explicit type annotations may be needed is + resolving ambiguity between two record types that have fields with + the same name. The alternative is to encapsulate those types in + modules, but both topics are a bit out of scope of this + tutorial. *) (* You need to mark recursive function definitions as such with "rec" keyword. *) let rec factorial n = -- cgit v1.2.3 From 5cf408a7a9f0d72f40dadd95d81430f35dee3a1e Mon Sep 17 00:00:00 2001 From: Daniil Baturin Date: Sat, 13 Sep 2014 00:54:23 +0700 Subject: Add anonymous functions and list map/filter sections to the OCaml tutorial. --- ocaml.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index bb9a1a75..b9505f13 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -150,6 +150,8 @@ x + y ;; works for non-recursive definitions too. *) let a = 3 and b = 4 in a * b ;; +(* Anonymous functions use the following syntax: *) +let my_lambda = fun x -> x * x ;; (*** Operators ***) @@ -207,6 +209,10 @@ let bad_list = [1, 2] ;; (* Becomes [(1, 2)] *) (* You can access individual list items with the List.nth function. *) List.nth my_list 1 ;; +(* There are higher-order functions for lists such as map and filter. *) +List.map (fun x -> x * 2) [1; 2; 3] ;; +List.filter (fun x -> if x mod 2 = 0 then true else false) [1; 2; 3; 4] ;; + (* You can add an item to the beginning of a list with the "::" constructor often referred to as "cons". *) 1 :: [2; 3] ;; (* Gives [1; 2; 3] *) -- cgit v1.2.3 From 39b7ae4d188c0cc366db17558d3fdd42941df25f Mon Sep 17 00:00:00 2001 From: Kirill Date: Sat, 13 Sep 2014 15:04:49 +0600 Subject: Added missing ";" --- c++.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 8cf72e47..7609dd46 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -183,15 +183,15 @@ int main() int myInt; //Prints to stdout (or terminal/screen) - cout << "Enter your fav number:\n" + cout << "Enter your fav number:\n"; //Takes in input cin >> myInt; //cout can also be formatted - cout << "Your fav number is " << myInt << "\n" + cout << "Your fav number is " << myInt << "\n"; //Your fav number is ## - cerr << "Used for error messages" + cerr << "Used for error messages"; } -- cgit v1.2.3 From a1a64276425800b03a3b29a5843ad9dc772a4c2a Mon Sep 17 00:00:00 2001 From: Aleksey Pirogov Date: Sat, 13 Sep 2014 22:31:33 +0400 Subject: russian translation for Markdown --- ru-ru/markdown-ru.html.markdown | 270 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 ru-ru/markdown-ru.html.markdown diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown new file mode 100644 index 00000000..c8b643b6 --- /dev/null +++ b/ru-ru/markdown-ru.html.markdown @@ -0,0 +1,270 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] + - ["Pirogov Alexey", "http://twitter.com/alex_pir"] +filename: markdown.md +--- + +Язык разметки Markdown создан Джоном Грубером (англ. John Gruber) и Аароном Шварцем (англ. Aaron H. Swartz) в 2004 году. Авторы задавались целью создать максимально удобочитаемый и удобный в публикации облегчённый язык разметки, пригодный для последующего преобразования в HTML (а также и в другие форматы). + + ```markdown + + + + + + + +# Это заголовок h1 +## Это заголовок h2 +### Это заголовок h3 +#### Это заголовок h4 +##### Это заголовок h5 +###### Это заголовок h6 + + +Это заголовок h1 +================ + +А это заголовок h2 +------------------ + + + + + +*Этот текст будет выведен курсивом.* +_Также как этот._ + +**А этот текст будет полужирным.** +__И этот тоже.__ + +***Полужирный курсив.*** +**_И тут!_** +*__И даже здесь!__* + + + +~~Зачёркнутый текст.~~ + + + +Это параграф. Всё предельно просто. + +А тут уже параграф №2. +Эта строка всё ещё относится к параграфу №2! + + +О, а вот это уже параграф №3! + + + +Принудительный
перенос! + + + +> Это цитата. В цитатах можно +> принудительно переносить строки, вставляя ">" в начало каждой следующей строки. А можно просто оставлять достаточно длинными, и такие длинные строки будут перенесены автоматически. +> Разницы между этими двумя подходами к переносу строк нет, коль скоро +> каждая строка начинается с символа ">" + +> А ещё цитаты могут быть многоуровневыми: +>> как здесь +>>> и здесь :) +> Неплохо? + + + + +* Список, +* Размеченный +* "Звёздочками" + +либо + ++ Список, ++ Размеченный ++ "Плюсами" + +либо + +- Список, +- Размеченный +- "Дефисами" + + + +1. Первый элемент +2. Второй элемент +3. Третий элемент + + + +1. Первый элемент +1. Второй элемент +1. Третий элемент + + + + +1. Введение +2. Начало работы +3. Примеры использования + * Простые + * Сложные +4. Заключение + + + + + Это код, + причём - многострочный + + + + my_array.each do |item| + puts item + end + + + +Например, можно выделить имя функции `go_to()` прямо посреди текста. + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + +<-- Обратите внимание: фрагмент, указанный выше, не предваряется отступами, +поскольку Github сам в состоянии определить границы блока - по строкам "```" --> + + + + +*** +--- +- - - +**************** + + + + +[Ссылка!](http://test.com/) + + + +[Ссылка!](http://test.com/ "Ссылка на Test.com") + + + +[Перейти к музыке](/music/). + + + +[Здесь][link1] высможете узнать больше! +А можно кликнуть [сюда][foobar], если очень хочется. + + +[link1]: http://test.com/ "Круто!" +[foobar]: http://foobar.biz/ "Тоже хорошо!" + + + + + +Ссылка на [Google][]. + +[google]: http://google.com/ + + + + + + +![Альтернативный текст для изображения](http://imgur.com/myimage.jpg "Подсказка") + + + +![Альтернативный текст][myimage] + +![То же изображение ещё раз][myimage] + +[myimage]: relative/urls/cool/image.jpg "подсказка" + + + + +Ссылка вида эквивалентна +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + + + +\*текст, заключённый в звёздочки!\* + + + + +| Колонка 1 | Колонка 2 | Колонка 3 | +| :----------- | :----------: | -----------: | +| Выравнивание | Выравнивание | Выравнивание | +| влево | по центру | вправо | + + + +Колонка 1|Колонка 2|Колонка 3 +:--|:-:|--: +Выглядит|это|страшновато... + + + +``` + +За более подробной информацией обращайтесь к [статье](http://daringfireball.net/projects/markdown/syntax) Джона Грубера о синтаксисе Markdown. + +Также часто бывает полезной отличная ["шпаргалка"](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) по Markdown от Adam Pritchard. + +Если вдруг встретите ошибки в переводе или же захотите его дополнить, делайте pull requests - авторы всегда рады обратной связи! -- cgit v1.2.3 From 16b1249444203485168124bfa54c66b3b1abf1ee Mon Sep 17 00:00:00 2001 From: Aleksey Pirogov Date: Sat, 13 Sep 2014 22:34:40 +0400 Subject: Markdown-ru: language tag --- ru-ru/markdown-ru.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown index c8b643b6..8b2a0982 100644 --- a/ru-ru/markdown-ru.html.markdown +++ b/ru-ru/markdown-ru.html.markdown @@ -3,7 +3,8 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] - ["Pirogov Alexey", "http://twitter.com/alex_pir"] -filename: markdown.md +filename: markdown-ru.md +lang: ru-ru --- Язык разметки Markdown создан Джоном Грубером (англ. John Gruber) и Аароном Шварцем (англ. Aaron H. Swartz) в 2004 году. Авторы задавались целью создать максимально удобочитаемый и удобный в публикации облегчённый язык разметки, пригодный для последующего преобразования в HTML (а также и в другие форматы). -- cgit v1.2.3 From 931db8c6857ddbf47f4d2a6cb7d905f61cb61e84 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sat, 13 Sep 2014 21:37:35 +0200 Subject: Regexes thingies. --- perl6.html.markdown | 52 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index fe5b197c..4e7d8c6e 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1246,7 +1246,7 @@ so 'abc' ~~ / a b* c /; # `True` so 'abbbbc' ~~ / a b* c /; # `True` so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, not replaceable. -# - `**` - "Quantify It Yourself". +# - `**` - (Unbound) Quantifier # If you squint hard enough, you might understand # why exponentation is used for quantity. so 'abc' ~~ / a b ** 1 c /; # `True` (exactly one time) @@ -1255,6 +1255,27 @@ so 'abbbc' ~~ / a b ** 1..3 c /; # `True` so 'abbbbbbc' ~~ / a b ** 1..3 c /; # `False` (too much) so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay) +# - `<[]>` - Character classes +# Character classes are the equivalent of PCRE's `[]` classes, but +# they use a more perl6-ish syntax: +say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa' +# You can use ranges: +say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'aeiou' +# Just like in normal regexes, if you want to use a special character, escape it +# (the last one is escaping a space) +say 'he-he !' ~~ / 'he-' <[ a..z \! \ ]> + /; #=> 'he-he !' +# You'll get a warning if you put duplicate names +# (which has the nice effect of catching the wrote quoting:) +'he he' ~~ / <[ h e ' ' ]> /; # Warns "Repeated characters found in characters class" + +# You can also negate them ... (equivalent to `[^]` in PCRE) +so 'foo' ~~ / <-[ f o ]> + /; # False + +# ... and compose them: : +so 'foo' ~~ / <[ a..z ] - [ f o ]> + /; # False (any letter except f and o) +so 'foo' ~~ / <-[ a..z ] + [ f o ]> + /; # True (no letter except f and o) +so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left part) + ## Grouping and capturing # Group: you can group parts of your regexp with `[]`. # These groups are *not* captured (like PCRE's `(?:)`). @@ -1297,7 +1318,7 @@ say $0.WHAT; #=> (Array) # may it be a range or a specific value (even 1). # If you're wondering how the captures are numbered, here's an explanation: -TODO use graphs from s05 +# (TODO use graphs from s05) ## Alternatives - the `or` of regexps @@ -1305,6 +1326,31 @@ TODO use graphs from s05 so 'abc' ~~ / a [ b | y ] c /; # `True`. Either "b" or "y". so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... +# The difference between this `|` and the one you're probably used to is LTM. +# LTM means "Longest Token Matching". This means that the engine will always +# try to match as much as possible in the strng +'foo' ~~ / fo | foo /; # `foo`, because it's longer. +# To decide which part is the "longest", it first splits the regex in two parts: +# The "declarative prefix" (the part that can be statically analyzed) +# and the procedural parts. +# Declarative prefixes include alternations (`|`), conjuctions (`&`), +# sub-rule calls (not yet introduced), literals, characters classes and quantifiers. +# The latter include everything else: back-references, code assertions, +# and other things that can't traditionnaly be represented by normal regexps. +# +# Then, all the alternatives are tried at once, and the longest wins. +# Exemples: +# DECLARATIVE | PROCEDURAL +/ 'foo' \d+ [ || ] /; +# DECLARATIVE (nested groups are not a problem) +/ \s* [ \w & b ] [ c | d ] /; +# However, closures and recursion (of named regexps) are procedural. +# ... There are also more complicated rules, like specificity +# (literals win over character classes) + +# Note: the first-matching `or` still exists, but is now spelled `||` +'foo' ~~ / fo || foo /; # `fo` now. + ### Extra: the MAIN subroutime # The `MAIN` subroutine is called when you run a Perl 6 file directly. # It's very powerful, because Perl 6 actually parses the argument @@ -1317,7 +1363,7 @@ sub MAIN($name) { say "Hello, you !" } # t.pl # And since it's a regular Perl 6 sub, you can haz multi-dispatch: -# (using a "Bool" for the named argument so that we get `--replace` +# (using a "Bool" for the named argument so that we can do `--replace` # instead of `--replace=1`) subset File of Str where *.IO.d; # convert to IO object to check the file exists -- cgit v1.2.3 From 93423c1b828062bc800d44d7cce8c3a20169294b Mon Sep 17 00:00:00 2001 From: Joel Gallant Date: Sun, 14 Sep 2014 13:18:43 -0600 Subject: Fixed very small spelling mistake semantices -> semantics --- coffeescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index 6af692b9..4c080bc6 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -20,7 +20,7 @@ See also [the CoffeeScript website](http://coffeescript.org/), which has a compl Block comments are like these, and they translate directly to '/ *'s and '* /'s for the resulting JavaScript code. -You should understand most of JavaScript semantices +You should understand most of JavaScript semantics before continuing. ### -- cgit v1.2.3 From 6d68c2317bfd9cdcf062f8a06ea941e96862b883 Mon Sep 17 00:00:00 2001 From: Muhammad Wang Date: Mon, 15 Sep 2014 10:12:36 +0800 Subject: Fix a typo --- zh-cn/ruby-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 3c47f3f9..99250b43 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -40,7 +40,7 @@ translators: 1.+(3) #=> 4 10.* 5 #=> 50 -# 特殊的只也是对象 +# 特殊的值也是对象 nil # 空 true # 真 false # 假 -- cgit v1.2.3 From 9df9e23aa4f9d36ec4d27528318b173aec3b0b8e Mon Sep 17 00:00:00 2001 From: Pierre-Arnaud Baciocchini Date: Tue, 16 Sep 2014 17:33:10 +0200 Subject: Fixes french translation of CSS --- fr-fr/css-fr.html.markdown | 60 ++++++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown index 17f1eab4..bff922df 100644 --- a/fr-fr/css-fr.html.markdown +++ b/fr-fr/css-fr.html.markdown @@ -10,17 +10,16 @@ lang: fr-fr Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le developemnt des navigateurs, des pages avec du contenu visuel sont arrivées. -CSS est le langage standard qui existe et permet de garder une séparation entre +CSS est le langage standard qui existe et permet de garder une séparation entre le contenu (HTML) et le style d'une page web. -En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents -sur un page HTML afin de leurs donner des propriétés visuelles différentes. +En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents +sur une page HTML afin de leur donner des propriétés visuelles différentes. -Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parlons de CSS2.0 +Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parlons de CSS2.0 qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateur. -**NOTE:** Parce que le résultat du code CSS est un effet visuel, vous pouvez utiliser [dabblet](http://dabblet.com/) afin de -voir les résultats, comprendre, et vous familiariser avec le langage. +**NOTE :** Vous pouvez tester les effets visuels que vous ajoutez au fur et à mesure du tutoriel sur des sites comme [dabblet](http://dabblet.com/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. Cet article porte principalement sur la syntaxe et quelques astuces. @@ -28,7 +27,7 @@ Cet article porte principalement sur la syntaxe et quelques astuces. /* Les commentaires sont entourés par slash-étoile, comme cette ligne! */ /* #################### - ## SELECTEURS + ## SÉLECTEURS ####################*/ /* Généralement, la première déclaration en CSS est très simple */ @@ -40,7 +39,7 @@ Vous pouvez cibler tous les éléments d'une page! */ * { color:red; } /* -Voici un élément dans notre HTML: +Voici un élément dans notre HTML :
*/ @@ -48,7 +47,7 @@ Voici un élément dans notre HTML: /* Vous pouvez le cibler par une classe */ .une-classe { } -/* ou les deux */ +/* ou par deux */ .une-classe.classe2 { } /* ou par son type */ @@ -74,18 +73,18 @@ div { } /* Ce qu'il faut bien comprendre, c'est que vous pouvez combiner ceci -- Il ne doit pas y avoir -d'espaces entre.*/ +d'espaces entre. */ div.une-classe[attr$='eu'] { } -/* Vous pouvez aussi cibler un élément par son parent.*/ +/* Vous pouvez aussi cibler un élément par son parent. */ /* Un élément qui est en enfant direct */ div.un-parent > .enfant {} -/* Cela cible aussi les .enfants plus profond dans la structure HTML */ +/* Cela cible aussi les .enfants plus profonds dans la structure HTML */ div.un-parent .enfants {} -/* Attention: le même sélécteur sans espace a un autre sens. */ +/* Attention : le même sélecteur sans espace a un autre sens. */ div.un-parent.classe {} /* Vous pouvez cibler un élément basé sur un enfant de même parent */ @@ -94,8 +93,8 @@ div.un-parent.classe {} /* ou n'importe quel enfant de même parent avec celui ci */ .je-suis-tout-avant ~ .cet-element {} -/* Il y a des pseudo-classes qui permettent de cibler un élément -basé sur le comportement, plus que la structure de la page */ +/* Il y a des pseudo-classes qui permettent de cibler un élément +basé sur le comportement, en plus de la structure de la page */ /* élément avec le curseur au-dessus */ :hover {} @@ -111,20 +110,20 @@ basé sur le comportement, plus que la structure de la page */ /* #################### - ## PROPRIETES + ## PROPRIÉTÉS ####################*/ selecteur { - + /* Units */ width: 50%; /* pourcentage */ - font-size: 2em; /* times current font-size */ + font-size: 2em; /* taille de la police multipliée par X */ width: 200px; /* pixels */ font-size: 20pt; /* points */ width: 5cm; /* centimetres */ width: 50mm; /* millimetres */ width: 5in; /* pouces */ - + /* Couleurs */ background-color: #F6E; /* court hex */ background-color: #F262E2; /* long hex */ @@ -132,14 +131,14 @@ selecteur { background-color: rgb(255, 255, 255); /* rouge, vert, bleu */ background-color: rgb(10%, 20%, 50%); /* rouge, vert, bleu en pourcent */ background-color: rgba(255, 0, 0, 0.3); /* rouge, vert, bleu avec transparence */ - + /* Images */ background-image: url(/chemin-vers-image/image.jpg); - + /* Polices */ font-family: Arial; font-family: "Courier New"; /* Si espace, entre guillemets */ - font-family: "Courier New", Trebuchet, Arial; /* Si la première n'est pas trouvée, deuxième, etc... */ + font-family: "Courier New", Trebuchet, Arial; /* Si la première n'est pas trouvée, la deuxième est utilisée, etc... */ } ``` @@ -149,7 +148,7 @@ selecteur { Le CSS s'écrit dans des fichiers `.css`. ```xml - + @@ -157,8 +156,8 @@ Le CSS s'écrit dans des fichiers `.css`. selecteur { propriete:valeur; } - +
@@ -166,11 +165,11 @@ PS: À ne pas faire. --> ## Priorités -Comme on vient de le voir, un élément peut être ciblé par plus qu'un seul sélécteur +Comme on vient de le voir, un élément peut être ciblé par plus qu'un seul sélecteur et une même propriété peut être définie plusieurs fois. Dans ces cas, une des propriétés devient prioritaire. -Voici du code CSS: +Voici du code CSS : ```css /*A*/ @@ -197,7 +196,7 @@ et le code HTML:

``` -Les priorités de style sont: +Les priorités de style sont : Attention, les priorités s'appliquent aux **propriétés**, pas aux blocs entiers. * `E` a la priorité grâce à `!important`. @@ -210,8 +209,8 @@ Attention, les priorités s'appliquent aux **propriétés**, pas aux blocs entie ## Compatibilité -La plupart des fonctionnalités de CSS2 (et de plus en plus CSS3) sont compatibles -avec tous les navigateurs. Mais c'est important de vérifier la compatibilité. +La plupart des fonctionnalités de CSS2 (et de plus en plus CSS3) sont compatibles +avec tous les navigateurs. Mais il est important de vérifier la compatibilité. [QuirksMode CSS](http://www.quirksmode.org/css/) est une très bonne source pour cela. @@ -220,4 +219,3 @@ avec tous les navigateurs. Mais c'est important de vérifier la compatibilité. * [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) * [QuirksMode CSS](http://www.quirksmode.org/css/) * [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) - -- cgit v1.2.3 From 79f7d3100f50cc1479c0dab63606a0103470d580 Mon Sep 17 00:00:00 2001 From: Pierre-Arnaud Baciocchini Date: Thu, 18 Sep 2014 16:01:42 +0200 Subject: Fixed typo --- fr-fr/css-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown index bff922df..bdab9715 100644 --- a/fr-fr/css-fr.html.markdown +++ b/fr-fr/css-fr.html.markdown @@ -8,7 +8,7 @@ translators: lang: fr-fr --- -Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le developemnt des navigateurs, +Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le dévelopement des navigateurs, des pages avec du contenu visuel sont arrivées. CSS est le langage standard qui existe et permet de garder une séparation entre le contenu (HTML) et le style d'une page web. -- cgit v1.2.3 From 27c7f4c4f039d07fc32e5b67493fdfe9c92a9e9d Mon Sep 17 00:00:00 2001 From: Nikhil Thomas Date: Thu, 18 Sep 2014 13:41:47 -0400 Subject: fix typo --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 946c0a1b..c0abc815 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -360,7 +360,7 @@ spawn(f) #=> #PID<0.40.0> # `spawn` returns a pid (process identifier), you can use this pid to send # messages to the process. To do message passing we use the `send` operator. # For all of this to be useful we need to be able to receive messages. This is -# achived with the `receive` mechanism: +# achieved with the `receive` mechanism: defmodule Geometry do def area_loop do receive do -- cgit v1.2.3 From 695159a751966becf726436761e78c33d51c80ba Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Thu, 18 Sep 2014 18:07:51 -0500 Subject: IC --- nim.html.markdown | 259 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 259 insertions(+) create mode 100644 nim.html.markdown diff --git a/nim.html.markdown b/nim.html.markdown new file mode 100644 index 00000000..25b99e57 --- /dev/null +++ b/nim.html.markdown @@ -0,0 +1,259 @@ +--- +language: nim +filename: learnNim.c +contributors: + - ["Jason J. Ayala P.", "http://JasonAyala.com"] +--- + +Nim is a statically typed, imperative programming language that tries to give +the programmer ultimate power without compromises on runtime efficiency. This +means it focuses on compile-time mechanisms in all their various forms. + +Nim is efficient, expressive, and elegant. + +```nimrod + +var x: int # Declare a variable and its type +x = 1 # Assign it a value +var z = "Yep" # Declare and assign, with or without type annotations + +var # Several, with or without type annotations + letter: char = 'n' # One byte character + name = "Nimrod" # string + truth: bool = false # Common boolean operators: `and` `not` `or` + seconds: int = 42 + thoughts = """ +A great programming language +that everyone can enjoy! +""" # Multiline raw strings + boat: float + +let # Use let to declare and bind an variable *once*. + legs = 400 # legs is immutable. + arms = 2_000 # _ are ignored and are useful for long numbers. + +const # Constants are computed at compile time. This provides + debug = true # performance and is useful in compile time expressions. + aboutPi = 3.15 + compileBadCode = false + +when compileBadCode: # `when` is a compile time `if` + legs = legs + 1 # This error will never be compiled. + const input = readline(stdin) # const values must be known at compile time. + +discard 1 > 2 # The compiler will complain if the result of an expression + # is unused. `discard` bypasses this. + +discard """ +This can work as a +multiline comment +""" + +# +# Common Operations on Basic Types +# + +var nim = "Nimrod is a progamming language" +name = nim[0..5] + +# TODO More common operations? + +# +# Data Structures +# + +# Tuples + +var + child: tuple[name: string, age: int] # Tuples have *both* field names + today: tuple[sun: string, temp: float] # *and* order. + +child = (name: "Rudiger", age: 2) # Assign all at once with literal () +today.sun = "Overcast" # or individual fields. +today.temp = 70.1 + +# Sequences + +var + drinks: seq[string] + +drinks = @["Water", "Juice", "Chocolate"] # @[V1,..,Vn] is the sequence literal + +# +# Defining Your Own Types +# + +# Defining your own types puts the compiler to work for you. It's what makes +# static typing powerful and useful. + +type + Name = string # A type alias gives you a new type that is interchangable + Age = int # with the old type but is more descriptive. + Person = tuple[name: Name, age: Age] # Define data structures too. + +var + john: Person = ("John B.", 17) + newage: int = 18 # It would be better to use Age than int + +john.age = newage # But still works because int and Age are synonyms + +type + Cash = distinct int # `distinct` makes a new type incompatible with it's + Desc = distinct string # base type. + +var + money: Cash = 100.Cash # `.Cash` converts the int to our type + desc: Desc = "Interesting".Desc + +when compileBadCode: + john.age = money # Error! age is of type int and money is Cash + john.name = desc # Compiler says: "No way!" + +# +# More Types and Data Structures +# + +# Enumerations allow a type to be one of a limited number of values + +type + Directions = enum north, west, east, south + Colors = enum red, blue, green +var + orient = north # `orient` is of type Directions, with the value `north` + pixel = green # `pixel` is of type Colors, with the value `green` + +discard north > east # Enums are usually an "ordinal" type + +# Subranges specify a limited valid range + +type + DieFaces = range[1..20] # Only an int from 1 to 20 is a valid value +var + my_roll: DieFaces = 13 + +when compileBadCode: + my_roll = 23 # Error! + +# Arrays + +type + RollCounter = array[DieFaces, int] # Array's are fixed length and + DirNames = array[Directions, string] # indexed by any ordinal type. + Truths = array[42..44, bool] +var + rollCounter: RollCounter + directions: DirNames + truths: Truths + +truths = [false, false, false] # Literal arrays are created with [V1,..,Vn] +truths[42] = true + +directions[north] = "Ahh. The Great White North!" +directions[west] = "No, don't go there." + +my_roll = 13 +rollCounter[my_roll] += 1 +rollCounter[my_roll] += 1 + +var anotherArray = ["Default index", "starts at", "0"] + +# TODO common operations + +# +# IO and Control Flow +# + +# `case`, `readLine()` + +echo "Read any good books lately?" +case readLine(stdin) +of "no", "No": + echo "Go to your local library." +of "yes", "Yes": + echo "Carry on, then." +else: + echo "That's great; I assume." + +# `while`, `if`, `continue`, `break` + +import strutils as str +echo "I'm thinking of a number between 41 and 43. Guess which!" +var + answer: int = 42 + raw_guess: string + guess: int +while guess != answer: + raw_guess = readLine(stdin) + if raw_guess == "": + continue # `continue` restarts loop/block + guess = str.parseInt(raw_guess) + if guess == 1001: + echo("AAAAAAGGG!") + break + elif guess > answer: + echo("Too high.") + elif guess < answer: + echo("Too low") + else: + echo("Yeeeeeehaw!") + +# +# Iteration +# + +# Iterate with the `for` keyword +# TODO `for` examples for strings, arrays, etc + +for elem in ["Yes", "No", "Maybe so"]: + echo elem + +# string iterators + +let myString = """ +an example +string to +play with +""" + +for line in splitLines(myString): + echo(line) + +# +# Procedures +# + +type Answer = enum yes, no + +proc ask(question: string): Answer = + echo(question, " (y/n)") + while true: + case readLine(stdin) + of "y", "Y", "yes", "Yes": + return Answer.yes # Enums can be qualified + of "n", "N", "no", "No": + return Answer.no + else: echo("Please be clear: yes or no") + +proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing + for a in 1..amount: + echo a, " sugar..." + +case ask("Would you like sugar in your tea?") +of yes: + addSugar(3) +of no: + echo "Oh do take a little!" + addSugar() +# No need for an `else` here. only `yes` and `no` are possible. + +``` + +## Further Reading + +* [Home Page](http://nimrod-lang.org) +* [Download](http://nimrod-lang.org/download.html) +* [Community](http://nimrod-lang.org/community.html) +* [FAQ](http://nimrod-lang.org/question.html) +* [Documentation](http://nimrod-lang.org/documentation.html) +* [Manual](http://nimrod-lang.org/manual.html) +* [Standard Libray](http://nimrod-lang.org/lib.html) -- cgit v1.2.3 From f665bf27539b51a24b5dc8a1e8a1fdb7bbb57a52 Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Thu, 18 Sep 2014 18:11:27 -0500 Subject: filename fix --- nim.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nim.html.markdown b/nim.html.markdown index 25b99e57..f9ba975e 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -1,6 +1,6 @@ --- language: nim -filename: learnNim.c +filename: learnNim.nim contributors: - ["Jason J. Ayala P.", "http://JasonAyala.com"] --- -- cgit v1.2.3 From a261b8c445d0c0af70348d6518d3e0204da94e1d Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Thu, 18 Sep 2014 18:28:42 -0500 Subject: mention rename --- nim.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index f9ba975e..ae9f5ce0 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -5,9 +5,10 @@ contributors: - ["Jason J. Ayala P.", "http://JasonAyala.com"] --- -Nim is a statically typed, imperative programming language that tries to give -the programmer ultimate power without compromises on runtime efficiency. This -means it focuses on compile-time mechanisms in all their various forms. +Nim (formally Nimrod) is a statically typed, imperative programming language +that tries to give the programmer ultimate power without compromises on runtime +efficiency. This means it focuses on compile-time mechanisms in all their +various forms. Nim is efficient, expressive, and elegant. -- cgit v1.2.3 From 08a444ddc632603178900484477186a6ae7d9b9e Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Thu, 18 Sep 2014 19:02:33 -0500 Subject: Renamed vars and types for clarity; minor stuff; enum prefix --- nim.html.markdown | 80 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 44 insertions(+), 36 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index ae9f5ce0..69d0f804 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -18,15 +18,15 @@ var x: int # Declare a variable and its type x = 1 # Assign it a value var z = "Yep" # Declare and assign, with or without type annotations -var # Several, with or without type annotations - letter: char = 'n' # One byte character - name = "Nimrod" # string - truth: bool = false # Common boolean operators: `and` `not` `or` +var # Several, with or without type annotations + letter: char = 'n' # One byte character + lang = "Nimrod" # string + truth: bool = false # Common boolean operators: `and` `not` `or` seconds: int = 42 - thoughts = """ + thoughts = """ A great programming language that everyone can enjoy! -""" # Multiline raw strings +""" # Multiline raw strings boat: float let # Use let to declare and bind an variable *once*. @@ -54,8 +54,9 @@ multiline comment # Common Operations on Basic Types # -var nim = "Nimrod is a progamming language" -name = nim[0..5] +let + phrase = "Nim is a progamming language" + nim = phrase[0..5] # TODO More common operations? @@ -91,6 +92,9 @@ type Name = string # A type alias gives you a new type that is interchangable Age = int # with the old type but is more descriptive. Person = tuple[name: Name, age: Age] # Define data structures too. + LongTuple = tuple + fieldOne: string + secondField: int var john: Person = ("John B.", 17) @@ -104,11 +108,11 @@ type var money: Cash = 100.Cash # `.Cash` converts the int to our type - desc: Desc = "Interesting".Desc + description: Desc = "Interesting".Desc when compileBadCode: - john.age = money # Error! age is of type int and money is Cash - john.name = desc # Compiler says: "No way!" + john.age = money # Error! age is of type int and money is Cash + john.name = description # Compiler says: "No way!" # # More Types and Data Structures @@ -117,13 +121,17 @@ when compileBadCode: # Enumerations allow a type to be one of a limited number of values type - Directions = enum north, west, east, south - Colors = enum red, blue, green + Color = enum cRed, cBlue, cGreen + Direction = enum # Alternative formating + dNorth + dWest + dEast + dSouth var - orient = north # `orient` is of type Directions, with the value `north` - pixel = green # `pixel` is of type Colors, with the value `green` + orient = dNorth # `orient` is of type Direction, with the value `dNorth` + pixel = cGreen # `pixel` is of type Color, with the value `cGreen` -discard north > east # Enums are usually an "ordinal" type +discard dNorth > dEast # Enums are usually an "ordinal" type # Subranges specify a limited valid range @@ -138,23 +146,23 @@ when compileBadCode: # Arrays type - RollCounter = array[DieFaces, int] # Array's are fixed length and - DirNames = array[Directions, string] # indexed by any ordinal type. - Truths = array[42..44, bool] + RollCounter = array[DieFaces, int] # Array's are fixed length and + DirNames = array[Direction, string] # indexed by any ordinal type. + Truths = array[42..44, bool] var - rollCounter: RollCounter + counter: RollCounter directions: DirNames - truths: Truths + possible: Truths -truths = [false, false, false] # Literal arrays are created with [V1,..,Vn] -truths[42] = true +possible = [false, false, false] # Literal arrays are created with [V1,..,Vn] +possible[42] = true -directions[north] = "Ahh. The Great White North!" -directions[west] = "No, don't go there." +directions[dNorth] = "Ahh. The Great White North!" +directions[dWest] = "No, don't go there." my_roll = 13 -rollCounter[my_roll] += 1 -rollCounter[my_roll] += 1 +counter[my_roll] += 1 +counter[my_roll] += 1 var anotherArray = ["Default index", "starts at", "0"] @@ -180,10 +188,10 @@ else: import strutils as str echo "I'm thinking of a number between 41 and 43. Guess which!" var - answer: int = 42 + number: int = 42 raw_guess: string guess: int -while guess != answer: +while guess != number: raw_guess = readLine(stdin) if raw_guess == "": continue # `continue` restarts loop/block @@ -191,9 +199,9 @@ while guess != answer: if guess == 1001: echo("AAAAAAGGG!") break - elif guess > answer: + elif guess > number: echo("Too high.") - elif guess < answer: + elif guess < number: echo("Too low") else: echo("Yeeeeeehaw!") @@ -223,16 +231,16 @@ for line in splitLines(myString): # Procedures # -type Answer = enum yes, no +type Answer = enum aYes, aNo proc ask(question: string): Answer = echo(question, " (y/n)") while true: case readLine(stdin) of "y", "Y", "yes", "Yes": - return Answer.yes # Enums can be qualified + return Answer.aYes # Enums can be qualified of "n", "N", "no", "No": - return Answer.no + return Answer.aNo else: echo("Please be clear: yes or no") proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing @@ -240,9 +248,9 @@ proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing echo a, " sugar..." case ask("Would you like sugar in your tea?") -of yes: +of aYes: addSugar(3) -of no: +of aNo: echo "Oh do take a little!" addSugar() # No need for an `else` here. only `yes` and `no` are possible. -- cgit v1.2.3 From 2f2536a6ea85f21e8e0cb4aad91fbca589b5220b 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: Fri, 19 Sep 2014 17:03:33 +0300 Subject: Corrected as reviewed by @astynax. And yes, Jack be nimble's analog is also there! --- ru-ru/python3-ru.html.markdown | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown index 767773fa..bf1af599 100644 --- a/ru-ru/python3-ru.html.markdown +++ b/ru-ru/python3-ru.html.markdown @@ -23,7 +23,7 @@ filename: learnpython3-ru.py # Однострочные комментарии начинаются с символа решётки. """ Многострочный текст может быть записан, используя 3 знака " и обычно используется - в качестве комментария + в качестве встроенной документации """ #################################################### @@ -61,7 +61,7 @@ filename: learnpython3-ru.py # Приоритет операций указывается скобками (1 + 3) * 2 #=> 8 -# Логические (булевы) значения являются примитивами +# Для логических (булевых) значений существует отдельный примитивный тип True False @@ -83,7 +83,7 @@ not False #=> True 2 <= 2 #=> True 2 >= 2 #=> True -# Сравнения могут быть соединены в цепь! +# Сравнения могут быть записаны цепочкой: 1 < 2 < 3 #=> True 2 < 3 < 2 #=> False @@ -101,10 +101,8 @@ not False #=> True "{0} могут быть {1}".format("строки", "форматированы") # Вы можете повторять аргументы форматирования, чтобы меньше печатать. -# TODO: Find a good analog to "Jack be nimble" in Russian -"{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" - +"Ехал {0} через реку, видит {0} - в реке {1}! Сунул {0} руку в реку, {1} за руку греку цап!".format("грека", "рак") +#=> "Ехал грека через реку, видит грека - в реке рак! Сунул грека руку в реку, рак за руку греку цап!" # Если вы не хотите считать, можете использовать ключевые слова. "{name} хочет есть {food}".format(name="Боб", food="лазанью") -- cgit v1.2.3 From b66872c9eb2e33ed57d628c8a6aa1daf4f33ca6e Mon Sep 17 00:00:00 2001 From: Jelle Besseling Date: Fri, 19 Sep 2014 18:05:13 +0200 Subject: Dutch translation of the coffeescript tutorial --- nl-nl/coffeescript-nl.html.markdown | 109 ++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 nl-nl/coffeescript-nl.html.markdown diff --git a/nl-nl/coffeescript-nl.html.markdown b/nl-nl/coffeescript-nl.html.markdown new file mode 100644 index 00000000..70dcd463 --- /dev/null +++ b/nl-nl/coffeescript-nl.html.markdown @@ -0,0 +1,109 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Jelle Besseling", "https://github.com/Jell-E"] +filename: coffeescript-nl.coffee +lang: nl-nl +--- + +CoffeeScript is een kleine programmeertaal die compileerd naar JavaScript, +er is geen interpretatie tijdens het uitvoeren. +Als een van de nakomelingen van JavaScript probeert CoffeeScript om leesbare, +goed geformatteerdeen goed draaiende JavaScript code te genereren, +die in elke JavaScript runtime werkt. + +Op [de CoffeeScript website](http://coffeescript.org/), staat een +vollediger tutorial voor CoffeeScript. + +``` coffeescript +# CoffeeScript is een taal voor hipsters. +# Het gaat mee met alle trends van moderne talen. +# Dus commentaar begint met een hekje, net zoals bij Python en Ruby. + +### +Blokken commentaar maak je zo, ze vertalen naar JavaScripts */ en /* +in de uitvoer van de CoffeeScript compiler. + +Het is belangrijk dat je ongeveer snapt hoe JavaScript +werkt voordat je verder gaat. +### + +# Toewijzing: +getal = 42 #=> var getal = 42; +tegengestelde = true #=> var tegengestelde = true; + +# Voorwaarden: +getal = -42 if tegengestelde #=> if(tegengestelde) { getal = -42; } + +# Functies: +kwadraat = (x) -> x * x #=> var kwadraat = function(x) { return x * x; } + +vul = (houder, vloeistof = "koffie") -> + "Nu de #{houder} met #{koffie} aan het vullen..." +#=>var vul; +# +#vul = function(houder, vloeistof) { +# if (vloeistof == null) { +# vloeistof = "coffee"; +# } +# return "Nu de " + houder + " met " + vloeistof + " aan het vullen..."; +#}; + +# Reeksen: +lijst = [1..5] #=> var lijst = [1, 2, 3, 4, 5]; + +# Objecten: +wiskunde = + wortel: Math.sqrt + kwadraat: kwadraat + derdemacht: (x) -> x * kwadraat x +#=> var wiskunde = { +# "wortel": Math.sqrt, +# "kwadraat": kwadraat, +# "derdemacht": function(x) { return x * kwadraat(x); } +#} + +# "Splats": +wedstrijd = (winnaar, lopers...) -> + print winnaar, lopers +#=>wedstrijd = function() { +# var lopers, winnaar; +# winnaar = arguments[0], lopers = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winnaar, lopers); +#}; + +# Bestaan: +alert "Ik wist het!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# Lijst abstractie: +derdemachten = (wiskunde.derdemacht num for num in lijst) +#=>derdemachten = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = lijst.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(wiskunde.derdemacht(num)); +# } +# return _results; +# })(); + +etenswaren = ['broccoli', 'spinazie', 'chocolade'] +eet eten for eten in etenswaren when eten isnt 'chocolade' +#=>etenswaren = ['broccoli', 'spinazie', 'chocolade']; +# +#for (_k = 0, _len2 = etenswaren.length; _k < _len2; _k++) { +# eten = etenswaren[_k]; +# if (eten !== 'chocolade') { +# eet(eten); +# } +#} +``` + +## Handige links (in het Engels): + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) -- cgit v1.2.3 From a58968d81385090ed626bdfe23371286624e6db6 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: Fri, 19 Sep 2014 22:54:06 +0300 Subject: Oops, now I hope that's all --- ru-ru/python3-ru.html.markdown | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown index bf1af599..637c0157 100644 --- a/ru-ru/python3-ru.html.markdown +++ b/ru-ru/python3-ru.html.markdown @@ -113,7 +113,7 @@ not False #=> True # None является объектом None #=> None -# Не используйте оператор равенства '=='' для сравнения +# Не используйте оператор равенства '==' для сравнения # объектов с None. Используйте для этого 'is' "etc" is None #=> False None is None #=> True @@ -266,7 +266,7 @@ del filled_dict["one"] # Удаляет ключ «one» из словаря # Множества содержат... ну, в общем, множества empty_set = set() # Инициализация множества набором значений. -# Да, оно выглядит примерно как словарь… ну извините. +# Да, оно выглядит примерно как словарь… ну извините, так уж вышло. filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} # Множеству можно назначать новую переменную @@ -307,14 +307,10 @@ else: # Это тоже необязательно. print("some_var равно 10.") -""" -Циклы For проходят по спискам - -Результат: - собака — это млекопитающее - кошка — это млекопитающее - мышь — это млекопитающее -""" +# Циклы For проходят по спискам. Результат: + # собака — это млекопитающее + # кошка — это млекопитающее + # мышь — это млекопитающее for animal in ["собака", "кошка", "мышь"]: # Можете использовать format() для интерполяции форматированных строк print("{} — это млекопитающее".format(animal)) @@ -386,7 +382,7 @@ our_iterator.__next__() #=> "three" # Возвратив все данные, итератор выбрасывает исключение StopIterator our_iterator.__next__() # Выбрасывает исключение остановки итератора -# Вы можете взять все элементы итератора, вызвав на нём функцию list(). +# Вы можете получить сразу все элементы итератора, вызвав на нём функцию list(). list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"] @@ -455,7 +451,7 @@ def setGlobalX(num): setX(43) setGlobalX(6) -# В Python есть функции первого класса +# В Python функции — «объекты первого класса». Это означает, что их можно использовать наравне с любыми другими значениями def create_adder(x): def adder(y): return x + y @@ -578,7 +574,7 @@ def double_numbers(iterable): # мы используем подчёркивание в конце range_ = range(1, 900000000) -# Будет удваивать все числа, пока результат не будет >= 30 +# Будет удваивать все числа, пока результат не превысит 30 for i in double_numbers(xrange_): print(i) if i >= 30: -- cgit v1.2.3 From 17e1f7293a2054260519cb39ba2ac743f64d573a Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Fri, 19 Sep 2014 19:55:52 -0500 Subject: Fixes and updates --- nim.html.markdown | 98 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 56 insertions(+), 42 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index 69d0f804..edbbd92c 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -1,5 +1,5 @@ --- -language: nim +language: Nim filename: learnNim.nim contributors: - ["Jason J. Ayala P.", "http://JasonAyala.com"] @@ -14,20 +14,12 @@ Nim is efficient, expressive, and elegant. ```nimrod -var x: int # Declare a variable and its type -x = 1 # Assign it a value -var z = "Yep" # Declare and assign, with or without type annotations - -var # Several, with or without type annotations - letter: char = 'n' # One byte character - lang = "Nimrod" # string - truth: bool = false # Common boolean operators: `and` `not` `or` - seconds: int = 42 - thoughts = """ -A great programming language -that everyone can enjoy! -""" # Multiline raw strings +var # Declare and assign several variables, + letter: char = 'n' # with or without type annotations + lang = "Nimrod" boat: float + truth: bool = false + seconds: int = 42 let # Use let to declare and bind an variable *once*. legs = 400 # legs is immutable. @@ -46,19 +38,20 @@ discard 1 > 2 # The compiler will complain if the result of an expression # is unused. `discard` bypasses this. discard """ -This can work as a -multiline comment +This can work as a multiline comment. +Or for unparsable, broken code """ # # Common Operations on Basic Types # +# Strings let - phrase = "Nim is a progamming language" + phrase = "Nim is a" nim = phrase[0..5] - -# TODO More common operations? + fullPhrase = phrase & "programming language." + length = len(fullPhrase) # Or: fullPhrase.len # # Data Structures @@ -90,7 +83,7 @@ drinks = @["Water", "Juice", "Chocolate"] # @[V1,..,Vn] is the sequence literal type Name = string # A type alias gives you a new type that is interchangable - Age = int # with the old type but is more descriptive. + Age = int # with the old type but is more descriptive. Person = tuple[name: Name, age: Age] # Define data structures too. LongTuple = tuple fieldOne: string @@ -103,11 +96,11 @@ var john.age = newage # But still works because int and Age are synonyms type - Cash = distinct int # `distinct` makes a new type incompatible with it's + Cash = distinct int # `distinct` makes a new type incompatible with its Desc = distinct string # base type. var - money: Cash = 100.Cash # `.Cash` converts the int to our type + money: Cash = 100.Cash # `.Cash` converts the int to our type description: Desc = "Interesting".Desc when compileBadCode: @@ -121,7 +114,7 @@ when compileBadCode: # Enumerations allow a type to be one of a limited number of values type - Color = enum cRed, cBlue, cGreen + Color = enum cRed, cBlue, cGreen Direction = enum # Alternative formating dNorth dWest @@ -129,7 +122,7 @@ type dSouth var orient = dNorth # `orient` is of type Direction, with the value `dNorth` - pixel = cGreen # `pixel` is of type Color, with the value `cGreen` + pixel = cGreen # `pixel` is of type Color, with the value `cGreen` discard dNorth > dEast # Enums are usually an "ordinal" type @@ -166,7 +159,9 @@ counter[my_roll] += 1 var anotherArray = ["Default index", "starts at", "0"] -# TODO common operations +# More data structures are available, including tables, sets, lists, queues, +# and crit bit trees. +# http://nimrod-lang.org/lib.html#collections-and-algorithms # # IO and Control Flow @@ -183,26 +178,24 @@ of "yes", "Yes": else: echo "That's great; I assume." -# `while`, `if`, `continue`, `break` +# `while`, `if`, `break` -import strutils as str +import strutils as str # http://nimrod-lang.org/strutils.html echo "I'm thinking of a number between 41 and 43. Guess which!" +let number: int = 42 var - number: int = 42 raw_guess: string guess: int while guess != number: raw_guess = readLine(stdin) - if raw_guess == "": - continue # `continue` restarts loop/block guess = str.parseInt(raw_guess) if guess == 1001: echo("AAAAAAGGG!") break elif guess > number: - echo("Too high.") + echo("Nope. Too high.") elif guess < number: - echo("Too low") + echo(guess, " is too low") else: echo("Yeeeeeehaw!") @@ -210,23 +203,25 @@ while guess != number: # Iteration # -# Iterate with the `for` keyword -# TODO `for` examples for strings, arrays, etc +for i, elem in ["Yes", "No", "Maybe so"]: # Or just `for elem in` + echo(elem, " is at index: ", i) -for elem in ["Yes", "No", "Maybe so"]: - echo elem - -# string iterators +for k, v in items(@[(person: "You", power: 100), (person: "Me", power: 9000)]): + echo v let myString = """ -an example -string to +an +`string` to play with -""" +""" # Multiline raw string for line in splitLines(myString): echo(line) +for i, c in myString: # Index and letter. Or `for j in` for just letter + if i mod 2 == 0: continue # Compact `if` form + elif c == 'X': break + else: echo(c) # # Procedures # @@ -244,8 +239,9 @@ proc ask(question: string): Answer = else: echo("Please be clear: yes or no") proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing + assert(amount > 0 or amount < 9000, "Crazy Sugar") for a in 1..amount: - echo a, " sugar..." + echo(a, " sugar...") case ask("Would you like sugar in your tea?") of aYes: @@ -255,8 +251,25 @@ of aNo: addSugar() # No need for an `else` here. only `yes` and `no` are possible. +proc pluralize(a: int): string = + if a > 1 or a == 0: return "s" + else: return "" + +# +# FFI +# + +# Because Nim compiles to C, FFI is easy: + +proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.} + +var cmp = strcmp("C?", "Easy!") + ``` +Additionally, Nim separates itself from its peers with metaprogramming, +performance, and compile-time features. + ## Further Reading * [Home Page](http://nimrod-lang.org) @@ -266,3 +279,4 @@ of aNo: * [Documentation](http://nimrod-lang.org/documentation.html) * [Manual](http://nimrod-lang.org/manual.html) * [Standard Libray](http://nimrod-lang.org/lib.html) +* [Rosetta Code](http://rosettacode.org/wiki/Category:Nimrod) -- cgit v1.2.3 From e0c71555d9f521480c44df2da58334bdacb7cdc9 Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Fri, 19 Sep 2014 19:57:33 -0500 Subject: shorter desc --- nim.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index edbbd92c..48a24834 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -7,8 +7,7 @@ contributors: Nim (formally Nimrod) is a statically typed, imperative programming language that tries to give the programmer ultimate power without compromises on runtime -efficiency. This means it focuses on compile-time mechanisms in all their -various forms. +efficiency. Nim is efficient, expressive, and elegant. -- cgit v1.2.3 From 4595c7e3ed55b10b449e817657f3647f51e5a501 Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Fri, 19 Sep 2014 20:00:13 -0500 Subject: Removed common operations, explained continue --- nim.html.markdown | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index 48a24834..f22d0365 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -41,17 +41,6 @@ This can work as a multiline comment. Or for unparsable, broken code """ -# -# Common Operations on Basic Types -# - -# Strings -let - phrase = "Nim is a" - nim = phrase[0..5] - fullPhrase = phrase & "programming language." - length = len(fullPhrase) # Or: fullPhrase.len - # # Data Structures # @@ -218,8 +207,8 @@ for line in splitLines(myString): echo(line) for i, c in myString: # Index and letter. Or `for j in` for just letter - if i mod 2 == 0: continue # Compact `if` form - elif c == 'X': break + if i mod 2 == 0: continue # Skip rest of iteration + elif c == 'X': break # Compact `if` form else: echo(c) # # Procedures @@ -259,7 +248,7 @@ proc pluralize(a: int): string = # # Because Nim compiles to C, FFI is easy: - +# proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.} var cmp = strcmp("C?", "Easy!") -- cgit v1.2.3 From 08c18afeb327303bab9473199f43d903d03a2607 Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Fri, 19 Sep 2014 20:02:13 -0500 Subject: cleanup --- nim.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index f22d0365..f84b8bbd 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -210,6 +210,7 @@ for i, c in myString: # Index and letter. Or `for j in` for just letter if i mod 2 == 0: continue # Skip rest of iteration elif c == 'X': break # Compact `if` form else: echo(c) + # # Procedures # @@ -237,7 +238,7 @@ of aYes: of aNo: echo "Oh do take a little!" addSugar() -# No need for an `else` here. only `yes` and `no` are possible. +# No need for an `else` here. Only `yes` and `no` are possible. proc pluralize(a: int): string = if a > 1 or a == 0: return "s" @@ -248,7 +249,7 @@ proc pluralize(a: int): string = # # Because Nim compiles to C, FFI is easy: -# + proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.} var cmp = strcmp("C?", "Easy!") -- cgit v1.2.3 From 91e68f583099518b7ab64c323d5f13750eb2b14c Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Fri, 19 Sep 2014 20:04:08 -0500 Subject: cleanup --- nim.html.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index f84b8bbd..929d0a74 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -240,10 +240,6 @@ of aNo: addSugar() # No need for an `else` here. Only `yes` and `no` are possible. -proc pluralize(a: int): string = - if a > 1 or a == 0: return "s" - else: return "" - # # FFI # -- cgit v1.2.3 From b87f1acc216ae59ec29c7481008d86de081ffedc Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Fri, 19 Sep 2014 20:14:51 -0500 Subject: cleanup --- nim.html.markdown | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index 929d0a74..eca3aa2d 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -12,28 +12,27 @@ efficiency. Nim is efficient, expressive, and elegant. ```nimrod - var # Declare and assign several variables, letter: char = 'n' # with or without type annotations - lang = "Nimrod" + lang = "N" & "im" + n_let : int = len(lang) boat: float truth: bool = false - seconds: int = 42 let # Use let to declare and bind an variable *once*. legs = 400 # legs is immutable. arms = 2_000 # _ are ignored and are useful for long numbers. + aboutPi = 3.15 const # Constants are computed at compile time. This provides debug = true # performance and is useful in compile time expressions. - aboutPi = 3.15 compileBadCode = false when compileBadCode: # `when` is a compile time `if` legs = legs + 1 # This error will never be compiled. - const input = readline(stdin) # const values must be known at compile time. + const input = readline(stdin) # Const values must be known at compile time. -discard 1 > 2 # The compiler will complain if the result of an expression +discard 1 > 2 # Note: The compiler will complain if the result of an expression # is unused. `discard` bypasses this. discard """ @@ -63,7 +62,7 @@ var drinks = @["Water", "Juice", "Chocolate"] # @[V1,..,Vn] is the sequence literal # -# Defining Your Own Types +# Defining Types # # Defining your own types puts the compiler to work for you. It's what makes @@ -73,13 +72,13 @@ type Name = string # A type alias gives you a new type that is interchangable Age = int # with the old type but is more descriptive. Person = tuple[name: Name, age: Age] # Define data structures too. - LongTuple = tuple + AnotherSyntax = tuple fieldOne: string secondField: int var - john: Person = ("John B.", 17) - newage: int = 18 # It would be better to use Age than int + john: Person = (name: "John B.", age: 17) + newage: int = 18 # It would be better to use Age than int john.age = newage # But still works because int and Age are synonyms @@ -166,7 +165,7 @@ of "yes", "Yes": else: echo "That's great; I assume." -# `while`, `if`, `break` +# `while`, `if`, `continue`, `break` import strutils as str # http://nimrod-lang.org/strutils.html echo "I'm thinking of a number between 41 and 43. Guess which!" @@ -176,6 +175,7 @@ var guess: int while guess != number: raw_guess = readLine(stdin) + if raw_guess = "": continue # Skip this iteration guess = str.parseInt(raw_guess) if guess == 1001: echo("AAAAAAGGG!") @@ -207,8 +207,8 @@ for line in splitLines(myString): echo(line) for i, c in myString: # Index and letter. Or `for j in` for just letter - if i mod 2 == 0: continue # Skip rest of iteration - elif c == 'X': break # Compact `if` form + if i mod 2 == 0: continue # Compact `if` form + elif c == 'X': break else: echo(c) # @@ -240,6 +240,10 @@ of aNo: addSugar() # No need for an `else` here. Only `yes` and `no` are possible. +proc pluralize(a: int): string = + if a > 1 or a == 0: return "s" + else: return "" + # # FFI # @@ -249,7 +253,6 @@ of aNo: proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.} var cmp = strcmp("C?", "Easy!") - ``` Additionally, Nim separates itself from its peers with metaprogramming, -- cgit v1.2.3 From 64cd3c4e2245b66546dbc091c1737d9660f7ef94 Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Fri, 19 Sep 2014 20:17:59 -0500 Subject: cleanup --- nim.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index eca3aa2d..3b826cf4 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -12,14 +12,14 @@ efficiency. Nim is efficient, expressive, and elegant. ```nimrod -var # Declare and assign several variables, +var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" n_let : int = len(lang) boat: float truth: bool = false -let # Use let to declare and bind an variable *once*. +let # Use let to declare and bind variables *once*. legs = 400 # legs is immutable. arms = 2_000 # _ are ignored and are useful for long numbers. aboutPi = 3.15 -- cgit v1.2.3 From 2caa82052da942c95b8bfa937c7183ac16652718 Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Fri, 19 Sep 2014 20:19:16 -0500 Subject: cleanup --- nim.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nim.html.markdown b/nim.html.markdown index 3b826cf4..b14f0a7e 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -15,7 +15,7 @@ Nim is efficient, expressive, and elegant. var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" - n_let : int = len(lang) + n_length : int = len(lang) boat: float truth: bool = false -- cgit v1.2.3 From 24cee5a4e6c2f7f4dd5519bd2ae161a5df21de0a Mon Sep 17 00:00:00 2001 From: JasonJAyalaP Date: Fri, 19 Sep 2014 20:20:08 -0500 Subject: cleanup --- nim.html.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index b14f0a7e..cb5f71a2 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -240,10 +240,6 @@ of aNo: addSugar() # No need for an `else` here. Only `yes` and `no` are possible. -proc pluralize(a: int): string = - if a > 1 or a == 0: return "s" - else: return "" - # # FFI # -- cgit v1.2.3 From dce5898d0696fe76940723b85a52c6fe191196fd Mon Sep 17 00:00:00 2001 From: Jason J Ayala P Date: Fri, 19 Sep 2014 20:26:31 -0500 Subject: cleanup --- nim.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index cb5f71a2..c878b5b6 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -6,8 +6,7 @@ contributors: --- Nim (formally Nimrod) is a statically typed, imperative programming language -that tries to give the programmer ultimate power without compromises on runtime -efficiency. +that gives the programmer power without compromises on runtime efficiency. Nim is efficient, expressive, and elegant. -- cgit v1.2.3 From 7c450ebc0c10aa7a696045131e41db8c09974dc8 Mon Sep 17 00:00:00 2001 From: Jason J Ayala P Date: Fri, 19 Sep 2014 20:30:11 -0500 Subject: minor fix --- nim.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nim.html.markdown b/nim.html.markdown index c878b5b6..468e6442 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -174,7 +174,7 @@ var guess: int while guess != number: raw_guess = readLine(stdin) - if raw_guess = "": continue # Skip this iteration + if raw_guess == "": continue # Skip this iteration guess = str.parseInt(raw_guess) if guess == 1001: echo("AAAAAAGGG!") -- cgit v1.2.3 From 86022f3f3fa9a17ae0902855f25578815b6be49d Mon Sep 17 00:00:00 2001 From: Jason J Ayala P Date: Fri, 19 Sep 2014 20:33:21 -0500 Subject: proof reading --- nim.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nim.html.markdown b/nim.html.markdown index 468e6442..06adba81 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -97,7 +97,7 @@ when compileBadCode: # More Types and Data Structures # -# Enumerations allow a type to be one of a limited number of values +# Enumerations allow a type to have one of a limited number of values type Color = enum cRed, cBlue, cGreen -- cgit v1.2.3 From d7e939ffd712e3b6ae1f45b81b1cc0248a28d00a Mon Sep 17 00:00:00 2001 From: Jason J Ayala P Date: Sat, 20 Sep 2014 07:07:06 -0500 Subject: minor tweaks --- nim.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index 06adba81..4619975d 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -14,7 +14,7 @@ Nim is efficient, expressive, and elegant. var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" - n_length : int = len(lang) + nLength : int = len(lang) boat: float truth: bool = false @@ -247,7 +247,7 @@ of aNo: proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.} -var cmp = strcmp("C?", "Easy!") +let cmp = strcmp("C?", "Easy!") ``` Additionally, Nim separates itself from its peers with metaprogramming, -- cgit v1.2.3 From 92a2dbf34eeec0f4faf610e1b4d464d91dd10010 Mon Sep 17 00:00:00 2001 From: Geoffrey Liu Date: Sun, 21 Sep 2014 00:07:34 -0700 Subject: Fixes issue #747 --- julia.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index e9d3a162..82712553 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -12,7 +12,7 @@ This is based on the current development version of Julia, as of October 18th, 2 ```ruby -# Single line comments start with a number symbol. +# Single line comments start with a hash (pound) symbol. #= Multiline comments can be written by putting '#=' before the text and '=#' after the text. They can also be nested. -- cgit v1.2.3 From 1b90e0f41b8222ac3472e427e401073483760bfa Mon Sep 17 00:00:00 2001 From: Geoffrey Liu Date: Sun, 21 Sep 2014 00:22:26 -0700 Subject: Update the CSS tutorial add more properties, formatting, spelling/grammar, more actual examples --- css.html.markdown | 91 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 51 insertions(+), 40 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index cdef50cc..e058d691 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -3,6 +3,7 @@ language: css contributors: - ["Mohammad Valipour", "https://github.com/mvalipour"] - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] filename: learncss.css --- @@ -24,18 +25,19 @@ The main focus of this article is on the syntax and some general tips. ```css -/* comments appear inside slash-asterisk, just like this line! */ +/* comments appear inside slash-asterisk, just like this line! + there are no "one-line comments"; this is the only comment style */ /* #################### ## SELECTORS - ####################*/ + #################### */ /* Generally, the primary statement in CSS is very simple */ selector { property: value; /* more properties...*/ } /* the selector is used to target an element on page. -You can target all elments on the page! */ +You can target all elments on the page using asterisk! */ * { color:red; } /* @@ -62,61 +64,61 @@ div { } /* or that the attribute has a specific value */ [attr='value'] { font-size:smaller; } -/* start with a value*/ +/* start with a value (CSS3) */ [attr^='val'] { font-size:smaller; } -/* or ends with */ +/* or ends with (CSS3) */ [attr$='ue'] { font-size:smaller; } -/* or even contains a value */ +/* or even contains a value (CSS3) */ [attr~='lu'] { font-size:smaller; } /* and more importantly you can combine these together -- there shouldn't be -any spaaace between different parts because that makes it to have another -meaning.*/ +any space between different parts because that makes it to have another +meaning. */ div.some-class[attr$='ue'] { } -/* you can also select an element based on its parent.*/ +/* you can also select an element based on its parent. */ -/*an element which is direct child of an element (selected the same way) */ +/* an element which is direct child of an element (selected the same way) */ div.some-parent > .class-name {} -/* or any of its parents in the tree */ -/* the following basically means any element that has class "class-name" -and is child of a div with class name "some-parent" IN ANY DEPTH */ +/* or any of its parents in the tree + the following basically means any element that has class "class-name" + and is child of a div with class name "some-parent" IN ANY DEPTH */ div.some-parent .class-name {} /* warning: the same selector wihout spaaace has another meaning. -can you say what? */ + can you say what? */ div.some-parent.class-name {} /* you also might choose to select an element based on its direct -previous sibling */ + previous sibling */ .i-am-before + .this-element { } -/*or any sibling before this */ +/* or any sibling before this */ .i-am-any-before ~ .this-element {} /* There are some pseudo classes that allows you to select an element -based on its page behaviour (rather than page structure) */ + based on its page behaviour (rather than page structure) */ /* for example for when an element is hovered */ -:hover {} +selector:hover {} -/* or a visited link*/ -:visited {} +/* or a visited link */ +selected:visited {} -/* or not visited link*/ -:link {} +/* or not visited link */ +selected:link {} /* or an input element which is focused */ -:focus {} +selected:focus {} /* #################### ## PROPERTIES - ####################*/ + #################### */ selector { @@ -126,8 +128,12 @@ selector { width: 200px; /* in pixels */ font-size: 20pt; /* in points */ width: 5cm; /* in centimeters */ - width: 50mm; /* in millimeters */ - width: 5in; /* in inches */ + min-width: 50mm; /* in millimeters */ + max-width: 5in; /* in inches. max-(width|height) */ + height: 0.2vh; /* times vertical height of browser viewport (CSS3) */ + width: 0.4vw; /* times horizontal width of browser viewport (CSS3) */ + min-height: 0.1vmin; /* the lesser of vertical, horizontal dimensions of browser viewport (CSS3) */ + max-width: 0.3vmax; /* same as above, except the greater of the dimensions (CSS3) */ /* Colors */ background-color: #F6E; /* in short hex */ @@ -135,16 +141,20 @@ selector { background-color: tomato; /* can be a named color */ background-color: rgb(255, 255, 255); /* in rgb */ background-color: rgb(10%, 20%, 50%); /* in rgb percent */ - background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb */ + background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb (CSS3) */ + background-color: transparent; /* see thru */ + background-color: hsl(0, 100%, 50%); /* hsl format (CSS3). */ + background-color: hsla(0, 100%, 50%, 0.3); /* Similar to RGBA, specify opacity at end (CSS3) */ + /* Images */ - background-image: url(/path-to-image/image.jpg); + background-image: url(/path-to-image/image.jpg); /* quotes inside url() optional */ /* Fonts */ font-family: Arial; - font-family: "Courier New"; /* if name has spaaace it appears in double-quote */ - font-family: "Courier New", Trebuchet, Arial; /* if first one was not found - browser uses the second font, and so forth */ + font-family: "Courier New"; /* if name has spaaace it appears in single or double quotes */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; /* if first one was not found + browser uses the second font, and so forth */ } ``` @@ -155,17 +165,17 @@ Save any CSS you want in a file with extension `.css`. ```xml - + -
+
``` @@ -207,27 +217,28 @@ The precedence of style is as followed: Remember, the precedence is for each **property**, not for the entire block. * `E` has the highest precedence because of the keyword `!important`. - It is recommended to avoid this unless it is strictly necessary to use. + It is recommended to avoid this unless it is strictly necessary to use. * `F` is next, because it is inline style. * `A` is next, because it is more "specific" than anything else. - more specific = more specifiers. here 3 specifiers: 1 tagname `p` + - class name `class1` + 1 attribute `attr='value'` + more specific = more specifiers. here 3 specifiers: 1 tagname `p` + + class name `class1` + 1 attribute `attr='value'` * `C` is next. although it has the same specificness as `B` - but it appears last. + but it appears last. * Then is `B` * and lastly is `D`. ## Compatibility Most of the features in CSS2 (and gradually in CSS3) are compatible across -all browsers and devices. But it's always vital to have in mind the compatiblity +all browsers and devices. But it's always vital to have in mind the compatiblity of what you use in CSS with your target browsers. [QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. +To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource. + ## Further Reading * [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) * [QuirksMode CSS](http://www.quirksmode.org/css/) * [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) - -- cgit v1.2.3 From c3dc01418092cc13e13ce0c81da2c8ef7208f228 Mon Sep 17 00:00:00 2001 From: m90 Date: Sun, 21 Sep 2014 10:57:16 +0200 Subject: fix lots of typos, weird phrasings and translation errors --- de-de/css-de.html.markdown | 179 ++++++++++++++++++++++----------------------- 1 file changed, 89 insertions(+), 90 deletions(-) diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown index 8909b251..23c1df94 100644 --- a/de-de/css-de.html.markdown +++ b/de-de/css-de.html.markdown @@ -8,107 +8,106 @@ lang: de-de filename: learncss-de.css --- -In den frühen Tagen des Internets gab es keine visuellen Elemente, alles war nur reiner Text. Aber mit der Weiterentwickliung von Browsern wurden auch vollständig visuelle Webseiten zu einem Standard. -CSS ist die allgemeine Sprache, die dazu da ist, damit man den HTML-Code und die Designelemente von Webseiten (strikt) unterscheiden kann. +In den frühen Tagen des Internets gab es keine visuellen Elemente, alles war nur reiner Text. Aber mit der Weiterentwicklung von Browsern wurden auch vollständig visuelle Webseiten zu einem Standard. +Durch Verwendung von CSS lässt sich eine strikte Trennung zwischen HTML-Code und Designelementen erreichen. -Kurzgefasst, CSS ermöglicht es, verschiedene HTML-Elemente anzuvisieren und ihnen stilistische Eigenschaften zu geben. +Kurzgefasst, CSS ermöglicht es, verschiedene HTML-Elemente innerhalb eines Dokuments auszuwählen und ihnen visuelle Eigenschaften zu geben. CSS hat wie jede andere Sprache viele Versionen. Hier fokussieren wir uns auf CSS2.0, welche nicht die neueste, aber die am weitesten verbreitete und unterstützte Version ist. -**NOTE:** Weil die Ausgabe von CSS visuelle Eigenschaften sind, wirst du wahrscheinlich eine CSS-Sandbox wie [dabblet](http://dabblet.com/) benutzen müssen, um die Sprache richtig zu lernen. +**HINWEIS:** Weil die Ausgabe von CSS visuelle Eigenschaften sind, wirst du wahrscheinlich eine CSS-Sandbox wie [dabblet](http://dabblet.com/) benutzen müssen, um die Sprache richtig zu lernen. In diesem Artikel wird am meisten auf generelle Hinweise und die Syntax geachtet. ```css -/* kommentare werden in sternchen-schrägstrichkombinationen gepackt (genauso wie hier!) */ +/* Kommentare werden in Sternchen-Schrägstrichkombinationen gepackt (genauso wie hier!) */ /* #################### ## SELEKTOREN ####################*/ -/* Eigentlich ist die häufigste Anwendungsweise von CSS sehr simpel */ +/* Eigentlich ist das grundlegende CSS-Statement sehr simpel */ selektor { eigenschaft: wert; /* mehr eigenschaften...*/ } -/* der selektor wird dazu benutzt, ein element auf der seite anzuvisieren +/* Der Selektor wird dazu benutzt, ein Element auf der Seite auszuwählen. -Aber man kann auch alle Elemente auf einer Seite anvisieren! */ +Man kann aber auch alle Elemente auf einer Seite auswählen! */ * { color:red; } /* farbe:rot */ /* -Wenn wir so ein Element auf einer Seite haben: +Angenommen wir haben folgendes Element auf einer Seite:
*/ -/* kann man es so bei seiner klasse anvisieren */ +/* kann man es so über seine Klasse auswählen */ .eine-klasse { } -/*oder bei beiden klassen! */ +/* oder über beide Klassen! */ .eine-klasse.klasse2 { } -/* oder beim namen des tags */ +/* oder über den Namen des Tags */ div { } -/* oder bei seiner id */ +/* oder über seine Id */ #eineId { } -/* oder daran, dass es ein Attribut hat! */ +/* oder darüber, dass es ein Attribut hat! */ [attr] { font-size:smaller; } -/* oder daran, dass das attribut einen bestimmten wert hat*/ +/* oder auch darüber, dass das Attribut einen bestimmten Wert hat */ [attr='wert'] { font-size:smaller; } -/* beginnt mit einem wert*/ -[attr^='wert'] { font-size:smaller; } +/* beginnt mit dem übergebenen Wert */ +[attr^='we'] { font-size:smaller; } -/* oder endet mit */ +/* endet damit */ [attr$='rt'] { font-size:smaller; } -/* oder sogar nur beinhaltet */ +/* oder beinhaltet einen Teil davon */ [attr~='er'] { font-size:smaller; } -/* was aber noch wichtiger ist, ist dass man alle diese kombinieren -kann - man sollte nur mit der leerzeichensetzung vorsichtig sein, -da es mit einem leerzeichen zwei verschiedene selektoren wären*/ +/* Noch wichtiger ist aber die Möglichkeit, all das miteinander kombinieren +zu können - man sollte hierbei nur mit der Leerzeichensetzung vorsichtig sein, +ein Leerzeichen macht es zu zwei verschiedenen Selektoren */ + div.eine-klasse[attr$='rt'] { } /* so ist es richtig */ -/* man kann auch ein element daran festmachen, wie sich die übergeordneten -elemente verhalten!*/ +/* Man kann auch ein Element über seine Elternelemente auswählen */ -/*es muss allerdings ein direktes kind sein */ +/* > wählt ein direktes Kind aus */ div.ein-elternteil > .klassen-name {} -/* oder jeder seiner eltern in der struktur */ -/* das folgende heißt also, dass jedes element mit der klasse 'klassen-name' -und dem elternteil IN JEDER TIEFE ausgewählt wird */ +/* Mit einem Leerzeichen getrennt kann man alle Elternelemente ansprechen */ +/* Das folgende heißt also, dass jedes Element mit der Klasse 'klassen-name' +und dem Elternteil IN JEDER TIEFE ausgewählt wird */ div.ein-elternteil .klassen-name {} -/* achtung: dasselbe ohne das leerzeichen hat eine andere bedeutung, +/* Achtung: das selbe ohne das Leerzeichen hat eine andere Bedeutung, kannst du mir sagen, was? */ div.ein-elternteil.klassen-name {} -/* man kann auch ein element nach seinem direkten vorherigen zwilling +/* Man kann ein Element auch nach seinem direkten Nachbarelement auswählen */ .ich-bin-vorher + .dieses-element { } -/* oder jeden zwilling davor */ +/* Oder über jedes Geschwisterelement davor */ .ich-kann-jeder-davor-sein ~ .dieses-element {} -/* es gibt ein paar pseudoklassen, die sich basierend auf dem -seitenverhalten, nämlich nicht auf der seitenstruktur auswählen -lassen können */ +/* Mit Pseudoklassen lassen sich Elemente anhand ihres momentanen Zustands +auf der Seite auswählen (anstatt über die Seitenstruktur) */ -/* zum beispiel, wenn über ein element mit dem mauszeiger gefahren wird */ +/* Zum Beispiel, wenn über ein Element mit dem Mauszeiger gefahren wird */ :hover {} -/* oder einen bereits besuchten link*/ +/* Oder einen bereits besuchten Link*/ :visited {} -/* oder einen noch nicht besuchten link*/ +/* Oder einen noch nicht besuchten Link*/ :link {} -/* oder ein eingabeelement, das zurzeit im fokus steht */ +/* Oder ein Eingabeelement, das zurzeit im Fokus steht */ :focus {} @@ -117,64 +116,64 @@ lassen können */ ####################*/ selector { - - /* einheiten */ - width: 50%; /* in prozent */ - font-size: 2em; /* mal der derzeitigen schriftgröße */ - width: 200px; /* in pixeln */ - font-size: 20pt; /* in punkten */ - width: 5cm; /* in zentimetern */ - width: 50mm; /* in millimetern */ - width: 5in; /* in zoll */ - - /* farben */ - background-color: #F6E /* in kurzem hex */ - background-color: #F262E2 /* in langem hex */ - background-color: tomato /* kann auch eine genannte farbe sein */ - background-color: rgb(255, 255, 255) /* in rgb */ - background-color: rgb(10%, 20%, 50%) /* in rgb prozent */ - background-color: rgba(255, 0, 0, 0.3); /* in semi-transparentem rgb */ - - /* bilder */ + + /* Einheiten */ + width: 50%; /* in Prozent */ + font-size: 2em; /* mal der derzeitigen Schriftgröße */ + width: 200px; /* in Pixeln */ + font-size: 20pt; /* in Punkten */ + width: 5cm; /* in Zentimetern */ + width: 50mm; /* in Millimetern */ + width: 5in; /* in Zoll */ + + /* Farben */ + background-color: #F6E /* in kurzem Hex */ + background-color: #F262E2 /* in langem Hex */ + background-color: tomato /* kann auch eine benannte Farbe sein */ + background-color: rgb(255, 255, 255) /* in RGB */ + background-color: rgb(10%, 20%, 50%) /* in RGB Prozent */ + background-color: rgba(255, 0, 0, 0.3); /* in semi-transparentem RGB */ + + /* Bilder */ background-image: url(/pfad-zum-bild/image.jpg); - - /* schriften */ + + /* Schriften */ font-family: Arial; - font-family: "Courier New"; /* wenn der name ein leerzeichen beinhält, kommt er in - apostrophe */ - font-family: "Courier New", Trebuchet, Arial; /* wenn der erste nicht gefunden wird, wird - der zweite benutzt, und so weiter */ + font-family: "Courier New"; /* wenn der Name ein Leerzeichen beinhält, kommt er in + Anführungszeichen */ + font-family: "Courier New", Trebuchet, Arial; /* wird die erste Schriftart + nicht gefunden, wird die zweite benutzt, usw. */ } ``` ## Benutzung -speichere das css, das du benutzen willst mit der endung '.css'. +Speichere das CSS, das du benutzen willst mit der endung '.css'. ```xml - + - - +
``` -## Wichtigkeit +## Spezifität -ein element kann von mehr als einem selektoren angezielt werden. -und kann auch eine eigenschaft mehr als einmal zugewiesen bekommen. -in diesen fällen gibt es regeln, die die wichtigkeit von selektoren einführen. +Ein Element kann natürlich auch von mehr als einer Regel in einem Stylesheet +angesprochen werdenm und kann eine Eigenschaft auch öfters als einmal zugewiesen +bekommen. In diesen Fällen gibt es Regeln, die die Spezifität von Selektoren regeln. -wie haben dieses CSS: +Wir haben dieses CSS: ```css /*A*/ @@ -194,34 +193,34 @@ p { property: wert !important; } ``` -und das folgende markup: +und das folgende Markup: ```xml

``` -die wichtigkeit der stile ist wie folgt: -(die wichtigkeit gilt nur für **eigenschaften**, nicht für ganze blöcke) - -* `E` hat die größte wichtigkeit wegen dem schlüsselwort `!important`. - man sollte diese form aber vermeiden. -* `F` ist als nächstes, da es direkt an dem element definiert ist. -* `A` ist als nächstes, da es "spezifischer" als alle anderen ist. - spezifischer = mehr zuweisungen: 1 tagname `p` + - klassenname `klasse1` + 1 attribut `attr='value'` -* `C` ist als nächstes obwohl es genau so ist wie `B` - aber es erscheint als letztes. -* dann ist `B` +Die Spezifität der Stile ist wie folgt: +(die Spezifität gilt nur für **einzelne Eigenschaften**, nicht für ganze Blöcke) + +* `E` hat die größte Spezifität wegen dem Schlüsselwort `!important`. + man sollte diese Form aber vermeiden. +* `F` ist als nächstes dran, da es direkt an dem element definiert ist. +* Dann folgt `A`, da es "spezifischer" als alle anderen ist. + spezifischer = mehr Zuweisungen: 1 Tagname `p` + + Klassenname `klasse1` + 1 Attribut `attr='value'` +* `C` kommt als nächstes, obwohl es genau so ist wie `B`, + es erscheint aber später im Stylesheet. +* dann kommt `B` * und als letztes `D`. -## Kompabilität +## Kompatibilität -die meisten features von CSS sind in allen browsern verfügbar. -man sollte jedoch immer darauf achten, wenn man etwas mit CSS -programmiert. +Die meisten Features von CSS sind in allen Browsern verfügbar. Man sollte +jedoch immer darauf achten die benutzten Features auf Verfügbarkeit in den +vom Projekt unterstützten Browser zu überprüfen. -[QuirksMode CSS](http://www.quirksmode.org/css/) ist eine der besten quellen dafür. +[QuirksMode CSS](http://www.quirksmode.org/css/) oder [Can I Use](http://caniuse.com/) sind zwei der besten Quellen dafür. ## Weiterlesen -- cgit v1.2.3 From 074d488aa2ce33683ee5066aeffa5b010ffe38a4 Mon Sep 17 00:00:00 2001 From: Frederik Ring Date: Sun, 21 Sep 2014 18:27:43 +0200 Subject: [json/en] JSON should not use single quote delimited strings --- json.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/json.html.markdown b/json.html.markdown index 9041eaa2..f5287138 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -17,7 +17,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. { "key": "value", - "keys": "must always be enclosed in quotes (either double or single)", + "keys": "must always be enclosed in double quotes", "numbers": 0, "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", "has bools?": true, -- cgit v1.2.3 From 41c3d0329a8149340a0703209ba948e45135e239 Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 21 Sep 2014 22:31:07 +0200 Subject: Ruby syntax for nimrod for now --- nim.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nim.html.markdown b/nim.html.markdown index 4619975d..c74fece7 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -10,7 +10,7 @@ that gives the programmer power without compromises on runtime efficiency. Nim is efficient, expressive, and elegant. -```nimrod +```ruby var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" -- cgit v1.2.3 From 54fad387b51371a9af1cb409dac74215c053c1ba Mon Sep 17 00:00:00 2001 From: Geoffrey Liu Date: Sun, 21 Sep 2014 17:16:05 -0700 Subject: Naming conventions in Julia As suggested in #768 by @ChristianPeel --- julia.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 82712553..feb38463 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -125,8 +125,9 @@ SomeOtherVar123! = 6 # => 6 # A note on naming conventions in Julia: # -# * Names of variables are in lower case, with word separation indicated by -# underscores ('\_'). +# * Word separation can be indicated by underscores ('_'), but use of +# underscores is discouraged unless the name would be hard to read +# otherwise. # # * Names of Types begin with a capital letter and word separation is shown # with CamelCase instead of underscores. -- cgit v1.2.3 From 5e5a7a19feb42afad6b678cc970db2ea248fcc9b Mon Sep 17 00:00:00 2001 From: kb Date: Mon, 22 Sep 2014 12:11:49 +0000 Subject: [go] Fix no new variables on left side of := Cannot short declaration twice without at least one new var. Also changing type from string to slice. $ go run learnxiny.go # command-line-arguments ./learnxiny.go:83: no new variables on left side of := ./learnxiny.go:83: cannot use []int literal (type []int) as type string in assignment ./learnxiny.go:84: first argument to append must be slice; have string ./learnxiny.go:90: first argument to append must be slice; have string --- go.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index b4c6afff..17f10bd9 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -72,7 +72,7 @@ func learnMultiple(x, y int) (sum, prod int) { // Some built-in types and literals. func learnTypes() { // Short declaration usually gives you what you want. - s := "Learn Go!" // string type. + str := "Learn Go!" // string type. s2 := `A "raw" string literal can include line breaks.` // Same string type. @@ -126,7 +126,7 @@ can include line breaks.` // Same string type. // Unused variables are an error in Go. // The underbar lets you "use" a variable but discard its value. - _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs // Output of course counts as using a variable. fmt.Println(s, c, a4, s3, d2, m) -- cgit v1.2.3 From e68f2b4da1eb766f7c21e4ae1f3185fb3dba5c3f Mon Sep 17 00:00:00 2001 From: Mienaikage Date: Tue, 23 Sep 2014 17:15:36 +0100 Subject: Added 'lang: es-es' --- es-es/bash-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/bash-es.html.markdown b/es-es/bash-es.html.markdown index 489fd39e..fb89b2a0 100644 --- a/es-es/bash-es.html.markdown +++ b/es-es/bash-es.html.markdown @@ -11,6 +11,7 @@ contributors: translators: - ["Daniel Zendejas", "https://github.com/danielzendejas"] filename: LearnBash-es.sh +lang: es-es --- Tutorial de Shell en español. -- cgit v1.2.3 From b6ba516743d4362b3f079872b1e60c1a54e72aee Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Tue, 23 Sep 2014 23:28:24 +0200 Subject: Exception thingies! --- perl6.html.markdown | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 4e7d8c6e..d12b99ae 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -700,15 +700,37 @@ try { open 'foo'; CATCH { when X::AdHoc { say "unable to open file !" } - # any other exception will be re-raised, since we don't have a `default` + # Any other exception will be re-raised, since we don't have a `default` + # Basically, if a `when` matches (or there's a `default`) marks the exception as + # "handled" so that it doesn't get re-thrown from the `CATCH`. + # You still can re-throw the exception (see below) by hand. } } # You can throw an exception using `die`: die X::AdHoc.new(payload => 'Error !'); -# TODO warn -# TODO fail -# TODO CONTROL + +# You can access the last exception with `$!` (usually used in a `CATCH` block) + +# There are also some subtelties to exceptions. Some Perl 6 subs return a `Failure`, +# which is a kind of "unthrown exception". They're not thrown until you tried to look +# at their content, unless you call `.Bool`/`.defined` on them - then they're handled. +# (the `.handled` method is `rw`, so you can mark it as `False` back yourself) +# +# You can throw a `Failure` using `fail`. Note that if the pragma `use fatal` is on, +# `fail` will throw an exception (like `die`). +fail "foo"; # We're not trying to access the value, so no problem. +try { + fail "foo"; + CATCH { + default { say "It threw because we try to get the fail's value!" } + } +} + +# There is also another kind of exception: Control exceptions. +# Those are "good" exceptions, which happen when you change your program's flow, +# using operators like `return`, `next` or `last`. +# You can "catch" those with `CONTROL` (not 100% working in Rakudo yet). ### Packages # Packages are a way to reuse code. Packages are like "namespaces", and any @@ -1351,6 +1373,9 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... # Note: the first-matching `or` still exists, but is now spelled `||` 'foo' ~~ / fo || foo /; # `fo` now. + + + ### Extra: the MAIN subroutime # The `MAIN` subroutine is called when you run a Perl 6 file directly. # It's very powerful, because Perl 6 actually parses the argument -- cgit v1.2.3 From 7b95a1e9217c6a40d9300681adf1bc2f217507da Mon Sep 17 00:00:00 2001 From: eternalthinker Date: Wed, 24 Sep 2014 08:42:21 +0530 Subject: Added correct syntax for c++ inheritance. [more] Minor indent correction at namespaces intro example --- c++.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 7609dd46..5bf7e2ea 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -132,7 +132,7 @@ namespace myFirstNameSpace cos(int x) { printf("My inner soul was made to program."); - } + } } } @@ -266,10 +266,9 @@ int main () { //C++ Class inheritance -class German_Sheperd +class German_Sheperd : public Doggie { - //This class now inherits everything public and protected from Doggie class - Doggie d_dog; + //This class now inherits everything public and protected from Doggie class //Good practice to put d_ in front of datatypes in classes std::string d_type; -- cgit v1.2.3 From 83d20b05f317732e208819118a3617cad41a950f Mon Sep 17 00:00:00 2001 From: sdlyu Date: Fri, 26 Sep 2014 15:11:06 +0800 Subject: Add chinese translate of LiveScript --- zh-cn/livescript-cn.html.markdown | 319 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 319 insertions(+) create mode 100644 zh-cn/livescript-cn.html.markdown diff --git a/zh-cn/livescript-cn.html.markdown b/zh-cn/livescript-cn.html.markdown new file mode 100644 index 00000000..f6643447 --- /dev/null +++ b/zh-cn/livescript-cn.html.markdown @@ -0,0 +1,319 @@ +--- +language: LiveScript +filename: learnLivescript.ls +contributors: + - ["Christina Whyte", "http://github.com/kurisuwhyte/"] +--- + +LiveScript 是一种具有函数式特性且编译成 JavaScript 的语言,能对应 JavaScript 的基本语法。 +还有些额外的特性如:柯里化,函式组合,模式匹配,还有借镜于 Haskell,F# 和 Scala 的许多特点。 + +LiveScript 诞生于 [Coco][],而 Coco 诞生于 [CoffeeScript][]。 +LiveScript 目前已释出稳定版本,开发中的新版本将会加入更多特性。 + +[Coco]: http://satyr.github.io/coco/ +[CoffeeScript]: http://coffeescript.org/ + +非常期待您的反馈,你可以透过 +[@kurisuwhyte](https://twitter.com/kurisuwhyte) 与我连系 :) + + +```coffeescript +# 与 CoffeeScript 一样,LiveScript 使用 # 单行注解。 + +/* +*多行注解与 C 相同。使用注解可以避免被当成 JavaScript 输出。 +*/ +``` +```coffeescript +# 语法的部份,LiveScript 使用缩进取代 {} 来定义区块, +# 使用空白取代 () 来执行函数。 + + +######################################################################## +## 1. 值类型 +######################################################################## + +# `void` 取代 `undefined` 表示未定义的值 +void # 与 `undefined` 等价但更安全(不会被覆写) + +# 空值则表示成 Null。 +null + + +# 最基本的值类型数据是罗辑类型: +true +false + +# 罗辑类型的一些别名,等价于前者: +on; off +yes; no + + +# 数字与 JS 一样,使用倍精度浮点数表示。 +10 +0.4 # 开头的 0 是必要的 + + +# 可以使用底线及单位后缀提高可读性,编译器自动会略过底线及单位后缀。 +12_344km + + +# 字串与 JS 一样,是一种不可变的字元序列: +"Christina" # 单引号也可以! +"""Multi-line + strings + are + okay + too.""" + +# 在前面加上 \ 符号也可以表示字串: +\keyword # => 'keyword' + + +# 阵列是值的有序集合。 +fruits = + * \apple + * \orange + * \pear + +# 可以用 [] 简洁地表示阵列: +fruits = [ \apple, \orange, \pear ] + + +# 你可以更方便地建立字串阵列,并使用空白区隔元素。 +fruits = <[ apple orange pear ]> + +# 以 0 为起始值的数组下标获取元素: +fruits[0] # => "apple" + + +# 物件是无序键值对集合(更多给节将在下面章节讨论) 。 +person = + name: "Christina" + likes: + * "kittens" + * "and other cute stuff" + +# 你也可以用更简洁的方式表示物件: +person = {name: "Christina", likes: ["kittens", "and other cute stuff"]} + +# 可以透过键值获取值: +person.name # => "Christina" +person["name"] # => "Christina" + + +# 正则表达式的使用跟 JavaScript 一样: +trailing-space = /\s$/ # dashed-words 变成 dashedWords + +# 你也可以用多行描述表达式!(注解和空白会被忽略) +funRE = // + function\s+(.+) # name + \s* \((.*)\) \s* # arguments + { (.*) } # body + // + + +######################################################################## +## 2. 基本运算 +######################################################################## + +# 数值运算子与 JavaScript 一样: +1 + 2 # => 3 +2 - 1 # => 1 +2 * 3 # => 6 +4 / 2 # => 2 +3 % 2 # => 1 + + +# 比较运算子大部份也一样,除了 `==` 等价于 JS 中的 `===`, +# JS 中的 `==` 在 LiveScript 里等价于 `~=`, +# `===` 能进行物件、阵列和严格比较。 +2 == 2 # => true +2 == "2" # => false +2 ~= "2" # => true +2 === "2" # => false + +[1,2,3] == [1,2,3] # => false +[1,2,3] === [1,2,3] # => true + ++0 == -0 # => true ++0 === -0 # => false + +# 其它关系运算子包括 <、<=、> 和 >= + +# 罗辑值可以透过 `or`、`and` 和 `not` 结合: +true and false # => false +false or true # => true +not false # => true + + +# 集合也有一些便利的运算子 +[1, 2] ++ [3, 4] # => [1, 2, 3, 4] +'a' in <[ a b c ]> # => true +'name' of { name: 'Chris' } # => true + + +######################################################################## +## 3. 函数 +######################################################################## + +# 因为 LiveScript 是函数式特性的语言,你可以期待函数在语言里被高规格的对待。 +add = (left, right) -> left + right +add 1, 2 # => 3 + +# 加上 ! 防止函数执行后的回传值 +two = -> 2 +two! + +# LiveScript 与 JavaScript 一样使用函式作用域,且一样拥有闭包的特性。 +# 与 JavaScript 不同的地方在于,`=` 变数赋值时,左边的运算元永远不用变数宣告。 + +# `:=` 运算子在作用域里允许*重用*变数名并创建新的变数作用域。 + + +# 你可以解构函数的参数,从不定长度的参数结构里获取感兴趣的值。 +tail = ([head, ...rest]) -> rest +tail [1, 2, 3] # => [2, 3] + +# 你也可以使用一元或二元运算子转换参数。当然也可以预设传入的参数值。 +foo = (a = 1, b = 2) -> a + b +foo! # => 3 + +# 你可以以复制的方式传入参数来避免副作用,例如: +copy = (^^target, source) -> + for k,v of source => target[k] = v + target +a = { a: 1 } +copy a, { b: 2 } # => { a: 1, b: 2 } +a # => { a: 1 } + + +# 使用长箭号取代短箭号来柯里化一个函数: +add = (left, right) --> left + right +add1 = add 1 +add1 2 # => 3 + +# 函式里有一个隐式的 `it` 变数,意谓着你不用宣告它。 +identity = -> it +identity 1 # => 1 + +# 运算子在 LiveScript 里不是一個函数,但你可以简单地将它们转换成函数! +# Enter the operator sectioning: +divide-by-2 = (/ 2) +[2, 4, 8, 16].map(divide-by-2) .reduce (+) + + +# LiveScript 里不只有应用函数,如同其它良好的函数式语言,你可以合并函数获得更多发挥: +double-minus-one = (- 1) . (* 2) + +# 除了普通的数学公式合并 `f . g` 之外,还有 `>>` 和 `<<` 运算子定义函数的合并顺序。 +double-minus-one = (* 2) >> (- 1) +double-minus-one = (- 1) << (* 2) + + +# 说到合并函数的参数, LiveScript 使用 `|>` 和 `<|` 运算子将参数传入: +map = (f, xs) --> xs.map f +[1 2 3] |> map (* 2) # => [2 4 6] + +# 你也可以选择填入值的位置,只需要使用底线 _ 标记: +reduce = (f, xs, initial) --> xs.reduce f, initial +[1 2 3] |> reduce (+), _, 0 # => 6 + + +# 你也能使 _ 让任何函数变成偏函数应用: +div = (left, right) -> left / right +div-by-2 = div _, 2 +div-by-2 4 # => 2 + + +# 最后,也很重要的,LiveScript 拥有後呼叫特性, 它可以是基於回调的代码 +# (你可以试试其它函数式特性的解法,比如 Promises): +readFile = (name, f) -> f name +a <- readFile 'foo' +b <- readFile 'bar' +console.log a + b + +# 等同於: +readFile 'foo', (a) -> readFile 'bar', (b) -> console.log a + b + + +######################################################################## +## 4. 模式、判断和流程控制 +######################################################################## + +# 流程控制可以使用 `if...else` 表达式: +x = if n > 0 then \positive else \negative + +# 除了 `then` 你也可以使用 `=>` +x = if n > 0 => \positive + else \negative + +# 过於复杂的流程可以用 `switch` 表达式代替: +y = {} +x = switch + | (typeof y) is \number => \number + | (typeof y) is \string => \string + | 'length' of y => \array + | otherwise => \object # `otherwise` 和 `_` 是等价的。 + +# 函数主体、宣告式和赋值式可以表式成 `switch`,这可以省去一些代码: +take = (n, [x, ...xs]) --> + | n == 0 => [] + | _ => [x] ++ take (n - 1), xs + + +######################################################################## +## 5. 推导式 +######################################################################## + +# 在 JavaScript 的标准函式库里有一些辅助函数能帮助处理列表及物件 +#(LiveScript 则带有一个 prelude.ls ,作为标准函式库的补充 ), +# 推导式能让你使用优雅的语法且快速地处理这些事: +oneToTwenty = [1 to 20] +evens = [x for x in oneToTwenty when x % 2 == 0] + +# 在推导式里 `when` 和 `unless` 可以当成过滤器使用。 + +# 物件推导式在使用上也是同样的方式,差别在于你使用的是物件而不是阵列: +copy = { [k, v] for k, v of source } + + +######################################################################## +## 6. OOP +######################################################################## + +# 虽然 LiveScript 是一门函数式语言,但有具自一些命令式及面向物件语言的特性。 +# 像是 class 语法和一些借镜於 CoffeeScript 的类别继承语法糖: +class Animal + (@name, kind) -> + @kind = kind + action: (what) -> "*#{@name} (a #{@kind}) #{what}*" + +class Cat extends Animal + (@name) -> super @name, 'cat' + purr: -> @action 'purrs' + +kitten = new Cat 'Mei' +kitten.purr! # => "*Mei (a cat) purrs*" + +# 除了类别的单一继承模式之外,还提供了像混入( Mixins )这种特性。 +# Mixins 在语言里被当成普通物件: +Huggable = + hug: -> @action 'is hugged' + +class SnugglyCat extends Cat implements Huggable + +kitten = new SnugglyCat 'Purr' +kitten.hug! # => "*Mei (a cat) is hugged*" +``` + +## 延伸阅读 + +LiveScript 还有许多强大之处,但这些应该足够启发你写些小型函数式程式了。 +[LiveScript](http://livescript.net/)有更多关于 LiveScript 的资讯 +和线上编译器等着你来试! + +你也可以参考 +[prelude.ls](http://gkz.github.io/prelude-ls/),和一些 `#livescript` +的网路聊天室频道。 -- cgit v1.2.3 From 6de34992770654cdb2c7f8d61bd27131c3cb88db Mon Sep 17 00:00:00 2001 From: sdlyu Date: Fri, 26 Sep 2014 15:13:10 +0800 Subject: Fix typo --- zh-cn/livescript-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/livescript-cn.html.markdown b/zh-cn/livescript-cn.html.markdown index f6643447..c04805c9 100644 --- a/zh-cn/livescript-cn.html.markdown +++ b/zh-cn/livescript-cn.html.markdown @@ -22,7 +22,7 @@ LiveScript 目前已释出稳定版本,开发中的新版本将会加入更多 # 与 CoffeeScript 一样,LiveScript 使用 # 单行注解。 /* -*多行注解与 C 相同。使用注解可以避免被当成 JavaScript 输出。 + 多行注解与 C 相同。使用注解可以避免被当成 JavaScript 输出。 */ ``` ```coffeescript -- cgit v1.2.3 From 0c77c29c88f850d81a884d90a036c50931157782 Mon Sep 17 00:00:00 2001 From: sdlyu Date: Fri, 26 Sep 2014 16:16:19 +0800 Subject: Add translators information. --- zh-cn/livescript-cn.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/zh-cn/livescript-cn.html.markdown b/zh-cn/livescript-cn.html.markdown index c04805c9..5a808807 100644 --- a/zh-cn/livescript-cn.html.markdown +++ b/zh-cn/livescript-cn.html.markdown @@ -3,6 +3,9 @@ language: LiveScript filename: learnLivescript.ls contributors: - ["Christina Whyte", "http://github.com/kurisuwhyte/"] +translators: + - ["ShengDa Lyu", "http://github.com/SDLyu/"] +lang: zh-cn --- LiveScript 是一种具有函数式特性且编译成 JavaScript 的语言,能对应 JavaScript 的基本语法。 -- cgit v1.2.3 From b52a32dd2439c293892b72e35b57b4887a5a53cf Mon Sep 17 00:00:00 2001 From: "Gregory S. Kielian" Date: Sat, 27 Sep 2014 12:04:25 -0700 Subject: Added `sed` and `grep` examples to useful-commands --- bash.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index dc7d32b6..0f571e83 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -9,6 +9,7 @@ contributors: - ["akirahirose", "https://twitter.com/akirahirose"] - ["Anton Strömkvist", "http://lutic.org/"] - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] filename: LearnBash.sh --- @@ -199,4 +200,8 @@ sort file.txt uniq -d file.txt # prints only the first column before the ',' character cut -d ',' -f 1 file.txt +# replaces every occurance of 'apples' with 'oranges' in file.txt +sed -i 's/apples/oranges/g' file.txt +# prints the number of occurances of "foo" in file.txt +grep -c "foo" file.txt ``` -- cgit v1.2.3 From e9c21740df4c93ee4575eca41b0028fa2d90ce1b Mon Sep 17 00:00:00 2001 From: "Gregory S. Kielian" Date: Sat, 27 Sep 2014 12:06:36 -0700 Subject: amended grep description --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index 0f571e83..fd347488 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -202,6 +202,6 @@ uniq -d file.txt cut -d ',' -f 1 file.txt # replaces every occurance of 'apples' with 'oranges' in file.txt sed -i 's/apples/oranges/g' file.txt -# prints the number of occurances of "foo" in file.txt +# prints the number of lines with the string "foo" in file.txt grep -c "foo" file.txt ``` -- cgit v1.2.3 From d22d591e3e2120dd1bed70cd8093569c8b7101c2 Mon Sep 17 00:00:00 2001 From: "Gregory S. Kielian" Date: Sat, 27 Sep 2014 12:12:56 -0700 Subject: amended sed and bash descriptions --- bash.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index fd347488..160fe8f2 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -200,8 +200,8 @@ sort file.txt uniq -d file.txt # prints only the first column before the ',' character cut -d ',' -f 1 file.txt -# replaces every occurance of 'apples' with 'oranges' in file.txt +# replaces every occurrence of 'apples' with 'oranges' in file.txt sed -i 's/apples/oranges/g' file.txt -# prints the number of lines with the string "foo" in file.txt +# prints the number of lines containing the string "foo" in file.txt grep -c "foo" file.txt ``` -- cgit v1.2.3 From a5b7319eac940cd81693fd590f3df01b5a70816b Mon Sep 17 00:00:00 2001 From: adventuretc Date: Sat, 27 Sep 2014 21:38:30 +0200 Subject: Correction to use the intended variables. --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index cbb6d289..10e6fa45 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -217,7 +217,7 @@ int main() { int e = 5; int f = 10; int z; - z = (a > b) ? a : b; // => 10 "if a > b return a, else return b." + z = (e > f) ? e : f; // => 10 "if e > f return e, else return f." //Increment and decrement operators: char *s = "iLoveC"; -- cgit v1.2.3 From 160c82684721b62e3369a912542a5f045d286d9c Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Sat, 27 Sep 2014 21:57:10 +0200 Subject: Capturing captures, and numbering them also, multi-indexing in arrays also, labeled loops (draft) also, arrays vs $() vs parcel vs ... (@moritz++) --- perl6.html.markdown | 86 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 76 insertions(+), 10 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index d12b99ae..7afcc930 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -46,18 +46,36 @@ my $inverse = !$bool; # You can invert a bool with the prefix `!` operator my $forced-bool = so $str; # And you can use the prefix `so` operator # which turns its operand into a Bool -## * Arrays. They represent multiple values. Their name start with `@`. +## * Lists. They represent multiple values. Their name start with `@`. -my @array = 1, 2, 3; my @array = 'a', 'b', 'c'; # equivalent to : -my @array = ; # array of words, delimited by space. +my @letters = ; # array of words, delimited by space. # Similar to perl5's qw, or Ruby's %w. +my @array = 1, 2, 3; say @array[2]; # Array indices start at 0 -- This is the third element say "Interpolate an array using [] : @array[]"; -#=> Interpolate an array using [] : a b c +#=> Interpolate an array using [] : 1 2 3 + +@array[0] = -1; # Assign a new value to an array index +@array[0, 1] = 5, 6; # Assign multiple values + +my @keys = 0, 2; +@array[@keys] = @letters; # Assign using an array +say @array; #=> a 2 b + +# There are two more kinds of lists: Parcel and Arrays. +# Parcels are immutable lists (you can't modify a list that's not assigned). +# This is a parcel: +(1, 2, 3); # Not assigned to anything. Changing an element would provoke an error +# This is a list: +my @a = (1, 2, 3); # Assigned to `@a`. Changing elements is okay! + +# Lists flatten (in list context). You'll see below how to apply item context +# or use arrays to have real nested lists. + ## * Hashes. Key-Value Pairs. # Hashes are actually arrays of Pairs (`Key => Value`), @@ -303,6 +321,37 @@ if long-computation() -> $result { say "The result is $result"; } +## Loops can also have a label, and be jumped to through these. +OUTER: while 1 { + say "hey"; + while 1 { + OUTER.last; # All the control keywords must be called on the label itself + } +} + +# 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 (except if some sub-list were put in item context ($)). +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. + +# The other difference between `$()` and `[]` is that `[]` always returns a mutable Array +# whereas `$()` will return a Parcel when given a Parcel. + + ### Operators ## Since Perl languages are very much operator-based languages @@ -359,9 +408,9 @@ $arg ~~ &bool-returning-function; # `True` if the function, passed `$arg` # This also works as a shortcut for `0..^N`: ^10; # means 0..^10 -# This also allows us to demonstrate that Perl 6 has lazy arrays, +# This also allows us to demonstrate that Perl 6 has lazy/infinite arrays, # using the Whatever Star: -my @array = 1..*; # 1 to Infinite ! +my @array = 1..*; # 1 to Infinite ! `1..Inf` is the same. say @array[^10]; # you can pass arrays as subscripts and it'll return # an array of results. This will print # "1 2 3 4 5 6 7 8 9 10" (and not run out of memory !) @@ -372,6 +421,13 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return # 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 + + ## * And, Or 3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`. 0 || False; # False. Calls `.Bool` on `0` @@ -1325,7 +1381,7 @@ say $0; # The same as above. # You might be wondering why it's an array, and the answer is simple: # Some capture (indexed using `$0`, `$/[0]` or a named one) will be an array # IFF it can have more than one element -# (so, with `*`, `+` and any `**`, but not with `?`). +# (so, with `*`, `+` and `**` (whatever the operands), but not with `?`). # Let's use examples to see that: so 'fooABCbar' ~~ / foo ( A B C )? bar /; # `True` say $/[0]; #=> 「ABC」 @@ -1339,16 +1395,26 @@ say $0.WHAT; #=> (Array) # A specific quantifier will always capture an Array, # may it be a range or a specific value (even 1). -# If you're wondering how the captures are numbered, here's an explanation: -# (TODO use graphs from s05) +# The captures are indexed per nesting. This means a group in a group will be nested +# under its parent group: `$/[0][0]`, for this code: +'hello-~-world' ~~ / ( 'hello' ( <[ \- \~ ]> + ) ) 'world' /; +say $/[0].Str; #=> hello~ +say $/[0][0].Str; #=> ~ +# This stems from a very simple fact: `$/` does not contain strings, integers or arrays, +# it only contains match objects. These contain the `.list`, `.hash` and `.Str` methods. +# (but you can also just use `match` for hash access and `match[idx]` for array access) +say $/[0].list.perl; #=> (Match.new(...),).list + # We can see it's a list of Match objects. Those contain a bunch of infos: + # where the match started/ended, the "ast" (see actions later), etc. + # You'll see named capture below with grammars. ## Alternatives - the `or` of regexps # WARNING: They are DIFFERENT from PCRE regexps. so 'abc' ~~ / a [ b | y ] c /; # `True`. Either "b" or "y". so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... -# The difference between this `|` and the one you're probably used to is LTM. +# The difference between this `|` and the one you're used to is LTM. # LTM means "Longest Token Matching". This means that the engine will always # try to match as much as possible in the strng 'foo' ~~ / fo | foo /; # `foo`, because it's longer. -- cgit v1.2.3 From 221d72bcb06f1677b61e28dde430ba651fd896df Mon Sep 17 00:00:00 2001 From: sdlyu Date: Mon, 29 Sep 2014 10:30:40 +0800 Subject: Correct typo and rewrite the meaning of := --- zh-cn/livescript-cn.html.markdown | 102 +++++++++++++++++++------------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/zh-cn/livescript-cn.html.markdown b/zh-cn/livescript-cn.html.markdown index 5a808807..fea00bc1 100644 --- a/zh-cn/livescript-cn.html.markdown +++ b/zh-cn/livescript-cn.html.markdown @@ -9,7 +9,7 @@ lang: zh-cn --- LiveScript 是一种具有函数式特性且编译成 JavaScript 的语言,能对应 JavaScript 的基本语法。 -还有些额外的特性如:柯里化,函式组合,模式匹配,还有借镜于 Haskell,F# 和 Scala 的许多特点。 +还有些额外的特性如:柯里化,组合函数,模式匹配,还有借镜于 Haskell,F# 和 Scala 的许多特点。 LiveScript 诞生于 [Coco][],而 Coco 诞生于 [CoffeeScript][]。 LiveScript 目前已释出稳定版本,开发中的新版本将会加入更多特性。 @@ -17,7 +17,7 @@ LiveScript 目前已释出稳定版本,开发中的新版本将会加入更多 [Coco]: http://satyr.github.io/coco/ [CoffeeScript]: http://coffeescript.org/ -非常期待您的反馈,你可以透过 +非常期待您的反馈,你可以通过 [@kurisuwhyte](https://twitter.com/kurisuwhyte) 与我连系 :) @@ -44,11 +44,11 @@ void # 与 `undefined` 等价但更安全(不会被覆写) null -# 最基本的值类型数据是罗辑类型: +# 最基本的值类型数据是罗辑类型: true false -# 罗辑类型的一些别名,等价于前者: +# 罗辑类型的一些别名,等价于前者: on; off yes; no @@ -58,55 +58,55 @@ yes; no 0.4 # 开头的 0 是必要的 -# 可以使用底线及单位后缀提高可读性,编译器自动会略过底线及单位后缀。 +# 可以使用底线及单位后缀提高可读性,编译器会自动略过底线及单位后缀。 12_344km -# 字串与 JS 一样,是一种不可变的字元序列: -"Christina" # 单引号也可以! +# 字串与 JS 一样,是一种不可变的字元序列: +"Christina" # 单引号也可以! """Multi-line strings are okay too.""" -# 在前面加上 \ 符号也可以表示字串: +# 在前面加上 \ 符号也可以表示字串: \keyword # => 'keyword' -# 阵列是值的有序集合。 +# 数组是值的有序集合。 fruits = * \apple * \orange * \pear -# 可以用 [] 简洁地表示阵列: +# 可以用 [] 简洁地表示数组: fruits = [ \apple, \orange, \pear ] -# 你可以更方便地建立字串阵列,并使用空白区隔元素。 +# 你可以更方便地建立字串数组,并使用空白区隔元素。 fruits = <[ apple orange pear ]> -# 以 0 为起始值的数组下标获取元素: +# 以 0 为起始值的数组下标获取元素: fruits[0] # => "apple" -# 物件是无序键值对集合(更多给节将在下面章节讨论) 。 +# 对象是无序键值对集合(更多给节将在下面章节讨论)。 person = name: "Christina" likes: * "kittens" * "and other cute stuff" -# 你也可以用更简洁的方式表示物件: +# 你也可以用更简洁的方式表示对象: person = {name: "Christina", likes: ["kittens", "and other cute stuff"]} -# 可以透过键值获取值: +# 可以通过键值获取值: person.name # => "Christina" person["name"] # => "Christina" -# 正则表达式的使用跟 JavaScript 一样: +# 正则表达式的使用跟 JavaScript 一样: trailing-space = /\s$/ # dashed-words 变成 dashedWords # 你也可以用多行描述表达式!(注解和空白会被忽略) @@ -121,7 +121,7 @@ funRE = // ## 2. 基本运算 ######################################################################## -# 数值运算子与 JavaScript 一样: +# 数值操作符与 JavaScript 一样: 1 + 2 # => 3 2 - 1 # => 1 2 * 3 # => 6 @@ -129,9 +129,9 @@ funRE = // 3 % 2 # => 1 -# 比较运算子大部份也一样,除了 `==` 等价于 JS 中的 `===`, +# 比较操作符大部份也一样,除了 `==` 等价于 JS 中的 `===`, # JS 中的 `==` 在 LiveScript 里等价于 `~=`, -# `===` 能进行物件、阵列和严格比较。 +# `===` 能进行对象、数组和严格比较。 2 == 2 # => true 2 == "2" # => false 2 ~= "2" # => true @@ -143,15 +143,15 @@ funRE = // +0 == -0 # => true +0 === -0 # => false -# 其它关系运算子包括 <、<=、> 和 >= +# 其它关系操作符包括 <、<=、> 和 >= -# 罗辑值可以透过 `or`、`and` 和 `not` 结合: +# 罗辑值可以通过 `or`、`and` 和 `not` 结合: true and false # => false false or true # => true not false # => true -# 集合也有一些便利的运算子 +# 集合也有一些便利的操作符 [1, 2] ++ [3, 4] # => [1, 2, 3, 4] 'a' in <[ a b c ]> # => true 'name' of { name: 'Chris' } # => true @@ -165,25 +165,25 @@ not false # => true add = (left, right) -> left + right add 1, 2 # => 3 -# 加上 ! 防止函数执行后的回传值 +# 加上 ! 防止函数执行后的返回值 two = -> 2 two! # LiveScript 与 JavaScript 一样使用函式作用域,且一样拥有闭包的特性。 -# 与 JavaScript 不同的地方在于,`=` 变数赋值时,左边的运算元永远不用变数宣告。 +# 与 JavaScript 不同的地方在于,`=` 变量赋值时,左边的对象永远不用变量宣告。 -# `:=` 运算子在作用域里允许*重用*变数名并创建新的变数作用域。 +# `:=` 操作符允许*重新賦值*父作用域里的变量。 # 你可以解构函数的参数,从不定长度的参数结构里获取感兴趣的值。 tail = ([head, ...rest]) -> rest tail [1, 2, 3] # => [2, 3] -# 你也可以使用一元或二元运算子转换参数。当然也可以预设传入的参数值。 +# 你也可以使用一元或二元操作符转换参数。当然也可以预设传入的参数值。 foo = (a = 1, b = 2) -> a + b foo! # => 3 -# 你可以以复制的方式传入参数来避免副作用,例如: +# 你可以以拷贝的方式传入参数来避免副作用,例如: copy = (^^target, source) -> for k,v of source => target[k] = v target @@ -192,52 +192,52 @@ copy a, { b: 2 } # => { a: 1, b: 2 } a # => { a: 1 } -# 使用长箭号取代短箭号来柯里化一个函数: +# 使用长箭号取代短箭号来柯里化一个函数: add = (left, right) --> left + right add1 = add 1 add1 2 # => 3 -# 函式里有一个隐式的 `it` 变数,意谓着你不用宣告它。 +# 函式里有一个隐式的 `it` 变量,意谓着你不用宣告它。 identity = -> it identity 1 # => 1 -# 运算子在 LiveScript 里不是一個函数,但你可以简单地将它们转换成函数! -# Enter the operator sectioning: +# 操作符在 LiveScript 里不是一個函数,但你可以简单地将它们转换成函数! +# Enter the operator sectioning: divide-by-2 = (/ 2) [2, 4, 8, 16].map(divide-by-2) .reduce (+) -# LiveScript 里不只有应用函数,如同其它良好的函数式语言,你可以合并函数获得更多发挥: +# LiveScript 里不只有应用函数,如同其它良好的函数式语言,你可以合并函数获得更多发挥: double-minus-one = (- 1) . (* 2) -# 除了普通的数学公式合并 `f . g` 之外,还有 `>>` 和 `<<` 运算子定义函数的合并顺序。 +# 除了普通的数学公式合并 `f . g` 之外,还有 `>>` 和 `<<` 操作符定义函数的合并顺序。 double-minus-one = (* 2) >> (- 1) double-minus-one = (- 1) << (* 2) -# 说到合并函数的参数, LiveScript 使用 `|>` 和 `<|` 运算子将参数传入: +# 说到合并函数的参数, LiveScript 使用 `|>` 和 `<|` 操作符将参数传入: map = (f, xs) --> xs.map f [1 2 3] |> map (* 2) # => [2 4 6] -# 你也可以选择填入值的位置,只需要使用底线 _ 标记: +# 你也可以选择填入值的位置,只需要使用底线 _ 标记: reduce = (f, xs, initial) --> xs.reduce f, initial [1 2 3] |> reduce (+), _, 0 # => 6 -# 你也能使 _ 让任何函数变成偏函数应用: +# 你也能使 _ 让任何函数变成偏函数应用: div = (left, right) -> left / right div-by-2 = div _, 2 div-by-2 4 # => 2 -# 最后,也很重要的,LiveScript 拥有後呼叫特性, 它可以是基於回调的代码 -# (你可以试试其它函数式特性的解法,比如 Promises): +# 最后,也很重要的,LiveScript 拥有後呼叫特性, 可以是基於回调的代码 +# (你可以试试其它函数式特性的解法,比如 Promises): readFile = (name, f) -> f name a <- readFile 'foo' b <- readFile 'bar' console.log a + b -# 等同於: +# 等同於: readFile 'foo', (a) -> readFile 'bar', (b) -> console.log a + b @@ -245,14 +245,14 @@ readFile 'foo', (a) -> readFile 'bar', (b) -> console.log a + b ## 4. 模式、判断和流程控制 ######################################################################## -# 流程控制可以使用 `if...else` 表达式: +# 流程控制可以使用 `if...else` 表达式: x = if n > 0 then \positive else \negative # 除了 `then` 你也可以使用 `=>` x = if n > 0 => \positive else \negative -# 过於复杂的流程可以用 `switch` 表达式代替: +# 过於复杂的流程可以用 `switch` 表达式代替: y = {} x = switch | (typeof y) is \number => \number @@ -260,7 +260,7 @@ x = switch | 'length' of y => \array | otherwise => \object # `otherwise` 和 `_` 是等价的。 -# 函数主体、宣告式和赋值式可以表式成 `switch`,这可以省去一些代码: +# 函数主体、宣告式和赋值式可以表式成 `switch`,这可以省去一些代码: take = (n, [x, ...xs]) --> | n == 0 => [] | _ => [x] ++ take (n - 1), xs @@ -270,15 +270,15 @@ take = (n, [x, ...xs]) --> ## 5. 推导式 ######################################################################## -# 在 JavaScript 的标准函式库里有一些辅助函数能帮助处理列表及物件 +# 在 JavaScript 的标准函式库里有一些辅助函数能帮助处理列表及对象 #(LiveScript 则带有一个 prelude.ls ,作为标准函式库的补充 ), -# 推导式能让你使用优雅的语法且快速地处理这些事: +# 推导式能让你使用优雅的语法且快速地处理这些事: oneToTwenty = [1 to 20] evens = [x for x in oneToTwenty when x % 2 == 0] # 在推导式里 `when` 和 `unless` 可以当成过滤器使用。 -# 物件推导式在使用上也是同样的方式,差别在于你使用的是物件而不是阵列: +# 对象推导式在使用上也是同样的方式,差别在于你使用的是对象而不是数组: copy = { [k, v] for k, v of source } @@ -286,8 +286,8 @@ copy = { [k, v] for k, v of source } ## 6. OOP ######################################################################## -# 虽然 LiveScript 是一门函数式语言,但有具自一些命令式及面向物件语言的特性。 -# 像是 class 语法和一些借镜於 CoffeeScript 的类别继承语法糖: +# 虽然 LiveScript 是一门函数式语言,但具有一些命令式及面向对象的特性。 +# 像是 class 语法和一些借镜於 CoffeeScript 的类别继承语法糖: class Animal (@name, kind) -> @kind = kind @@ -300,8 +300,8 @@ class Cat extends Animal kitten = new Cat 'Mei' kitten.purr! # => "*Mei (a cat) purrs*" -# 除了类别的单一继承模式之外,还提供了像混入( Mixins )这种特性。 -# Mixins 在语言里被当成普通物件: +# 除了类别的单一继承模式之外,还提供了像混入 (Mixins) 这种特性。 +# Mixins 在语言里被当成普通对象: Huggable = hug: -> @action 'is hugged' @@ -315,8 +315,8 @@ kitten.hug! # => "*Mei (a cat) is hugged*" LiveScript 还有许多强大之处,但这些应该足够启发你写些小型函数式程式了。 [LiveScript](http://livescript.net/)有更多关于 LiveScript 的资讯 -和线上编译器等着你来试! +和线上编译器等着你来试! 你也可以参考 [prelude.ls](http://gkz.github.io/prelude-ls/),和一些 `#livescript` -的网路聊天室频道。 +的网络聊天室频道。 -- cgit v1.2.3 From 923a8ed99b1648cc2ece83660ed263492c332afe Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sat, 4 Oct 2014 12:08:23 -0500 Subject: - mo betta examples - add `inout` example - better `optional` example - Playground issue has been resolved, uncommented `protocol` example --- swift.html.markdown | 81 ++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 59 insertions(+), 22 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 77047355..ffe6cac2 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -13,6 +13,9 @@ The official [Swift Programming Language](https://itunes.apple.com/us/book/swift See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. ```swift +// import a module +import UIKit + // // MARK: Basics // @@ -26,7 +29,7 @@ println("Hello, world") var myVariable = 42 let øπΩ = "value" // unicode variable names -let myConstant = 3.1415926 +let π = 3.1415926 let convenience = "keyword" // contextual variable name let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon let `class` = "keyword" // backticks allow keywords to be used as variable names @@ -34,9 +37,24 @@ let explicitDouble: Double = 70 let intValue = 0007 // 7 let largeIntValue = 77_000 // 77000 let label = "some text " + String(myVariable) // Casting -let piText = "Pi = \(myConstant), Pi 2 = \(myConstant * 2)" // String interpolation -var optionalString: String? = "optional" // Can be nil -optionalString = nil +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation +var someOptionalString: String? = "optional" // Can be nil + +if someOptionalString != nil { + // I am not nil + if someOptionalString!.hasPrefix("opt") { + println("has the prefix") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +if let someStringConstant = someOptionalString { + // has Some value +} + +// AnyObject == id /* Comment here @@ -84,9 +102,10 @@ for (key, value) in dict { } // for loop (range) -for i in -1...1 { // [-1, 0, 1] +for i in -1...shoppingList.count { println(i) } +shoppingList[1...2] = ["steak", "peacons"] // use ..< to exclude the last number // while loop @@ -123,14 +142,14 @@ default: // required (in order to cover all possible input) // Function with Swift header docs (format as reStructedText) /** - A greet operation +A greet operation - - A bullet in docs - - Another bullet in the docs +- A bullet in docs +- Another bullet in the docs - :param: name A name - :param: day A day - :returns: A string containing the name and day value. +:param: name A name +:param: day A day +:returns: A string containing the name and day value. */ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." @@ -141,9 +160,16 @@ greet("Bob", "Tuesday") func getGasPrices() -> (Double, Double, Double) { return (3.59, 3.69, 3.79) } +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +println("Gas price: \(price)") // Variadic Args -func setup(numbers: Int...) {} +func setup(numbers: Int...) { + // its an array + let number = numbers[0] + let argCount = numbers.count +} // Passing and returning functions func makeIncrementer() -> (Int -> Int) { @@ -155,6 +181,17 @@ func makeIncrementer() -> (Int -> Int) { var increment = makeIncrementer() increment(7) +// pass by ref +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +println(someIntB) // 7 + // // MARK: Closures @@ -197,7 +234,7 @@ print(numbers) // [3, 6, 18] // Structures and classes have very similar capabilites struct NamesTable { let names: [String] - + // Custom subscript subscript(index: Int) -> String { return names[index] @@ -239,7 +276,7 @@ internal class Rect: Shape { sideLength = newValue / 4 } } - + // Lazily load a property // subShape remains nil (uninitialized) until getter called lazy var subShape = Rect(sideLength: 4) @@ -255,8 +292,9 @@ internal class Rect: Shape { } init(sideLength: Int) { - super.init() self.sideLength = sideLength + // always super.init last when init custom properties + super.init() } func shrink() { @@ -313,7 +351,7 @@ enum Suit { // // `protocol`s can require that conforming types have specific -// instance properties, instance methods, type methods, +// instance properties, instance methods, type methods, // operators, and subscripts. protocol ShapeGenerator { @@ -321,7 +359,6 @@ protocol ShapeGenerator { func buildShape() -> Shape } -/* // Protocols declared with @objc allow optional functions, // which allow you to check for conformance @objc protocol TransformShape { @@ -331,17 +368,17 @@ protocol ShapeGenerator { class MyShape: Rect { var delegate: TransformShape? - + func grow() { sideLength += 2 - + if let allow = self.delegate?.canReshape?() { // test for delegate then for method self.delegate?.reshaped?() } } } -*/ + // // MARK: Other @@ -363,7 +400,7 @@ extension Int { var customProperty: String { return "This is \(self)" } - + func multiplyBy(num: Int) -> Int { return num * self } @@ -372,7 +409,7 @@ extension Int { println(7.customProperty) // "This is 7" println(14.multiplyBy(2)) // 42 -// Generics: Similar to Java. Use the `where` keyword to specify the +// Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. func findIndex(array: [T], valueToFind: T) -> Int? { -- cgit v1.2.3 From d83a0f038558cf32680287417bbd692b33fe13cc Mon Sep 17 00:00:00 2001 From: "Gregory S. Kielian" Date: Sat, 4 Oct 2014 14:50:00 -0700 Subject: Changed descriptions, added grep, fgrep examples --- bash.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 160fe8f2..9b199b8c 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -200,8 +200,12 @@ sort file.txt uniq -d file.txt # prints only the first column before the ',' character cut -d ',' -f 1 file.txt -# replaces every occurrence of 'apples' with 'oranges' in file.txt -sed -i 's/apples/oranges/g' file.txt -# prints the number of lines containing the string "foo" in file.txt -grep -c "foo" file.txt +# replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible) +sed -i 's/okay/great/g' file.txt +# print to stdout all lines of file.txt which match some regex, the example prints lines which beginning with "foo" and end in "bar" +grep "^foo.*bar$" file.txt +# pass the option "-c" to instead print the number of lines matching the regex +grep -c "^foo.*bar$" file.txt +# if you literally want to search for the string, and not the regex, use fgrep (or grep -F) +fgrep "^foo.*bar$" file.txt ``` -- cgit v1.2.3 From d786c94f8408b2fb2f0a0b39c7c5cc8ec77e0808 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Tue, 7 Oct 2014 15:47:06 +0200 Subject: Fix a braino caught by @wryk++ --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 7afcc930..ee27ff42 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1447,7 +1447,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... # It's very powerful, because Perl 6 actually parses the argument # and pass them as such to the sub. It also handles named argument (`--foo`) # and will even go as far as to autogenerate a `--help` -sub MAIN($name) { say "Hello, you !" } +sub MAIN($name) { say "Hello, $name !" } # This produces: # $ perl6 cli.pl # Usage: -- cgit v1.2.3 From 6ce6aa7b548151371bcc31f00925aa890a4356e7 Mon Sep 17 00:00:00 2001 From: m90 Date: Tue, 7 Oct 2014 20:38:14 +0200 Subject: fix typo -> re(s)pository pattern --- csharp.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 136f6c50..f6708590 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -508,7 +508,7 @@ on a new line! ""Wow!"", the masses cried"; // LINQ - maps a store to IQueryable objects, with delayed execution // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document - var db = new BikeRespository(); + var db = new BikeRepository(); // execution is delayed, which is great when querying a database var filter = db.Bikes.Where(b => b.HasTassles); // no query run @@ -767,9 +767,9 @@ on a new line! ""Wow!"", the masses cried"; /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) /// http://msdn.microsoft.com/en-us/data/jj193542.aspx /// - public class BikeRespository : DbSet + public class BikeRepository : DbSet { - public BikeRespository() + public BikeRepository() : base() { } -- cgit v1.2.3 From fd29de7f5904f75bd00c7e74652803eac11a994b Mon Sep 17 00:00:00 2001 From: jmaud Date: Tue, 7 Oct 2014 16:55:40 -0400 Subject: Adjustments to Style & Content Style changes - Site format has changed back to ~80 columns, certain rows have had line breaks removed. - Indentation has been adjusted globally to give additional space and consistency. - Configuring Tmux has been separated due to long lines causing the entire page to scroll horizontally and block text. - tmux.conf has been reorganized to better explain settings categorically to new users. Content Changes - Unmapping the prefix key contained erroneous data - Misc section and it's contained "bind r source.." setting are superfluous, as when this points to the next file to use in the configuration, not the current file. Since no additional configuration files have been used, it has been removed. --- tmux.html.markdown | 176 +++++++++++++++++++++++++---------------------------- 1 file changed, 82 insertions(+), 94 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 8d7aa752..1fe97699 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -2,22 +2,23 @@ category: tool tool: tmux contributors: - - ["kaernyk", "http://github.com/kaernyk"] + - ["kaernyk", "https://github.com/kaernyk"] + - ["jmaud". "https://github.com/jmaud"] filename: LearnTmux.txt --- -tmux is a terminal multiplexer: it enables a number of terminals -to be created, accessed, and controlled from a single screen. tmux +tmux is a terminal multiplexer: it enables a number of terminals +to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background then later reattached. ``` + tmux [command] # Run a command - # 'tmux' with no commands will create a new - session + # 'tmux' with no commands will create a new session new # Create a new session -s "Session" # Create named session @@ -54,7 +55,7 @@ then later reattached. ## Key Bindings -# The method of controlling an attached tmux session is via key +# The method of controlling an attached tmux session is via key # combinations called 'Prefix' keys. ---------------------------------------------------------------------- @@ -63,47 +64,48 @@ then later reattached. (M-1) = Meta + 1 -or- Alt + 1 ---------------------------------------------------------------------- - ? # List all key bindings - : # Enter the tmux command prompt - r # Force redraw of the attached client - c # Create a new window + ? # List all key bindings + : # Enter the tmux command prompt + r # Force redraw of the attached client + c # Create a new window - ! # Break the current pane out of the window. - % # Split the current pane into two, left and right - " # Split the current pane into two, top and bottom + ! # Break the current pane out of the window. + % # Split the current pane into two, left and right + " # Split the current pane into two, top and bottom - n # Change to the next window - p # Change to the previous window - { # Swap the current pane with the previous pane - } # Swap the current pane with the next pane + n # Change to the next window + p # Change to the previous window + { # Swap the current pane with the previous pane + } # Swap the current pane with the next pane - s # Select a new session for the attached client + s # Select a new session for the attached client interactively - w # Choose the current window interactively - 0 to 9 # Select windows 0 to 9 + w # Choose the current window interactively + 0 to 9 # Select windows 0 to 9 - d # Detach the current client - D # Choose a client to detach + d # Detach the current client + D # Choose a client to detach - & # Kill the current window - x # Kill the current pane + & # Kill the current window + x # Kill the current pane - Up, Down # Change to the pane above, below, left, or right - Left, Right + Up, Down # Change to the pane above, below, left, or right + Left, Right - M-1 to M-5 # Arrange panes: - # 1) even-horizontal - # 2) even-vertical - # 3) main-horizontal - # 4) main-vertical - # 5) tiled + M-1 to M-5 # Arrange panes: + # 1) even-horizontal + # 2) even-vertical + # 3) main-horizontal + # 4) main-vertical + # 5) tiled - C-Up, C-Down # Resize the current pane in steps of one cell - C-Left, C-Right + C-Up, C-Down # Resize the current pane in steps of one cell + C-Left, C-Right - M-Up, M-Down # Resize the current pane in steps of five cells - M-Left, M-Right + M-Up, M-Down # Resize the current pane in steps of five cells + M-Left, M-Right +``` ### Configuring ~/.tmux.conf @@ -111,15 +113,36 @@ then later reattached. tmux.conf can be used to set options automatically on start up, much like how .vimrc or init.el are used. +``` # Example tmux.conf -# 2014.9 +# 2014.10 + + +### General +########################################################################### + +# Enable UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Scrollback/History limit +set -g history-limit 2048 + +# Index Start +set -g base-index 1 + +# Mouse +set-option -g mouse-select-pane on ### Keybinds -###################################################################### +########################################################################### # Unbind C-b as the default prefix -unbind-key C-befix C-a +unbind-key C-b + +# Set new default prefix +set-option -g prefix ` # Return to previous window when prefix is pressed twice bind-key C-a last-window @@ -129,12 +152,15 @@ bind-key ` last-window bind-key F11 set-option -g prefix C-a bind-key F12 set-option -g prefix ` -# Activate inner-most session (when nesting tmux) -# to send commands -bind-key a send-prefix +# Keybind preference +setw -g mode-keys vi +set-option -g status-keys vi -# Index Start -set -g base-index 1 +# Moving between panes with vim movement keys +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R # Window Cycle/Swap bind e previous-window @@ -142,23 +168,21 @@ bind f next-window bind E swap-window -t -1 bind F swap-window -t +1 -# easy-to-remember split pane commands -bind | split-window -h +# Easy split pane commands +bind = split-window -h bind - split-window -v unbind '"' unbind % -# moving between panes with vim movement keys -bind h select-pane -L -bind j select-pane -D -bind k select-pane -U -bind l select-pane -R +# Activate inner-most session (when nesting tmux) to send commands +bind-key a send-prefix + ### Theme -##################################################################### +########################################################################### -# Statusbar Color Palette +# Statusbar Color Palatte set-option -g status-justify left set-option -g status-bg black set-option -g status-fg white @@ -187,14 +211,7 @@ setw -g window-status-activity-fg yellow ### UI -###################################################################### - -# Statusbar -set-option -g status-utf8 on - -# Keybind preference -setw -g mode-keys vi -set-option -g status-keys vi +########################################################################### # Notification setw -g monitor-activity on @@ -202,43 +219,14 @@ set -g visual-activity on set-option -g bell-action any set-option -g visual-bell off -# Mouse -setw -g mode-mouse on -set-option -g mouse-select-pane on -set -g mouse-resize-pane on -set -g mouse-select-window on - # Automatically set window titles set-option -g set-titles on - -# window number,program name,active (or not) -set-option -g set-titles-string '#H:#S.#I.#P #W #T' +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) # Statusbar Adjustments -set -g status-left '#[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default]' -set -g status-interval 3 - -# Statusbar with right-aligned Date / Time -#set -g status-right '#[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default]' +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S #[fg=green]][#[default]" # Show performance counters in statusbar # Requires https://github.com/thewtex/tmux-mem-cpu-load/ -#set -g status-right '#[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default]' - - -### Misc -###################################################################### - -# Scrollback/History limit -set -g history-limit 4096 - -bind r source-file ~/.tmux.conf -``` - -### External Resources - -Tmux | Home
-Tmux Manual page
-Archlinux Wiki
-Gentoo Wiki
-Display CPU/MEM % in statusbar
+#set -g status-interval 4 +#set -g status-right "#[fg=green]][ #[fg=white]#(tmux-mem-cpu-load) #[fg=green]][ #[fg=yellow]%H:%M #[default]" -- cgit v1.2.3 From a66c00c599dcea54f2095fb56343a7e8a200d9f1 Mon Sep 17 00:00:00 2001 From: Johnathan Maudlin Date: Tue, 7 Oct 2014 17:12:25 -0400 Subject: Correct Contributor's list & line spacing - Contributor's list had an improper character which ruined the formatting. - The Theme section was preceded by three line breaks rather than two. --- tmux.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 1fe97699..79829c88 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -3,7 +3,7 @@ category: tool tool: tmux contributors: - ["kaernyk", "https://github.com/kaernyk"] - - ["jmaud". "https://github.com/jmaud"] + - ["jmaud", "https://github.com/jmaud"] filename: LearnTmux.txt --- @@ -113,6 +113,7 @@ then later reattached. tmux.conf can be used to set options automatically on start up, much like how .vimrc or init.el are used. + ``` # Example tmux.conf # 2014.10 @@ -178,7 +179,6 @@ unbind % bind-key a send-prefix - ### Theme ########################################################################### -- cgit v1.2.3 From 645233dce9b4d97f1958dbb08b18551b9bfe906d Mon Sep 17 00:00:00 2001 From: Simon Neveu Date: Wed, 8 Oct 2014 09:38:07 +0100 Subject: Init haml md --- haml.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 haml.html.markdown diff --git a/haml.html.markdown b/haml.html.markdown new file mode 100644 index 00000000..cde76eee --- /dev/null +++ b/haml.html.markdown @@ -0,0 +1,8 @@ +--- +language: haml +filename: learnhaml.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] +--- + +HAML is a \ No newline at end of file -- cgit v1.2.3 From 269d717224db16057d8c0f20084df533d8dc45dd Mon Sep 17 00:00:00 2001 From: Simon Neveu Date: Wed, 8 Oct 2014 23:18:30 +0100 Subject: added comments, tags, classes, and attributes --- haml.html.markdown | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/haml.html.markdown b/haml.html.markdown index cde76eee..124f160b 100644 --- a/haml.html.markdown +++ b/haml.html.markdown @@ -5,4 +5,66 @@ contributors: - ["Simon Neveu", "https://github.com/sneveu"] --- -HAML is a \ No newline at end of file +Haml is a markup language predominantly used with Ruby that’s used to cleanly and simply describe the HTML of any web document without the use of inline code. It encourages well-written markup. + +Haml aims to reduce repetition in your markup by closing tags for you based on the structure of the indents in your code. The result is markup that is well-structured, DRY, logical, and easier to read. + +```haml +/ ------------------------------------------- +/ Comments +/ ------------------------------------------- + +/ This is what a comment looks like haml + +/ + To write a multi line comment, indent your commented code to be + wrapped by the forward slash + +-# This is a silent comment, which means it wont be rendered into the doc at all + + +/ ------------------------------------------- +/ Html elements +/ ------------------------------------------- + +/ To write your tags, use the percent sign followed by the name of the tag +%body + %header + %nav + +/ Notice no closing tags. The above code would output + + +
+ +
+ + +/ Divs are the default elements so they can be written simply like this +.foo + +/ To add content to a tag, nest it +%h1 Headline copy + +/ + To output a ruby value as the contents of the tag, use an equals sign followed + by the ruby code + +%h1= author.name + +/ Classes can be added to your tags either by chaining .classnames to the tag +%div.foo.bar + +/ or as part of a ruby hash +%div{:class => 'foo bar'} + +/ Attributes for any tag can be added in the hash +%a{:href => '#', :class => 'bar', :title => 'Bar'} + +/ For boolean attributes assign the value 'true' +%input{:selected => true} + +/ To write data-attributes, use the :data key with it's value as another hash +%div{:data => {:attribute => 'foo'}} + + -- cgit v1.2.3 From f6a604e1551233cb2f9b6a2c2c723f0acdc84f50 Mon Sep 17 00:00:00 2001 From: Simon Neveu Date: Wed, 8 Oct 2014 23:25:21 +0100 Subject: Copy change to intro and formatting --- haml.html.markdown | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/haml.html.markdown b/haml.html.markdown index 124f160b..60dc5426 100644 --- a/haml.html.markdown +++ b/haml.html.markdown @@ -1,13 +1,17 @@ --- language: haml -filename: learnhaml.haml +filename: learnhaml.html.haml contributors: - ["Simon Neveu", "https://github.com/sneveu"] --- -Haml is a markup language predominantly used with Ruby that’s used to cleanly and simply describe the HTML of any web document without the use of inline code. It encourages well-written markup. +Haml is a markup language predominantly used with Ruby that cleanly +and simply describes the HTML of any web document without the use of +inline code. -Haml aims to reduce repetition in your markup by closing tags for you based on the structure of the indents in your code. The result is markup that is well-structured, DRY, logical, and easier to read. +It aims to reduce repetition in your markup by closing tags for you +based on the structure of the indents in your code. The result is +markup that is well-structured, DRY, logical, and easier to read. ```haml / ------------------------------------------- -- cgit v1.2.3 From 46f174fab100f31659f3141a9aeca137035e34b3 Mon Sep 17 00:00:00 2001 From: Simon Neveu Date: Wed, 8 Oct 2014 23:32:22 +0100 Subject: testing git config --- haml.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/haml.html.markdown b/haml.html.markdown index 60dc5426..9cde462e 100644 --- a/haml.html.markdown +++ b/haml.html.markdown @@ -13,6 +13,7 @@ It aims to reduce repetition in your markup by closing tags for you based on the structure of the indents in your code. The result is markup that is well-structured, DRY, logical, and easier to read. + ```haml / ------------------------------------------- / Comments -- cgit v1.2.3 From 54835f209475cf6ace7fcd7fab8140ecedcec340 Mon Sep 17 00:00:00 2001 From: jmaud Date: Wed, 8 Oct 2014 21:23:20 -0400 Subject: Updates to tmux.conf Added reloading tmux configuration --- tmux.html.markdown | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 79829c88..ebc312ed 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -135,23 +135,27 @@ set -g base-index 1 # Mouse set-option -g mouse-select-pane on +# Force reload of config file +unbind r +bind r source-file ~/.tmux.conf + ### Keybinds ########################################################################### # Unbind C-b as the default prefix -unbind-key C-b +unbind C-b # Set new default prefix set-option -g prefix ` # Return to previous window when prefix is pressed twice -bind-key C-a last-window -bind-key ` last-window +bind C-a last-window +bind ` last-window # Allow swapping C-a and ` using F11/F12 -bind-key F11 set-option -g prefix C-a -bind-key F12 set-option -g prefix ` +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` # Keybind preference setw -g mode-keys vi @@ -176,7 +180,7 @@ unbind '"' unbind % # Activate inner-most session (when nesting tmux) to send commands -bind-key a send-prefix +bind a send-prefix ### Theme @@ -224,9 +228,17 @@ set-option -g set-titles on set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) # Statusbar Adjustments -set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S #[fg=green]][#[default]" +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" # Show performance counters in statusbar # Requires https://github.com/thewtex/tmux-mem-cpu-load/ -#set -g status-interval 4 -#set -g status-right "#[fg=green]][ #[fg=white]#(tmux-mem-cpu-load) #[fg=green]][ #[fg=yellow]%H:%M #[default]" +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + +Tmux | Home
+Tmux Manual page
+Archlinux Wiki
+Gentoo Wiki
+Display CPU/MEM % in statusbar
-- cgit v1.2.3 From 6629b5cd39b4d87ef47b57060d050919c7f40aa8 Mon Sep 17 00:00:00 2001 From: Alexander Sologub Date: Thu, 9 Oct 2014 19:50:55 +0300 Subject: [python/en] Removed unnecessary plus signs in bool operators section --- python.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 390c7b76..42a1f63a 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -58,15 +58,15 @@ to Python 2.x. Look for another tour of Python 3 soon! (1 + 3) * 2 # => 8 # 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 +# 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 # negate with not -- cgit v1.2.3 From 39d8753d5285348b998a7b87ae68614acf816df8 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: Thu, 9 Oct 2014 22:49:47 +0300 Subject: [python/en] Adding exponentiation operator --- python.html.markdown | 4 ++++ python3.html.markdown | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 390c7b76..a980b6dc 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -3,6 +3,7 @@ language: python contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "http://aminbandali.com"] + - "Andre Polykanine", "https://github.com/Oire"] filename: learnpython.py --- @@ -54,6 +55,9 @@ to Python 2.x. Look for another tour of Python 3 soon! # Modulo operation 7 % 3 # => 1 +# Exponentiation (x to the y'th power) +2 ** 4 # => 16 + # Enforce precedence with parentheses (1 + 3) * 2 # => 8 diff --git a/python3.html.markdown b/python3.html.markdown index a94f4eae..6fce9bf7 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -3,6 +3,7 @@ language: python3 contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] filename: learnpython3.py --- @@ -50,6 +51,9 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Modulo operation 7 % 3 # => 1 +# Exponentiation (x to the y'th power) +2 ** 4 # => 16 + # Enforce precedence with parentheses (1 + 3) * 2 # => 8 -- cgit v1.2.3 From 68c9aed1346fe20df741014de415f4297460dc67 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: Thu, 9 Oct 2014 23:06:24 +0300 Subject: Corrected as per @iirelu's comment --- python.html.markdown | 2 +- python3.html.markdown | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index a980b6dc..cac9d539 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -56,7 +56,7 @@ to Python 2.x. Look for another tour of Python 3 soon! 7 % 3 # => 1 # Exponentiation (x to the y'th power) -2 ** 4 # => 16 +2**4 # => 16 # Enforce precedence with parentheses (1 + 3) * 2 # => 8 diff --git a/python3.html.markdown b/python3.html.markdown index 6fce9bf7..e478e57f 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -52,7 +52,7 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria 7 % 3 # => 1 # Exponentiation (x to the y'th power) -2 ** 4 # => 16 +2**4 # => 16 # Enforce precedence with parentheses (1 + 3) * 2 # => 8 -- cgit v1.2.3 From a2043f3adbbeaca72c7ef15c4505924903111c5c 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: Thu, 9 Oct 2014 23:22:24 +0300 Subject: Gosh, what happened to me today?( Fixed the left bracket --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index cac9d539..febfa119 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -3,7 +3,7 @@ language: python contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "http://aminbandali.com"] - - "Andre Polykanine", "https://github.com/Oire"] + - ["Andre Polykanine", "https://github.com/Oire"] filename: learnpython.py --- -- cgit v1.2.3 From d1ef1771ad5448c3c004f1aec3e8b836df3cb96e Mon Sep 17 00:00:00 2001 From: Simon Neveu Date: Thu, 9 Oct 2014 23:13:37 +0100 Subject: Added filters, ruby interpolation and additional resources --- haml.html.markdown | 82 ++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 74 insertions(+), 8 deletions(-) diff --git a/haml.html.markdown b/haml.html.markdown index 9cde462e..47da2aee 100644 --- a/haml.html.markdown +++ b/haml.html.markdown @@ -7,7 +7,8 @@ contributors: Haml is a markup language predominantly used with Ruby that cleanly and simply describes the HTML of any web document without the use of -inline code. +inline code. It is a popular alternative to using rails templating +language (.erb) and allows you to embed ruby code into your markup. It aims to reduce repetition in your markup by closing tags for you based on the structure of the indents in your code. The result is @@ -19,7 +20,7 @@ markup that is well-structured, DRY, logical, and easier to read. / Comments / ------------------------------------------- -/ This is what a comment looks like haml +/ This is what a comment looks like haml. / To write a multi line comment, indent your commented code to be @@ -38,7 +39,6 @@ markup that is well-structured, DRY, logical, and easier to read. %nav / Notice no closing tags. The above code would output -
@@ -48,14 +48,25 @@ markup that is well-structured, DRY, logical, and easier to read. / Divs are the default elements so they can be written simply like this .foo -/ To add content to a tag, nest it +/ To add content to a tag, add the text directly after the declaration %h1 Headline copy -/ - To output a ruby value as the contents of the tag, use an equals sign followed - by the ruby code +/ To write multiline content, nest it instead +%p + This is a lot of content that we could probably split onto two + separate lines. + +/ You can escape html by using the ampersand and equals sign ( &= ) +%p + &= "Yes & yes" + +/ which would output 'Yes & yes' -%h1= author.name +/ You can unescape html by using the bang and equals sign ( != ) +%p + != "This is how you write a paragraph tag

" + +/ which would output 'This is how you write a paragraph tag

' / Classes can be added to your tags either by chaining .classnames to the tag %div.foo.bar @@ -73,3 +84,58 @@ markup that is well-structured, DRY, logical, and easier to read. %div{:data => {:attribute => 'foo'}} +/ ------------------------------------------- +/ Inserting Ruby +/ ------------------------------------------- + +/ + To output a ruby value as the contents of a tag, use an equals sign followed + by the ruby code + +%h1= book.name + +%p + = book.author + = book.publisher + + +/ To run some ruby code without rendering it to the html, use a hyphen instead +- books = ['book one', 'book 2', 'book 3'] + +/ Allowing you to do all sorts of awesome, like ruby blocks +- books.shuffle.each_with_index do |book, index| + %h1= book + + if book do + %p This is a book + +/ + Again, no need to add the closing tags to the block, even for the ruby. + Indentation will take care of that for you. + + +/ ------------------------------------------- +/ Inline Ruby / Ruby interpolation +/ ------------------------------------------- + +/ Include a ruby variable in a line of plain text using #{} +%p Your highest scoring game is #{best_game} + + +/ ------------------------------------------- +/ Filters +/ ------------------------------------------- + +/ + Use the colon to define haml filters, one example of a filter you can + use is :javascript, which can be used for writing inline js + + :javascript + console.log('This is inline + + +``` + +### Optimizing a whole project using r.js + +Many people prefer using AMD for sane code organization during development, but still want to ship a single script file in production instead of performing hundreds of XHRs on page load. + +`require.js` comes with a script called `r.js` (that you will probably run in node.js, although Rhino is supported too) that can analyse your project's dependency graph, and build a single file containing all your modules (properly named), minified and ready for consumption. + +Install it using `npm`: +```sh +$ npm install requirejs -g +``` +Now you can feed it with a configuration file: +```sh +$ r.js -o app.build.js +``` +For our above example the configuration might look like: +```javascript +/* file : app.build.js */ +({ + name : 'main', // name of the entry point + out : 'main-built.js', // name of the file to write the output to + baseUrl : 'app', + paths : { + // `empty:` tells r.js that this should still be loaded from the CDN, using + // the location specified in `main.js` + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` +To use the built file in production, simply swap `data-main`: +```html + +``` +An incredibly detailed [overview of build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is available in the GitHub repo. + +### Topics not covered in this tutorial +* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html) +* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html) +* [Advanced configuration](http://requirejs.org/docs/api.html#config) +* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim) +* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Using almond.js for builds](https://github.com/jrburke/almond) + +### Further reading: + +* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [Why AMD?](http://requirejs.org/docs/whyamd.html) +* [Universal Module Definition](https://github.com/umdjs/umd) + +### Implementations: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) -- cgit v1.2.3 From 74533ea29279c82957b45c6af0083e344800a17c Mon Sep 17 00:00:00 2001 From: Peter Palfrader Date: Sun, 12 Oct 2014 19:41:07 +0200 Subject: Fix a comment that indicates what "say @array" will print. We assigned 6 to @array[1] a few lines before, so say @array will print "a 6 b", not "a 2 b". --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index ee27ff42..52625bc2 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -64,7 +64,7 @@ say "Interpolate an array using [] : @array[]"; my @keys = 0, 2; @array[@keys] = @letters; # Assign using an array -say @array; #=> a 2 b +say @array; #=> a 6 b # There are two more kinds of lists: Parcel and Arrays. # Parcels are immutable lists (you can't modify a list that's not assigned). -- cgit v1.2.3 From 6933d24227ec5a0f220bf897e57d5222eaba0084 Mon Sep 17 00:00:00 2001 From: Geoffrey Liu Date: Sun, 12 Oct 2014 12:24:52 -0700 Subject: Capitalize language names. See #137 --- haskell.html.markdown | 2 +- julia.html.markdown | 2 +- lua.html.markdown | 2 +- php.html.markdown | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index e0489710..ad12de2a 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell contributors: - ["Adit Bhargava", "http://adit.io"] --- diff --git a/julia.html.markdown b/julia.html.markdown index feb38463..3a52018c 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -1,5 +1,5 @@ --- -language: julia +language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] filename: learnjulia.jl diff --git a/lua.html.markdown b/lua.html.markdown index be9f3141..0809215f 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -1,5 +1,5 @@ --- -language: lua +language: Lua contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] filename: learnlua.lua diff --git a/php.html.markdown b/php.html.markdown index e1bb86a0..039288a0 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] -- cgit v1.2.3 From e2913890cbc9d79d7840cead6157ff8e0f3216f9 Mon Sep 17 00:00:00 2001 From: Geoffrey Liu Date: Sun, 12 Oct 2014 13:43:05 -0700 Subject: Corrections Merci @Oire ! --- fr-fr/xml-fr.html.markdown | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/fr-fr/xml-fr.html.markdown b/fr-fr/xml-fr.html.markdown index 4dd09937..d7e76892 100644 --- a/fr-fr/xml-fr.html.markdown +++ b/fr-fr/xml-fr.html.markdown @@ -9,7 +9,7 @@ filename: learnxml.xml XML est un langage de balisage conçu pour stocker et transporter les informations. -Contrairement à HTML, XML ne spécifie pas comment afficher ou formater les informations, juste comment le porter. +Contrairement à HTML, XML ne spécifie pas comment afficher ou formater les informations, juste comment les porter. * La syntaxe XML @@ -17,40 +17,40 @@ Contrairement à HTML, XML ne spécifie pas comment afficher ou formater les inf - + Everyday Italian Giada De Laurentiis 2005 30.00 - + Harry Potter J. K. Rowling 2005 29.99 - + Learning XML Erik T. Ray 2003 39.95 - + - @@ -62,9 +62,9 @@ On crée les nœuds avec des balises d'ouverture / fermeture, et les enfants son ``` -* Un document bien-formaté & le validation +* Un document bien formaté & le validation -Un document XML est bien formaté s'il est syntaxiquement correcte. +Un document XML est bien formaté s'il est syntaxiquement correct. Cependant, il est possible d'injecter plus de contraintes dans le document, en utilisant les définitions de documents, tels que les schémas DTD et XML. @@ -79,19 +79,19 @@ Avec cet outil, vous pouvez vérifier les données XML en dehors de la logique d    avec l'addition de définition DTD. --> - - + + Everyday Italian 30.00 - + + @@ -103,25 +103,25 @@ Avec cet outil, vous pouvez vérifier les données XML en dehors de la logique d    Chaque «livre» doit contenir exactement un «titre» et «prix» et un attribut    appelé «catégorie», avec «littérature» comme valeur par défaut.    Les nœuds de «titre» et «prix» contiennent des informations de caractère analysés - (anglais: «parsed character data») --> + (Anglais: «parsed character data») --> - + + ]> - + Everyday Italian 30.00 - + ``` -- cgit v1.2.3 From ef6544a8868d3b19a115804b2db3962d91ad7979 Mon Sep 17 00:00:00 2001 From: Geoffrey Liu Date: Sun, 12 Oct 2014 14:24:42 -0700 Subject: Capitalize language names for translations. #137 --- de-de/haskell-de.html.markdown | 2 +- es-es/julia-es.html.markdown | 5 +++-- fr-fr/haskell.html.markdown | 2 +- fr-fr/lua-fr.html.markdown | 2 +- ko-kr/lua-kr.html.markdown | 2 +- ko-kr/php-kr.html.markdown | 2 +- pt-br/haskell-pt.html.markdown | 2 +- pt-br/php-pt.html.markdown | 2 +- ru-ru/haskell-ru.html.markdown | 2 +- ru-ru/julia-ru.html.markdown | 2 +- ru-ru/php-ru.html.markdown | 2 +- tr-tr/php-tr.html.markdown | 2 +- zh-cn/haskell-cn.html.markdown | 2 +- zh-cn/julia-cn.html.markdown | 2 +- zh-cn/lua-cn.html.markdown | 2 +- zh-cn/php-cn.html.markdown | 2 +- 16 files changed, 18 insertions(+), 17 deletions(-) diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown index df6267f9..2c548961 100644 --- a/de-de/haskell-de.html.markdown +++ b/de-de/haskell-de.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell lang: de-de contributors: - ["Adit Bhargava", "http://adit.io"] diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 41a7c68b..203ee3bb 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -1,8 +1,9 @@ --- -language: julia +language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] - - ["Guillermo Garza" ] +translators: + - ["Guillermo Garza", "http://github.com/ggarza"] filename: learnjulia-es.jl lang: es-es --- diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown index 989db1d5..d9d3151f 100644 --- a/fr-fr/haskell.html.markdown +++ b/fr-fr/haskell.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell contributors: - ["Adit Bhargava", "http://adit.io"] translators: diff --git a/fr-fr/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown index 922d6ebc..b4e2a161 100644 --- a/fr-fr/lua-fr.html.markdown +++ b/fr-fr/lua-fr.html.markdown @@ -1,5 +1,5 @@ --- -language: lua +language: Lua filename: learnlua-fr.lua contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index 850587a0..b4a018ef 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -1,5 +1,5 @@ --- -language: lua +language: Lua category: language contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] diff --git a/ko-kr/php-kr.html.markdown b/ko-kr/php-kr.html.markdown index 80f324f3..1f53221f 100644 --- a/ko-kr/php-kr.html.markdown +++ b/ko-kr/php-kr.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP category: language contributors: - ["Malcolm Fell", "http://emarref.net/"] diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index 55f90bd6..788dc1d2 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell contributors: - ["Adit Bhargava", "http://adit.io"] translators: diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown index 344df43a..0e710742 100644 --- a/pt-br/php-pt.html.markdown +++ b/pt-br/php-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] diff --git a/ru-ru/haskell-ru.html.markdown b/ru-ru/haskell-ru.html.markdown index 03e66d05..e15fe6b7 100644 --- a/ru-ru/haskell-ru.html.markdown +++ b/ru-ru/haskell-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell contributors: - ["Adit Bhargava", "http://adit.io"] translators: diff --git a/ru-ru/julia-ru.html.markdown b/ru-ru/julia-ru.html.markdown index cd55e116..29392604 100644 --- a/ru-ru/julia-ru.html.markdown +++ b/ru-ru/julia-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: julia +language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] translators: diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index edcac4dd..53b2f916 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] diff --git a/tr-tr/php-tr.html.markdown b/tr-tr/php-tr.html.markdown index 3db437cf..5258d785 100644 --- a/tr-tr/php-tr.html.markdown +++ b/tr-tr/php-tr.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP filename: learnphp-tr.php contributors: - ["Malcolm Fell", "http://emarref.net/"] diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index 8d51f144..cb7ccdee 100644 --- a/zh-cn/haskell-cn.html.markdown +++ b/zh-cn/haskell-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell filename: learn-haskell-zh.hs contributors: - ["Adit Bhargava", "http://adit.io"] diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index 7afc9043..1f91d52c 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: julia +language: Julia filename: learn-julia-zh.jl contributors: - ["Jichao Ouyang", "http://oyanglul.us"] diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 3ba098ec..53a603a2 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: lua +language: Lua lang: zh-cn contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] diff --git a/zh-cn/php-cn.html.markdown b/zh-cn/php-cn.html.markdown index 24939681..2def7f1c 100644 --- a/zh-cn/php-cn.html.markdown +++ b/zh-cn/php-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] -- cgit v1.2.3 From 8e9d5af1ea5680bbf5f232d5510f35f3c69619c2 Mon Sep 17 00:00:00 2001 From: Matt Kline Date: Sun, 12 Oct 2014 23:35:49 -0700 Subject: Minor C++ fixes --- c++.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index ce2d2d65..b55a764c 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -150,7 +150,7 @@ int main() #include // Include for I/O streams -using namespace std; +using namespace std; // Streams are in the std namespace (standard library) int main() { @@ -175,7 +175,7 @@ int main() // Strings in C++ are objects and have many member functions #include -using namespace std; // Strings are in the namespace std (standard library) +using namespace std; // Strings are also in the namespace std (standard library) string myString = "Hello"; string myOtherString = " World"; @@ -210,7 +210,7 @@ string bar = "I am bar"; string& fooRef = foo; // This creates a reference to foo. fooRef += ". Hi!"; // Modifies foo through the reference -cout << foo; // Prints "I am foo. Hi!" +cout << fooRef; // Prints "I am foo. Hi!" fooRef = bar; // Error: references cannot be reassigned. @@ -373,6 +373,9 @@ public: // Overload the += operator Point& operator+=(const Point& rhs); + + // It would also make sense to add the - and -= operators, + // but we will skip those for brevity. }; Point Point::operator+(const Point& rhs) const -- cgit v1.2.3 From 6119f4b3072200007990d4b0000fa46de5106951 Mon Sep 17 00:00:00 2001 From: zang Date: Tue, 14 Oct 2014 16:13:22 +0800 Subject: octal is eight in Chinese --- 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 223f6e35..1e10416e 100644 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -566,7 +566,7 @@ typedef void (*my_fnp_type)(char *); '\'' // 单引号 '\"' // 双引号 '\xhh' // 十六进制数字. 例子: '\xb' = vertical tab -'\ooo' // 十进制数字. 例子: '\013' = vertical tab +'\ooo' // 八进制数字. 例子: '\013' = vertical tab // 打印格式: "%d" // 整数 @@ -579,7 +579,7 @@ typedef void (*my_fnp_type)(char *); "%c" // 字母 "%p" // 指针 "%x" // 十六进制 -"%o" // 十进制 +"%o" // 八进制 "%%" // 打印 % /////////////////////////////////////// -- cgit v1.2.3 From 8768176023c4bb2efaea70ed19a89831e67fd402 Mon Sep 17 00:00:00 2001 From: Justin Campbell Date: Tue, 14 Oct 2014 16:42:39 -0400 Subject: Rust tutorial -> The Rust Guide Previous link is deprecated --- rust.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 0b9a5e58..3717a7d9 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -255,8 +255,8 @@ fn main() { ## Further reading There’s a lot more to Rust—this is just the basics of Rust so you can -understand the most important things. To learn more about Rust, read the -[Rust tutorial](http://doc.rust-lang.org/tutorial.html) and check out the +understand the most important things. To learn more about Rust, read [The Rust +Guide](http://doc.rust-lang.org/guide.html) and check out the [/r/rust](http://reddit.com/r/rust) subreddit. The folks on the #rust channel on irc.mozilla.org are also always keen to help newcomers. -- cgit v1.2.3 From eadecf8b95eba4afec302c0ab49b0ca0ca921299 Mon Sep 17 00:00:00 2001 From: Matt Kline Date: Fri, 17 Oct 2014 00:03:33 -0700 Subject: Spell out favorite (instead of fav) in C++ doc --- c++.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index b55a764c..4a070d95 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -157,13 +157,13 @@ int main() int myInt; // Prints to stdout (or terminal/screen) - cout << "Enter your fav number:\n"; + cout << "Enter your favorite number:\n"; // Takes in input cin >> myInt; // cout can also be formatted - cout << "Your fav number is " << myInt << "\n"; - // Your fav number is ## + cout << "Your favorite number is " << myInt << "\n"; + // prints "Your favorite number is " cerr << "Used for error messages"; } -- cgit v1.2.3 From fbf3c6d588cf39525afd23cb01230a997440dfcf Mon Sep 17 00:00:00 2001 From: Matt Kline Date: Fri, 17 Oct 2014 00:57:32 -0700 Subject: Add C++ section about RAII Future contributions will include standard library containers and C++11 features. --- c++.html.markdown | 130 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 129 insertions(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 4a070d95..dbca751f 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -263,7 +263,7 @@ public: // Along with constructors, C++ provides destructors. // These are called when an object is deleted or falls out of scope. // This enables powerful paradigms such as RAII - // (http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) + // (see below) // Destructors must be virtual to allow classes to be derived from this one. virtual ~Dog(); @@ -427,6 +427,134 @@ catch (const std::exception& ex) std::cout << "Unknown exception caught"; throw; // Re-throws the exception } + +/////// +// RAII +/////// + +// RAII stands for 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. + +// To understand how this is useful, +// consider a function that uses a C file handle: +void doSomethingWithAFile(const char* filename) +{ + // To begin with, assume nothing can fail. + + FILE* fh = fopen(filename, "r"); // Open the file in read mode. + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // Close the file handle. +} + +// Unfortunately, things are quickly complicated by error handling. +// Suppose fopen can fail, and that doSomethingWithTheFile and +// doSomethingElseWithIt return error codes if they fail. +// (Exceptions are the preferred way of handling failure, +// but some programmers, especially those with a C background, +// disagree on the utility of exceptions). +// We now have to check each call for failure and close the file handle +// if a problem occurred. +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Open the file in read mode + if (fh == nullptr) // The returned pointer is null on failure. + reuturn false; // Report that failure to the caller. + + // Assume each function returns false if it failed + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // Propagate the error. + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // Propagate the error. + } + + fclose(fh); // Close the file handle so it doesn't leak. + return true; // Indicate success +} + +// C programmers often clean this up a little bit using goto: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + reuturn false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Close the file + return true; // Indicate success + +failure: + fclose(fh); + return false; // Propagate the error +} + +// 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"); // Open the file in read mode + if (fh == nullptr) + throw std::exception("Could not open the file."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Be sure to close the file if an error occurs. + throw; // Then re-throw the exception. + } + + fclose(fh); // Close the file + // Everything succeeded +} + +// 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. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream is short for input file stream + std::ifstream fh(filename); // Open the file + + // Do things with the file + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // The file is automatically closed here by the destructor + +// This has _massive_ advantages: +// 1. No matter what happens, +// the resource (in this case the file handle) will be cleaned up. +// Once you write the destructor correctly, +// It is _impossible_ to forget to close the handle and leak the resource. +// 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 ``` Futher Reading: -- cgit v1.2.3 From 03d1bc5ed97f16627afc64d4c7a53e84a0281906 Mon Sep 17 00:00:00 2001 From: Matt Kline Date: Fri, 17 Oct 2014 18:42:30 -0700 Subject: Address @levibostian's concerns for #800 --- c++.html.markdown | 56 ++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 15 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index dbca751f..50de5eff 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -7,12 +7,14 @@ contributors: lang: en --- -C++ was designed as a systems programming language that +C++ is a systems programming language that, +[according to its inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +was designed to -- is a "better C" -- supports data abstraction -- supports object-oriented programming -- supports generic programming +- be a "better C" +- support data abstraction +- support object-oriented programming +- support generic programming Though its syntax can be more difficult or complex than newer languages, it is widely used because it compiles to native instructions that can be @@ -32,9 +34,21 @@ one of the most widely-used programming languages. // A main() function in C++ should return an int, // though void main() is accepted by most compilers (gcc, clang, etc.) -int main() // or int main(int argc, char** argv) +// This value serves as the program's exit status. +// See http://en.wikipedia.org/wiki/Exit_status for more information. +int main(int argc, char** argv) { - return 0; // Can also end without return statement + // Command line arguments are passed in by argc and argv in the same way + // they are in C. + // argc indicates the number of arguments, + // and argv is an array of C-style strings (char*) + // representing the arguments. + // The first argument is the name by which the program was called. + // argc and argv can be omitted if you do not care about arguments, + // giving the function signature of int main() + + // An exit status of 0 indicates success. + return 0; } // In C++, character literals are one byte. @@ -82,21 +96,33 @@ void print(int myInt) int main() { - printing("Hello"); // Resolves to void print(const char*) - printing(15); // Resolves to void print(int) + print("Hello"); // Resolves to void print(const char*) + print(15); // Resolves to void print(int) } ///////////////////////////// // Default function arguments ///////////////////////////// -void two_ints(int a = 1, int b = 4); +// You can provide default arguments for a function +// if they are not provided by the caller. + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // Do something with the ints here +} int main() { - two_ints(); // a = 1, b = 4 - two_ints(20); // a = 20, b = 4 - two_ints(20, 5); // a = 20, b = 5 + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// Default arguments must be at the end of the arguments list. + +void invalidDeclaration(int a = 1, int b) // Error! +{ } @@ -106,7 +132,7 @@ int main() // Namespaces provide separate scopes for variable, function, // and other declarations. -// Namespaces can be nested +// Namespaces can be nested. namespace First { namespace Nested { @@ -362,7 +388,7 @@ public: Point() { }; // The following syntax is known as an initialization list - // and is the proper way to initialize class member values + // and is the proper way to initialize class member values Point (double a, double b) : x(a), y(b) -- cgit v1.2.3 From 01b671bf398001647650db24dcc51f584ea82490 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 17 Oct 2014 20:54:45 -0500 Subject: Fix beginning typo from bash --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index 9b199b8c..11c1f3a2 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -202,7 +202,7 @@ uniq -d file.txt cut -d ',' -f 1 file.txt # replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible) sed -i 's/okay/great/g' file.txt -# print to stdout all lines of file.txt which match some regex, the example prints lines which beginning with "foo" and end in "bar" +# print to stdout all lines of file.txt which match some regex, the example prints lines which begin with "foo" and end in "bar" grep "^foo.*bar$" file.txt # pass the option "-c" to instead print the number of lines matching the regex grep -c "^foo.*bar$" file.txt -- cgit v1.2.3 From 0ec14c6914ae9a0c968b8f2e70e31b43f3aaaf73 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 17 Oct 2014 20:57:18 -0500 Subject: Add fixes from @marcom's PR https://github.com/adambard/learnxinyminutes-docs/pull/765 --- c.html.markdown | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 10e6fa45..6daabe94 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Adam Bard", "http://adambard.com/"] - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] + - ["Marco Scannadinari", "https://marcoms.github.io"] --- @@ -21,6 +22,10 @@ memory management and C will take you as far as you need to go. Multi-line comments look like this. They work in C89 as well. */ +/* +Multi-line comments don't nest /* Be careful */ // comment ends on this line... +*/ // ...not this one! + // Constants: #define #define DAYS_IN_YEAR 365 @@ -74,10 +79,10 @@ int main() { long long x_long_long = 0; // floats are usually 32-bit floating point numbers - float x_float = 0.0; + float x_float = 0.0f; // 'f' suffix here denotes floating point literal // doubles are usually 64-bit floating-point numbers - double x_double = 0.0; + double x_double = 0.0; // real numbers without any suffix are doubles // Integral types may be unsigned. unsigned short ux_short; -- cgit v1.2.3 From 780826ac277bdbbc7d6841facbcc8df9f19b22f3 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 17 Oct 2014 20:58:45 -0500 Subject: Fix typos from amd.html PR https://github.com/adambard/learnxinyminutes-docs/pull/803 --- amd.html.markdown | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/amd.html.markdown b/amd.html.markdown index 3500fa58..36210d03 100644 --- a/amd.html.markdown +++ b/amd.html.markdown @@ -8,7 +8,11 @@ filename: learnamd.js ## Getting Started with AMD -The **Asynchronous Module Definition** API specifies a mechanism for defining JavaScript modules such that the module and its dependencies can be asynchronously loaded. This is particularly well suited for the browser environment where synchronous loading of modules incurs performance, usability, debugging, and cross-domain access problems. +The **Asynchronous Module Definition** API specifies a mechanism for defining +JavaScript modules such that the module and its dependencies can be asynchronously +loaded. This is particularly well suited for the browser environment where +synchronous loading of modules incurs performance, usability, debugging, and +cross-domain access problems. ### Basic concept ```javascript @@ -55,7 +59,7 @@ require(['loudmouth'], function(loudmouth){ loudmouth(); }); -// To make this tutorial running code, let's implement a very basic +// To make this tutorial run code, let's implement a very basic // (non-asynchronous) version of AMD right here on the spot: function define(name, deps, factory){ // notice how modules without dependencies are handled -- cgit v1.2.3 From ccdd47267b28104a74352151a0424bd6f62bd390 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 17 Oct 2014 21:09:51 -0500 Subject: Add a couple missing parts to the markdown doc from @ukom PR https://github.com/adambard/learnxinyminutes-docs/pull/341 --- markdown.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/markdown.html.markdown b/markdown.html.markdown index 3d4d0af6..7541f904 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -126,6 +126,14 @@ render the numbers in order, but this may not be a good idea --> * Sub-item 4. Item four + + +Boxes below without the 'x' are unchecked HTML checkboxes. +- [ ] First task to complete. +- [ ] Second task that needs done +This checkbox below will be a checked HTML checkbox. +- [x] This task has been completed + -- cgit v1.2.3 From 4a7a7e3e9dabc3b02e656a377ca3f8342e781f48 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 17 Oct 2014 21:17:43 -0500 Subject: Add @ukom Polish Perl translation from PR https://github.com/adambard/learnxinyminutes-docs/pull/341 --- pl-pl/perl-pl.html.markdown | 169 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 pl-pl/perl-pl.html.markdown diff --git a/pl-pl/perl-pl.html.markdown b/pl-pl/perl-pl.html.markdown new file mode 100644 index 00000000..9e8ade5b --- /dev/null +++ b/pl-pl/perl-pl.html.markdown @@ -0,0 +1,169 @@ +--- +name: perl +category: language +language: perl +filename: learnperl.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] + - ["Michał Kupczyński", "http://github.com/ukoms"] +lang: pl-pl +--- + +Perl 5 jest wysoce użytecznym, bogatym w wiele opcji językiem programowania +z ponad 25 latami nieustannego rozwoju. + +Perl 5 używany jest na ponad 100 różnych platformach (od przenośnych do w +pełni stacjonarnych) i nadaje się zarówno do szybkiego prototypowania jak +i projektów deweloperskich prowadzonych na szeroką skalę. + +```perl + +# Pojedyncza linia komentarza zaczyna się od znaku hasha (płotka) "#". + +#### Typy zmiennych w Perlu + +# Zmienna zaczyna się od symbolu dolara "$". +# Prawidłowa nazwa zmiennej zaczyna się od litery lub podkreślnika "_", +# po których następuje dowolna ilość liter, cyfr i podkreślników. + +### W Perlu występują trzy główne typy zmiennych: skalary, tablice i hasze. + +## Skalary +# Skalar przechowuje pojedynczą wartość: +my $zwierze = "wielbłąd"; +my $odpowiedź = 42; + +# Wartości skalarne mogą być ciągami znaków, liczbami całkowitymi lub +# zmiennoprzecinkowymi, zaś Perl automatycznie dokonuje konwersji pomiędzy nimi, +# w zależności od wykonywanego kodu/kontekstu. + +## Tablice +# Tablica przechowuje listę wartości: +my @zwierzęta = ("wielbłąd", "alpaka", "sowa"); +my @liczby = (23, 42, 69); +my @mieszanka = ("wielbłąd", 42, 1.23); + +## Hasze +# Hasz przechowuje zestawy par klucz-wartość: +my %kolor_owocu = ('jabłko', 'czerwony', 'banan', 'żółty'); + +# Możesz używać białych znaków (spacje, tabulatory) i operatora strzałki "=>" +# by czytelniej sformatować zapis hasza: +my %kolor_owocu = ( + jabłko => 'czerwony', + banan => 'żółty', +); + +# Skalary, tablice i hasze są bardziej wyczerpująco udokumentowane w dokumencie +# [perldoc perldata](http://perldoc.perl.org/perldata.html). + +# Bardziej złożone typy danych mogą być stworzone poprzez używanie referencji, +# które pozwalają Ci zbudować listy i hasze wewnątrz list i haszy. + +#### Warunki logiczne i pętle + +# W Perlu występują typowe warunki i pętle. +if ($var) { + ... +} elsif ($var eq 'bar') { + ... +} else { + ... +} + +unless (warunek) { + ... +} +# Powyższy zapis jest równoznaczny zapisowi "if (!warunek)" + +# Perlowy skrócony zapis warunków: +print "Siema!" if $rozochocony; +print "Nie mamy bananów" unless $banany; + +# Pętla while +while (warunek) { + ... +} + +# Pętle for oraz foreach +for ($i = 0; $i <= $max; $i++) { + ... +} + +foreach (@tablica) { + print "Tym elementem jest $_\n"; +} + +# lub + +foreach my $iterator (@tablica) { + print "Iterowanym elementem jest $iterator\n"; +} + +#### Wyrażenia regularne + +# Perlowe wyrażenia regularne są tematem tak rozległym, jak wymagającym. +# Istnieje ogromna ilość dokumentacji w artykułach takich jak +# [perlrequick](http://perldoc.perl.org/perlrequick.html), +# [perlretut](http://perldoc.perl.org/perlretut.html) i inne. +# W dużym skrócie, podstawy perlowych wyrażeń regularnych są następujące: + +# Proste dopasowanie: +if (/foo/) { ... } # prawda jeżeli $_ zawiera "foo" +if ($a =~ /foo/) { ... } # prawda jeżeli $a zawiera "foo" + +# Prosta zamiana: +# Zamienia "foo" na "bar" w zmiennej $a +$a =~ s/foo/bar/; +# Zamienia WSZYSTKIE WYSTĄPIENIA "foo" na "bar" w zmiennej $a +$a =~ s/foo/bar/g; + +#### Pliki i I/O + +# Możesz otworzyć plik do odczytu lub zapisu używając funkcji "open ()". +open (my $odczyt, "<", "odczyt.txt") or die "Błąd otwierania input.txt: $!"; +open (my $zapis, ">", "zapis.txt") or die "Błąd otwierania output.txt: $!"; +open (my $dopisanie, ">>", "my.log") or die "Błąd otwierania my.log: $!"; + +# Pliki możesz odczytywać z otworzonego handlera używając operatora "<>" +# (operator diamentowy). W kontekście skalarnym (przypisanie wyniku do skalara) +# operator ten zczytuje pojedynczą linię pliku, w kontekście listowym +# (przypisanie wyniku do tablicy) zczytuje całą zawartość pliku, przypisując +# każdą linię jako kolejny element listy: +my $linia = <$in>; +my @linie = <$in>; + +#### Perlowe funkcje (procedury) + +# Pisanie funkcji (procedur) jest proste: +sub logger { + my $wiadomosc_do_loga = shift; + open (my HANDLER, ">>", "my.log") or die "Błąd otwierania my.log: $!"; + print HANDLER $wiadomosc_do_loga; +} + +# Teraz można używać napisanej funkcji, tak jak każdej innej wbudowanej +# funkcji perlowej: +logger ("Mamy funkcję perlową"); + +``` + +#### Używanie modułów perlowych + +Moduły perlowe dostarczają szeroki wachlarz możliwości, byś nie musiał +wynajdywać koła na nowo. Moduły te można pobrać z [CPAN](http://www.cpan.org). +Sam Perl zawiera w swoich dystrybucjach kilka najpopularniejszych modułów +z repozytorium [CPAN](http://www.cpan.org). + +Najczęściej zadawane pytania [perlfaq](http://perldoc.perl.org/perlfaq.html) +- zawierają pytania i odpowiedzi dotyczące wielu typowo realizowanych zadań. +Często znajdziesz tam również sugestie dotyczące użycia najlepszego modułu +z repozytorium CPAN do zrealizowania konkretnego zadania. + + +#### Do doczytania + + - [perl-tutorial](http://perl-tutorial.org/) + - [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - wbudowane w Perla: `perldoc perlintro` \ No newline at end of file -- cgit v1.2.3 From 679d7098f2fe663b62e7a7e328369b760f94195c Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Fri, 17 Oct 2014 21:22:28 -0500 Subject: - update examples - further explain Optional types - add build config example - explain array/dictionary mutability - expand tuple example --- swift.html.markdown | 56 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 4 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index ffe6cac2..005e511c 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -27,6 +27,9 @@ import UIKit println("Hello, world") +// variables (var) value can change after being set +// constants (let) value can NOT be changed after being set + var myVariable = 42 let øπΩ = "value" // unicode variable names let π = 3.1415926 @@ -38,7 +41,29 @@ let intValue = 0007 // 7 let largeIntValue = 77_000 // 77000 let label = "some text " + String(myVariable) // Casting let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation + +// Build Specific values +// uses -D build configuration +#if false + println("Not printed") + let buildValue = 3 +#else + let buildValue = 7 +#endif +println("Build value: \(buildValue)") // Build value: 7 + +/* + Optionals are a Swift language feature that allows you to store a `Some` or + `None` value. + + Because Swift requires every property to have a value, even nil must be + explicitly stored as an Optional value. + + Optional is an enum. +*/ var someOptionalString: String? = "optional" // Can be nil +// same as above, but ? is a postfix operator (syntax candy) +var someOptionalString2: Optional = "optional" if someOptionalString != nil { // I am not nil @@ -50,11 +75,23 @@ if someOptionalString != nil { } someOptionalString = nil -if let someStringConstant = someOptionalString { - // has Some value +// implicitly unwrapped optional +var unwrappedString: String! = "Value is expected." +// same as above, but ! is a postfix operator (more syntax candy) +var unwrappedString2: ImplicitlyUnwrappedOptional = "Value is expected." + +if let someOptionalStringConstant = someOptionalString { + // has `Some` value, non-nil + if !someOptionalStringConstant.hasPrefix("ok") { + // does not have the prefix + } } +// Swift has support for storing a value of any type. // AnyObject == id +// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Changed value to a string, not good practice, but possible." /* Comment here @@ -67,10 +104,17 @@ Comment here // MARK: Collections // +/* + Array and Dictionary types are structs. So `let` and `var` also indicate + that they are mutable (var) or immutable (let) when declaring these types. +*/ + // Array var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" -let emptyArray = [String]() +let emptyArray = [String]() // immutable +var emptyMutableArray = [String]() // mutable + // Dictionary var occupations = [ @@ -78,7 +122,8 @@ var occupations = [ "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" -let emptyDictionary = [String: Float]() +let emptyDictionary = [String: Float]() // immutable +var emptyMutableDictionary = [String: Float]() // mutable // @@ -162,6 +207,9 @@ func getGasPrices() -> (Double, Double, Double) { } let pricesTuple = getGasPrices() let price = pricesTuple.2 // 3.79 +// Ignore Tuple (or other) values by using _ (underscore) +let (_, price1, _) = pricesTuple // price1 == 3.69 +println(price1 == pricesTuple.1) // true println("Gas price: \(price)") // Variadic Args -- cgit v1.2.3 From 8e723a5f456403911b512c92979c9417a972406c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 17 Oct 2014 21:43:23 -0500 Subject: Update language type for XML fr --- fr-fr/xml-fr.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fr-fr/xml-fr.html.markdown b/fr-fr/xml-fr.html.markdown index d7e76892..ed5f55ff 100644 --- a/fr-fr/xml-fr.html.markdown +++ b/fr-fr/xml-fr.html.markdown @@ -4,7 +4,8 @@ contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Geoffrey Liu", "https://github.com/g-liu"] -filename: learnxml.xml +filename: learnxml-fr.xml +lang: fr-fr --- XML est un langage de balisage conçu pour stocker et transporter les informations. -- cgit v1.2.3 From b2cb538a5a758ce03a219545a77b274cd8609cc4 Mon Sep 17 00:00:00 2001 From: Oscar Date: Sat, 18 Oct 2014 11:44:44 +0800 Subject: Recursive function a little bit to recursive Infinitely recursive --- ocaml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index b9505f13..f9db7080 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -93,7 +93,7 @@ let inc_int (x: int) : int = x + 1 ;; (* You need to mark recursive function definitions as such with "rec" keyword. *) let rec factorial n = if n = 0 then 1 - else factorial n * factorial (n-1) + else n * factorial (n-1) ;; (* Function application usually doesn't need parentheses around arguments *) -- cgit v1.2.3 From c49e6f1928d6a717734fe1afbb3f96adac37c0b7 Mon Sep 17 00:00:00 2001 From: Dzianis Dashkevich Date: Sat, 18 Oct 2014 14:00:32 +0300 Subject: [elixir/en] Replace Records section w/ Structs one Fix typos Add "Programming Elixir" and Elixir Cheat Sheet to References section --- elixir.html.markdown | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index c0abc815..0a20e3df 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -2,6 +2,7 @@ language: elixir contributors: - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] filename: learnelixir.ex --- @@ -59,7 +60,7 @@ tail #=> [2,3] # the tuples have different sizes. # {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} -# There's also binaries +# There are also binaries <<1,2,3>> # binary # Strings and char lists @@ -108,7 +109,7 @@ div(10, 2) #=> 5 # To get the division remainder use `rem` rem(10, 3) #=> 1 -# There's also boolean operators: `or`, `and` and `not`. +# There are also boolean operators: `or`, `and` and `not`. # These operators expect a boolean as their first argument. true and true #=> true false or true #=> true @@ -119,7 +120,6 @@ false or true #=> true 1 || true #=> 1 false && 1 #=> false nil && 20 #=> nil - !true #=> false # For comparisons we have: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>` @@ -165,12 +165,12 @@ case {:one, :two} do {:four, :five} -> "This won't match" {:one, x} -> - "This will match and assign `x` to `:two`" + "This will match and bind `x` to `:two`" _ -> "This will match any value" end -# It's common practice to assign a value to `_` if we don't need it. +# It's common to bind the value to `_` if we don't need it. # For example, if only the head of a list matters to us: [head | _] = [1,2,3] head #=> 1 @@ -190,7 +190,7 @@ cond do "But I will" end -# It is common to see a last condition equal to `true`, which will always match. +# It is common to see the last condition equal to `true`, which will always match. cond do 1 + 1 == 3 -> "I will never be seen" @@ -301,7 +301,7 @@ end Recursion.sum_list([1,2,3], 0) #=> 6 # Elixir modules support attributes, there are built-in attributes and you -# may also add custom attributes. +# may also add custom ones. defmodule MyMod do @moduledoc """ This is a built-in attribute on a example module. @@ -312,21 +312,24 @@ defmodule MyMod do end ## --------------------------- -## -- Records and Exceptions +## -- Structs and Exceptions ## --------------------------- -# Records are basically structures that allow you to associate a name with -# a particular value. -defrecord Person, name: nil, age: 0, height: 0 +# Structs are extensions on top of maps that bring default values, +# compile-time guarantees and polymorphism into Elixir. +defmodule Person do + defstruct name: nil, age: 0, height: 0 +end -joe_info = Person.new(name: "Joe", age: 30, height: 180) -#=> Person[name: "Joe", age: 30, height: 180] +joe_info = %Person{ name: "Joe", age: 30, height: 180 } +#=> %Person{age: 30, height: 180, name: "Joe"} # Access the value of name joe_info.name #=> "Joe" # Update the value of age -joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] +older_joe_info = %{ joe_info | age: 31 } +#=> %Person{age: 31, height: 180, name: "Joe"} # The `try` block with the `rescue` keyword is used to handle exceptions try do @@ -394,5 +397,7 @@ self() #=> #PID<0.27.0> * [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org) * [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) by Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) * ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) by Fred Hebert -* "Programming Erlang: Software for a Concurrent World" by Joe Armstrong +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong -- cgit v1.2.3 From 1f39917528fc13b20a12b0d7567c0171b7ffaaaf Mon Sep 17 00:00:00 2001 From: Simon Neveu Date: Sat, 18 Oct 2014 12:25:42 +0100 Subject: Added info on indentation and escaping html, typos --- haml.html.markdown | 58 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 36 insertions(+), 22 deletions(-) diff --git a/haml.html.markdown b/haml.html.markdown index 86d9ba81..aed3dcae 100644 --- a/haml.html.markdown +++ b/haml.html.markdown @@ -1,26 +1,36 @@ --- language: haml -filename: learnhaml.html.haml +filename: learnhaml.haml contributors: - ["Simon Neveu", "https://github.com/sneveu"] --- -Haml is a markup language predominantly used with Ruby that cleanly -and simply describes the HTML of any web document without the use of -inline code. It is a popular alternative to using rails templating -language (.erb) and allows you to embed ruby code into your markup. +Haml is a markup language predominantly used with Ruby that cleanly and simply describes the HTML of any web document without the use of inline code. It is a popular alternative to using Rails templating language (.erb) and allows you to embed Ruby code into your markup. -It aims to reduce repetition in your markup by closing tags for you -based on the structure of the indents in your code. The result is -markup that is well-structured, DRY, logical, and easier to read. +It aims to reduce repetition in your markup by closing tags for you based on the structure of the indents in your code. The result is markup that is well-structured, DRY, logical, and easier to read. + +You can also use Haml on a project independent of Ruby, by installing the Haml gem on your machine and using the command line to convert it to html. + +$ haml input_file.haml output_file.html ```haml +/ ------------------------------------------- +/ Indenting +/ ------------------------------------------- + +/ + Because of the importance indentation has on how your code is rendered, the + indents should be consistent throughout the document. Any differences in + indentation will throw an error. It's common-practice to use two spaces, + but it's really up to you, as long as they're constant. + + / ------------------------------------------- / Comments / ------------------------------------------- -/ This is what a comment looks like haml. +/ This is what a comment looks like in Haml. / To write a multi line comment, indent your commented code to be @@ -45,7 +55,7 @@ markup that is well-structured, DRY, logical, and easier to read.
-/ Divs are the default elements so they can be written simply like this +/ The div tag is the default element, so they can be written simply like this .foo / To add content to a tag, add the text directly after the declaration @@ -56,11 +66,15 @@ markup that is well-structured, DRY, logical, and easier to read. This is a lot of content that we could probably split onto two separate lines. -/ You can escape html by using the ampersand and equals sign ( &= ) +/ + You can escape html by using the ampersand and equals sign ( &= ). This + converts html-sensitive characters (&, /, :) into their html encoded + equivalents. For example + %p &= "Yes & yes" -/ which would output 'Yes & yes' +/ would output 'Yes & yes' / You can unescape html by using the bang and equals sign ( != ) %p @@ -68,10 +82,10 @@ markup that is well-structured, DRY, logical, and easier to read. / which would output 'This is how you write a paragraph tag

' -/ Classes can be added to your tags either by chaining .classnames to the tag +/ CSS classes can be added to your tags either by chaining .classnames to the tag %div.foo.bar -/ or as part of a ruby hash +/ or as part of a Ruby hash %div{:class => 'foo bar'} / Attributes for any tag can be added in the hash @@ -80,7 +94,7 @@ markup that is well-structured, DRY, logical, and easier to read. / For boolean attributes assign the value 'true' %input{:selected => true} -/ To write data-attributes, use the :data key with it's value as another hash +/ To write data-attributes, use the :data key with its value as another hash %div{:data => {:attribute => 'foo'}} @@ -89,8 +103,8 @@ markup that is well-structured, DRY, logical, and easier to read. / ------------------------------------------- / - To output a ruby value as the contents of a tag, use an equals sign followed - by the ruby code + To output a Ruby value as the contents of a tag, use an equals sign followed + by the Ruby code %h1= book.name @@ -99,10 +113,10 @@ markup that is well-structured, DRY, logical, and easier to read. = book.publisher -/ To run some ruby code without rendering it to the html, use a hyphen instead +/ To run some Ruby code without rendering it to the html, use a hyphen instead - books = ['book 1', 'book 2', 'book 3'] -/ Allowing you to do all sorts of awesome, like ruby blocks +/ Allowing you to do all sorts of awesome, like Ruby blocks - books.shuffle.each_with_index do |book, index| %h1= book @@ -110,7 +124,7 @@ markup that is well-structured, DRY, logical, and easier to read. %p This is a book / - Again, no need to add the closing tags to the block, even for the ruby. + Again, no need to add the closing tags to the block, even for the Ruby. Indentation will take care of that for you. @@ -118,7 +132,7 @@ markup that is well-structured, DRY, logical, and easier to read. / Inline Ruby / Ruby interpolation / ------------------------------------------- -/ Include a ruby variable in a line of plain text using #{} +/ Include a Ruby variable in a line of plain text using #{} %p Your highest scoring game is #{best_game} @@ -127,7 +141,7 @@ markup that is well-structured, DRY, logical, and easier to read. / ------------------------------------------- / - Use the colon to define haml filters, one example of a filter you can + Use the colon to define Haml filters, one example of a filter you can use is :javascript, which can be used for writing inline js :javascript -- cgit v1.2.3 From b9466505f55bf99d8f93beab1e7f0fdce7b64319 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 18 Oct 2014 13:19:07 -0500 Subject: Attempt at fixing amd file's markdown on site. --- amd.html.markdown | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/amd.html.markdown b/amd.html.markdown index 36210d03..b3237dc7 100644 --- a/amd.html.markdown +++ b/amd.html.markdown @@ -136,6 +136,7 @@ require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolL }); ``` `require.js`-based apps will usually have a single entry point (`main.js`) that is passed to the `require.js` script tag as a data-attribute. It will be automatically loaded and executed on pageload: + ```html @@ -155,13 +156,15 @@ Many people prefer using AMD for sane code organization during development, but `require.js` comes with a script called `r.js` (that you will probably run in node.js, although Rhino is supported too) that can analyse your project's dependency graph, and build a single file containing all your modules (properly named), minified and ready for consumption. Install it using `npm`: -```sh +```shell $ npm install requirejs -g ``` + Now you can feed it with a configuration file: -```sh +```shell $ r.js -o app.build.js ``` + For our above example the configuration might look like: ```javascript /* file : app.build.js */ @@ -177,10 +180,12 @@ For our above example the configuration might look like: } }) ``` + To use the built file in production, simply swap `data-main`: ```html ``` + An incredibly detailed [overview of build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is available in the GitHub repo. ### Topics not covered in this tutorial -- cgit v1.2.3 From 484b01e663f209b86000ee181a6a8832ec130242 Mon Sep 17 00:00:00 2001 From: Joao Farias Date: Sat, 18 Oct 2014 19:52:45 -0300 Subject: [groovy-pt] Translation of Groovy page to pt-br --- pt-br/groovy-pt.html.markdown | 435 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 435 insertions(+) create mode 100644 pt-br/groovy-pt.html.markdown diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown new file mode 100644 index 00000000..885d5b27 --- /dev/null +++ b/pt-br/groovy-pt.html.markdown @@ -0,0 +1,435 @@ +--- +language: Groovy +category: language +filename: learngroovy.groovy +contributors: + - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"] +translators: + - ["João Farias", "https://github.com/JoaoGFarias"] +lang: pt-br +--- + +Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http://groovy.codehaus.org) + +```groovy + +/* + Prepara-se: + + 1) Instale a máquina virtual de Groovy - http://gvmtool.net/ + 2) Intalse o Groovy: gvm install groovy + 3) Inicie o console groovy digitando: groovyConsole + +*/ + +// Comentário de uma linha inicia-se com duas barras +/* +Comentário de múltiplas linhas são assim. +*/ + +// Olá Mundo! +println "Olá mundo!" + +/* + Variáveis: + + Você pode atribuir valores a variáveis para uso posterior +*/ + +def x = 1 +println x + +x = new java.util.Date() +println x + +x = -3.1499392 +println x + +x = false +println x + +x = "Groovy!" +println x + +/* + Coleções e mapeamentos +*/ + +//Criando uma lista vazia +def tecnologias = [] + +/*** Adicionando elementos à lista ***/ + +// Assim como Java +tecnologias.add("Grails") + +// Shift para esquerda adiciona e retorna a lista +tecnologias << "Groovy" + +// Adição de múltiplos elementos +tecnologias.addAll(["Gradle","Griffon"]) + +/*** Removendo elementos da lista ***/ + +// Assim como Java +tecnologias.remove("Griffon") + +// Subtração também funciona +tecnologias = technologies - 'Grails' + +/*** Iterando sobre listas ***/ + +// Itera sobre os elementos da lista +tecnologias.each { println "Tecnologias: $it"} +tecnologias.eachWithIndex { it, i -> println "$i: $it"} + +/*** Checando os elementos da lista ***/ + +//Avalia se a lista contém o elemento 'Groovy' +contem = tecnologias.contains( 'Groovy' ) + +// Ou +contem = 'Groovy' in tecnologias + +// Checagem por múltiplos elementos +tecnologias.containsAll(['Groovy','Grails']) + +/*** Ordenando listas ***/ + +// Ordena a lista (altera a lista in-place) +tecnologias.sort() + +// Para ordenar a lista sem alterar a original +tecnologiasOrdenadas = tecnologias.sort( false ) + +/*** Manipulando listas ***/ + +//Substitue todos os elementos da lista +Collections.replaceAll(tecnologias, 'Gradle', 'gradle') + +//Desorganiza a lista +Collections.shuffle(tecnologias, new Random()) + +//Limpa a lista +technologies.clear() + +//Criando um mapeamento vazio +def devMap = [:] + +//Adicionando valores +devMap = ['nome':'Roberto', 'framework':'Grails', 'linguagem':'Groovy'] +devMap.put('ultimoNome','Perez') + +//Iterando sobre os elementos do mapeamento +devMap.each { println "$it.key: $it.value" } +devMap.eachWithIndex { it, i -> println "$i: $it"} + +//Avalia se um mapeamento contém uma chave +assert devMap.containsKey('nome') + +//Avalia se um mapeamento contém um valor +assert devMap.containsValue('Roberto') + +//Pega as chaves de um mapeamento +println devMap.keySet() + +//Pega os valores de um mapeamento +println devMap.values() + +/* + Groovy Beans + + GroovyBeans são JavaBeans com uma sintaxe muito mais simples. + + Quando Groovy é compilado para bytecode, as seguintes regras são usadas: + + * Se o nome é declarado com um modificador de acesso(public, private or + protected) então um atributo é gerado. + + * Um nome declarado sem modificador de acesso gera um campo privado com + getter e setter públicos (ou seja, uma propriedade). + + * Se uma propriedade é declarada como final, um campo private final é criado + e o setter não é gerado. + + * Você pode declarar uma propriedade e também declarar seus próprios getters + e setters. + + * Você pode declarar uma propriedade e um campo com o mesmo nome, a propriedade + usará este campo. + + * Se você quer uma propriedade private ou protected, você deve prover seus + próprios getters e setter, que devem ser declarados como private ou protected. + + * Se você acessar uma propriedade dentro da classe e esta propriedade é definida + em tempo de compilação com 'this', implícito ou explícito (por exemplo, + this.foo, ou simplesmente foo), Groovy acessará este campo diretamente, sem + passar pelo getter ou setter. + + * Se você acessar uma propriedade que não existe usando foo, explicitamente ou + implicitamente, então Groovy irá acessar esta propriedade através da meta + classe, o que pode falhar em tempo de execução. + +*/ + +class Foo { + // propriedade de leitura, apenas + final String nome = "Roberto" + + // propriedade de leitura, apenas, com getter e setter públicos + String linguagem + protected void setLinguagem(String linguagem) { this.linguagem = linguagem } + + // propriedade tipada dinamicamente + def ultimoNome +} + +/* + Condicionais e loops +*/ + +//Groovy suporta a sintaxe if-else +def x = 3 + +if(x==1) { + println "Um" +} else if(x==2) { + println "Dois" +} else { + println "X é maior que Dois" +} + +//Groovy também suporta o operador ternário +def y = 10 +def x = (y > 1) ? "functionou" : "falhou" +assert x == "functionou" + +//Loop 'for' +//Itera sobre um intervalo (range) +def x = 0 +for (i in 0 .. 30) { + x += i +} + +//Itera sobre uma lista +x = 0 +for( i in [5,3,2,1] ) { + x += i +} + +//Itera sobre um array +array = (0..20).toArray() +x = 0 +for (i in array) { + x += i +} + +//Itera sobre um mapa +def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +x = 0 +for ( e in map ) { + x += e.value +} + +/* + Operadores + + Sobrecarregamento de Operadores para uma lsita dos operadores comuns que + Grooby suporta: + http://groovy.codehaus.org/Operator+Overloading + + Operadores Groovy úteis +*/ +//Operador de espalhamento: invoca uma ação sobre todos os itens de um +//objeto agregador. +def tecnologias = ['Groovy','Grails','Gradle'] +tecnologias*.toUpperCase() // = to tecnologias.collect { it?.toUpperCase() } + +//Operador de navegação segura: usado para evitar NullPointerException. +def usuario = User.get(1) +def nomeUsuario = usuario?.nomeUsuario + + +/* + Closures + Um closure, em Grooby, é como um "bloco de código" ou um ponteiro para método. + É um pedação de código que é definido e executado em um momento posterior. + + Mais informação em: http://groovy.codehaus.org/Closures+-+Formal+Definition +*/ +//Exemplo: +def clos = { println "Hello World!" } + +println "Executando o closure:" +clos() + +//Passando parêmetros para um closure +def soma = { a, b -> println a+b } +soma(2,4) + +//Closdures por referir-se a variáveis que não estão listadas em sua +//lista de parêmetros. +def x = 5 +def multiplicarPor = { num -> num * x } +println multiplicarPor(10) + +// Se você tiver um closure que tem apenas um argumento, você pode omitir +// o parâmetro na definição do closure +def clos = { print it } +clos( "oi" ) + +/* + Groovy pode memorizar resultados de closures [1][2][3] +*/ +def cl = {a, b -> + sleep(3000) // simula processamento + a + b +} + +mem = cl.memoize() + +def chamaClosure(a, b) { + def inicio = System.currentTimeMillis() + mem(a, b) + println "Os inputs(a = $a, b = $b) - tomam ${System.currentTimeMillis() - inicio} msecs." +} + +chamaClosure(1, 2) +chamaClosure(1, 2) +chamaClosure(2, 3) +chamaClosure(2, 3) +chamaClosure(3, 4) +chamaClosure(3, 4) +chamaClosure(1, 2) +chamaClosure(2, 3) +chamaClosure(3, 4) + +/* + Expando + + A classe Expando é um bean dinâmico que permite adicionar propriedade e + closures como métodos a uma instância desta classe + + http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html +*/ + def usuario = new Expando(nome:"Roberto") + assert 'Roberto' == nome.name + + nome.lastName = 'Pérez' + assert 'Pérez' == nome.lastName + + nome.showInfo = { out -> + out << "Name: $name" + out << ", Last name: $lastName" + } + + def sw = new StringWriter() + println nome.showInfo(sw) + + +/* + Metaprogramação (MOP) +*/ + +//Usando a ExpandoMetaClasse para adicionar comportamento +String.metaClass.testAdd = { + println "adicionamos isto" +} + +String x = "teste" +x?.testAdd() + +//Interceptando chamadas a métodos +class Test implements GroovyInterceptable { + def soma(Integer x, Integer y) { x + y } + + def invocaMetodo(String name, args) { + System.out.println "Invoca método $name com argumentos: $args" + } +} + +def teste = new Test() +teste?.soma(2,3) +teste?.multiplica(2,3) + +//Groovy suporta propertyMissing para lidar com tentativas de resolução de +//propriedades. +class Foo { + def propertyMissing(String nome) { nome } +} +def f = new Foo() + +assertEquals "boo", f.boo + +/* + TypeChecked e CompileStatic + Groovy, por natureza, é e sempre será uma linguagem dinâmica, mas ela também + suporta typecheked e compilestatic + + Mais informações: http://www.infoq.com/articles/new-groovy-20 +*/ +//TypeChecked +import groovy.transform.TypeChecked + +void testeMethod() {} + +@TypeChecked +void test() { + testeMethod() + + def nome = "Roberto" + + println noomee + +} + +//Outro exemplo: +import groovy.transform.TypeChecked + +@TypeChecked +Integer test() { + Integer num = "1" + + Integer[] numeros = [1,2,3,4] + + Date dia = numeros[1] + + return "Teste" + +} + +//Exemplo de CompileStatic : +import groovy.transform.CompileStatic + +@CompileStatic +int soma(int x, int y) { + x + y +} + +assert soma(2,5) == 7 + + +``` + +## Referências + +[Groovy documentation](http://groovy.codehaus.org/Documentation) + +[Groovy web console](http://groovyconsole.appspot.com/) + +Junte-se a um [grupo de usuários Groovy](http://groovy.codehaus.org/User+Groups) + +## Livro + +* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) + +* [Groovy in Action] (http://manning.com/koenig2/) + +* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) + +[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ +[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize +[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html + + + -- cgit v1.2.3 From 9a2123c6757bd11f8723437032e823656987a011 Mon Sep 17 00:00:00 2001 From: Aleksey Pirogov Date: Sun, 19 Oct 2014 09:23:10 +0400 Subject: edits of ru-ru/markdown-ru --- ru-ru/markdown-ru.html.markdown | 68 +++++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 30 deletions(-) diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown index 8b2a0982..eb8e4881 100644 --- a/ru-ru/markdown-ru.html.markdown +++ b/ru-ru/markdown-ru.html.markdown @@ -7,27 +7,32 @@ filename: markdown-ru.md lang: ru-ru --- -Язык разметки Markdown создан Джоном Грубером (англ. John Gruber) и Аароном Шварцем (англ. Aaron H. Swartz) в 2004 году. Авторы задавались целью создать максимально удобочитаемый и удобный в публикации облегчённый язык разметки, пригодный для последующего преобразования в HTML (а также и в другие форматы). +Язык разметки Markdown создан Джоном Грубером (англ. John Gruber) +и Аароном Шварцем (англ. Aaron H. Swartz) в 2004 году. +Авторы задавались целью создать максимально удобочитаемый +и удобный в публикации облегчённый язык разметки, +пригодный для последующего преобразования в HTML +(а также и в другие форматы). ```markdown +текст, который должен стать заголовком, предваряется +соответствующим количеством символов "#": --> # Это заголовок h1 ## Это заголовок h2 ### Это заголовок h3 @@ -47,7 +52,7 @@ HTML-элементов --> *Этот текст будет выведен курсивом.* -_Также как этот._ +_Так же, как этот._ **А этот текст будет полужирным.** __И этот тоже.__ @@ -56,15 +61,15 @@ __И этот тоже.__ **_И тут!_** *__И даже здесь!__* - ~~Зачёркнутый текст.~~ - + -Это параграф. Всё предельно просто. +Это абзац. Всё предельно просто. А тут уже параграф №2. Эта строка всё ещё относится к параграфу №2! @@ -72,7 +77,7 @@ __И этот тоже.__ О, а вот это уже параграф №3! - + Принудительный
перенос! @@ -90,24 +95,24 @@ __И этот тоже.__ * Список, * Размеченный -* "Звёздочками" +* Звёздочками либо + Список, + Размеченный -+ "Плюсами" ++ Плюсами либо - Список, - Размеченный -- "Дефисами" +- Дефисами @@ -155,7 +160,7 @@ __И этот тоже.__ -\`\`\`ruby +\`\`\`ruby def foobar puts "Hello world!" end @@ -174,9 +179,10 @@ end **************** - + [Ссылка!](http://test.com/) @@ -193,15 +199,16 @@ end [Здесь][link1] высможете узнать больше! А можно кликнуть [сюда][foobar], если очень хочется. - + [link1]: http://test.com/ "Круто!" [foobar]: http://foobar.biz/ "Тоже хорошо!" + а также в круглые скобки. +- Сноска может находиться в любом месте документа и может иметь +идентификатор (далее ID) произвольной длины, +лишь бы это ID был уникальным. --> @@ -227,20 +234,21 @@ end [myimage]: relative/urls/cool/image.jpg "подсказка" - + Ссылка вида эквивалентна [http://testwebsite.com/](http://testwebsite.com/) - + - +Такой символ должен быть "экранирован" с помощью обратной косой черты +(символа "\"): --> \*текст, заключённый в звёздочки!\* @@ -249,7 +257,7 @@ end да и синтаксис имеют не слишком удобный. Но если очень нужно, размечайте таблицы так: --> -| Колонка 1 | Колонка 2 | Колонка 3 | +| Столбец 1 | Столбец 2 | Столбец 3 | | :----------- | :----------: | -----------: | | Выравнивание | Выравнивание | Выравнивание | | влево | по центру | вправо | -- cgit v1.2.3 From a7b885816d08372d33e0eece7c8e0834c699e7a6 Mon Sep 17 00:00:00 2001 From: hobozo Date: Tue, 21 Oct 2014 15:30:30 -0700 Subject: Update haskell.html.markdown Corrected terminology: currying -> partial application --- haskell.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index ad12de2a..2785405c 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -171,8 +171,8 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15 -- 4. More functions ---------------------------------------------------- --- currying: if you don't pass in all the arguments to a function, --- it gets "curried". That means it returns a function that takes the +-- partial application: if you don't pass in all the arguments to a function, +-- it gets "partially applied". That means it returns a function that takes the -- rest of the arguments. add a b = a + b -- cgit v1.2.3 From 2ae89e20bc4c61052f122e572e42d48830d4d075 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 24 Oct 2014 00:48:59 -0400 Subject: Add Python3 simplified Chinese version. --- zh-cn/python3-cn.html.markdown | 648 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 648 insertions(+) create mode 100644 zh-cn/python3-cn.html.markdown diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown new file mode 100644 index 00000000..dc09de4f --- /dev/null +++ b/zh-cn/python3-cn.html.markdown @@ -0,0 +1,648 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Geoff Liu", "http://geoffliu.me"] +filename: learnpython3.py +--- + +Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular +languages in existence. I fell in love with Python for its syntactic clarity. It's basically +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 + +```python + +# 用井字符开头的是单行注释 + +""" 多行字符串用三个引号 + 包裹,也常被用来做多 + 行注释 +""" + +#################################################### +## 1. 原始数据类型和运算符 +#################################################### + +# 整数 +3 # => 3 + +# 算术没有什么出乎意料的 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# 但是除法例外,会自动转换成浮点数 +35 / 5 # => 7.0 +5 / 3 # => 1.6666666666666667 + +# 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 + +# 浮点数的运算结果也是浮点数 +3 * 2.0 # => 6.0 + +# Modulo operation +7 % 3 # => 1 + +# x的y次方 +2**4 # => 16 + +# 用括号决定优先级 +(1 + 3) * 2 # => 8 + +# 布尔值 +True +False + +# 用not取非 +not True # => False +not False # => True + +# 逻辑运算符,注意and和or都是小写 +True and False #=> False +False or True #=> True + +# 整数也可以是布尔值 +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# 用==判断相等 +1 == 1 # => True +2 == 1 # => False + +# 用!=判断不等 +1 != 1 # => False +2 != 1 # => True + +# 比较大小 +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# 大小比较可以连起来! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# 字符串用单引双引都可以 +"这是个字符串" +'这也是个字符串' + +# 用加好连接字符串 +"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. 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/) +* [Python Module of the Week](http://pymotw.com/3/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### 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 d7d131f4406ac86c50b563797c4432dc79e244ec Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 24 Oct 2014 01:05:33 -0400 Subject: Fix a typo, plus section headings --- zh-cn/python3-cn.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index dc09de4f..74e997ec 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -51,7 +51,7 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # 浮点数的运算结果也是浮点数 3 * 2.0 # => 6.0 -# Modulo operation +# 模除 7 % 3 # => 1 # x的y次方 @@ -72,7 +72,7 @@ not False # => True True and False #=> False False or True #=> True -# 整数也可以是布尔值 +# 整数也可以当作布尔值 0 and 2 #=> 0 -5 or 0 #=> -5 0 == False #=> True @@ -101,10 +101,10 @@ False or True #=> True "这是个字符串" '这也是个字符串' -# 用加好连接字符串 +# 用加号连接字符串 "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: @@ -139,7 +139,7 @@ bool({}) #=> False #################################################### -## 2. Variables and Collections +## 2. 变量和集合 #################################################### # Python has a print function @@ -300,7 +300,7 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} #################################################### -## 3. Control Flow and Iterables +## 3. 流程控制和迭代器 #################################################### # Let's just make a variable @@ -398,7 +398,7 @@ list(filled_dict.keys()) #=> Returns ["one", "two", "three"] #################################################### -## 4. Functions +## 4. 函数 #################################################### # Use "def" to create new functions @@ -490,7 +490,7 @@ 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. 类 #################################################### @@ -544,7 +544,7 @@ Human.grunt() # => "*grunt*" #################################################### -## 6. Modules +## 6. 模块 #################################################### # You can import modules @@ -575,7 +575,7 @@ dir(math) #################################################### -## 7. Advanced +## 7. 高级用法 #################################################### # Generators help you make lazy code -- cgit v1.2.3 From c917dc75ac25641b86ecd2d14928175c3d1cc684 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 24 Oct 2014 11:24:51 -0400 Subject: Finish most lines in section 1 --- zh-cn/python3-cn.html.markdown | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index 74e997ec..e297a7ce 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -42,9 +42,9 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria 35 / 5 # => 7.0 5 / 3 # => 1.6666666666666667 -# 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.0 // 3.0 # => 1.0 # 浮点数也可以 -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 @@ -107,22 +107,20 @@ False or True #=> True # 字符串可以被当作字符列表 "This is a string"[0] # => 'T' -# .format can be used to format strings, like this: +# 用.format来格式化字符串 "{} 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: +# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法 "%s can be %s the %s way" % ("strings", "interpolated", "old") - -# None is an object +# None是一个对象 None # => None # Don't use the equality "==" symbol to compare objects to None @@ -130,8 +128,8 @@ None # => None "etc" 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,空字符串,空列表,空关联数组都算是False +# 所有其他值都是True bool(0) # => False bool("") # => False bool([]) #=> False -- cgit v1.2.3 From b4e5719ae90dbba989b1f3f5b9018d436d99e25d Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Sat, 25 Oct 2014 01:28:23 +0200 Subject: =?UTF-8?q?D=C3=A9but=20de=20traduction=20Markdown?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fr-fr/markdown.html.markdown | 255 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 fr-fr/markdown.html.markdown diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown new file mode 100644 index 00000000..32806054 --- /dev/null +++ b/fr-fr/markdown.html.markdown @@ -0,0 +1,255 @@ +--- +language: markdown +contributors: + - ["Andrei Curelaru", "http://infinidad.fr/"] +filename: markdown.md +--- + +Markdown a été crée par Jhon Gruber en 2004. Ceci se veut être une syntaxe facile à lire et à écrire, aisément convertible en HTML(et beaucoup d'autres formats aussi à present). + +Donnez moi autant de retours que vous voulez! +Sentez vous libre de forker et envoyer des pull request! + + +```markdown + + + + + + +# Ceci est un

+## Ceci est un

+### Ceci est un

+#### Ceci est un

+##### Ceci est un

+###### Ceci est un
+ + +Ceci est un h1 +============= + +Ceci est un h2 +------------- + + + + +*This text is in italics.* +_And so is this text._ + +**This text is in bold.** +__And so is this text.__ + +***This text is in both.*** +**_As is this!_** +*__And this!__* + + + +~~This text is rendered with strikethrough.~~ + + + +This is a paragraph. I'm typing in a paragraph isn't this fun? + +Now I'm in paragraph 2. +I'm still in paragraph 2 too! + + +I'm in paragraph three! + + + +I end with two spaces (highlight me to see them). + +There's a
above me! + + + +> This is a block quote. You can either +> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. +> It doesn't make a difference so long as they start with a `>`. + +> You can also use more than one level +>> of indentation? +> How neat is that? + + + + +* Item +* Item +* Another item + +or + ++ Item ++ Item ++ One more item + +or + +- Item +- Item +- One last item + + + +1. Item one +2. Item two +3. Item three + + + +1. Item one +1. Item two +1. Item three + + + + +1. Item one +2. Item two +3. Item three + * Sub-item + * Sub-item +4. Item four + + + +Boxes below without the 'x' are unchecked HTML checkboxes. +- [ ] First task to complete. +- [ ] Second task that needs done +This checkbox below will be a checked HTML checkbox. +- [x] This task has been completed + + + + + This is code + So is this + + + + my_array.each do |item| + puts item + end + + + +John didn't even know what the `go_to()` function did! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + +<-- The above text doesn't require indenting, plus Github will use syntax +highlighting of the language you specify after the ``` --> + + + + +*** +--- +- - - +**************** + + + + +[Click me!](http://test.com/) + + + +[Click me!](http://test.com/ "Link to Test.com") + + + +[Go to music](/music/). + + + +[Click this link][link1] for more info about it! +[Also check out this link][foobar] if you want to. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Alright!" + + + + + +[This][] is a link. + +[this]: http://thisisalink.com/ + + + + + + +![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") + + + +![This is the alt-attribute.][myimage] + +[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" + + + + + is equivalent to +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +I want to type *this text surrounded by asterisks* but I don't want it to be +in italics, so I do this: \*this text surrounded by asterisks\*. + + + + +| Col1 | Col2 | Col3 | +| :----------- | :------: | ------------: | +| Left-aligned | Centered | Right-aligned | +| blah | blah | blah | + + + +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ugh this is so ugly | make it | stop + + + +``` + +For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From f7b1bfeb45d3f1a0c3a059740541f856bdcb1606 Mon Sep 17 00:00:00 2001 From: Vinh Nguyen Date: Sat, 25 Oct 2014 09:59:01 +0700 Subject: Fix Vietnamese Git guide typo and update content --- vi-vn/git-vi.html.markdown | 66 ++++++++++++++++++++++++++-------------------- 1 file changed, 38 insertions(+), 28 deletions(-) diff --git a/vi-vn/git-vi.html.markdown b/vi-vn/git-vi.html.markdown index bdb88204..1bcc94a0 100644 --- a/vi-vn/git-vi.html.markdown +++ b/vi-vn/git-vi.html.markdown @@ -2,14 +2,15 @@ category: tool tool: git contributors: - - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Vinh Nguyen", "https://twitter.com/vinhnx"] filename: LearnGit-vi.txt lang: vi-vn --- Git là một hệ quản lý mã nguồn và phiên bản phân tán (distributed version control and source code management system). -Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, and nó hoạt động +Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, và nó hoạt động với các snapshot đó để cung cấp cho bạn với chức năng đến phiên bản và quản lý mã nguồn của bạn. @@ -19,7 +20,7 @@ quản lý mã nguồn của bạn. Version Control là một hệ thống ghi lại những thay đổi ở một tập tin, hay một nhóm các tập tin, theo thời gian. -### Centralized Versioning VS Distributed Versioning +### So sánh giữa Centralized Versioning và Distributed Versioning * Quản lý phiên bản tập trung (Centralized Versioning) tập trung vào việc đồng bộ hóa, theo dõi, và lưu trữ tập tin. * Quản lý phiên bản phân tán (Distributed Versioning) tập trung vào việc chia sẻ các thay đổi. Mỗi sự thay đổi có một mã định dạng (id) duy nhất. @@ -75,7 +76,7 @@ con trỏ này sẽ cập nhật tự động và trỏ đến commit mới nh ### HEAD và head (thành phần của thư mục .git) -HEAD là một con trỏ đến nhánh hiện tại. Một repo chỉ có một HEAD *đang hoạt động*. +HEAD là một con trỏ đến branch hiện tại. Một repo chỉ có một HEAD *đang hoạt động*. head là một con trỏ đến bất kỳ commit nào. Một repo có thể có nhiều head. ### Các Tài Nguyên Mang Tính Khái Niệm @@ -165,29 +166,29 @@ $ git add ./*.java ### branch -Quản lý nhánh. Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này. +Quản lý nhánh (branch). Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này. ```bash -# liệt kê các nhanh đang có và ở remote +# liệt kê các branch đang có và ở remote $ git branch -a -# tạo nhánh mới +# tạo branch mới $ git branch myNewBranch -# xóa một nhánh +# xóa một branch $ git branch -d myBranch -# đặt tên lại một nhánh +# đặt tên lại một branch # git branch -m $ git branch -m myBranchName myNewBranchName -# chỉnh sủa diễn giải của một nhánh +# chỉnh sửa diễn giải của một branch $ git branch myBranchName --edit-description ``` ### checkout -Cập nhật tất cả các file torng tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể. +Cập nhật tất cả các file trong tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể. ```bash # Checkout (chuyển) một repo - mặc định là nhánh master @@ -201,8 +202,8 @@ $ git checkout -b newBranch ### clone Nhân bản, hoặc sao chép, một repo hiện có thành một thư mục mới. Nó cũng thêm -các nhánh có remote-tracking cho mỗi nhánh trong một repo được nhân bản, mà -cho phép bạn push đến một nhánh remote. +các branch có remote-tracking cho mỗi branch trong một repo được nhân bản, mà +cho phép bạn push đến một remote branch. ```bash # Nhân bản learnxinyminutes-docs @@ -211,7 +212,7 @@ $ git clone https://github.com/adambard/learnxinyminutes-docs.git ### commit -Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một lời nhắn (ghi chú) tạo ra bởi người dùng. +Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một ghi chú tạo ra bởi người dùng. ```bash # commit với một ghi chú @@ -279,7 +280,7 @@ $ git log --merges "Trộn" các thay đổi từ commit bên ngoài vào trong nhánh hiện tại. ```bash -# Merge nhánh cụ thể vào nhánh hiện tại. +# Merge branch cụ thể vào branch hiện tại. $ git merge branchName # Luôn khởi tạo một merge commit khi trộn (merge) @@ -304,30 +305,35 @@ $ git mv -f myFile existingFile ### pull -Kéo (tải) về từ một repo và merge nó vào nhánh khác. +Pull về từ một repo và merge nó vào branch khác. ```bash -# Cập nhật repo cục bộ của bạn, bằng cách merge các thay đổi mới +# Cập nhật repo local của bạn, bằng cách merge các thay đổi mới # từ remote "origin" và nhánh "master". # git pull # git pull => hoàn toàn mặc định như => git pull origin master $ git pull origin master -# Merge các thay đổi từ nhánh remote và rebase -# các commit nhánh lên trên thư mục cục bộ, như: "git pull , git rebase " +# Merge các thay đổi từ remote branch và rebase +# các commit trong branch lên trên local repo, như sau: "git pull , git rebase " $ git pull origin master --rebase ``` ### push -Đẩy và trộn (mege) các tay đổi từ một nhánh đế một remote & nhánh. - -```bash -# Push và merge các thay đổi từ repo cục bộ đến một -# remote tên là "origin" và nhánh "master". -# git push -# git push => hoàn toàn defaults to => git push origin master -$ git push origin master +push và merge các thay đổi từ một branch đến một remote & branch. + +```bash +# Push và merge các thay đổi từ một repo local đến một +# remote có tên là "origin" và nhánh "master". +# git push +# git push => mặc định ẩn đến => git push origin master +$ git push origin master + +# Để liên kết đến một branch local với một branch remote, thêm vào cờ -u: +$ git push -u origin master +# Từ lúc này, bất cứ khi nào bạn muốn push từ cùng một nhánh local đó, sử dụng lối tắt: +$ git push ``` ### rebase (thận trọng) @@ -390,4 +396,8 @@ $ 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/) +* [GitGuys](http://www.gitguys.com/) + +* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) + + -- cgit v1.2.3 From e4889157c7e1f0550b0f2b57b46bc7c085a917f4 Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Sat, 25 Oct 2014 14:56:07 +0200 Subject: mi chemin --- fr-fr/markdown.html.markdown | 174 +++++++++++++++++++++---------------------- 1 file changed, 87 insertions(+), 87 deletions(-) diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index 32806054..82c26bb0 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -1,30 +1,27 @@ --- language: markdown contributors: - - ["Andrei Curelaru", "http://infinidad.fr/"] +- ["Andrei Curelaru", "http://www.infinidad.fr"] filename: markdown.md --- -Markdown a été crée par Jhon Gruber en 2004. Ceci se veut être une syntaxe facile à lire et à écrire, aisément convertible en HTML(et beaucoup d'autres formats aussi à present). +Markdown a été crée par Jhon Gruber en 2004. Ceci se veut être d'une syntaxe facile à lire et à écrire, +aisément convertible en HTML(et beaucoup d'autres formats aussi à présent). -Donnez moi autant de retours que vous voulez! -Sentez vous libre de forker et envoyer des pull request! +Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" et envoyer des pull request! ```markdown - - - + + - + # Ceci est un

## Ceci est un

### Ceci est un

@@ -32,122 +29,125 @@ text you want to be in that element by a number of hashes (#) --> ##### Ceci est un

###### Ceci est un
- + Ceci est un h1 ============= Ceci est un h2 ------------- - - - -*This text is in italics.* -_And so is this text._ + + -**This text is in bold.** -__And so is this text.__ +*Ce texte est en italique.* +_Celui-ci aussi._ -***This text is in both.*** -**_As is this!_** -*__And this!__* +**CE texte est en gras.** +__Celui-là aussi.__ - +***Ce texte a les deux styles.*** +**_Pareil ici_** +*__Et là!__* -~~This text is rendered with strikethrough.~~ + - +~~Ce texte est barré avec strikethrough.~~ + -This is a paragraph. I'm typing in a paragraph isn't this fun? +Ceci est un paragraphe. J'écris dans un paragraphe, marrant non? -Now I'm in paragraph 2. -I'm still in paragraph 2 too! +Maintenant je suis dans le paragraphe 2. +Je suis toujours dans le paragraphe 2 ici aussi! -I'm in paragraph three! +Puis là, eh oui, le paragraphe3! + -I end with two spaces (highlight me to see them). +J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). -There's a
above me! +Bigre, il y a un
au dessus de moi! - + -> This is a block quote. You can either -> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. -> It doesn't make a difference so long as they start with a `>`. +> Ceci est une superbe citation. Vous pouvez même +> revenir à la ligne quand ça vous chante, et placer un `>` devant chaque bout de ligne faisant partie +> de la citation. +> La taille ne compte pas^^ tant que chaque ligne commence par un `>`. -> You can also use more than one level ->> of indentation? -> How neat is that? +> Vous pouvez aussi utiliser plus d'un niveau +>> d'imbrication! +> Class et facile, pas vrai? - - + + * Item * Item -* Another item +* Un autre item or + Item + Item -+ One more item ++ Encore un item -or +or - Item - Item -- One last item +- Un dernier item - + -1. Item one -2. Item two -3. Item three +1. Item un +2. Item deux +3. Item trois - + -1. Item one -1. Item two -1. Item three - +1. Item un +1. Item deux +1. Item trois + - + -1. Item one -2. Item two -3. Item three - * Sub-item - * Sub-item -4. Item four +1. Item un +2. Item deux +3. Item trois +* Sub-item +* Sub-item +4. Item quatre - + -Boxes below without the 'x' are unchecked HTML checkboxes. -- [ ] First task to complete. -- [ ] Second task that needs done -This checkbox below will be a checked HTML checkbox. -- [x] This task has been completed +Les [ ] ci dessous, n'ayant pas de [ x ], deviendront des cases à cocher HTML non-cochées. +- [ ] Première tache à réaliser. +- [ ] Une autre chose à faire. +La case suivante sera une case à cocher HTML cochée. +- [x] Ca ... c'est fait! - - + + - This is code - So is this +This is code +So is this - my_array.each do |item| - puts item - end +my_array.each do |item| +puts item +end @@ -157,7 +157,7 @@ John didn't even know what the `go_to()` function did! \`\`\`ruby def foobar - puts "Hello world!" +puts "Hello world!" end \`\`\` @@ -170,7 +170,7 @@ with or without spaces. --> *** --- -- - - +- - - **************** @@ -237,10 +237,10 @@ in italics, so I do this: \*this text surrounded by asterisks\*. -| Col1 | Col2 | Col3 | +| Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Left-aligned | Centered | Right-aligned | -| blah | blah | blah | +| blah | blah | blah | @@ -248,8 +248,8 @@ Col 1 | Col2 | Col3 :-- | :-: | --: Ugh this is so ugly | make it | stop - + ``` -For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). +For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). \ No newline at end of file -- cgit v1.2.3 From 476c3a21c6f38c4497c968f8b8d2a946542da137 Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Sat, 25 Oct 2014 16:43:50 +0200 Subject: =?UTF-8?q?ay=C3=A9=20c'est=20fait?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fr-fr/markdown.html.markdown | 155 ++++++++++++++++++++----------------------- 1 file changed, 72 insertions(+), 83 deletions(-) diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index 82c26bb0..b1b000fa 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -5,23 +5,20 @@ contributors: filename: markdown.md --- -Markdown a été crée par Jhon Gruber en 2004. Ceci se veut être d'une syntaxe facile à lire et à écrire, -aisément convertible en HTML(et beaucoup d'autres formats aussi à présent). +Markdown a été crée par Jhon Gruber en 2004. Ceci se veut être d'une syntaxe facile à lire et à écrire, aisément convertible en HTML (et beaucoup d'autres formats aussi à présent). Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" et envoyer des pull request! ```markdown - - + + + + + - + # Ceci est un

## Ceci est un

### Ceci est un

@@ -42,40 +39,37 @@ Ceci est un h2 *Ce texte est en italique.* _Celui-ci aussi._ -**CE texte est en gras.** +**Ce texte est en gras.** __Celui-là aussi.__ ***Ce texte a les deux styles.*** **_Pareil ici_** *__Et là!__* - + ~~Ce texte est barré avec strikethrough.~~ + +séparées par une ou plusieurs lignes vides. --> -Ceci est un paragraphe. J'écris dans un paragraphe, marrant non? +Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? Maintenant je suis dans le paragraphe 2. Je suis toujours dans le paragraphe 2 ici aussi! -Puis là, eh oui, le paragraphe3! +Puis là, eh oui, le paragraphe 3! - J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). Bigre, il y a un
au dessus de moi! - + > Ceci est une superbe citation. Vous pouvez même > revenir à la ligne quand ça vous chante, et placer un `>` devant chaque bout de ligne faisant partie @@ -87,32 +81,31 @@ Bigre, il y a un
au dessus de moi! > Class et facile, pas vrai? - + * Item * Item * Un autre item -or +ou + Item + Item + Encore un item -or +ou - Item - Item - Un dernier item - + 1. Item un 2. Item deux 3. Item trois - + 1. Item un 1. Item deux @@ -137,119 +130,115 @@ La case suivante sera une case à cocher HTML cochée. - [x] Ca ... c'est fait! - + -This is code -So is this + echo "Ca, c'est du Code!"; + var Ca = "aussi !"; - + -my_array.each do |item| -puts item -end + my_array.each do |item| + puts item + end - + -John didn't even know what the `go_to()` function did! +La fonction `run()` ne vous oblige pas d'aller courir! - + -\`\`\`ruby +\`\`\`ruby def foobar puts "Hello world!" end -\`\`\` +\`\`\` -<-- The above text doesn't require indenting, plus Github will use syntax -highlighting of the language you specify after the ``` --> +<-- Pas besoin d'indentation pour le code juste au dessus, de plus, Github va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> - - + + *** --- - - - **************** - - + + -[Click me!](http://test.com/) +[Clic moi!](http://test.com/) - + -[Click me!](http://test.com/ "Link to Test.com") +[Clic moi!](http://test.com/ "Lien vers Test.com") - + -[Go to music](/music/). +[En avant la musique](/music/). - + -[Click this link][link1] for more info about it! -[Also check out this link][foobar] if you want to. +[Cliquez ici][link1] pour plus d'information! +[Regardez aussi par ici][foobar] si vous voulez. [link1]: http://test.com/ "Cool!" [foobar]: http://foobar.biz/ "Alright!" - + - + -[This][] is a link. +[Ceci][] est un lien. -[this]: http://thisisalink.com/ +[ceci]: http://ceciestunlien.com/ - + - + -![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") +![Ceci est l'attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") - + -![This is the alt-attribute.][myimage] +![Ceci est l'attribut ALT de l'image][monimage] -[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" +[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici." - - + + - is equivalent to + est équivalent à : [http://testwebsite.com/](http://testwebsite.com/) - + - + +Il suffit de précéder les caractères spécifiques à ignorer par des backslash \ -I want to type *this text surrounded by asterisks* but I don't want it to be -in italics, so I do this: \*this text surrounded by asterisks\*. +Pour taper *ce texte* entouré d'astérisques mais pas en italique : Tapez \*ce texte\*. - - + + | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | -| Left-aligned | Centered | Right-aligned | -| blah | blah | blah | +| Alignement Gauche | Centé | Alignement Droite | +| bla | bla | bla | - + Col 1 | Col2 | Col3 :-- | :-: | --: -Ugh this is so ugly | make it | stop +Ough que c'est moche | svp | arrêtez ``` -For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). \ No newline at end of file +Pour plus d'information, consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. \ No newline at end of file -- cgit v1.2.3 From 710e504fbcb4c70abb2f9eb2ac8c6f7cbd879d50 Mon Sep 17 00:00:00 2001 From: Jelle Besseling Date: Sat, 25 Oct 2014 16:19:40 +0200 Subject: Dutch translation of the brainfuck tutorial --- nl-nl/brainfuck-nl.html.markdown | 86 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 nl-nl/brainfuck-nl.html.markdown diff --git a/nl-nl/brainfuck-nl.html.markdown b/nl-nl/brainfuck-nl.html.markdown new file mode 100644 index 00000000..cd12b1d0 --- /dev/null +++ b/nl-nl/brainfuck-nl.html.markdown @@ -0,0 +1,86 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Jelle Besseling", "https://github.com/Jell-E"] +lang: nl-nl +--- + +Brainfuck (schrijf je niet met een hoofdletter behalve aan het begin van een +zin) is een extreem +minimalistische Turing-complete programmeertaal met maar acht commando's. + +``` +Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd. + +Brainfuck wordt gerepresenteerd door een array met 30,000 cellen die initieel +gevuld is met nullen en een pointer die wijst naar de huidige cel. + +Dit zijn de acht commando's: ++ : Verhoog de huidige cell met 1. +- : Verminder de huidige cell met 1. +> : Beweeg de pointer naar de volgende cell (één naar rechts). +< : Beweeg de pointer naar de vorige cell (één naar links). +. : Print de huidige cell als een ASCII karakter(d.w.z. 65 = 'A'). +, : Lees een karakter in de huidige cell. +[ : Als de huidige cell nul is ga dan naar de bijbehorende ] . + Als het geen nul is, ga dan gewoon verder. +] : Als de huidige cell nul is ga dan gewoon verder. + Als het geen nul is, ga dan terug naar de bijbehorende [ . + +[ en ] maken een while loop. Ze moeten uiteraard wel gebalanceerd zijn + +Laten we een kijkje nemen naar een paar brainfuck programma's. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Dit programma print het karakter 'A'. Eerst verhoogt het cell #1 tot 6. +Cell #1 wordt gebruikt om te loopen. Dan begint het de loop ([) en gaat +naar cell #2. Het verhoogt cell #2 tien keer, gaat terug naar cell #1, en +verlaagt cell #1. Deze loop gebeurt zes keer (na zes keer staat cell #1 +weer op nul, waarna het doorgaat naar het einde van de loop (]) en +verder gaat). + +De pointer staat nu weer op cell #1, deze heeft een waarde van 0, en cell #2 +heeft een waarde van 60. > beweegt de pointer naar cell #2, daarna verhoogt +het de cell vijf keer, waardoor het een waarde van 65 bevat, en print dan +de waarde van cell #2. 65 is 'A' in ASCII, dus 'A' wordt geprint in de terminal. + + +, [ > + < - ] > . + +Dit programma leest een karakter van de gebruiker in put en kopieert dat +karakter in cel #1. Dan start de loop. Ga naar cel #2, verhoog de waarde in +cel #2, ga terug naar cel #1, en verklein de waarde in cel #1. Dit gaat door +totdat cel #1 nul is en cel #2 de oude waarde heeft van cell #1. Omdat we +op cel #1 staan verplaatst > de pointer één naar rechts en . print het +karakter in cel #2. + +Houd wel in gedachten dat de spaties alleen zijn voor leesbaarheid, je kan het +bovenstaande programma net zo goed schrijven als: + +,[>+<-]>. + +Probeer maar eens te bedenken wat het volgende programma doet: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Dit programma neemt twee getallen als input, en vermenigvuldigt ze. + +In het begin leest het twee karakters in cel #1 en #2. Dan start het de +buitenste loop, met als teller cel #1. Het beweegt naar cel #2, dan start het +de binnenste loop met als teller cel #2, daar verhoogd het cel #3. Maar +dan is er een probleem als cel #2 nul wordt aan het einde van de binnenste loop. +Om dit op te lossen wordt ook cel #4 verhoogd naar het oorspronkelijke getal +uit cel #2 en daarna wordt cel #4 weer gekopieerd naar cell #2. +Het resultaat komt in cel #3 te staan. +``` + +En dat is dan brainfuck. Niet heel moeilijk, toch? Je kan zelf voor de lol +brainfuck programma's gaan schrijven, of je kan een interpreter schrijven +voor brainfuck in een andere taal. Het is namelijk redelijk makkelijk om te +implementeren aangezien brainfuck maar acht commando's heeft. En als je een +masochist bent kan je ook nog proberen om brainfuck te implementeren… in +brainfuck. -- cgit v1.2.3 From 9ff3a57c07c654a41460d113f7a8535a97d5c642 Mon Sep 17 00:00:00 2001 From: Jelle Besseling Date: Sat, 25 Oct 2014 16:36:27 +0200 Subject: [python/de] Fix typo in url of German translation My text editor apparently also fixed some incorrect trailing spaces and tabs on empty lines --- de-de/python-de.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 5ddb6f4b..b996ccae 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -3,7 +3,7 @@ language: python contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - - ["kultprok", "http:/www.kulturproktologie.de"] + - ["kultprok", "http://www.kulturproktologie.de"] filename: learnpython-de.py lang: de-de --- @@ -17,7 +17,7 @@ Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber au ```python # Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) -""" Mehrzeilige Strings werden mit +""" Mehrzeilige Strings werden mit drei '-Zeichen geschrieben und werden oft als Kommentare genutzt. """ @@ -283,7 +283,7 @@ Ausgabe: for animal in ["hund", "katze", "maus"]: # Wir können Strings mit % formatieren print "%s ist ein Säugetier" % animal - + """ `range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder Ausgabe: @@ -458,7 +458,7 @@ import math as m math.sqrt(16) == m.sqrt(16) #=> True # Module sind in Python nur gewöhnliche Dateien. Wir -# können unsere eigenen schreiben und importieren. Der Name des +# können unsere eigenen schreiben und importieren. Der Name des # Moduls ist der Dateiname. # Wir können auch die Funktionen und Attribute eines @@ -484,4 +484,3 @@ dir(math) * [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 059ef4ebfafb9ae46603599c0619f0e2634c693a Mon Sep 17 00:00:00 2001 From: Jelle Besseling Date: Sat, 25 Oct 2014 16:38:43 +0200 Subject: Revert "[python/de] Fix typo in url of German translation" This reverts commit c44552b25840c742043aa64470f5cc3caaac4a5b. --- de-de/python-de.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index b996ccae..5ddb6f4b 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -3,7 +3,7 @@ language: python contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - - ["kultprok", "http://www.kulturproktologie.de"] + - ["kultprok", "http:/www.kulturproktologie.de"] filename: learnpython-de.py lang: de-de --- @@ -17,7 +17,7 @@ Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber au ```python # Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) -""" Mehrzeilige Strings werden mit +""" Mehrzeilige Strings werden mit drei '-Zeichen geschrieben und werden oft als Kommentare genutzt. """ @@ -283,7 +283,7 @@ Ausgabe: for animal in ["hund", "katze", "maus"]: # Wir können Strings mit % formatieren print "%s ist ein Säugetier" % animal - + """ `range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder Ausgabe: @@ -458,7 +458,7 @@ import math as m math.sqrt(16) == m.sqrt(16) #=> True # Module sind in Python nur gewöhnliche Dateien. Wir -# können unsere eigenen schreiben und importieren. Der Name des +# können unsere eigenen schreiben und importieren. Der Name des # Moduls ist der Dateiname. # Wir können auch die Funktionen und Attribute eines @@ -484,3 +484,4 @@ dir(math) * [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 f7aadaff81b3d0c55c4ea2fbea65774590daa2e6 Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Sat, 25 Oct 2014 16:59:58 +0200 Subject: some fixes on line-length --- fr-fr/markdown.html.markdown | 106 ++++++++++++++++++++++++++++++------------- 1 file changed, 75 insertions(+), 31 deletions(-) diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index b1b000fa..ba6c038d 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -5,20 +5,32 @@ contributors: filename: markdown.md --- -Markdown a été crée par Jhon Gruber en 2004. Ceci se veut être d'une syntaxe facile à lire et à écrire, aisément convertible en HTML (et beaucoup d'autres formats aussi à présent). +Markdown a été crée par Jhon Gruber en 2004. Ceci se veut être d'une syntaxe +facile à lire et à écrire, aisément convertible en HTML, +(et beaucoup d'autres formats aussi à présent). -Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" et envoyer des pull request! +Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" +et envoyer des pull request! ```markdown - + - + - + - + # Ceci est un

## Ceci est un

### Ceci est un

@@ -26,7 +38,10 @@ Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" et e ##### Ceci est un

###### Ceci est un
- + + Ceci est un h1 ============= @@ -46,11 +61,12 @@ __Celui-là aussi.__ **_Pareil ici_** *__Et là!__* - + ~~Ce texte est barré avec strikethrough.~~ - Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? @@ -62,17 +78,21 @@ Je suis toujours dans le paragraphe 2 ici aussi! Puis là, eh oui, le paragraphe 3! J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). Bigre, il y a un
au dessus de moi! - + > Ceci est une superbe citation. Vous pouvez même -> revenir à la ligne quand ça vous chante, et placer un `>` devant chaque bout de ligne faisant partie +> revenir à la ligne quand ça vous chante, et placer un `>` +> devant chaque bout de ligne faisant partie > de la citation. > La taille ne compte pas^^ tant que chaque ligne commence par un `>`. @@ -81,7 +101,8 @@ Bigre, il y a un
au dessus de moi! > Class et facile, pas vrai? - + * Item * Item @@ -105,12 +126,13 @@ ou 2. Item deux 3. Item trois - + 1. Item un 1. Item deux 1. Item trois - + @@ -121,16 +143,20 @@ ou * Sub-item 4. Item quatre - + + +Les [ ] ci dessous, n'ayant pas de [ x ], +deviendront des cases à cocher HTML non-cochées. -Les [ ] ci dessous, n'ayant pas de [ x ], deviendront des cases à cocher HTML non-cochées. - [ ] Première tache à réaliser. - [ ] Une autre chose à faire. La case suivante sera une case à cocher HTML cochée. - [x] Ca ... c'est fait! - + echo "Ca, c'est du Code!"; var Ca = "aussi !"; @@ -146,18 +172,21 @@ fonctionne aussi à l'intérieur du bloc de code --> La fonction `run()` ne vous oblige pas d'aller courir! - + -\`\`\`ruby +\`\`\`ruby + def foobar puts "Hello world!" end \`\`\` -<-- Pas besoin d'indentation pour le code juste au dessus, de plus, Github va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> +<-- Pas besoin d'indentation pour le code juste au dessus, de plus, Github +va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> - *** @@ -166,12 +195,16 @@ avec ou sans espaces entre chaque un. --> **************** - [Clic moi!](http://test.com/) - + [Clic moi!](http://test.com/ "Lien vers Test.com") @@ -187,9 +220,13 @@ avec ou sans espaces entre chaque un. --> [link1]: http://test.com/ "Cool!" [foobar]: http://foobar.biz/ "Alright!" - + - + [Ceci][] est un lien. @@ -198,9 +235,10 @@ avec ou sans espaces entre chaque un. --> - + -![Ceci est l'attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") +![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") @@ -221,10 +259,14 @@ avec ou sans espaces entre chaque un. --> Il suffit de précéder les caractères spécifiques à ignorer par des backslash \ -Pour taper *ce texte* entouré d'astérisques mais pas en italique : Tapez \*ce texte\*. +Pour taper *ce texte* entouré d'astérisques mais pas en italique : +Tapez \*ce texte\*. - + | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | @@ -241,4 +283,6 @@ Ough que c'est moche | svp | arrêtez ``` -Pour plus d'information, consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. \ No newline at end of file +Pour plus d'information : + consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, + et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. \ No newline at end of file -- cgit v1.2.3 From 9bfb86a75df37132f915d964990d25862d9ded7d Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Sat, 25 Oct 2014 19:47:24 +0200 Subject: typographic and other fixes --- fr-fr/markdown.html.markdown | 43 +++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index ba6c038d..edd3f025 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -5,9 +5,9 @@ contributors: filename: markdown.md --- -Markdown a été crée par Jhon Gruber en 2004. Ceci se veut être d'une syntaxe -facile à lire et à écrire, aisément convertible en HTML, -(et beaucoup d'autres formats aussi à présent). +Markdown a été créé par Jhon Gruber en 2004. Il se veut être d'une syntaxe +facile à lire et à écrire, aisément convertible en HTML + (et beaucoup d'autres formats aussi à présent). Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" et envoyer des pull request! @@ -18,18 +18,18 @@ et envoyer des pull request! est un document Markdown valide. Autrement dit, vous pouvez utiliser des balises HTML dans un fichier Markdown, comme la balise commentaire dans laquelle nous sommes à présent, car celle-ci ne sera pas affectée par -le parser(analyseur syntaxique) Markdown. --> +le parser( analyseur syntaxique ) Markdown. --> - + - + # Ceci est un

## Ceci est un

@@ -61,8 +61,8 @@ __Celui-là aussi.__ **_Pareil ici_** *__Et là!__* - + ~~Ce texte est barré avec strikethrough.~~ @@ -72,7 +72,7 @@ séparées par une ou plusieurs lignes vides. --> Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? Maintenant je suis dans le paragraphe 2. -Je suis toujours dans le paragraphe 2 ici aussi! +Je suis toujours dans le paragraphe 2! Puis là, eh oui, le paragraphe 3! @@ -87,18 +87,17 @@ J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). Bigre, il y a un
au dessus de moi! - + > Ceci est une superbe citation. Vous pouvez même -> revenir à la ligne quand ça vous chante, et placer un `>` +> revenir à la ligne quand ça vous chante, et placer un `>` > devant chaque bout de ligne faisant partie > de la citation. > La taille ne compte pas^^ tant que chaque ligne commence par un `>`. > Vous pouvez aussi utiliser plus d'un niveau >> d'imbrication! -> Class et facile, pas vrai? +> Classe et facile, pas vrai? +les bons chiffres. Ceci dit, cette variante perd en clarté.--> 1. Item un 1. Item deux 1. Item trois - + @@ -152,16 +151,16 @@ deviendront des cases à cocher HTML non-cochées. - [ ] Première tache à réaliser. - [ ] Une autre chose à faire. La case suivante sera une case à cocher HTML cochée. -- [x] Ca ... c'est fait! +- [x] Ça ... c'est fait! - echo "Ca, c'est du Code!"; - var Ca = "aussi !"; + echo "Ça, c'est du Code!"; + var Ça = "aussi !"; - my_array.each do |item| @@ -170,7 +169,7 @@ fonctionne aussi à l'intérieur du bloc de code --> -La fonction `run()` ne vous oblige pas d'aller courir! +La fonction `run()` ne vous oblige pas à aller courir! -- cgit v1.2.3 From 10fad1328574fdadef79b3e960dc759cebea8770 Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Sat, 25 Oct 2014 19:51:39 +0200 Subject: Good bye Asterix --- fr-fr/markdown.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index edd3f025..fa10e62f 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -100,8 +100,8 @@ Bigre, il y a un
au dessus de moi! > Classe et facile, pas vrai? - + * Item * Item -- cgit v1.2.3 From b4edd938235f139dcacd555121a1f755f55482f3 Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Sat, 25 Oct 2014 22:36:40 +0200 Subject: other fixes --- fr-fr/markdown.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index fa10e62f..e3ac5a92 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -175,11 +175,12 @@ La fonction `run()` ne vous oblige pas à aller courir! des syntaxes spécifiques --> \`\`\`ruby - + def foobar puts "Hello world!" end -\`\`\` +\`\`\` <-- Pas besoin d'indentation pour le code juste au dessus, de plus, Github va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> -- cgit v1.2.3 From 928fdd34b03a3e5ef5f30327a3072c242c549fd7 Mon Sep 17 00:00:00 2001 From: Baptiste Fontaine Date: Sun, 26 Oct 2014 12:57:49 +0100 Subject: [markdown/en] Fixed typo in language author MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It’s “John Gruber”, not “Jhon Gruber”. --- fr-fr/markdown.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index e3ac5a92..50e507cd 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -5,7 +5,7 @@ contributors: filename: markdown.md --- -Markdown a été créé par Jhon Gruber en 2004. Il se veut être d'une syntaxe +Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe facile à lire et à écrire, aisément convertible en HTML (et beaucoup d'autres formats aussi à présent). @@ -285,4 +285,4 @@ Ough que c'est moche | svp | arrêtez Pour plus d'information : consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, - et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. \ No newline at end of file + et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. -- cgit v1.2.3 From ff43d607bd22a7125658e28eb623e537a96b52a5 Mon Sep 17 00:00:00 2001 From: Baptiste Fontaine Date: Sun, 26 Oct 2014 13:44:38 +0100 Subject: Bash French translation added --- fr-fr/bash-fr.html.markdown | 228 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 fr-fr/bash-fr.html.markdown diff --git a/fr-fr/bash-fr.html.markdown b/fr-fr/bash-fr.html.markdown new file mode 100644 index 00000000..d4685124 --- /dev/null +++ b/fr-fr/bash-fr.html.markdown @@ -0,0 +1,228 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Baptiste Fontaine", "http://bfontaine.net"] +filename: LearnBash-fr.sh +lang: fr-fr +--- + +Bash est le nom du shell UNIX, qui était aussi distribué avec le système +d’exploitation GNU et est le shell par défaut sur Linux et Mac OS X. + +Presque tous les exemples ci-dessous peuvent être écrits dans un script shell +ou exécutés directement dans le terminal. + +[Plus d’informations ici.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# La première ligne du script s’appelle le « shebang, » qui indique au système +# comment exécuter le script : http://fr.wikipedia.org/wiki/Shebang +# Comme vous pouvez le remarquer, les commentaires commencent par #. Le shebang +# est aussi un commentaire + +# Un exemple simple qui affiche « Hello world! » : +echo Hello world! + +# Chaque commande commence sur une nouvelle ligne ou après un point-virgule : +echo 'Ceci est la première ligne'; echo 'Ceci est la seconde ligne' + +# La déclaration d’une variable ressemble à ça : +VARIABLE="Du texte" + +# Mais pas comme ça : +VARIABLE = "Du texte" +# Bash va penser que VARIABLE est une commande qu’il doit exécuter et va +# afficher une erreur parce qu’elle est introuvable. + +# Utiliser la variable : +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' +# Quand vous utilisez la variable en elle-même – en lui assignant une valeur, +# en l’exportant ou autre – vous écrivez son nom sans $. Si vous voulez +# utiliser sa valeur, vous devez utiliser $. +# Notez que ' (guillemet droit simple) empêche l’expansion des variables ! + +# Substitution de chaîne de caractères dans les variables +echo ${VARIABLE/Some/A} +# Ceci va remplacer la première occurrence de « Some » par « A » + +# Sous-chaîne d’une variable +echo ${VARIABLE:0:7} +# Ceci va retourner seulement les 7 premiers caractères de la valeur + +# Valeur par défaut d’une variable +echo ${FOO:-"ValeurParDefautSiFOOestVideOuInexistant"} +# Ceci marche pour null (FOO=), la chaîne de caractères vide (FOO=""). Zéro +# (FOO=0) retourne 0 + +# Variables pré-remplies : +# Il y a quelques variables pré-remplies utiles, comme : +echo "La valeur de retour du dernier programme : $?" +echo "Le PID du script : $$" +echo "Nombre d’arguments : $#" +echo "Arguments du script : $@" +echo "Arguments du script séparés en plusieurs variables : $1 $2..." + +# Lire une valeur depuis l’entrée standard : +echo "Quel est votre nom ?" +read NAME # Notez que l’on a pas eu à déclarer une nouvelle variable +echo Bonjour, $NAME! + +# Nous avons l’habituelle structure « if » : +# Utilisez 'man test' pour plus d’informations à propos des conditions +if [ $NAME -ne $USER ] +then + echo "Votre nom n’est pas votre pseudo" +else + echo "Votre nom est votre pseudo" +fi + +# Il y a aussi l’exécution conditionnelle +echo "Toujours exécuté" || echo "Exécuté si la première commande ne réussit pas" +echo "Toujours exécuté" && echo "Exécuté si la première commande réussit" + +# Pour utiliser && et || avec des commandes « if, » vous devez utiliser +# plusieurs paires de crochets : +if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] +then + echo "Ceci sera exécuté si $NAME est Steve ET $AGE est 15." +fi + +if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] +then + echo "Ceci sera exécuté si $NAME est Daniya OU Zach." +fi + +# Les expressions sont écrites dans le format suivant : +echo $(( 10 + 5 )) + +# Contrairement aux autres langages de programmation, Bash est un shell — il +# est donc exécuté dans le contexte du répertoire courant. Vous pouvez lister +# les fichiers et dossiers dans le répertoire courant avec la commande `ls` : +ls + +# Ces commandes ont des options qui contrôlent leur exécution : +ls -l # Liste tous les fichiers et répertoires sur des lignes séparées + +# Les résultat de la commande précédente peuvent être passés à la commande +# suivante en entrée. +# La commande grep filtre l’entrée avec les motifs donnés. On peut ainsi lister +# les fichiers .txt dans le répertoire courant : +ls -l | grep "\.txt" + +# Vous pouvez aussi rediriger l’entrée et les sorties standards et d’erreur +# d’une commande : +python2 hello.py < "entrée.in" +python2 hello.py > "sortie.out" +python2 hello.py 2> "erreur.err" +# Ceci va écraser le fichier s'il existe; si vous préférez écrire à la fin de +celui-ci, utilisez >> à la place. + +# Les commandes peuvent se substituer à l’intérieur d’autres commandes en +# utilisant $( ) : +# La commande ci-dessous affiche le nombre de fichiers et répertoires dans le +# répertoire courant : +echo "Il y a $(ls | wc -l) choses ici." + +# On peut faire la même chose avec les accents graves `` mais on ne peut pas +# les imbriquer — la façon la plus courante est d’utiliser $( ). +echo "There are `ls | wc -l` items here." + +# Bash a une commande case qui marche de façon similaire au switch de Java et +# C++ : +case "$VARIABLE" in + #List patterns for the conditions you want to meet + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# La boucle for itère autant de fois qu’elle a d’arguments : +# Le contenu de $VARIABLE est affiché trois fois. +for VARIABLE in {1..3} +do + echo "$VARIABLE" +done + +# Ou écrivez-la de façon « traditionnelle » : +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Elles peuvent aussi être utilisées pour agir sur des fichiers : +# Cette boucle va exécuter la commande 'cat' sur fichier1 et fichier2 +for VARIABLE in fichier1 fichier2 +do + cat "$VARIABLE" +done + +# …ou la sortie d’une commande : +# Ceci va afficher la sortie de ls. +for OUTPUT in $(ls) +do + cat "$OUTPUT" +done + +# Boucle while : +while [ true ] +do + echo "corps de la boucle ..." + break +done + +# Vous pouvez aussi définir des fonctions +# Définition : +function foo () +{ + echo "Les arguments fonctionnent comme les arguments de script : $@" + echo "Et : $1 $2..." + echo "Ceci est une fonction" + return 0 +} + +# Ou plus simplement : +bar () +{ + echo "Une autre façon de définir des fonctions !" + return 0 +} + +# Appeler votre fonction +foo "Mon nom est" $NAME + +# Il y a plein de commandes utiles que vous devriez apprendre : +# affiche les 10 dernières lignes de fichier.txt +tail -n 10 fichier.txt +# affiche les 10 premières lignes de fichier.txt +head -n 10 fichier.txt +# trie les lignes de fichier.txt +sort fichier.txt +# montre ou omet les lignes répétées, avec -d pour les montrer +uniq -d fichier.txt +# affiche uniquement la première colonne avant le caractère « , » +cut -d ',' -f 1 fichier.txt +# remplace chaque occurrence de 'okay' par 'super' dans fichier.txt +# (compatible avec les expression rationnelles) +sed -i 's/okay/super/g' fichier.txt +# affiche toutes les lignes de fichier.txt qui correspondent à une expression +# rationnelle, dans cet exemple les lignes qui commencent par « foo » et +# finissent par « bar » +grep "^foo.*bar$" fichier.txt +# ajoutez l’option « -c » pour afficher le nombre de lignes concernées +grep -c "^foo.*bar$" fichier.txt +# Si vous voulez vraiment chercher une chaîne de caractères, et non +# l’expression rationnelle, utilisez fgrep (ou grep -F) +fgrep "^foo.*bar$" fichier.txt +``` -- cgit v1.2.3 From c7e8b6f06bdb11e611277b24d140542794d4a201 Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Sun, 26 Oct 2014 17:07:25 +0100 Subject: Added yaml-fr --- fr-fr/yaml-fr.html.markdown | 156 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 fr-fr/yaml-fr.html.markdown diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown new file mode 100644 index 00000000..6bdcb6e8 --- /dev/null +++ b/fr-fr/yaml-fr.html.markdown @@ -0,0 +1,156 @@ +--- +language: yaml +filename: learnyaml.yaml +contributors: + - ["Andrei Curelaru", "http://www.infinidad.fr"] +--- + +Proposé à l'origine par Clark Evans en Mai 2001, YAML est un un format de +représentation de données par sérialisation, conçu pour être aisément +éditable et lisible par nous même, les humains. + +YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont il est un parent naturel. Toutefois, YAML emprunte également des idées et concepts de chez Python, et s'intègre bien avec bon nombre de langages. + + +```yaml +# les Commentaires sont précédés d'un signe "#", comme cette ligne. + +############# +# SCALAIRES # +############# + +# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections +# ( listes ou tableaux associatifs ). + +# Notre objet root ( racine ), sera une map ( carte ) et englobera +# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire, +# hash ou objet dans d'autres langages. +clé: valeur +aurtre_clé: une autre valeur +valeur_numérique: 100 +notation_scientifique: 1e+12 +boolean: true +valeur_null: null +clé avec espaces: valeur +# Bien qu'il ne soit pas nécessaire d'enfermer les chaînes de caractères +# entre guillemets, cela reste possible, et parfois utile. +toutefois: "Une chaîne, peut être contenue entre guillemets." +"Une clé entre guillemets.": "Utile si on veut utiliser ':' dans la clé." + +# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix, +# comme un 'bloc littéral' ( avec | ) ou bien 'bloc replié' avec ( > ). +bloc_littéral: | + Tout ce bloc de texte sera la valeur de la clé 'bloc_littéral', + avec préservation des retours à la ligne. ( chaque ligne vide à + l'intérieur du même bloc, sera remplacée par "\n\n" ) + + Le littéral continue jusqu'à ce que l'indentation soit annulée. + + Toutes lignes qui serait "d'avantage indentées" conservent leur indentation, constituée de 4 espaces. +bloc_replié: > + Tout ce bloc de texte sera la valeur de la clé 'bloc_replié', mais + cette fois ci, toutes les nouvelles lignes deviendront un simple espace. + + Les lignes vides, comme ci-dessus, seront converties en caractère "\n". + + Les lignes 'plus-indentées' gardent leurs retours à la ligne - + ce texte apparaîtra sur deux lignes. + +############### +# COLLECTIONS # +############### + +# l'Imbrication est créée par indentation. +une_map_imbriquée: + clé: valeur + autre_clé: autre valeur + autre_map_imbriquée: + bonjour: bonjour + +# les Clés des Maps ne sont pas nécessairement des chaînes de caractères. +0.25: une clé de type float + +# les Clés peuvent également être des objets s'étendant sur plusieurs lignes, +# en utilisant le signe "?" pour indiquer le début de la clé. +? | + ceci est une Clé + sur de multiples lignes +: et ceci est sa Valeur + +# YAML autorise aussi l'usage des collections à l'intérieur des clés, +# mais certains langages de programmation ne le tolère pas si bien. + +# les Séquences ( équivalent des listes ou tableaux ) ressemblent à cela: +une_séquence: + - Item 1 + - Item 2 + - 0.5 # les séquences peuvent contenir des types variés. + - Item 4 + - clé: valeur + autre_clé: autre_valeur + - + - Ceci est une séquence + - dans une autre séquence + +# YAML étant un proche parent de JSON, vous pouvez écrire directement +# des maps et séquences façon JSON +json_map: {"clé": "valeur"} +json_seq: [1, 2, 3, "soleil"] + +################################# +# AUTRES FONCTIONNALITEES YAML # +################################# + +# YAML possède une fonctionnalité fort utile nommée 'ancres'. Celle-ci +# vous permet de dupliquer aisément du contenu au sein de votre document. + +# Les deux clés suivantes auront la même valeur: +contenu_ancré: &nom_ancre Cette chaîne sera la valeur des deux clés. +autre_ancre: *nom_ancre + +# Avec les Tags YAML, vous pouvez explicitement déclarer des types de données. +chaine_explicite: !!str 0.5 + +# Certains parsers implémentent des tags spécifiques à d'autres langages, +# comme par exemple le "complex number" de Python. +python_complex_number: !!python/complex 1+2j + +##################### +# AUTRES TYPES YAML # +##################### + +# YAML comprends aussi les données formatées ISO de type date et datetime, +# pas seulement les chaînes et nombres. +datetime: 2001-12-15T02:59:43.1Z +datetime_avec_espaces: 2001-12-14 21:59:43.10 -5 +date: 2002-12-14 + +# Le tag !!binary indique que la chaîne à suivre est la représentation binaire +# d'un blob encodé en base64. En clair ? Une image! +fichier_gif: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML a de même un type "set", qui ressemble à cela: +set: + ? item1 + ? item2 + ? item3 + +# Comme dans Python, les sets ne sont que des maps contenant des valeurs null; +# le set précédent est l'équivalent du suivant: +set2: + item1: null + item2: null + item3: null + +``` + + \//||\/|| + // || ||__ Références Externes et outils : + +[Specs YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais* +[Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) +[Online YAML parser](http://yaml-online-parser.appspot.com/) -- cgit v1.2.3 From ef30c1918c9d1b208c0f2206d40d8cd3ca075ef3 Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Sun, 26 Oct 2014 17:16:25 +0100 Subject: first fixes --- fr-fr/yaml-fr.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown index 6bdcb6e8..7f962f61 100644 --- a/fr-fr/yaml-fr.html.markdown +++ b/fr-fr/yaml-fr.html.markdown @@ -46,7 +46,8 @@ bloc_littéral: | Le littéral continue jusqu'à ce que l'indentation soit annulée. - Toutes lignes qui serait "d'avantage indentées" conservent leur indentation, constituée de 4 espaces. + Toutes lignes qui serait "d'avantage indentées" conservent leur + indentation, constituée de 4 espaces. bloc_replié: > Tout ce bloc de texte sera la valeur de la clé 'bloc_replié', mais cette fois ci, toutes les nouvelles lignes deviendront un simple espace. @@ -148,9 +149,8 @@ set2: ``` - \//||\/|| - // || ||__ Références Externes et outils : +Quelques références et outils : -[Specs YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais* -[Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) -[Online YAML parser](http://yaml-online-parser.appspot.com/) +- Doc officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*, +- Une [Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) très bien construite et claire, +- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples. \ No newline at end of file -- cgit v1.2.3 From 78bea60c369ff2a02b28024a29409938cfdff686 Mon Sep 17 00:00:00 2001 From: Baptiste Fontaine Date: Sun, 26 Oct 2014 21:33:31 +0100 Subject: [bash/fr] translators section added --- fr-fr/bash-fr.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/fr-fr/bash-fr.html.markdown b/fr-fr/bash-fr.html.markdown index d4685124..4678237d 100644 --- a/fr-fr/bash-fr.html.markdown +++ b/fr-fr/bash-fr.html.markdown @@ -10,6 +10,7 @@ contributors: - ["Anton Strömkvist", "http://lutic.org/"] - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gregrory Kielian", "https://github.com/gskielian"] +translators: - ["Baptiste Fontaine", "http://bfontaine.net"] filename: LearnBash-fr.sh lang: fr-fr -- cgit v1.2.3 From 9f2d4d80277bd8d420f002b4214fcd48cadad49e Mon Sep 17 00:00:00 2001 From: Baptiste Fontaine Date: Sun, 26 Oct 2014 13:58:11 +0100 Subject: Brainfuck French translation added --- fr-fr/brainfuck-fr.html.markdown | 87 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 fr-fr/brainfuck-fr.html.markdown diff --git a/fr-fr/brainfuck-fr.html.markdown b/fr-fr/brainfuck-fr.html.markdown new file mode 100644 index 00000000..4b8e918f --- /dev/null +++ b/fr-fr/brainfuck-fr.html.markdown @@ -0,0 +1,87 @@ +--- +language: brainfuck +filename: learnbrainfuck-fr.bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Baptiste Fontaine", "http://bfontaine.net"] +lang: fr-fr +--- + +Brainfuck (sans majuscule à part au début d’une phrase) est un langage +Turing-complet extrêmement simple avec seulement 8 commandes. + +``` +Tout caractère en dehors de "><+-.,[]" (en dehors des guillements) est ignoré. + +Brainfuck est représenté par un tableau de 30 000 cellules initialisées à 0 et +un pointeur de données pointant sur la cellule courante. + +Il y a huit commandes : ++ : Incrémente la valeur de la cellule courante de un. +- : Décrémente la valeur de la cellule courante de un. +> : Déplace le pointeur de données sur la cellule suivante (à droite). +< : Déplace le pointeur de données sur la cellule précédente (à gauche). +. : Affiche la valeur ASCII de la cellule courante (par ex. 65 = 'A'). +, : Lit un caractère et le place dans la cellule courante. +[ : Si la valeur dans la cellule courante vaut 0, saute au ] correspondant. + Sinon, continue avec la commande suivante. +] : Si la valeur dans la cellule courante vaut 0, continue avec la commande + suivante. Sinon, retourne au [ correspondant. + +[ et ] forment une boucle « tant que » (« while »). Ils doivent évidemment +aller par paires. + +Regardons quelques programmes simples en brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Ce programme affiche la lettre 'A'. Il commence par incrémenter la première +cellule à 6. Il entre ensuite dans une boucle et se déplace sur la seconde +cellule. Il l’incrémente 10 fois, retourne sur la première cellule, et la +décrémente. Cette boucle est exécutée 6 fois (ce qui correspond aux 6 +décrémentations de la première cellule pour la faire atteindre 0, ce qui fait +sortir de la boucle). + +À ce moment-là, nous sommes sur la première cellule, qui a une valeur de 0, +tandis que la seconde cellule a une valeur de 60. Nous nous déplaçons sur +celle-ci, l’incrémentons 5 fois, pour une valeur de 65, et affichons sa valeur. +En ASCII, 65 correspond à 'A' donc le programme affiche 'A' dans le terminal. + +, [ > + < - ] > . + +Ce programme lit un caractère sur l’entrée standard et le copie dans la +première cellule. Il commence ensuite une boucle : il bouge sur la seconde +cellule, incrémente sa valeur, retourne sur la première et décrémente sa +valeur. Il continue jusqu’à ce que cette valeur soit à 0, et que la seconde +cellule contienne l’ancienne valeur de la première. Comme nous sommes sur la +première cellule à la fin de la boucle, il bouge sur la seconde et affiche sa +valeur en ASCII. + +Souvenez-vous que les espaces sont uniquement pour favoriser la lisibilité, +vous pourriez tout aussi aisément écrire le programme comme ceci : + +,[>+<-]>. + +Essayez et devinez ce que ce programme fait : + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Ce programme prend deux nombres en entrée, et les multiplie. + +Il commence par lire deux entrées, puis commence une boucle externe, qui a une +condition sur la première cellule. Il bouge ensuite sur la seconde, et commence +une boucle interne sur celle-ci, en incrémentant la troisième cellule. Il y a +cependant un problème : à la fin de la boucle interne, la valeur de la seconde +cellule est à zéro. Dans ce cas, la boucle interne ne fonctionnera pas une +seconde fois. Pour régler le problème, nous incrémentons aussi la quatrième +cellule, puis recopions sa valeur dans la seconde cellule. +À la fin, la troisième cellule contient le résultat de la multiplication. +``` + +Et voilà ce qu’est le brainfuck. Pas très dur, hein ? Pour le fun, vous pouvez +écrire vos propres programmes en brainfuck, ou écrire un interpréteur brainfuck +dans un autre langage. L’interpréteur est relativement simple à implémenter, +mais si vous êtes un masochiste, essayez d’écrire un interpréteur brainfuck en… +brainfuck. -- cgit v1.2.3 From 00c4a6324e177b86c8b26318ed77d7373d8e716f Mon Sep 17 00:00:00 2001 From: Subramanian Date: Mon, 27 Oct 2014 09:06:43 +0530 Subject: correcting the setName method set the method argument dogsName to name, instead of doggie_name --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 50de5eff..9f357b08 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -305,7 +305,7 @@ void Dog::Dog() // if you are modifying them or const reference if you are not. void Dog::setName(const std::string& dogsName) { - name = doggie_name; + name = dogsName; } void Dog::setWeight(int dogsWeight) -- cgit v1.2.3 From fb28f2c10258eb92dc40db648a304f3e5b78bd2f Mon Sep 17 00:00:00 2001 From: ml242 Date: Mon, 27 Oct 2014 00:43:20 -0400 Subject: Your Name: Matt Subject Line: Addresses Comparisons in Javascript What Happened: I believe that starting out with the double equals instead of the triple equals for strict comparison checking is incorrect. Because double equals uses type coercion, it is more of a feature the needs to be understood. Beginners looking at the language should look upon the stricter method as the proper one because it is less likely to give a surprising result. I also tried to address the behaviour by adding an example to the double equals comparison. Hope that the community is interested in pulling in these changes, they stem from teaching beginners javaScript but I am by no means the authority. --- javascript.html.markdown | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 76017c17..f190ff98 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -77,13 +77,13 @@ false; !true; // = false !false; // = true -// Equality is == -1 == 1; // = true -2 == 1; // = false +// Equality is === +1 === 1; // = true +2 === 1; // = false -// Inequality is != -1 != 1; // = false -2 != 1; // = true +// Inequality is !== +1 !== 1; // = false +2 !== 1; // = true // More comparisons 1 < 10; // = true @@ -97,11 +97,13 @@ false; // and are compared with < and > "a" < "b"; // = true -// Type coercion is performed for comparisons... +// Type coercion is performed for comparisons with double equals... "5" == 5; // = true +null == undefined; // = true // ...unless you use === "5" === 5; // = false +null === undefined; // = false // You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' -- cgit v1.2.3 From b82da4edfe654617b3309f3fba382a13f2565c81 Mon Sep 17 00:00:00 2001 From: Russell Allen Date: Mon, 27 Oct 2014 22:07:24 +1100 Subject: First draft Self page --- self.html.markdown | 142 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 self.html.markdown diff --git a/self.html.markdown b/self.html.markdown new file mode 100644 index 00000000..bd81285e --- /dev/null +++ b/self.html.markdown @@ -0,0 +1,142 @@ +--- +language: self +contributors:r + - ["Russell Allen", "http://github.com/russellallen"] +filename: self.html.markdown +--- + +Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger. + +Everything in Self is an object. All computation is done by sending messages to objects. Objects in Self can be understood as sets of key-value slots. + +# Constructing objects + +The inbuild Self parser can construct objects, including method objects. + +``` +"This is a comment" + +"A string:" +'This is a string with \'escaped\' characters.\n' + +"A 30 bit integer" +23 + +"A 30 bit float" +3.2 + +"-20" +-14r16 + +"An object which only understands one message, 'x' which returns 20" +(| + x = 20. +|) + +"An object which also understands 'x:' which sets the x slot" +(| + x <- 20. +|) + +"An object which understands the method 'doubleX' which doubles the value of x and then returns the object" +(| + x <- 20. + doubleX = (x: x * 2. self) +|) + +"An object which understands all the messages that 'traits point' understands". The parser looks up 'traits point' by sending the messages 'traits' then 'point' to a known object called the 'lobby'. It looks up the 'true' object by also sending the message 'true' to the lobby." +(| parent* = traits point. + x = 7. + y <- 5. + isNice = true. +|) +``` + +# Sending messages to objects + +Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace. + +``` +23 printLine → unary message, sends 'printLine' to the object '23' + which prints the string '23' to stdout and returns the receiving object (ie 23) +(23 + 7) * 8 → sends the message '+' with '7' to '23', then the message '*' with '8' to the result +2 power: 8 → sends 'power:' to '2' with '8' returns 256 +'hello' keyOf: 'e' IfAbsent: -1 → sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'. Returns 1, the index of 'e' in 'hello'. +``` + +# Blocks + +Self defines flow control like Smalltalk and Ruby by way of blocks. Blocks are delayed computations of the form: + +``` +[|:x. localVar| x doSomthing With: localVar] +``` + +Examples of the use of a block: + +``` +'hello' copyMutable mapBy: [|:c| c capitalize] → 'HELLO' + +'hello' size > 5 ifTrue: ['Yay'] False: ['Nah'] → 'Nah' + +'hello' copyMutable mapBy: [|:c| + c = 'e' ifTrue: [c capitalize] + False: ['a']] + → 'HaLLO' +``` + +Multiple expressions are separated by a period. ^ returns immediately. + +``` +'hello' copyMutable mapBy: [|:c. tmp <- ''| + tmp: c capitalize. + tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!']. + c capitalize + ] + → An 'E'! How icky! +``` + +Blocks are performed by sending them the message 'value' and inherit (delegate to) their contexts: +``` +[|x| + x: 15. + "Repeatedly sends 'value' to the first block while the result of sending 'value' to the + second block is the 'true' object" + [x > 0] whileTrue: [x: x - 1]. + x +] value → 0 +``` + +# Methods + +Methods are like blocks but are not within a context but are the values of slots. Unlike Smalltalk, methods by default return their final value not 'self'. + +``` +"Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'" +(| + x <- 50. + reduceXTo: y = ( + [x > y] whileTrue: [x: x - 1]. + self) +|) +"Sending the message 'reduceXTo: 10' to this object will put the object '10' in the 'x' slot and return the original object" +``` + +# Prototypes + +Self has no classes. The way to get an object is to find a prototype and copy it. + +``` +| d | +d: dictionary copy. +d at: 'hello' Put: 23 + 8. +d at: 'goodbye' Put: 'No!. +"Prints No!" +( d at: 'goodbye' IfAbsent: 'Yes! ) printLine. +"Prints 31" +( d at: 'hello' IfAbsent: -1 ) printLine. +``` + +# Further information + +The [Self handbook](http://handbook.selflanguage.org) has much more information, and nothing beats hand-on experience with Self by downloading it from the [homepage](http://www.selflanguage.org). -- cgit v1.2.3 From 3c66f479413af0f7d00de8e46ec449cac293f4bd Mon Sep 17 00:00:00 2001 From: Russell Allen Date: Mon, 27 Oct 2014 22:11:20 +1100 Subject: Cleaner code samples --- self.html.markdown | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/self.html.markdown b/self.html.markdown index bd81285e..e1a52af8 100644 --- a/self.html.markdown +++ b/self.html.markdown @@ -57,11 +57,19 @@ The inbuild Self parser can construct objects, including method objects. Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace. ``` -23 printLine → unary message, sends 'printLine' to the object '23' - which prints the string '23' to stdout and returns the receiving object (ie 23) -(23 + 7) * 8 → sends the message '+' with '7' to '23', then the message '*' with '8' to the result -2 power: 8 → sends 'power:' to '2' with '8' returns 256 -'hello' keyOf: 'e' IfAbsent: -1 → sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'. Returns 1, the index of 'e' in 'hello'. +"unary message, sends 'printLine' to the object '23' +which prints the string '23' to stdout and returns the receiving object (ie 23)" +23 printLine + +"sends the message '+' with '7' to '23', then the message '*' with '8' to the result" +(23 + 7) * 8 + +"sends 'power:' to '2' with '8' returns 256" +2 power: 8 + +"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'. +Returns 1, the index of 'e' in 'hello'." +'hello' keyOf: 'e' IfAbsent: -1 ``` # Blocks @@ -75,14 +83,14 @@ Self defines flow control like Smalltalk and Ruby by way of blocks. Blocks are d Examples of the use of a block: ``` -'hello' copyMutable mapBy: [|:c| c capitalize] → 'HELLO' +'hello' copyMutable mapBy: [|:c| c capitalize] "returns 'HELLO'" -'hello' size > 5 ifTrue: ['Yay'] False: ['Nah'] → 'Nah' +'hello' size > 5 ifTrue: ['Yay'] False: ['Nah'] "returns 'Nah'" 'hello' copyMutable mapBy: [|:c| c = 'e' ifTrue: [c capitalize] False: ['a']] - → 'HaLLO' +"returns 'HaLLO'" ``` Multiple expressions are separated by a period. ^ returns immediately. @@ -93,7 +101,7 @@ Multiple expressions are separated by a period. ^ returns immediately. tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!']. c capitalize ] - → An 'E'! How icky! +"returns An 'E'! How icky!" ``` Blocks are performed by sending them the message 'value' and inherit (delegate to) their contexts: @@ -104,7 +112,8 @@ Blocks are performed by sending them the message 'value' and inherit (delegate t second block is the 'true' object" [x > 0] whileTrue: [x: x - 1]. x -] value → 0 +] value +"returns 0" ``` # Methods -- cgit v1.2.3 From 9fdfb3f56627c23b5dc5581fef353e010e7ff148 Mon Sep 17 00:00:00 2001 From: Russell Allen Date: Mon, 27 Oct 2014 22:13:08 +1100 Subject: Better use of linebreaks --- self.html.markdown | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/self.html.markdown b/self.html.markdown index e1a52af8..7b1f38af 100644 --- a/self.html.markdown +++ b/self.html.markdown @@ -83,29 +83,32 @@ Self defines flow control like Smalltalk and Ruby by way of blocks. Blocks are d Examples of the use of a block: ``` -'hello' copyMutable mapBy: [|:c| c capitalize] "returns 'HELLO'" +"returns 'HELLO'" +'hello' copyMutable mapBy: [|:c| c capitalize] -'hello' size > 5 ifTrue: ['Yay'] False: ['Nah'] "returns 'Nah'" +"returns 'Nah'" +'hello' size > 5 ifTrue: ['Yay'] False: ['Nah'] +"returns 'HaLLO'" 'hello' copyMutable mapBy: [|:c| c = 'e' ifTrue: [c capitalize] False: ['a']] -"returns 'HaLLO'" ``` Multiple expressions are separated by a period. ^ returns immediately. ``` +"returns An 'E'! How icky!" 'hello' copyMutable mapBy: [|:c. tmp <- ''| tmp: c capitalize. tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!']. c capitalize ] -"returns An 'E'! How icky!" ``` Blocks are performed by sending them the message 'value' and inherit (delegate to) their contexts: ``` +"returns 0" [|x| x: 15. "Repeatedly sends 'value' to the first block while the result of sending 'value' to the @@ -113,7 +116,6 @@ Blocks are performed by sending them the message 'value' and inherit (delegate t [x > 0] whileTrue: [x: x - 1]. x ] value -"returns 0" ``` # Methods @@ -121,14 +123,16 @@ Blocks are performed by sending them the message 'value' and inherit (delegate t Methods are like blocks but are not within a context but are the values of slots. Unlike Smalltalk, methods by default return their final value not 'self'. ``` -"Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'" +"Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'. +Sending the message 'reduceXTo: 10' to this object will put +the object '10' in the 'x' slot and return the original object" (| x <- 50. reduceXTo: y = ( [x > y] whileTrue: [x: x - 1]. self) |) -"Sending the message 'reduceXTo: 10' to this object will put the object '10' in the 'x' slot and return the original object" +. ``` # Prototypes -- cgit v1.2.3 From 122b9ab40855ad386e398e8f71cb539eeab47b85 Mon Sep 17 00:00:00 2001 From: Baptiste Fontaine Date: Mon, 27 Oct 2014 12:25:34 +0100 Subject: Brainfuck/fr: a couple fixes after proof-reading --- fr-fr/brainfuck-fr.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/fr-fr/brainfuck-fr.html.markdown b/fr-fr/brainfuck-fr.html.markdown index 4b8e918f..3882734d 100644 --- a/fr-fr/brainfuck-fr.html.markdown +++ b/fr-fr/brainfuck-fr.html.markdown @@ -54,12 +54,12 @@ En ASCII, 65 correspond à 'A' donc le programme affiche 'A' dans le terminal. Ce programme lit un caractère sur l’entrée standard et le copie dans la première cellule. Il commence ensuite une boucle : il bouge sur la seconde cellule, incrémente sa valeur, retourne sur la première et décrémente sa -valeur. Il continue jusqu’à ce que cette valeur soit à 0, et que la seconde -cellule contienne l’ancienne valeur de la première. Comme nous sommes sur la -première cellule à la fin de la boucle, il bouge sur la seconde et affiche sa -valeur en ASCII. +valeur. Il continue jusqu’à ce que la valeur de la première cellule soit à 0, +et que la seconde cellule contienne l’ancienne valeur de la première. Comme +nous sommes sur la première cellule à la fin de la boucle, il bouge sur la +seconde et affiche sa valeur en ASCII. -Souvenez-vous que les espaces sont uniquement pour favoriser la lisibilité, +Souvenez-vous que les espaces sont uniquement là pour favoriser la lisibilité, vous pourriez tout aussi aisément écrire le programme comme ceci : ,[>+<-]>. -- cgit v1.2.3 From 67de7d7281ce9703665cfcbf240cd2c79bac450c Mon Sep 17 00:00:00 2001 From: ven Date: Mon, 27 Oct 2014 20:01:55 +0100 Subject: [Common Lisp/en] Add a missing argument to `(walker)` --- common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 08134e35..c4ecb5e8 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -431,7 +431,7 @@ nil ; for false - and the empty list :walked (walker (1- n)))) -(walker) ; => :walked +(walker 5) ; => :walked ;; Most of the time, we use DOLIST or LOOP -- cgit v1.2.3 From 759f7349d2ff36ee7d9b28c20d9ce690de413683 Mon Sep 17 00:00:00 2001 From: Srinivas Gorur-Shandilya Date: Mon, 27 Oct 2014 16:52:14 -0400 Subject: cleaned up code, added struct docs cleaned up code, added struct docs --- matlab.html.markdown | 49 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 9dae8ef2..42db6ad7 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -40,36 +40,40 @@ ctrl-c % Abort current computation edit('myfunction.m') % Open function/script in editor type('myfunction.m') % Print the source of function/script to Command Window -profile viewer % Open profiler +profile on % turns on the code profiler +profile of % turns off the code profiler +profile viewer % Open profiler -help command % Displays documentation for command in Command Window -doc command % Displays documentation for command in Help Window -lookfor command % Searches for a given command +help command % Displays documentation for command in Command Window +doc command % Displays documentation for command in Help Window +lookfor command % Searches for a command in all other commands % 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 +format short % 4 decimals in a floating number +format long % 15 decimals +format bank % only two digits after decimal point - for financial calculations +fprintf('text') % print "text" to the screen +disp('text') % print "text" to the screen % Variables & Expressions -myVariable = 4 % Notice Workspace pane shows newly created variable +myVariable = 4 % Notice Workspace pane shows newly created variable myVariable = 4; % Semi colon suppresses output to the Command Window -4 + 6 % ans = 10 -8 * myVariable % ans = 32 -2 ^ 3 % ans = 8 +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 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') +load('myFile.mat', 'y') % arguments within parantheses, spererated by commas % Command syntax: -load myFile.mat y % no parentheses, and spaces instead of commas +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 +[V,D] = eig(A); % this has no equivalent in command form +[~,D] = eig(A); % if you only want D and not V @@ -100,6 +104,10 @@ a = {'one', 'two', 'three'} a(1) % ans = 'one' - returns a cell char(a(1)) % ans = one - returns a string +% Structures +A.b = {'one','two'}; +A.c = [1 2]; +A.d.e = false; % Vectors x = [4 32 53 7 1] @@ -160,6 +168,10 @@ A(1,:) % All columns in row 1 % 4 5 42 % 7 8 9 +% this is the same as +vertcat(A,A); + + [A , A] % Concatenation of matrices (horizontally) %ans = @@ -168,6 +180,8 @@ A(1,:) % All columns in row 1 % 4 5 42 4 5 42 % 7 8 9 7 8 9 +% this is the same as +horzcat(A,A); A(:, [3 1 2]) % Rearrange the columns of original matrix @@ -180,10 +194,13 @@ A(:, [3 1 2]) % Rearrange the columns of original matrix size(A) % ans = 3 3 A(1, :) =[] % Delete the first row of the matrix +A(:, 1) =[] % Delete the first column of the matrix +transpose(A) % Transpose the matrix, which is the same as: +A' ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) -transpose(A) % Transpose the matrix, without taking complex conjugate + -- cgit v1.2.3 From 02db45c5dc935043a9e19f3550121ae78965e5ca Mon Sep 17 00:00:00 2001 From: Dana de Waal Date: Tue, 28 Oct 2014 03:23:52 +0100 Subject: A few trailing spaces and take 2 on Dutch spelling and translation. --- nl-nl/coffeescript-nl.html.markdown | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/nl-nl/coffeescript-nl.html.markdown b/nl-nl/coffeescript-nl.html.markdown index 70dcd463..dc0b1e19 100644 --- a/nl-nl/coffeescript-nl.html.markdown +++ b/nl-nl/coffeescript-nl.html.markdown @@ -5,23 +5,24 @@ contributors: - ["Xavier Yao", "http://github.com/xavieryao"] translators: - ["Jelle Besseling", "https://github.com/Jell-E"] + - ["D.A.W. de Waal", "http://github.com/diodewaal"] filename: coffeescript-nl.coffee lang: nl-nl --- -CoffeeScript is een kleine programmeertaal die compileerd naar JavaScript, -er is geen interpretatie tijdens het uitvoeren. -Als een van de nakomelingen van JavaScript probeert CoffeeScript om leesbare, -goed geformatteerdeen goed draaiende JavaScript code te genereren, -die in elke JavaScript runtime werkt. +CoffeeScript is een kleine programmeertaal die direct compileert naar +JavaScript en er is geen interpretatie tijdens het uitvoeren. +CoffeeScript probeert om leesbare, goed geformatteerde en goed draaiende +JavaScript code te genereren, die in elke JavaScript runtime werkt, als een +opvolger van JavaScript. -Op [de CoffeeScript website](http://coffeescript.org/), staat een -vollediger tutorial voor CoffeeScript. +Op [de CoffeeScript website](http://coffeescript.org/), staat een +volledigere tutorial voor CoffeeScript. ``` coffeescript # CoffeeScript is een taal voor hipsters. # Het gaat mee met alle trends van moderne talen. -# Dus commentaar begint met een hekje, net zoals bij Python en Ruby. +# Commentaar begint dus met een hekje, net zoals bij Python en Ruby. ### Blokken commentaar maak je zo, ze vertalen naar JavaScripts */ en /* @@ -47,7 +48,7 @@ vul = (houder, vloeistof = "koffie") -> # #vul = function(houder, vloeistof) { # if (vloeistof == null) { -# vloeistof = "coffee"; +# vloeistof = "koffie"; # } # return "Nu de " + houder + " met " + vloeistof + " aan het vullen..."; #}; @@ -75,12 +76,12 @@ wedstrijd = (winnaar, lopers...) -> # return print(winnaar, lopers); #}; -# Bestaan: +# Aanwezigheid: alert "Ik wist het!" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } # Lijst abstractie: -derdemachten = (wiskunde.derdemacht num for num in lijst) +derdemachten = (wiskunde.derdemacht num for num in lijst) #=>derdemachten = (function() { # var _i, _len, _results; # _results = []; -- cgit v1.2.3 From eb43eb7ccdeaad7440d9fda90128691effda15e1 Mon Sep 17 00:00:00 2001 From: i Date: Tue, 28 Oct 2014 03:11:59 -0400 Subject: basic arithmetic *doesn't* work It's not really true that arithmetic is accurate in JavaScript. --- javascript.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index cc210c4a..792cab98 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -39,13 +39,14 @@ doStuff() // 1. Numbers, Strings and Operators // JavaScript has one number type (which is a 64-bit IEEE 754 double). -// As with Lua, don't freak out about the lack of ints: doubles have a 52-bit -// mantissa, which is enough to store integers up to about 9✕10¹⁵ precisely. +// Doubles have a 52-bit mantissa, which is enough to store integers +// up to about 9✕10¹⁵ precisely. 3; // = 3 1.5; // = 1.5 -// All the basic arithmetic works as you'd expect. +// Some basic arithmetic works as you'd expect. 1 + 1; // = 2 +.1 + .2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 -- cgit v1.2.3 From 3921d11155780f8219a8110d8fe4ede88c9fcadf Mon Sep 17 00:00:00 2001 From: i Date: Tue, 28 Oct 2014 03:56:12 -0400 Subject: more oddities JavaScript is full of oddities .. I definitely wouldn't claim everything works "as it should" .. you don't have to include the gotcha's but I don't know, they're not that confusing for me. --- javascript.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index cc210c4a..2dece277 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -105,6 +105,10 @@ null == undefined; // = true "5" === 5; // = false null === undefined; // = false +// ...which can result in some weird behaviour... +13 + !0; // 14 +"13" + !0; // '13true' + // You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' -- cgit v1.2.3 From e1bdeff354c2535515ea31e733a5f078a2f469eb Mon Sep 17 00:00:00 2001 From: Srinivas Gorur-Shandilya Date: Tue, 28 Oct 2014 09:56:18 -0400 Subject: clarified lookfor --- matlab.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 42db6ad7..121f16de 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -46,7 +46,8 @@ profile viewer % Open profiler help command % Displays documentation for command in Command Window doc command % Displays documentation for command in Help Window -lookfor command % Searches for a command in all other commands +lookfor command % Searches for command in the first commented line of all functions +lookfor command -all % searches for command in all functions % Output formatting -- cgit v1.2.3 From b3cceac37eefae7cfeac73fad7eefde3e40a5fce Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 28 Oct 2014 23:12:58 +0200 Subject: Update markdown.html.markdown --- fr-fr/markdown.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index 50e507cd..29c0d65d 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -3,6 +3,7 @@ language: markdown contributors: - ["Andrei Curelaru", "http://www.infinidad.fr"] filename: markdown.md +lang: fr-fr --- Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe -- cgit v1.2.3 From 9d9dd467cd836e169d64ff6f24749a7c52865a22 Mon Sep 17 00:00:00 2001 From: Russell Allen Date: Wed, 29 Oct 2014 14:46:27 +1100 Subject: Fix typos --- self.html.markdown | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/self.html.markdown b/self.html.markdown index 7b1f38af..f4b5fefc 100644 --- a/self.html.markdown +++ b/self.html.markdown @@ -1,6 +1,6 @@ --- language: self -contributors:r +contributors: - ["Russell Allen", "http://github.com/russellallen"] filename: self.html.markdown --- @@ -38,13 +38,19 @@ The inbuild Self parser can construct objects, including method objects. x <- 20. |) -"An object which understands the method 'doubleX' which doubles the value of x and then returns the object" +"An object which understands the method 'doubleX' which +doubles the value of x and then returns the object" (| x <- 20. doubleX = (x: x * 2. self) |) -"An object which understands all the messages that 'traits point' understands". The parser looks up 'traits point' by sending the messages 'traits' then 'point' to a known object called the 'lobby'. It looks up the 'true' object by also sending the message 'true' to the lobby." +"An object which understands all the messages +that 'traits point' understands". The parser +looks up 'traits point' by sending the messages +'traits' then 'point' to a known object called +the 'lobby'. It looks up the 'true' object by +also sending the message 'true' to the lobby." (| parent* = traits point. x = 7. y <- 5. @@ -77,7 +83,7 @@ Returns 1, the index of 'e' in 'hello'." Self defines flow control like Smalltalk and Ruby by way of blocks. Blocks are delayed computations of the form: ``` -[|:x. localVar| x doSomthing With: localVar] +[|:x. localVar| x doSomething with: localVar] ``` Examples of the use of a block: @@ -120,7 +126,7 @@ Blocks are performed by sending them the message 'value' and inherit (delegate t # Methods -Methods are like blocks but are not within a context but are the values of slots. Unlike Smalltalk, methods by default return their final value not 'self'. +Methods are like blocks but they are not within a context but instead are stored as values of slots. Unlike Smalltalk, methods by default return their final value not 'self'. ``` "Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'. -- cgit v1.2.3 From 583f874cdf54c46ccfb1ea0a9480bdbffa308927 Mon Sep 17 00:00:00 2001 From: pbaisla Date: Wed, 29 Oct 2014 23:44:36 +0530 Subject: [tmux/en] Fix URL names --- tmux.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index ebc312ed..de3a8341 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -239,6 +239,6 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | Tmux | Home
Tmux Manual page
-Archlinux Wiki
-Gentoo Wiki
+Gentoo Wiki
+Archlinux Wiki
Display CPU/MEM % in statusbar
-- cgit v1.2.3 From 3f69c38ba3594eb93d86d1f4b2456241ffe9b14a Mon Sep 17 00:00:00 2001 From: xk liu Date: Thu, 30 Oct 2014 11:07:40 +0800 Subject: [matlab/en] Fix block comment syntax. The %{ and %} operators must appear alone on the lines that immediately precede and follow the block of help text. Do not include any other text on these lines. Reference: http://www.mathworks.com/help/matlab/matlab_prog/comments.html --- matlab.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 121f16de..2b9077d5 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -15,10 +15,12 @@ If you have any feedback please feel free to reach me at ```matlab % Comments start with a percent sign. -%{ Multi line comments look +%{ +Multi line comments look something like -this %} +this +%} % commands can span multiple lines, using '...': a = 1 + 2 + ... -- cgit v1.2.3 From 9324987c1fc465379060491d9a4b1c25cffde0fc Mon Sep 17 00:00:00 2001 From: Frederik Ring Date: Thu, 30 Oct 2014 16:43:49 +0100 Subject: use propernotation for decimals --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 792cab98..a92dcb4a 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -46,7 +46,7 @@ doStuff() // Some basic arithmetic works as you'd expect. 1 + 1; // = 2 -.1 + .2; // = 0.30000000000000004 +0.1 + 0.2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 -- cgit v1.2.3 From 02e81acfe1dc548553082672a2d04f826a0812e6 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 31 Oct 2014 00:44:24 +0200 Subject: Update self.html.markdown --- self.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/self.html.markdown b/self.html.markdown index f4b5fefc..69524a84 100644 --- a/self.html.markdown +++ b/self.html.markdown @@ -2,7 +2,7 @@ language: self contributors: - ["Russell Allen", "http://github.com/russellallen"] -filename: self.html.markdown +filename: learnself.self --- Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger. -- cgit v1.2.3 From 112b0b7662d3e235e8bee88ba45fccd8d7932e98 Mon Sep 17 00:00:00 2001 From: Wes Turner Date: Thu, 30 Oct 2014 19:46:37 -0500 Subject: DOC: bash.html.markdown: add bash docs examples --- bash.html.markdown | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 11c1f3a2..81d586c4 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -208,4 +208,30 @@ grep "^foo.*bar$" file.txt grep -c "^foo.*bar$" file.txt # if you literally want to search for the string, and not the regex, use fgrep (or grep -F) fgrep "^foo.*bar$" file.txt + + +# Read Bash shell builtins documentation with the bash 'help' builtin: +help +help help +help for +help return +help source +help . + +# Read Bash manpage documentation with man +apropos bash +man 1 bash +man bash + +# Read info documentation with info (? for help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Read bash info documentation: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash ``` -- cgit v1.2.3 From 3a12532da9d2b76adb960ece6d610bdc4099a57d Mon Sep 17 00:00:00 2001 From: Sergey Date: Fri, 31 Oct 2014 17:29:06 +0300 Subject: Added description of LinkedList, Map & HashMap. --- java.html.markdown | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index dffc3828..478d85d6 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -123,9 +123,15 @@ public class LearnJava { // Others to check out // ArrayLists - Like arrays except more functionality is offered, // and the size is mutable - // LinkedLists - // Maps - // HashMaps + // LinkedLists - Implementation of doubly-linked list. All of the + // operations perform as could be expected for + // a doubly-linked list. + // Maps - An objects that maps keys to values. A map cannot contain + // duplicate keys; each key can map to at most one value. + // HashMaps - This class uses a hashtable to implement the Map interface. + // This allows the execution time of basic operations, + // such as get and insert element, to remain constant even + // for large sets. /////////////////////////////////////// // Operators -- cgit v1.2.3 From c309cc6e06647a9c1b6feae0082ebb5a86297453 Mon Sep 17 00:00:00 2001 From: jmaud Date: Fri, 31 Oct 2014 15:57:52 -0400 Subject: Correct contributors - Correct my github url/name - Remove kaernyk (converted account, now deleted) --- tmux.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index de3a8341..9eb96303 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -2,8 +2,7 @@ category: tool tool: tmux contributors: - - ["kaernyk", "https://github.com/kaernyk"] - - ["jmaud", "https://github.com/jmaud"] + - ["wzsk", "https://github.com/wzsk"] filename: LearnTmux.txt --- -- cgit v1.2.3 From ba5c351f216ca63e4f46230db683224fd6d26355 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 31 Oct 2014 15:40:49 -0600 Subject: A bit of section 2, 3, 4 --- zh-cn/python3-cn.html.markdown | 90 +++++++++++++++++++++--------------------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index e297a7ce..78ecb4af 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -140,60 +140,60 @@ bool({}) #=> False ## 2. 变量和集合 #################################################### -# Python has a print function +# print是内置的打印函数 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 +# 存取未赋值的变量会抛出异常 +# 下面流程控制一段更深入讲解异常处理 +some_unknown_var # 抛出NameError -# Lists store sequences +# 用列表(list)储存序列 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 +# 用append在列表最后追加元素 +li.append(1) # li现在是[1] +li.append(2) # li现在是[1, 2] +li.append(4) # li现在是[1, 2, 4] +li.append(3) # li现在是[1, 2, 4, 3] +# 用pop从列表尾部删除 +li.pop() # => 3 且li现在是[1, 2, 4] +# 把3再放回去 +li.append(3) # li变回[1, 2, 4, 3] + +# 列表取值跟数组一样 li[0] # => 1 -# Look at the last element +# 取出最后一个元素 li[-1] # => 3 -# Looking out of bounds is an IndexError -li[4] # Raises an IndexError +# 越界读取会造成IndexError +li[4] # 抛出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删除任何一个元素 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的值都不变 li + other_li # => [1, 2, 3, 4, 5, 6] # Concatenate lists with "extend()" @@ -211,7 +211,7 @@ 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) @@ -301,17 +301,17 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} ## 3. 流程控制和迭代器 #################################################### -# 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语句。注意缩进在Python里是有意义的 +# 印出"some_var比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.") + print("some_var比10大") +elif some_var < 10: # elif句是可选的 + print("some_var比10小") +else: # else也是可选的 + print("some_var就是10") """ @@ -399,16 +399,16 @@ list(filled_dict.keys()) #=> Returns ["one", "two", "three"] ## 4. 函数 #################################################### -# Use "def" to create new functions +# 用def定义新函数 def add(x, y): print("x is {} and y is {}".format(x, y)) - return x + y # Return values with a return statement + return x + y # 用return语句返回 -# Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 +# 调用函数 +add(5, 6) # => 印出"x is 5 and y is 6"并且返回11 -# Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. +# 也可以用关键字参数来调用函数 +add(y=6, x=5) # 关键字参数可以用任何顺序 # You can define functions that take a variable number of -- cgit v1.2.3 From 2444690e5fae22d5f09f3f4966996785353fd3af Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 31 Oct 2014 15:52:20 -0600 Subject: All of section 6 --- zh-cn/python3-cn.html.markdown | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index 78ecb4af..efdfc158 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -545,29 +545,27 @@ Human.grunt() # => "*grunt*" ## 6. 模块 #################################################### -# You can import modules +# 用import导入模块 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. +# Python模块其实就是普通的Python文件。你可以自己写,然后导入, +# 模块的名字就是文件的名字。 -# You can find out which functions and attributes -# defines a module. +# 你可以这样列出一个模块里所有的值 import math dir(math) -- cgit v1.2.3 From fb89673ef1063c3446462d3249246929d492ea76 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 31 Oct 2014 16:01:10 -0600 Subject: Minor changes --- zh-cn/python3-cn.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index efdfc158..6ad23600 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -148,8 +148,8 @@ print("I'm Python. Nice to meet you!") some_var = 5 some_var # => 5 -# 存取未赋值的变量会抛出异常 -# 下面流程控制一段更深入讲解异常处理 +# 访问未赋值的变量会抛出异常 +# 参考流程控制一段来学习异常处理 some_unknown_var # 抛出NameError # 用列表(list)储存序列 @@ -167,22 +167,22 @@ li.pop() # => 3 且li现在是[1, 2, 4] # 把3再放回去 li.append(3) # li变回[1, 2, 4, 3] -# 列表取值跟数组一样 +# 列表存取跟数组一样 li[0] # => 1 # 取出最后一个元素 li[-1] # => 3 -# 越界读取会造成IndexError +# 越界存取会造成IndexError li[4] # 抛出IndexError -# 列表的切割语法 +# 列表有切割语法 # (It's a closed/open range for you mathy types.) li[1:3] # => [2, 4] # 取尾 li[2:] # => [4, 3] # 取头 li[:3] # => [1, 2, 4] -# 每两个取一个 +# 隔一个取一个 li[::2] # =>[1, 4] # 倒排列表 li[::-1] # => [3, 4, 2, 1] -- cgit v1.2.3 From d234d1c8945a7a4fdc812be65de89ca0c6aa52b6 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 31 Oct 2014 17:20:50 -0600 Subject: Finish sections 2 and 3 --- zh-cn/python3-cn.html.markdown | 153 ++++++++++++++++++++--------------------- 1 file changed, 74 insertions(+), 79 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index 6ad23600..2c1c03f8 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -9,13 +9,13 @@ translators: filename: learnpython3.py --- -Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular -languages in existence. I fell in love with Python for its syntactic clarity. It's basically -executable pseudocode. +Python是由吉多·范罗苏姆(Guido Van Rossum)在90年代早期设计。它是如今最常用的编程 +语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。 -Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] +欢迎大家斧正。英文版原作Louie Dinh [@louiedinh](http://twitter.com/louiedinh) +或着Email louiedinh [at] [谷歌的信箱服务]。中文翻译Geoff Liu。 -Note: This article applies to Python 3 specifically. Check out the other tutorial if you want to learn the old Python 2.7 +注意:这篇教程是特别为Python3写的。如果你想学旧版Python2,我们特别有另一篇教程。 ```python @@ -128,7 +128,7 @@ None # => None "etc" is None # => False None is None # => True -# None,0,空字符串,空列表,空关联数组都算是False +# None,0,空字符串,空列表,空字典都算是False # 所有其他值都是True bool(0) # => False bool("") # => False @@ -176,7 +176,6 @@ li[-1] # => 3 li[4] # 抛出IndexError # 列表有切割语法 -# (It's a closed/open range for you mathy types.) li[1:3] # => [2, 4] # 取尾 li[2:] # => [4, 3] @@ -196,103 +195,101 @@ del li[2] # li is now [1, 2, 3] # 注意:li和other_li的值都不变 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] +# 用extend拼接列表 +li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6] -# Check for existence in a list with "in" +# 用in测试列表是否包含值 1 in li # => True -# Examine the length with "len()" +# 用len取列表长度 len(li) # => 6 -# Tuples are like lists but are immutable. +# 元组是不可改变的序列 tup = (1, 2, 3) tup[0] # => 1 -tup[0] = 3 # Raises a TypeError +tup[0] = 3 # 抛出TypeError -# 列表允许的操作元组也可以 +# 列表允许的操作元组大都可以 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 +# 可以把元组合列表解包,赋值给变量 +a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3 +# 元组周围的括号是可以省略的 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 +# 交换两个变量的值就这么简单 +e, d = d, e # 现在d是5,e是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. + +# 用keys获得所有的键。因为keys返回一个可迭代对象,所以在这里把结果包在list里。我们下面会详细介绍可迭代。 +# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。 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. +# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。 list(filled_dict.values()) # => [3, 2, 1] -# Check for existence of keys in a dictionary with "in" +# 用in测试一个字典是否包含一个键 "one" in filled_dict # => True 1 in filled_dict # => False -# Looking up a non-existing key is a KeyError +# 访问不存在的键会导致KeyError filled_dict["four"] # KeyError -# Use "get()" method to avoid the KeyError +# 用get来避免KeyError filled_dict.get("one") # => 1 filled_dict.get("four") # => None -# The get method supports a default argument when the value is missing +# 当键不存在的时候get方法可以返回默认值 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 +# setdefault方法只有当键不存在的时候插入新值 +filled_dict.setdefault("five", 5) # filled_dict["five"]设为5 +filled_dict.setdefault("five", 6) # filled_dict["five"]还是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 +filled_dict["four"] = 4 # 另一种赋值方法 -# Remove keys from a dictionary with del -del filled_dict["one"] # Removes the key "one" from filled dict +# 用del删除 +del filled_dict["one"] # 从filled_dict中把one删除 -# Sets store ... well sets +# 用set表达集合 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} +# 初始化一个集合,语法跟字典相似。 +some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{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} +# 为集合添加元素 +filled_set.add(5) # filled_set现在是{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 +# in 测试集合是否包含元素 2 in filled_set # => True 10 in filled_set # => False @@ -315,20 +312,18 @@ else: # else也是可选的 """ -For loops iterate over lists -prints: +用for循环语句遍历列表 +打印: 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: +"range(number)"返回数字列表从0到给的数字 +打印: 0 1 2 @@ -338,8 +333,8 @@ for i in range(4): print(i) """ -While loops go until a condition is no longer met. -prints: +while循环直到条件不满足 +打印: 0 1 2 @@ -348,49 +343,49 @@ prints: x = 0 while x < 4: print(x) - x += 1 # Shorthand for x = x + 1 + x += 1 # x = x + 1 的简写 -# Handle exceptions with a try/except block +# try/except块处理异常状况 try: - # Use "raise" to raise an error + # 用raise来抛出异常 raise IndexError("This is an index error") except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. + pass # pass是无操作,但是应该在这里处理错误 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 # 可以同时处理不同类的错误 +else: # else语句是可选的,必须在所有的except之后 + print("All good!") # 只有当try运行完没有错误的时候这句才会运行 + -# 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. +# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列 +# 的对象。比如说上面range返回的对象就是可迭代的。 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 +print(our_iterable) # => range(1,10) 是一个实现可迭代接口的对象 -# We can loop over it. +# 可迭代对象可以遍历 for i in our_iterable: - print(i) # Prints one, two, three + print(i) # 打印 one, two, three -# However we cannot address elements by index. -our_iterable[1] # Raises a TypeError +# 但是不可以随机访问 +our_iterable[1] # 抛出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. +# 迭代器是一个可以记住遍历的位置的对象 +# 用__next__可以取得下一个元素 our_iterator.__next__() #=> "one" -# It maintains state as we call __next__. +# 再一次调取__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 +# 当迭代器所有元素都取出后,会抛出StopIteration +our_iterator.__next__() # 抛出StopIteration -# You can grab all the elements of an iterator by calling list() on it. +# 可以用list一次取出迭代器所有的元素 list(filled_dict.keys()) #=> Returns ["one", "two", "three"] -- cgit v1.2.3 From a32bb0a2cc3b53b4ffa4d2e93ebe664afb7a7729 Mon Sep 17 00:00:00 2001 From: Bruno Kim Medeiros Cesar Date: Sat, 1 Nov 2014 01:37:26 -0200 Subject: Remove misleading example of NA in Levels section The levels section was using a level "NA" together with "female" and "male", which is misleading (given that NA was just introduced as a missing value). I updated it to what I believe is a better example of how NAs are interpreted. Additionally, I edited a comment about Inf that wouldn't compile. How about inserting it at the tutorial altogether? --- r.html.markdown | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index 7cb56fd7..c555d748 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -179,7 +179,7 @@ c(3,3,3,2,2,1) # 3 3 3 2 2 1 # You can also have infinitely large or small numbers class(Inf) # "numeric" class(-Inf) # "numeric" -# You might use "Inf", for example, in integrate( dnorm(x), 3, Inf); +# You might use "Inf", for example, in integrate(dnorm, 3, Inf); # this obviates Z-score tables. # BASIC ARITHMETIC @@ -236,11 +236,12 @@ c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE # FACTORS # The factor class is for categorical data # Factors can be ordered (like childrens' grade levels) or unordered (like gender) -factor(c("female", "female", "male", "NA", "female")) -# female female male NA female -# Levels: female male NA +factor(c("female", "female", "male", NA, "female")) +# female female male female +# Levels: female male # The "levels" are the values the categorical data can take -levels(factor(c("male", "male", "female", "NA", "female"))) # "female" "male" "NA" +# Note that missing data does not enter the levels +levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male" # If a factor vector has length 1, its levels will have length 1, too length(factor("male")) # 1 length(levels(factor("male"))) # 1 -- cgit v1.2.3 From 45b02b939a6e61775f43f20a17854cf6a3c11f56 Mon Sep 17 00:00:00 2001 From: m90 Date: Sat, 1 Nov 2014 12:58:44 +0100 Subject: update javascript-de according to english master and fix some typos --- de-de/javascript-de.html.markdown | 114 ++++++++++++++++++++++++++++++++------ 1 file changed, 96 insertions(+), 18 deletions(-) diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index 38ce28e2..1cc30eea 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -9,11 +9,11 @@ lang: de-de --- (Anmerkungen des Original-Autors:) -JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzent zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java. +JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzend zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java. -Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, dass eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer. +Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, das eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer. -Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@adambrenecki](https://twitter.com/adambrenecki) oder [adam@brenecki.id.au](mailto:adam@brenecki.id.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.id.au). +Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@adambrenecki](https://twitter.com/adambrenecki) oder [adam@brenecki.id.au](mailto:adam@brenecki.id.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.de). ```js // Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei @@ -40,7 +40,7 @@ machWas() // Alle grundlegenden arithmetischen Operationen arbeiten wie erwartet. 1 + 1; // = 2 -8 - 1; // = 7 +0.1 + 0.2; // = 0.30000000000000004 10 * 2; // = 20 35 / 5; // = 7 @@ -72,13 +72,13 @@ false; !true; // = false !false; // = true -// Gleichheit wird mit == geprüft. -1 == 1; // = true -2 == 1; // = false +// Gleichheit wird mit === geprüft. +1 === 1; // = true +2 === 1; // = false -// Ungleichheit wird mit != überprüft. -1 != 1; // = false -2 != 1; // = true +// Ungleichheit wird mit !== überprüft. +1 !== 1; // = false +2 !== 1; // = true // Andere Vergleichsoperatoren sind 1 < 10; // = true @@ -92,16 +92,22 @@ false; // und mit < und > verglichen werden. "a" < "b"; // = true -// Für den Vergleich von Werten wird eine Typumwandlung erzwungen... +// Für den Vergleich von Werten mit "==" wird eine Typumwandlung erzwungen... "5" == 5; // = true // ...solange man nicht === verwendet. "5" === 5; // = false // Auf einzelne Buchstaben innerhalb eines Strings kann mit der Methode -// charAt zugegriffen werden +// 'charAt' zugegriffen werden "This is a string".charAt(0); // = "T" +// Die Methode 'substring' gibt Teilbereiche eines Strings zurück +"Hello world".substring(0, 5); // = "Hello" + +// 'length' ist eine Eigenschaft und wird folglich ohne '()' benutzt +"Hello".length; // = 5 + // Es gibt außerdem die Werte 'null' und 'undefined' null; // wird verwendet um einen vorsätzlich gewählten 'Nicht'-Wert anzuzeigen undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht @@ -147,6 +153,13 @@ var myArray = ["Hello", 45, true]; // beginnt bei 0. myArray[1]; // = 45 +// Arrays haben keine feste Länge +myArray.push("World"); +myArray.length; // = 4 + +// und sind veränderlich +myArray[3] = "Hello"; + // Die Objekte in JavaScript entsprechen 'dictionaries' oder 'maps' in anderen // Sprachen: es handelt sich um ungeordnete Schlüssel-Wert-Paare. var myObj = { key1: "Hello", key2: "World" }; @@ -218,15 +231,47 @@ if (colour == "red" || colour == "blue"){ // nützlich, um einen Default-Wert zu setzen. var name = otherName || "default"; +// Ein 'switch' Statement prüft Gleichheit mit === +// ohne ein 'break' nach jedem Fall +// werden auch die Fälle nach dem korrekten aufgerufen +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + /////////////////////////////////// // 4. Funktionen, Geltungsbereich und Closures -// In JavaScript werden Funktionen mit dem Schlüsselwort 'function' deklariert. +// In JavaScript werden Funktionen mit dem Schlüsselwort 'function' deklariert. function myFunction(thing){ return thing.toUpperCase(); } myFunction("foo"); // = "FOO" +// Vorsicht: der Ausdruck der den Rückgabewert einer Funktion bildet muss +// auf der selben Zeile beginnen auf der auch das 'return' Keyword steht +// Sonst wird hier ein automatisches Semikolon eingefügt und die Funktion +// gibt 'undefined' zurück +function myFunction() +{ + return // <- Hier wird automatisch ein Semikolon eingefügt + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + // In JavaScript sind Funktionen 'Bürger erster Klasse', also können sie wie // Variablen verwendet und als Parameter anderen Funktionen übergeben werden // - zum Beispiel, um einen 'event handler' zu 'beliefern'. @@ -236,9 +281,9 @@ function myFunction() { setTimeout(myFunction, 5000); // Funktionen können auch deklariert werden, ohne ihnen einen Namen zuzuweisen. -// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument +// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument // einer anderen Funktion zu definieren. -setTimeout(function() { +setTimeout(function(){ // wird ausgeführt, nachdem 5 Sekunden vergangen sind }, 5000); @@ -275,7 +320,7 @@ function sayHelloInFiveSeconds(name){ } setTimeout(inner, 5000); // setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds - // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein' + // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein' // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die // Variable prompt. @@ -320,6 +365,37 @@ var myOtherFunc = function(){ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" +// Mit den Methoden 'call' und 'apply' kann der Kontext eines Funktionsaufrufs +// verändert werden + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// 'apply' funktioniert beiahe identisch, erwartet die übergebenen Argumente +// aber in einem Array + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// Das ist hilfreich wenn man einer Funktion eine beliebige Zahl Argumente +// übergeben kann + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// 'call' und 'apply' beeinflussen aber nur den spezifischen Aufruf. +// Um den Kontext einer Funktion dauerhaft zu ändern wird 'bind' benutzt. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// Mit 'bind' lassen sich Funktionen auch teilweise anwenden / "curryen". +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + // Wenn eine Funktion mit dem Schlüsselwort 'new' aufgerufen wird, dann wird // ein neues Objekt erzeugt. Funktionen, die darauf ausgelegt sind in dieser // Art aufgerufen zu werden, werden Konstruktoren genannt. @@ -382,7 +458,7 @@ myObj.meaningOfLife; // = 43 // sich *nicht* um den Prototypen der Konstruktor-Funktion; stattdessen handelt // es sich um den Prototypen, der einem neuen Objekt mitgegeben wird, wenn es // mit dem Konstruktor und dem Schlüsselwort 'new' erzeugt wird. -myConstructor.prototype = { +MyConstructor.prototype = { getMyNumber: function(){ return this.myNumber } @@ -390,7 +466,7 @@ myConstructor.prototype = { var myNewObj2 = new myConstructor(); myNewObj2.getMyNumber(); // = 5 -// Die eingebauten Typen, also strings und numbers, haben auch Konstruktoren, +// Alle primitiven Typen, also strings und numbers, haben auch Konstruktoren, // die zu dem Typ äquivalente Wrapper-Objekte erzeugen. var myNumber = 12; var myNumberObj = new Number(12); @@ -447,4 +523,6 @@ Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den E [JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache. +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) ist ein Klassiker unter den Referenzen. + Zusätzlich zu direkten Beiträgen zu diesem Artikel ist der Inhalt in Anlehnung an Louie Dinh's Python-Tutorial auf dieser Seite und das [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) des Mozilla Developer Network entstanden. -- cgit v1.2.3 From 1d044a01c7ebe880a957310b2450e98c76ad4841 Mon Sep 17 00:00:00 2001 From: m90 Date: Sat, 1 Nov 2014 13:00:05 +0100 Subject: add mostly --- de-de/javascript-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index 1cc30eea..851fe852 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -38,7 +38,7 @@ machWas() 3; // = 3 1.5; // = 1.5 -// Alle grundlegenden arithmetischen Operationen arbeiten wie erwartet. +// Beinahe alle grundlegenden arithmetischen Operationen arbeiten wie erwartet. 1 + 1; // = 2 0.1 + 0.2; // = 0.30000000000000004 10 * 2; // = 20 -- cgit v1.2.3 From e287075690f73c934825fc413bcc4a3e2be4456d Mon Sep 17 00:00:00 2001 From: Wes Turner Date: Thu, 30 Oct 2014 19:20:05 -0500 Subject: [bash/en] bash.html.markdown: add bash redirection examples --- bash.html.markdown | 45 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 11c1f3a2..b0011420 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -111,12 +111,45 @@ 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, 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. +# You can redirect command input and output (stdin, stdout, and stderr). +# Read from stdin until ^EOF$ and overwrite hello.py with the lines +# between "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Run hello.py with various stdin, stdout, and stderr redirections: +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# The output error will overwrite the file if it exists, +# if you want to append instead, use ">>": +python hello.py >> "output.out" 2>> "error.err" + +# Overwrite output.txt, append to error.err, and count lines: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Run a command and print its file descriptor (e.g. /dev/fd/123) +# see: man fd +echo <(echo "#helloworld") + +# Overwrite output.txt with "#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Cleanup temporary files verbosely (add '-i' for interactive) +rm -v output.out error.err output-and-error.log # Commands can be substituted within other commands using $( ): # The following command displays the number of files and directories in the -- cgit v1.2.3 From 34fac1cf65a550c894192d6bee4fd01f2ae63c88 Mon Sep 17 00:00:00 2001 From: m90 Date: Sat, 1 Nov 2014 20:18:11 +0100 Subject: casing fix --- de-de/javascript-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index 851fe852..a295c1c2 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -463,7 +463,7 @@ MyConstructor.prototype = { return this.myNumber } }; -var myNewObj2 = new myConstructor(); +var myNewObj2 = new MyConstructor(); myNewObj2.getMyNumber(); // = 5 // Alle primitiven Typen, also strings und numbers, haben auch Konstruktoren, -- cgit v1.2.3 From 494d97c4ee624f384ce771bc06f14d53ffecfca9 Mon Sep 17 00:00:00 2001 From: Sergey Date: Sat, 1 Nov 2014 22:32:51 +0300 Subject: [Java] Maps description little fix. --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 478d85d6..f08c4679 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -126,7 +126,7 @@ public class LearnJava { // LinkedLists - Implementation of doubly-linked list. All of the // operations perform as could be expected for // a doubly-linked list. - // Maps - An objects that maps keys to values. A map cannot contain + // Maps - A set of objects that maps keys to values. A map cannot contain // duplicate keys; each key can map to at most one value. // HashMaps - This class uses a hashtable to implement the Map interface. // This allows the execution time of basic operations, -- cgit v1.2.3 From 56d86a244e93741535d6c5212f0378c105179745 Mon Sep 17 00:00:00 2001 From: Wes Turner Date: Sun, 2 Nov 2014 04:52:31 -0600 Subject: [c/en] Typo: integral -> integer --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 6daabe94..874197d3 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -84,7 +84,7 @@ int main() { // doubles are usually 64-bit floating-point numbers double x_double = 0.0; // real numbers without any suffix are doubles - // Integral types may be unsigned. + // integer types may be unsigned (only positive) unsigned short ux_short; unsigned int ux_int; unsigned long long ux_long_long; -- cgit v1.2.3 From c2f107ed4249921558703bc135c4ecc8b00e300c Mon Sep 17 00:00:00 2001 From: Sergey Date: Mon, 3 Nov 2014 19:03:10 +0300 Subject: [Java] Added Russian translation. --- ru-ru/java-ru.html.markdown | 504 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 504 insertions(+) create mode 100644 ru-ru/java-ru.html.markdown diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown new file mode 100644 index 00000000..9aee90b9 --- /dev/null +++ b/ru-ru/java-ru.html.markdown @@ -0,0 +1,504 @@ +--- + +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Madison Dickson", "http://github.com/mix3d"] +filename: LearnJava.java + +--- + +Java - это объектно ориентированный язык общего назначения. +[Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html) + +```java +// Однострочные комментарии начинаются с //. +/* +Многострочные комментарии +выглядят так. +*/ +/** +JavaDoc-комментарии выглядят так. Они используются для описания класса +и его членов. +*/ + +// Импорт класса ArrayList в пакет java.util. +import java.util.ArrayList; +// Импорт всех классов из пакета java.security. +import java.security.*; + +// Каждый .java файл содержит один публичный класс, имя которого совпадает с +// именем файла. +public class LearnJava { + + // Программа должна содержать метод main, который является точкой входа. + public static void main (String[] args) { + + // System.out.println используется для печати строк. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Чтобы напечатать что-либо не начиная с новой строки + // используется System.out.print. + System.out.print("Hello "); + System.out.print("World"); + + + /////////////////////////////////////// + // Типы и Переменные + /////////////////////////////////////// + + // Переменне объявляются с использованием <тип> <имя> + // Byte - 8-битное целое число. + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 16-битное целое число. + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 32-битное целое число. + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 64-битное целое число. + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L используется для указания на то, что переменная имеет тип long; + // По умолчанию, числа без L являются integer. + + // Замечание: в Java нет беззнаковых типов. + + // Float - 32-битное IEEE 754 число с плавающей запятой с одинарной степенью точности. + float fooFloat = 234.5f; + // f используется для указания на то, что переменная имеет тип float; + // иначе, число являлось бы double. + + // Double - 64-битное IEEE 754 число с плавающей запятой с двойной степенью точности. + double fooDouble = 123.4; + + // Boolean - true или false + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - Простой 16-битный символ Unicode. + char fooChar = 'A'; + + // Переменным final не может быть присвоен другой объект. + final int HOURS_I_WORK_PER_WEEK = 9001; + + // Строки. + String fooString = "My String Is Here!"; + + // \n - это не печатаемый символ, который означает начало новой строки. + String barString = "Printing on a new line?\nNo Problem!"; + // \t - это непечатаемый символ, который добавляет символ табуляции. + String bazString = "Do you want to add a tab?\tNo Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Массивы + // Размер массива должен быт указан при объявлении. + // Объявлять массив можно в следующих форматах: + //<тип данных> [] <имя> = new <тип данных>[<размер массива>]; + //<тип данных> <имя>[] = new <тип данных>[<размер массива>]; + int [] intArray = new int[10]; + String [] stringArray = new String[1]; + boolean boolArray [] = new boolean[100]; + + // Другой способ объявления и инициализации массива: + int [] y = {9000, 1000, 1337}; + String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Индексация массива - доступ к элементу. + System.out.println("intArray @ 0: " + intArray[0]); + + // Массивы изменяемы и индекс в них начинается с 0. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Дополнительно. + // ArrayLists - похож на массив, но предлагает больше возможностей, + // его размер изменяемый. + // LinkedLists - реализация двусвязного списка. Все операции + // выполняются так, как ожидается от двусвязного + // списка. + // Maps - набор объектов, в которых присутствует связь + // ключ-значение. В Map ключ не может дублироваться. + // Каждый ключ связан только с одним значением. + // HashMaps - этот класс использует хэш-таблицу для реализации + // интерфейса Map. Это позволяет сохранить постоянной + // скорость выполнения базовых операций, таких как + // добавление и удаление элементов, вне зависимости + // от размера множества. + + /////////////////////////////////////// + // Операторы + /////////////////////////////////////// + System.out.println("\n->Операторы"); + + int i1 = 1, i2 = 2; // Сокращение для множественного объявления. + + // Арифметика в Java проста. + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 округлено) + + // Остаток от деления + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Операторы сравнения. + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Побитовые операторы! + /* + ~ Унарное побитовое дополнение. + << Знаковый сдвиг влево. + >> Знаковый сдвиг вправо. + >>> Беззнаковый сдвиг вправо. + & Побитовое И. + ^ Побитовое исключающее ИЛИ. + | Побитовое И. + */ + + // Операторы инкремента. + int i = 0; + System.out.println("\n->Inc/Dec-rementation"); + // Операторы ++ и -- увеличивают и уменьшают значение на 1 соответственно. + // Если они находятся перед переменной, сначала происходит + // увеличение/уменьшение, затем операция, если после, + // то сначала выполняется операция, затем увеличение/уменьшение. + System.out.println(i++); //i = 1, prints 0 (post-increment) + System.out.println(++i); //i = 2, prints 2 (pre-increment) + System.out.println(i--); //i = 1, prints 2 (post-decrement) + System.out.println(--i); //i = 0, prints 0 (pre-decrement) + + /////////////////////////////////////// + // Контролирующие операторы. + /////////////////////////////////////// + System.out.println("\n->Контролирующие операторы"); + + // Оператор if такой-же, как и в С. + int j = 10; + if (j == 10){ + System.out.println("Я напечатаюсь!"); + } else if (j > 10) { + System.out.println("Я нет."); + } else { + System.out.println("И я тоже нет."); + } + + // Цикл while. + int fooWhile = 0; + while(fooWhile < 100) + { + // System.out.println(fooWhile); + // Увеличить счетчик. + // Будет пройдено 100 итераций, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("Значение fooWhile: " + fooWhile); + + // Цикл Do While. + int fooDoWhile = 0; + do + { + // System.out.println(fooDoWhile); + // Увеличить счетчик. + // Будет пройдено 100 итераций, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("Значение fooDoWhile: " + fooDoWhile); + + // Цикл for. + int fooFor; + // Структура цикла for => for(<начальное_состояние>; <условие>; <шаг>) + for(fooFor=0; fooFor<10; fooFor++){ + // System.out.println(fooFor); + // Пройдет 10 итераций., fooFor 0->9 + } + System.out.println("Значение fooFor: " + fooFor); + + // Цикл For Each + // Автоматический проход через массив или список объектов. + int[] fooList = {1,2,3,4,5,6,7,8,9}; + // Структура цикла for each => for(<объект> : <объект_массив>) + //reads as: for each object in the array + //note: the object type must match the array. + + for( int bar : fooList ){ + System.out.println(bar); + //Пройдет 9 итераций и напечатает 1-9 на новых строках. + } + + // Switch Case + // switch работает с типами byte, short, char и int. + // Так же он работает с перечислениями, + // классом String, и с некоторыми классами-обертками над + // примитивными типами: Character, Byte, Short, и Integer. + int month = 3; + String monthString; + switch (month){ + case 1: + monthString = "Январь"; + break; + case 2: + monthString = "Февраль"; + break; + case 3: + monthString = "Март"; + break; + default: + monthString = "Другой месяц"; + break; + } + System.out.println("Результат Switch Case: " + monthString); + + // Сокращенный синтаксис. + // Вы можете использовать этот синтаксис для быстрого присвоения + // или логических переходов. + // Читается так "Если (условие) истинно, использовать <значение 1>, + // в ином случае, использовать <значение 2>" + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Напечатает А, потому что условие истинно + + + /////////////////////////////////////// + // Преобразование и приведение типов данных. + /////////////////////////////////////// + + // Преобразование данных. + + // Преобразование строки в число. + Integer.parseInt("123"); // Вернет числовое представление "123". + + // Преобразование числа в строку + Integer.toString(123); // Вернет строковое представление 123. + + // Для других преобразований, смотрите следующие классы: + // Double + // Long + // String + + // Приведение типов + // Вы так же можете приводить типы в Java. + // Подробнее об этом можно узнать по ссылке: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Классы и Функции + /////////////////////////////////////// + + System.out.println("\n->Классы и Функции"); + + // (Класс Bicycle определен ниже) + + // Для создания экземпляра класса используется new. + Bicycle trek = new Bicycle(); + + // Вызов методов объекта. + trek.speedUp(3); // Вы должны всегда использовать сеттеры и геттеры. + trek.setCadence(100); + + // toString возвращает строковое представление объекта. + System.out.println("trek info: " + trek.toString()); + + } // Конец метода main. +} // Конец класса LearnJava. + + +// Вы можете включать другие, не публичные классы в .java файл. + + +// Синтаксис объявления класса: +// class <имя класса>{ +// // Поля с данными, конструкторы, функции, все внутри. +// // Функции называют методами в Java. +// } + +class Bicycle { + + // Поля/Переменные класса Bicycle. + public int cadence;// Публичные(public): Доступны из любого места. + private int speed; // Приватные(private): Доступны только внутри класса. + protected int gear;// Защищенные(protected): Доступ из класса и наследников. + String name; // по умолчанию: Доступны только внутри пакета. + + // Конструкторы - способ создания класса. + // Это конструктор: + public Bicycle() { + gear = 1; + cadence = 50; + speed = 5; + name = "Bontrager"; + } + + // Это конструктор, который принимает аргументы: + public Bicycle(int startCadence, int startSpeed, int startGear, String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // Синтаксис функций: + // <тип возвращаемого значения> <имя>(<аргументы>) + + // Классы в Java часто реализуют сеттеры и геттеры для своих полей. + + // Синтаксис определения метода: + // <модификатор> <тип возвращаемого значения> <имя>(<аргументы>) + public int getCadence() { + return cadence; + } + + // void-методы не возвращают значений. + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Метод для отображения значений атрибутов объекта. + @Override + public String toString() { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + speed + + " name: " + name; + } +} // конец класса Bicycle. + +// PennyFarthing - это класс, наследованный от Bicycle +class PennyFarthing extends Bicycle { + // (Penny Farthings - это такие велосипеды с большим передним колесом, + // у низ нет передач.) + + public PennyFarthing(int startCadence, int startSpeed){ + // Вызов конструктора родительского класса. + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // Вы должны пометить метод, который переопределяете при помощи @аннотации + // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте? + // http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + gear = 0; + } + +} + +// Интерфейсы +// Синтаксис определения интерфейса: +// <модификатор доступа> interface <имя> extends <базовый интерфейс> { +// // Константы +// // Определение методов. +//} + +// Пример - Еда: +public interface Edible { + // Любой класс, реализующий этот интерфейс, должен реализовать этот метод. + public void eat(); +} + +public interface Digestible { + public void digest(); +} + + +//We can now create a class that implements both of these interfaces +public class Fruit implements Edible, Digestible { + public void eat() { + //... + } + + public void digest() { + //... + } +} + +// В Java Вы можете наследоватьтолько один класс, однако, можете реализовывать +// несколько интерфейсов. Например: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { + public void InterfaceOneMethod() { + + } + + public void InterfaceTwoMethod() { + + } +} + +``` + +## Почитать еще + +Здесь приведены ссылки только для того, чтобы получить общее представление о Java. Гуглите, чтобы найти какие-либо конкретные примеры. + +**Официальные руководства Oracle**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Модификаторы доступа в Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Концепции объектно-ориентированного программирования](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Наследование](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Полиморфизм](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Абстракция](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Исключения](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Интерфейсы](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + +**Уроки онлайн** + +* [Learneroo.com - Изучение Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Книги**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) + + -- cgit v1.2.3 From 8c387c4ffadbcd32cc24df5202804459dbd0b83c Mon Sep 17 00:00:00 2001 From: Sergey Date: Mon, 3 Nov 2014 20:05:15 +0300 Subject: Little fixes. --- ru-ru/java-ru.html.markdown | 504 -------------------------------------- ru-ru/learnjava-ru.html.markdown | 506 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 506 insertions(+), 504 deletions(-) delete mode 100644 ru-ru/java-ru.html.markdown create mode 100644 ru-ru/learnjava-ru.html.markdown diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown deleted file mode 100644 index 9aee90b9..00000000 --- a/ru-ru/java-ru.html.markdown +++ /dev/null @@ -1,504 +0,0 @@ ---- - -language: java -contributors: - - ["Jake Prather", "http://github.com/JakeHP"] - - ["Madison Dickson", "http://github.com/mix3d"] -filename: LearnJava.java - ---- - -Java - это объектно ориентированный язык общего назначения. -[Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html) - -```java -// Однострочные комментарии начинаются с //. -/* -Многострочные комментарии -выглядят так. -*/ -/** -JavaDoc-комментарии выглядят так. Они используются для описания класса -и его членов. -*/ - -// Импорт класса ArrayList в пакет java.util. -import java.util.ArrayList; -// Импорт всех классов из пакета java.security. -import java.security.*; - -// Каждый .java файл содержит один публичный класс, имя которого совпадает с -// именем файла. -public class LearnJava { - - // Программа должна содержать метод main, который является точкой входа. - public static void main (String[] args) { - - // System.out.println используется для печати строк. - System.out.println("Hello World!"); - System.out.println( - "Integer: " + 10 + - " Double: " + 3.14 + - " Boolean: " + true); - - // Чтобы напечатать что-либо не начиная с новой строки - // используется System.out.print. - System.out.print("Hello "); - System.out.print("World"); - - - /////////////////////////////////////// - // Типы и Переменные - /////////////////////////////////////// - - // Переменне объявляются с использованием <тип> <имя> - // Byte - 8-битное целое число. - // (-128 <= byte <= 127) - byte fooByte = 100; - - // Short - 16-битное целое число. - // (-32,768 <= short <= 32,767) - short fooShort = 10000; - - // Integer - 32-битное целое число. - // (-2,147,483,648 <= int <= 2,147,483,647) - int fooInt = 1; - - // Long - 64-битное целое число. - // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - long fooLong = 100000L; - // L используется для указания на то, что переменная имеет тип long; - // По умолчанию, числа без L являются integer. - - // Замечание: в Java нет беззнаковых типов. - - // Float - 32-битное IEEE 754 число с плавающей запятой с одинарной степенью точности. - float fooFloat = 234.5f; - // f используется для указания на то, что переменная имеет тип float; - // иначе, число являлось бы double. - - // Double - 64-битное IEEE 754 число с плавающей запятой с двойной степенью точности. - double fooDouble = 123.4; - - // Boolean - true или false - boolean fooBoolean = true; - boolean barBoolean = false; - - // Char - Простой 16-битный символ Unicode. - char fooChar = 'A'; - - // Переменным final не может быть присвоен другой объект. - final int HOURS_I_WORK_PER_WEEK = 9001; - - // Строки. - String fooString = "My String Is Here!"; - - // \n - это не печатаемый символ, который означает начало новой строки. - String barString = "Printing on a new line?\nNo Problem!"; - // \t - это непечатаемый символ, который добавляет символ табуляции. - String bazString = "Do you want to add a tab?\tNo Problem!"; - System.out.println(fooString); - System.out.println(barString); - System.out.println(bazString); - - // Массивы - // Размер массива должен быт указан при объявлении. - // Объявлять массив можно в следующих форматах: - //<тип данных> [] <имя> = new <тип данных>[<размер массива>]; - //<тип данных> <имя>[] = new <тип данных>[<размер массива>]; - int [] intArray = new int[10]; - String [] stringArray = new String[1]; - boolean boolArray [] = new boolean[100]; - - // Другой способ объявления и инициализации массива: - int [] y = {9000, 1000, 1337}; - String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; - boolean bools[] = new boolean[] {true, false, false}; - - // Индексация массива - доступ к элементу. - System.out.println("intArray @ 0: " + intArray[0]); - - // Массивы изменяемы и индекс в них начинается с 0. - intArray[1] = 1; - System.out.println("intArray @ 1: " + intArray[1]); // => 1 - - // Дополнительно. - // ArrayLists - похож на массив, но предлагает больше возможностей, - // его размер изменяемый. - // LinkedLists - реализация двусвязного списка. Все операции - // выполняются так, как ожидается от двусвязного - // списка. - // Maps - набор объектов, в которых присутствует связь - // ключ-значение. В Map ключ не может дублироваться. - // Каждый ключ связан только с одним значением. - // HashMaps - этот класс использует хэш-таблицу для реализации - // интерфейса Map. Это позволяет сохранить постоянной - // скорость выполнения базовых операций, таких как - // добавление и удаление элементов, вне зависимости - // от размера множества. - - /////////////////////////////////////// - // Операторы - /////////////////////////////////////// - System.out.println("\n->Операторы"); - - int i1 = 1, i2 = 2; // Сокращение для множественного объявления. - - // Арифметика в Java проста. - System.out.println("1+2 = " + (i1 + i2)); // => 3 - System.out.println("2-1 = " + (i2 - i1)); // => 1 - System.out.println("2*1 = " + (i2 * i1)); // => 2 - System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 округлено) - - // Остаток от деления - System.out.println("11%3 = "+(11 % 3)); // => 2 - - // Операторы сравнения. - System.out.println("3 == 2? " + (3 == 2)); // => false - System.out.println("3 != 2? " + (3 != 2)); // => true - System.out.println("3 > 2? " + (3 > 2)); // => true - System.out.println("3 < 2? " + (3 < 2)); // => false - System.out.println("2 <= 2? " + (2 <= 2)); // => true - System.out.println("2 >= 2? " + (2 >= 2)); // => true - - // Побитовые операторы! - /* - ~ Унарное побитовое дополнение. - << Знаковый сдвиг влево. - >> Знаковый сдвиг вправо. - >>> Беззнаковый сдвиг вправо. - & Побитовое И. - ^ Побитовое исключающее ИЛИ. - | Побитовое И. - */ - - // Операторы инкремента. - int i = 0; - System.out.println("\n->Inc/Dec-rementation"); - // Операторы ++ и -- увеличивают и уменьшают значение на 1 соответственно. - // Если они находятся перед переменной, сначала происходит - // увеличение/уменьшение, затем операция, если после, - // то сначала выполняется операция, затем увеличение/уменьшение. - System.out.println(i++); //i = 1, prints 0 (post-increment) - System.out.println(++i); //i = 2, prints 2 (pre-increment) - System.out.println(i--); //i = 1, prints 2 (post-decrement) - System.out.println(--i); //i = 0, prints 0 (pre-decrement) - - /////////////////////////////////////// - // Контролирующие операторы. - /////////////////////////////////////// - System.out.println("\n->Контролирующие операторы"); - - // Оператор if такой-же, как и в С. - int j = 10; - if (j == 10){ - System.out.println("Я напечатаюсь!"); - } else if (j > 10) { - System.out.println("Я нет."); - } else { - System.out.println("И я тоже нет."); - } - - // Цикл while. - int fooWhile = 0; - while(fooWhile < 100) - { - // System.out.println(fooWhile); - // Увеличить счетчик. - // Будет пройдено 100 итераций, fooWhile 0,1,2...99 - fooWhile++; - } - System.out.println("Значение fooWhile: " + fooWhile); - - // Цикл Do While. - int fooDoWhile = 0; - do - { - // System.out.println(fooDoWhile); - // Увеличить счетчик. - // Будет пройдено 100 итераций, fooDoWhile 0->99 - fooDoWhile++; - } while(fooDoWhile < 100); - System.out.println("Значение fooDoWhile: " + fooDoWhile); - - // Цикл for. - int fooFor; - // Структура цикла for => for(<начальное_состояние>; <условие>; <шаг>) - for(fooFor=0; fooFor<10; fooFor++){ - // System.out.println(fooFor); - // Пройдет 10 итераций., fooFor 0->9 - } - System.out.println("Значение fooFor: " + fooFor); - - // Цикл For Each - // Автоматический проход через массив или список объектов. - int[] fooList = {1,2,3,4,5,6,7,8,9}; - // Структура цикла for each => for(<объект> : <объект_массив>) - //reads as: for each object in the array - //note: the object type must match the array. - - for( int bar : fooList ){ - System.out.println(bar); - //Пройдет 9 итераций и напечатает 1-9 на новых строках. - } - - // Switch Case - // switch работает с типами byte, short, char и int. - // Так же он работает с перечислениями, - // классом String, и с некоторыми классами-обертками над - // примитивными типами: Character, Byte, Short, и Integer. - int month = 3; - String monthString; - switch (month){ - case 1: - monthString = "Январь"; - break; - case 2: - monthString = "Февраль"; - break; - case 3: - monthString = "Март"; - break; - default: - monthString = "Другой месяц"; - break; - } - System.out.println("Результат Switch Case: " + monthString); - - // Сокращенный синтаксис. - // Вы можете использовать этот синтаксис для быстрого присвоения - // или логических переходов. - // Читается так "Если (условие) истинно, использовать <значение 1>, - // в ином случае, использовать <значение 2>" - int foo = 5; - String bar = (foo < 10) ? "A" : "B"; - System.out.println(bar); // Напечатает А, потому что условие истинно - - - /////////////////////////////////////// - // Преобразование и приведение типов данных. - /////////////////////////////////////// - - // Преобразование данных. - - // Преобразование строки в число. - Integer.parseInt("123"); // Вернет числовое представление "123". - - // Преобразование числа в строку - Integer.toString(123); // Вернет строковое представление 123. - - // Для других преобразований, смотрите следующие классы: - // Double - // Long - // String - - // Приведение типов - // Вы так же можете приводить типы в Java. - // Подробнее об этом можно узнать по ссылке: - // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html - - - /////////////////////////////////////// - // Классы и Функции - /////////////////////////////////////// - - System.out.println("\n->Классы и Функции"); - - // (Класс Bicycle определен ниже) - - // Для создания экземпляра класса используется new. - Bicycle trek = new Bicycle(); - - // Вызов методов объекта. - trek.speedUp(3); // Вы должны всегда использовать сеттеры и геттеры. - trek.setCadence(100); - - // toString возвращает строковое представление объекта. - System.out.println("trek info: " + trek.toString()); - - } // Конец метода main. -} // Конец класса LearnJava. - - -// Вы можете включать другие, не публичные классы в .java файл. - - -// Синтаксис объявления класса: -// class <имя класса>{ -// // Поля с данными, конструкторы, функции, все внутри. -// // Функции называют методами в Java. -// } - -class Bicycle { - - // Поля/Переменные класса Bicycle. - public int cadence;// Публичные(public): Доступны из любого места. - private int speed; // Приватные(private): Доступны только внутри класса. - protected int gear;// Защищенные(protected): Доступ из класса и наследников. - String name; // по умолчанию: Доступны только внутри пакета. - - // Конструкторы - способ создания класса. - // Это конструктор: - public Bicycle() { - gear = 1; - cadence = 50; - speed = 5; - name = "Bontrager"; - } - - // Это конструктор, который принимает аргументы: - public Bicycle(int startCadence, int startSpeed, int startGear, String name) { - this.gear = startGear; - this.cadence = startCadence; - this.speed = startSpeed; - this.name = name; - } - - // Синтаксис функций: - // <тип возвращаемого значения> <имя>(<аргументы>) - - // Классы в Java часто реализуют сеттеры и геттеры для своих полей. - - // Синтаксис определения метода: - // <модификатор> <тип возвращаемого значения> <имя>(<аргументы>) - public int getCadence() { - return cadence; - } - - // void-методы не возвращают значений. - public void setCadence(int newValue) { - cadence = newValue; - } - - public void setGear(int newValue) { - gear = newValue; - } - - public void speedUp(int increment) { - speed += increment; - } - - public void slowDown(int decrement) { - speed -= decrement; - } - - public void setName(String newName) { - name = newName; - } - - public String getName() { - return name; - } - - //Метод для отображения значений атрибутов объекта. - @Override - public String toString() { - return "gear: " + gear + - " cadence: " + cadence + - " speed: " + speed + - " name: " + name; - } -} // конец класса Bicycle. - -// PennyFarthing - это класс, наследованный от Bicycle -class PennyFarthing extends Bicycle { - // (Penny Farthings - это такие велосипеды с большим передним колесом, - // у низ нет передач.) - - public PennyFarthing(int startCadence, int startSpeed){ - // Вызов конструктора родительского класса. - super(startCadence, startSpeed, 0, "PennyFarthing"); - } - - // Вы должны пометить метод, который переопределяете при помощи @аннотации - // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте? - // http://docs.oracle.com/javase/tutorial/java/annotations/ - @Override - public void setGear(int gear) { - gear = 0; - } - -} - -// Интерфейсы -// Синтаксис определения интерфейса: -// <модификатор доступа> interface <имя> extends <базовый интерфейс> { -// // Константы -// // Определение методов. -//} - -// Пример - Еда: -public interface Edible { - // Любой класс, реализующий этот интерфейс, должен реализовать этот метод. - public void eat(); -} - -public interface Digestible { - public void digest(); -} - - -//We can now create a class that implements both of these interfaces -public class Fruit implements Edible, Digestible { - public void eat() { - //... - } - - public void digest() { - //... - } -} - -// В Java Вы можете наследоватьтолько один класс, однако, можете реализовывать -// несколько интерфейсов. Например: -public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { - public void InterfaceOneMethod() { - - } - - public void InterfaceTwoMethod() { - - } -} - -``` - -## Почитать еще - -Здесь приведены ссылки только для того, чтобы получить общее представление о Java. Гуглите, чтобы найти какие-либо конкретные примеры. - -**Официальные руководства Oracle**: - -* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) - -* [Модификаторы доступа в Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) - -* [Концепции объектно-ориентированного программирования](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): - * [Наследование](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) - * [Полиморфизм](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) - * [Абстракция](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) - -* [Исключения](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) - -* [Интерфейсы](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) - -* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) - -* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) - -**Уроки онлайн** - -* [Learneroo.com - Изучение Java](http://www.learneroo.com) - -* [Codingbat.com](http://codingbat.com/java) - - -**Книги**: - -* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) - -* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) - -* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) - - diff --git a/ru-ru/learnjava-ru.html.markdown b/ru-ru/learnjava-ru.html.markdown new file mode 100644 index 00000000..b429f06d --- /dev/null +++ b/ru-ru/learnjava-ru.html.markdown @@ -0,0 +1,506 @@ +--- + +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Madison Dickson", "http://github.com/mix3d"] +translators: + - ["Sergey Gaykov", "https://github.com/gaykov"] +filename: LearnJava.java + +--- + +Java - это объектно ориентированный язык общего назначения. +[Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html) + +```java +// Однострочные комментарии начинаются с //. +/* +Многострочные комментарии +выглядят так. +*/ +/** +JavaDoc-комментарии выглядят так. Они используются для описания класса +и его членов. +*/ + +// Импорт класса ArrayList из пакета java.util. +import java.util.ArrayList; +// Импорт всех классов из пакета java.security. +import java.security.*; + +// Каждый .java файл содержит один публичный класс, имя которого совпадает с +// именем файла. +public class LearnJava { + + // Программа должна содержать метод main, который является точкой входа. + public static void main (String[] args) { + + // System.out.println используется для печати строк. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Чтобы напечатать что-либо не заканчивая переводом строки + // используется System.out.print. + System.out.print("Hello "); + System.out.print("World"); + + + /////////////////////////////////////// + // Типы и Переменные + /////////////////////////////////////// + + // Переменные объявляются с использованием <тип> <имя> + // Byte - 8-битное целое число. + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 16-битное целое число. + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 32-битное целое число. + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 64-битное целое число. + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L используется для указания на то, что переменная имеет тип long; + // По умолчанию, числа без L являются integer. + + // Замечание: в Java нет беззнаковых типов. + + // Float - 32-битное IEEE 754 число с плавающей запятой с одинарной степенью точности. + float fooFloat = 234.5f; + // f используется для указания на то, что переменная имеет тип float; + // иначе, число являлось бы double. + + // Double - 64-битное IEEE 754 число с плавающей запятой с двойной степенью точности. + double fooDouble = 123.4; + + // Boolean - true или false + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - Простой 16-битный символ Unicode. + char fooChar = 'A'; + + // Переменным final не может быть присвоен другой объект. + final int HOURS_I_WORK_PER_WEEK = 9001; + + // Строки. + String fooString = "My String Is Here!"; + + // \n - это экранированный символ, который означает начало новой строки. + String barString = "Printing on a new line?\nNo Problem!"; + // \t - это экранированный символ, который добавляет символ табуляции. + String bazString = "Do you want to add a tab?\tNo Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Массивы + // Размер массива должен быть указан при объявлении. + // Объявлять массив можно в следующих форматах: + //<тип данных> [] <имя> = new <тип данных>[<размер массива>]; + //<тип данных> <имя>[] = new <тип данных>[<размер массива>]; + int [] intArray = new int[10]; + String [] stringArray = new String[1]; + boolean boolArray [] = new boolean[100]; + + // Другой способ объявления и инициализации массива: + int [] y = {9000, 1000, 1337}; + String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Индексация массива - доступ к элементу. + System.out.println("intArray @ 0: " + intArray[0]); + + // Массивы изменяемы и индекс в них начинается с 0. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Дополнительно. + // ArrayLists - похож на массив, но предлагает больше возможностей, + // его размер изменяемый. + // LinkedLists - реализация двусвязного списка. Все операции + // выполняются так, как ожидается от двусвязного + // списка. + // Maps - набор объектов, в которых присутствует связь + // ключ-значение. В Map ключ не может дублироваться. + // Каждый ключ связан только с одним значением. + // HashMaps - этот класс использует хэш-таблицу для реализации + // интерфейса Map. Это позволяет сохранить постоянной + // скорость выполнения базовых операций, таких как + // добавление и удаление элементов, вне зависимости + // от размера множества. + + /////////////////////////////////////// + // Операторы + /////////////////////////////////////// + System.out.println("\n->Операторы"); + + int i1 = 1, i2 = 2; // Сокращение для множественного объявления. + + // Арифметика в Java проста. + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 округлено) + + // Остаток от деления + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Операторы сравнения. + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Побитовые операторы! + /* + ~ Унарное побитовое дополнение. + << Знаковый сдвиг влево. + >> Знаковый сдвиг вправо. + >>> Беззнаковый сдвиг вправо. + & Побитовое И. + ^ Побитовое исключающее ИЛИ. + | Побитовое И. + */ + + // Операторы инкремента. + int i = 0; + System.out.println("\n->Inc/Dec-rementation"); + // Операторы ++ и -- увеличивают и уменьшают значение на 1 соответственно. + // Если они находятся перед переменной, сначала происходит + // увеличение/уменьшение, затем операция, если после, + // то сначала выполняется операция, затем увеличение/уменьшение. + System.out.println(i++); //i = 1, напечатает 0 (пре-инкремент) + System.out.println(++i); //i = 2, напечатает 2 (пре-инкремент) + System.out.println(i--); //i = 1, напечатает 2 (пост-декремент) + System.out.println(--i); //i = 0, напечатает 0 (пре-декремент) + + /////////////////////////////////////// + // Контролирующие операторы. + /////////////////////////////////////// + System.out.println("\n->Контролирующие операторы"); + + // Оператор if такой же, как и в С. + int j = 10; + if (j == 10){ + System.out.println("Я напечатаюсь!"); + } else if (j > 10) { + System.out.println("Я нет."); + } else { + System.out.println("И я тоже нет."); + } + + // Цикл while. + int fooWhile = 0; + while(fooWhile < 100) + { + // System.out.println(fooWhile); + // Увеличить счетчик. + // Будет пройдено 100 итераций, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("Значение fooWhile: " + fooWhile); + + // Цикл Do While. + int fooDoWhile = 0; + do + { + // System.out.println(fooDoWhile); + // Увеличить счетчик. + // Будет пройдено 100 итераций, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("Значение fooDoWhile: " + fooDoWhile); + + // Цикл for. + int fooFor; + // Структура цикла for => for(<начальное_состояние>; <условие>; <шаг>) + for(fooFor=0; fooFor<10; fooFor++){ + // System.out.println(fooFor); + // Пройдет 10 итераций., fooFor 0->9 + } + System.out.println("Значение fooFor: " + fooFor); + + // Цикл For Each + // Автоматический проход через массив или список объектов. + int[] fooList = {1,2,3,4,5,6,7,8,9}; + // Структура цикла for each => for(<объект> : <объект_массив>) + // читается как: для каждого объекта в массиве + // заметка: тип объекта должен совпадать с типом массива. + + for( int bar : fooList ){ + System.out.println(bar); + //Пройдет 9 итераций и напечатает 1-9 на новых строках. + } + + // Switch Case + // switch работает с типами byte, short, char и int. + // Также он работает с перечислениями, + // классом String и с некоторыми классами-обертками над + // примитивными типами: Character, Byte, Short и Integer. + int month = 3; + String monthString; + switch (month){ + case 1: + monthString = "Январь"; + break; + case 2: + monthString = "Февраль"; + break; + case 3: + monthString = "Март"; + break; + default: + monthString = "Другой месяц"; + break; + } + System.out.println("Результат Switch Case: " + monthString); + + // Сокращенный синтаксис условного оператора. + // Вы можете использовать этот синтаксис для быстрого присвоения + // или логических переходов. + // Читается так: "Если (условие) истинно, использовать <значение 1>, + // в ином случае, использовать <значение 2>" + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Напечатает А, потому что условие истинно + + + /////////////////////////////////////// + // Преобразование и приведение типов данных. + /////////////////////////////////////// + + // Преобразование данных. + + // Преобразование строки в число. + Integer.parseInt("123"); // Вернет числовое представление "123". + + // Преобразование числа в строку + Integer.toString(123); // Вернет строковое представление 123. + + // Для других преобразований, смотрите следующие классы: + // Double + // Long + // String + + // Приведение типов + // Вы так же можете приводить типы в Java. + // Подробнее об этом можно узнать по ссылке: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Классы и Функции + /////////////////////////////////////// + + System.out.println("\n->Классы и Функции"); + + // (Класс Bicycle определен ниже) + + // Для создания экземпляра класса используется new. + Bicycle trek = new Bicycle(); + + // Вызов методов объекта. + trek.speedUp(3); // Вы должны всегда использовать сеттеры и геттеры. + trek.setCadence(100); + + // toString возвращает строковое представление объекта. + System.out.println("trek info: " + trek.toString()); + + } // Конец метода main. +} // Конец класса LearnJava. + + +// Вы можете включать другие, не публичные классы в .java файл. + + +// Синтаксис объявления класса: +// class <имя класса>{ +// // Поля с данными, конструкторы, функции, все внутри. +// // Функции называют методами в Java. +// } + +class Bicycle { + + // Поля/Переменные класса Bicycle. + public int cadence;// Публичные(public): Доступны из любого места. + private int speed; // Приватные(private): Доступны только внутри класса. + protected int gear;// Защищенные(protected): Доступ из класса и наследников. + String name; // по умолчанию: Доступны только внутри пакета. + + // Конструкторы - способ создания класса. + // Это конструктор: + public Bicycle() { + gear = 1; + cadence = 50; + speed = 5; + name = "Bontrager"; + } + + // Это конструктор, который принимает аргументы: + public Bicycle(int startCadence, int startSpeed, int startGear, String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // Синтаксис функций: + // <тип возвращаемого значения> <имя>(<аргументы>) + + // Классы в Java часто реализуют сеттеры и геттеры для своих полей. + + // Синтаксис определения метода: + // <модификатор> <тип возвращаемого значения> <имя>(<аргументы>) + public int getCadence() { + return cadence; + } + + // void-методы не возвращают значений. + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Метод для отображения значений атрибутов объекта. + @Override + public String toString() { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + speed + + " name: " + name; + } +} // конец класса Bicycle. + +// PennyFarthing - это класс, наследованный от Bicycle +class PennyFarthing extends Bicycle { + // (Penny Farthings - это такие велосипеды с большим передним колесом, + // у низ нет передач.) + + public PennyFarthing(int startCadence, int startSpeed){ + // Вызов конструктора родительского класса. + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // Вы должны пометить метод, который переопределяете при помощи @аннотации + // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте? + // http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + gear = 0; + } + +} + +// Интерфейсы +// Синтаксис определения интерфейса: +// <модификатор доступа> interface <имя> extends <базовый интерфейс> { +// // Константы +// // Определение методов. +//} + +// Пример - Еда: +public interface Edible { + // Любой класс, реализующий этот интерфейс, должен реализовать этот метод. + public void eat(); +} + +public interface Digestible { + public void digest(); +} + + +//We can now create a class that implements both of these interfaces +public class Fruit implements Edible, Digestible { + public void eat() { + //... + } + + public void digest() { + //... + } +} + +// В Java Вы можете наследоватьтолько один класс, однако, можете реализовывать +// несколько интерфейсов. Например: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { + public void InterfaceOneMethod() { + + } + + public void InterfaceTwoMethod() { + + } +} + +``` + +## Почитать еще + +Здесь приведены ссылки только для того, чтобы получить общее представление о Java. Гуглите, чтобы найти какие-либо конкретные примеры. + +**Официальные руководства Oracle**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Модификаторы доступа в Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Концепции объектно-ориентированного программирования](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Наследование](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Полиморфизм](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Абстракция](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Исключения](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Интерфейсы](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + +**Уроки онлайн** + +* [Learneroo.com - Изучение Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Книги**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) + + -- cgit v1.2.3 From 3cfb6018e95798b9abae873667a790977382e160 Mon Sep 17 00:00:00 2001 From: Sergey Date: Mon, 3 Nov 2014 20:34:26 +0300 Subject: Some fixes. --- ru-ru/java-ru.html.markdown | 506 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 506 insertions(+) create mode 100644 ru-ru/java-ru.html.markdown diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown new file mode 100644 index 00000000..20095542 --- /dev/null +++ b/ru-ru/java-ru.html.markdown @@ -0,0 +1,506 @@ +--- + +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Madison Dickson", "http://github.com/mix3d"] +translators: + - ["Sergey Gaykov", "https://github.com/gaykov"] +filename: LearnJava.java + +--- + +Java - это объектно ориентированный язык общего назначения. +[Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html) + +```java +// Однострочные комментарии начинаются с //. +/* +Многострочные комментарии +выглядят так. +*/ +/** +JavaDoc-комментарии выглядят так. Они используются для описания класса +и его членов. +*/ + +// Импорт класса ArrayList из пакета java.util. +import java.util.ArrayList; +// Импорт всех классов из пакета java.security. +import java.security.*; + +// Каждый .java файл содержит один публичный класс, имя которого совпадает с +// именем файла. +public class LearnJava { + + // Программа должна содержать метод main, который является точкой входа. + public static void main (String[] args) { + + // System.out.println используется для печати строк. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Чтобы напечатать что-либо не заканчивая переводом строки + // используется System.out.print. + System.out.print("Hello "); + System.out.print("World"); + + + /////////////////////////////////////// + // Типы и Переменные + /////////////////////////////////////// + + // Переменные объявляются с использованием <тип> <имя> + // Byte - 8-битное целое число. + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 16-битное целое число. + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 32-битное целое число. + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 64-битное целое число. + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L используется для указания на то, что переменная имеет тип long; + // По умолчанию, числа без L являются integer. + + // Замечание: в Java нет беззнаковых типов. + + // Float - 32-битное IEEE 754 число с плавающей запятой с одинарной степенью точности. + float fooFloat = 234.5f; + // f используется для указания на то, что переменная имеет тип float; + // иначе, число являлось бы double. + + // Double - 64-битное IEEE 754 число с плавающей запятой с двойной степенью точности. + double fooDouble = 123.4; + + // Boolean - true или false + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - Простой 16-битный символ Unicode. + char fooChar = 'A'; + + // Переменным final не может быть присвоен другой объект. + final int HOURS_I_WORK_PER_WEEK = 9001; + + // Строки. + String fooString = "My String Is Here!"; + + // \n - это экранированный символ, который означает начало новой строки. + String barString = "Printing on a new line?\nNo Problem!"; + // \t - это экранированный символ, который добавляет символ табуляции. + String bazString = "Do you want to add a tab?\tNo Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Массивы + // Размер массива должен быть указан при объявлении. + // Объявлять массив можно в следующих форматах: + //<тип данных> [] <имя> = new <тип данных>[<размер массива>]; + //<тип данных> <имя>[] = new <тип данных>[<размер массива>]; + int [] intArray = new int[10]; + String [] stringArray = new String[1]; + boolean boolArray [] = new boolean[100]; + + // Другой способ объявления и инициализации массива: + int [] y = {9000, 1000, 1337}; + String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Индексация массива - доступ к элементу. + System.out.println("intArray @ 0: " + intArray[0]); + + // Массивы изменяемы и индекс в них начинается с 0. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Дополнительно. + // ArrayLists - похож на массив, но предлагает больше возможностей, + // его размер изменяемый. + // LinkedLists - реализация двусвязного списка. Все операции + // выполняются так, как ожидается от двусвязного + // списка. + // Maps - набор объектов, в которых присутствует связь + // ключ-значение. В Map ключ не может дублироваться. + // Каждый ключ связан только с одним значением. + // HashMaps - этот класс использует хэш-таблицу для реализации + // интерфейса Map. Это позволяет сохранить постоянной + // скорость выполнения базовых операций, таких как + // добавление и удаление элементов, вне зависимости + // от размера множества. + + /////////////////////////////////////// + // Операторы + /////////////////////////////////////// + System.out.println("\n->Операторы"); + + int i1 = 1, i2 = 2; // Сокращение для множественного объявления. + + // Арифметика в Java проста. + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 округлено) + + // Остаток от деления + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Операторы сравнения. + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Побитовые операторы! + /* + ~ Унарное побитовое дополнение. + << Знаковый сдвиг влево. + >> Знаковый сдвиг вправо. + >>> Беззнаковый сдвиг вправо. + & Побитовое И. + ^ Побитовое исключающее ИЛИ. + | Побитовое И. + */ + + // Операторы инкремента. + int i = 0; + System.out.println("\n->Inc/Dec-rementation"); + // Операторы ++ и -- увеличивают и уменьшают значение на 1 соответственно. + // Если они находятся перед переменной, сначала происходит + // увеличение/уменьшение, затем операция, если после, + // то сначала выполняется операция, затем увеличение/уменьшение. + System.out.println(i++); //i = 1, напечатает 0 (пре-инкремент) + System.out.println(++i); //i = 2, напечатает 2 (пре-инкремент) + System.out.println(i--); //i = 1, напечатает 2 (пост-декремент) + System.out.println(--i); //i = 0, напечатает 0 (пре-декремент) + + /////////////////////////////////////// + // Контролирующие операторы. + /////////////////////////////////////// + System.out.println("\n->Контролирующие операторы"); + + // Оператор if такой же, как и в С. + int j = 10; + if (j == 10){ + System.out.println("Я напечатаюсь!"); + } else if (j > 10) { + System.out.println("Я нет."); + } else { + System.out.println("И я тоже нет."); + } + + // Цикл while. + int fooWhile = 0; + while(fooWhile < 100) + { + // System.out.println(fooWhile); + // Увеличить счетчик. + // Будет пройдено 100 итераций, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("Значение fooWhile: " + fooWhile); + + // Цикл Do While. + int fooDoWhile = 0; + do + { + // System.out.println(fooDoWhile); + // Увеличить счетчик. + // Будет пройдено 100 итераций, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("Значение fooDoWhile: " + fooDoWhile); + + // Цикл for. + int fooFor; + // Структура цикла for => for(<начальное_состояние>; <условие>; <шаг>) + for(fooFor=0; fooFor<10; fooFor++){ + // System.out.println(fooFor); + // Пройдет 10 итераций., fooFor 0->9 + } + System.out.println("Значение fooFor: " + fooFor); + + // Цикл For Each + // Автоматический проход через массив или список объектов. + int[] fooList = {1,2,3,4,5,6,7,8,9}; + // Структура цикла for each => for(<объект> : <объект_массив>) + // читается как: для каждого объекта в массиве + // заметка: тип объекта должен совпадать с типом массива. + + for( int bar : fooList ){ + System.out.println(bar); + //Пройдет 9 итераций и напечатает 1-9 на новых строках. + } + + // Switch Case + // switch работает с типами byte, short, char и int. + // Также он работает с перечислениями, + // классом String и с некоторыми классами-обертками над + // примитивными типами: Character, Byte, Short и Integer. + int month = 3; + String monthString; + switch (month){ + case 1: + monthString = "Январь"; + break; + case 2: + monthString = "Февраль"; + break; + case 3: + monthString = "Март"; + break; + default: + monthString = "Другой месяц"; + break; + } + System.out.println("Результат Switch Case: " + monthString); + + // Сокращенный синтаксис условного оператора. + // Вы можете использовать этот синтаксис для быстрого присвоения + // или логических переходов. + // Читается так: "Если (условие) истинно, использовать <значение 1>, + // в ином случае, использовать <значение 2>" + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Напечатает А, потому что условие истинно + + + /////////////////////////////////////// + // Преобразование и приведение типов данных. + /////////////////////////////////////// + + // Преобразование данных. + + // Преобразование строки в число. + Integer.parseInt("123"); // Вернет числовое представление "123". + + // Преобразование числа в строку + Integer.toString(123); // Вернет строковое представление 123. + + // Для других преобразований смотрите следующие классы: + // Double + // Long + // String + + // Приведение типов + // Вы так же можете приводить типы в Java. + // Подробнее об этом можно узнать по ссылке: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Классы и Функции + /////////////////////////////////////// + + System.out.println("\n->Классы и Функции"); + + // (Класс Bicycle определен ниже) + + // Для создания экземпляра класса используется new. + Bicycle trek = new Bicycle(); + + // Вызов методов объекта. + trek.speedUp(3); // Вы должны всегда использовать сеттеры и геттеры. + trek.setCadence(100); + + // toString возвращает строковое представление объекта. + System.out.println("trek info: " + trek.toString()); + + } // Конец метода main. +} // Конец класса LearnJava. + + +// Вы можете включать другие, не публичные классы в .java файл. + + +// Синтаксис объявления класса: +// class <имя класса>{ +// // Поля с данными, конструкторы, функции, все внутри. +// // Функции называют методами в Java. +// } + +class Bicycle { + + // Поля/Переменные класса Bicycle. + public int cadence;// Публичные(public): Доступны из любого места. + private int speed; // Приватные(private): Доступны только внутри класса. + protected int gear;// Защищенные(protected): Доступ из класса и наследников. + String name; // по умолчанию: Доступны только внутри пакета. + + // Конструкторы - способ создания класса. + // Это конструктор: + public Bicycle() { + gear = 1; + cadence = 50; + speed = 5; + name = "Bontrager"; + } + + // Это конструктор, который принимает аргументы: + public Bicycle(int startCadence, int startSpeed, int startGear, String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // Синтаксис функций: + // <тип возвращаемого значения> <имя>(<аргументы>) + + // Классы в Java часто реализуют сеттеры и геттеры для своих полей. + + // Синтаксис определения метода: + // <модификатор> <тип возвращаемого значения> <имя>(<аргументы>) + public int getCadence() { + return cadence; + } + + // void-методы не возвращают значений. + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Метод для отображения значений атрибутов объекта. + @Override + public String toString() { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + speed + + " name: " + name; + } +} // конец класса Bicycle. + +// PennyFarthing - это класс, наследованный от Bicycle +class PennyFarthing extends Bicycle { + // (Penny Farthings - это такие велосипеды с большим передним колесом, + // у них нет передач.) + + public PennyFarthing(int startCadence, int startSpeed){ + // Вызов конструктора родительского класса. + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // Вы должны пометить метод, который переопределяете, при помощи @аннотации + // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте? + // http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + gear = 0; + } + +} + +// Интерфейсы +// Синтаксис определения интерфейса: +// <модификатор доступа> interface <имя> extends <базовый интерфейс> { +// // Константы +// // Определение методов. +//} + +// Пример - Еда: +public interface Edible { + // Любой класс, реализующий этот интерфейс, должен реализовать этот метод. + public void eat(); +} + +public interface Digestible { + public void digest(); +} + + +// Сейчас мы можем создать класс, реализующий оба эти интерфейса. +public class Fruit implements Edible, Digestible { + public void eat() { + //... + } + + public void digest() { + //... + } +} + +// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать +// несколько интерфейсов. Например: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { + public void InterfaceOneMethod() { + + } + + public void InterfaceTwoMethod() { + + } +} + +``` + +## Почитать еще + +Здесь приведены ссылки только для того, чтобы получить общее представление о Java. Гуглите, чтобы найти какие-либо конкретные примеры. + +**Официальные руководства Oracle**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Модификаторы доступа в Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Концепции объектно-ориентированного программирования](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Наследование](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Полиморфизм](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Абстракция](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Исключения](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Интерфейсы](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + +**Уроки онлайн** + +* [Learneroo.com - Изучение Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Книги**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) + + -- cgit v1.2.3 From 1167d88b3c20659143f020a1f5de97f389aeff0b Mon Sep 17 00:00:00 2001 From: Sergey Date: Tue, 4 Nov 2014 10:21:25 +0300 Subject: Description & typo. --- ru-ru/java-ru.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 20095542..7d0ff8db 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -10,7 +10,8 @@ filename: LearnJava.java --- -Java - это объектно ориентированный язык общего назначения. +Java - это объектно ориентированный язык программирования общего назначения, +основанный на классах и поддерживающий параллельное программирование. [Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html) ```java @@ -171,7 +172,7 @@ public class LearnJava { >>> Беззнаковый сдвиг вправо. & Побитовое И. ^ Побитовое исключающее ИЛИ. - | Побитовое И. + | Побитовое ИЛИ. */ // Операторы инкремента. @@ -413,7 +414,7 @@ class PennyFarthing extends Bicycle { } // Вы должны пометить метод, который переопределяете, при помощи @аннотации - // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте? + // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте: // http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setGear(int gear) { -- cgit v1.2.3 From e4290280ac1d508209cefca33210282fbdd574d5 Mon Sep 17 00:00:00 2001 From: Sergey Date: Tue, 4 Nov 2014 23:08:49 +0300 Subject: Done. --- ru-ru/learnjava-ru.html.markdown | 45 ++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/ru-ru/learnjava-ru.html.markdown b/ru-ru/learnjava-ru.html.markdown index b429f06d..0bb6393c 100644 --- a/ru-ru/learnjava-ru.html.markdown +++ b/ru-ru/learnjava-ru.html.markdown @@ -10,7 +10,8 @@ filename: LearnJava.java --- -Java - это объектно ориентированный язык общего назначения. +Java - это объектно ориентированный язык программирования общего назначения, +основанный на классах и поддерживающий параллельное программирование. [Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html) ```java @@ -171,7 +172,7 @@ public class LearnJava { >>> Беззнаковый сдвиг вправо. & Побитовое И. ^ Побитовое исключающее ИЛИ. - | Побитовое И. + | Побитовое ИЛИ. */ // Операторы инкремента. @@ -289,7 +290,7 @@ public class LearnJava { // Преобразование числа в строку Integer.toString(123); // Вернет строковое представление 123. - // Для других преобразований, смотрите следующие классы: + // Для других преобразований смотрите следующие классы: // Double // Long // String @@ -405,15 +406,15 @@ class Bicycle { // PennyFarthing - это класс, наследованный от Bicycle class PennyFarthing extends Bicycle { // (Penny Farthings - это такие велосипеды с большим передним колесом, - // у низ нет передач.) + // у них нет передач.) public PennyFarthing(int startCadence, int startSpeed){ // Вызов конструктора родительского класса. super(startCadence, startSpeed, 0, "PennyFarthing"); } - // Вы должны пометить метод, который переопределяете при помощи @аннотации - // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте? + // Вы должны пометить метод, который переопределяете, при помощи @аннотации + // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте: // http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setGear(int gear) { @@ -425,42 +426,42 @@ class PennyFarthing extends Bicycle { // Интерфейсы // Синтаксис определения интерфейса: // <модификатор доступа> interface <имя> extends <базовый интерфейс> { -// // Константы -// // Определение методов. +// // Константы +// // Определение методов. //} // Пример - Еда: public interface Edible { // Любой класс, реализующий этот интерфейс, должен реализовать этот метод. - public void eat(); + public void eat(); } public interface Digestible { - public void digest(); + public void digest(); } -//We can now create a class that implements both of these interfaces +// Сейчас мы можем создать класс, реализующий оба эти интерфейса. public class Fruit implements Edible, Digestible { - public void eat() { - //... - } + public void eat() { + //... + } - public void digest() { - //... - } + public void digest() { + //... + } } -// В Java Вы можете наследоватьтолько один класс, однако, можете реализовывать +// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать // несколько интерфейсов. Например: public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { - public void InterfaceOneMethod() { + public void InterfaceOneMethod() { - } + } - public void InterfaceTwoMethod() { + public void InterfaceTwoMethod() { - } + } } ``` -- cgit v1.2.3 From ce381ce958b45d5249e597b51703b5ef65247310 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Tue, 4 Nov 2014 13:15:57 -0700 Subject: Functions section --- zh-cn/python3-cn.html.markdown | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index 2c1c03f8..a490ea40 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -406,24 +406,22 @@ add(5, 6) # => 印出"x is 5 and y is 6"并且返回11 add(y=6, x=5) # 关键字参数可以用任何顺序 -# 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) @@ -433,8 +431,7 @@ all_the_args(1, 2, a=3, b=4) prints: {"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) @@ -442,25 +439,25 @@ 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和全局域的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 + x = num # 现在全局域的x被赋值 print (x) # => 6 setX(43) setGlobalX(6) -# Python has first class functions +# 函数在Python是一等公民 def create_adder(x): def adder(y): return x + y @@ -469,16 +466,14 @@ def create_adder(x): 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] -- cgit v1.2.3 From 82dbb8cdfbf8742059ffd3ad8de1e7720a58b43a Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 5 Nov 2014 21:34:53 +0200 Subject: Update java-ru.html.markdown --- ru-ru/java-ru.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 7d0ff8db..182f2df1 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -1,13 +1,12 @@ --- - language: java contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Madison Dickson", "http://github.com/mix3d"] translators: - ["Sergey Gaykov", "https://github.com/gaykov"] -filename: LearnJava.java - +filename: LearnJavaRu.java +lang: ru-ru --- Java - это объектно ориентированный язык программирования общего назначения, @@ -32,7 +31,7 @@ import java.security.*; // Каждый .java файл содержит один публичный класс, имя которого совпадает с // именем файла. -public class LearnJava { +public class LearnJavaRu { // Программа должна содержать метод main, который является точкой входа. public static void main (String[] args) { -- cgit v1.2.3 From 191a0c705010634fd2b091bce5653da72bbfcf4a Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Wed, 5 Nov 2014 12:36:28 -0700 Subject: Only one section left! --- zh-cn/python3-cn.html.markdown | 35 ++++++++++++++++------------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index a490ea40..1f294ebb 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -345,9 +345,9 @@ while x < 4: print(x) x += 1 # x = x + 1 的简写 -# try/except块处理异常状况 +# 用try/except块处理异常状况 try: - # 用raise来抛出异常 + # 用raise抛出异常 raise IndexError("This is an index error") except IndexError as e: pass # pass是无操作,但是应该在这里处理错误 @@ -564,31 +564,28 @@ dir(math) ## 7. 高级用法 #################################################### -# Generators help you make lazy code +# 用生成器(generators)方便地写惰性运算 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 +# 生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值,而不是把所有的 +# 值全部算好。这意味着double_numbers不会生成大于15的数字。 +# +# range的返回值也是一个生成器,不然一个1到900000000的列表会花很多时间和内存。 +# +# 如果你想用一个Python的关键字当作变量名,可以加一个下划线来区分。 range_ = range(1, 900000000) -# will double all numbers until a result >=30 found +# 当找到一个 >=30 的结果就会停 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 +# 装饰器(decorators) +# 这个例子中,beg装饰say +# beg会先调用say。如果返回的say_please为真,beg会改变返回的字符串。 from functools import wraps @@ -613,9 +610,9 @@ 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/) @@ -626,7 +623,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [Python Module of the Week](http://pymotw.com/3/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -### 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) -- cgit v1.2.3 From 17a0d9c96606dfd4fd1c014cb7d037c56bfd1f19 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 5 Nov 2014 21:49:48 +0200 Subject: Fixed russion java situation --- ru-ru/java-ru.html.markdown | 28 +-- ru-ru/learnjava-ru.html.markdown | 507 --------------------------------------- 2 files changed, 14 insertions(+), 521 deletions(-) delete mode 100644 ru-ru/learnjava-ru.html.markdown diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 182f2df1..460086e3 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -425,42 +425,42 @@ class PennyFarthing extends Bicycle { // Интерфейсы // Синтаксис определения интерфейса: // <модификатор доступа> interface <имя> extends <базовый интерфейс> { -// // Константы -// // Определение методов. +// // Константы +// // Определение методов. //} // Пример - Еда: public interface Edible { // Любой класс, реализующий этот интерфейс, должен реализовать этот метод. - public void eat(); + public void eat(); } public interface Digestible { - public void digest(); + public void digest(); } // Сейчас мы можем создать класс, реализующий оба эти интерфейса. public class Fruit implements Edible, Digestible { - public void eat() { - //... - } + public void eat() { + //... + } - public void digest() { - //... - } + public void digest() { + //... + } } // В Java Вы можете наследоватьтолько один класс, однако можете реализовывать // несколько интерфейсов. Например: public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { - public void InterfaceOneMethod() { + public void InterfaceOneMethod() { - } + } - public void InterfaceTwoMethod() { + public void InterfaceTwoMethod() { - } + } } ``` diff --git a/ru-ru/learnjava-ru.html.markdown b/ru-ru/learnjava-ru.html.markdown deleted file mode 100644 index 0bb6393c..00000000 --- a/ru-ru/learnjava-ru.html.markdown +++ /dev/null @@ -1,507 +0,0 @@ ---- - -language: java -contributors: - - ["Jake Prather", "http://github.com/JakeHP"] - - ["Madison Dickson", "http://github.com/mix3d"] -translators: - - ["Sergey Gaykov", "https://github.com/gaykov"] -filename: LearnJava.java - ---- - -Java - это объектно ориентированный язык программирования общего назначения, -основанный на классах и поддерживающий параллельное программирование. -[Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html) - -```java -// Однострочные комментарии начинаются с //. -/* -Многострочные комментарии -выглядят так. -*/ -/** -JavaDoc-комментарии выглядят так. Они используются для описания класса -и его членов. -*/ - -// Импорт класса ArrayList из пакета java.util. -import java.util.ArrayList; -// Импорт всех классов из пакета java.security. -import java.security.*; - -// Каждый .java файл содержит один публичный класс, имя которого совпадает с -// именем файла. -public class LearnJava { - - // Программа должна содержать метод main, который является точкой входа. - public static void main (String[] args) { - - // System.out.println используется для печати строк. - System.out.println("Hello World!"); - System.out.println( - "Integer: " + 10 + - " Double: " + 3.14 + - " Boolean: " + true); - - // Чтобы напечатать что-либо не заканчивая переводом строки - // используется System.out.print. - System.out.print("Hello "); - System.out.print("World"); - - - /////////////////////////////////////// - // Типы и Переменные - /////////////////////////////////////// - - // Переменные объявляются с использованием <тип> <имя> - // Byte - 8-битное целое число. - // (-128 <= byte <= 127) - byte fooByte = 100; - - // Short - 16-битное целое число. - // (-32,768 <= short <= 32,767) - short fooShort = 10000; - - // Integer - 32-битное целое число. - // (-2,147,483,648 <= int <= 2,147,483,647) - int fooInt = 1; - - // Long - 64-битное целое число. - // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - long fooLong = 100000L; - // L используется для указания на то, что переменная имеет тип long; - // По умолчанию, числа без L являются integer. - - // Замечание: в Java нет беззнаковых типов. - - // Float - 32-битное IEEE 754 число с плавающей запятой с одинарной степенью точности. - float fooFloat = 234.5f; - // f используется для указания на то, что переменная имеет тип float; - // иначе, число являлось бы double. - - // Double - 64-битное IEEE 754 число с плавающей запятой с двойной степенью точности. - double fooDouble = 123.4; - - // Boolean - true или false - boolean fooBoolean = true; - boolean barBoolean = false; - - // Char - Простой 16-битный символ Unicode. - char fooChar = 'A'; - - // Переменным final не может быть присвоен другой объект. - final int HOURS_I_WORK_PER_WEEK = 9001; - - // Строки. - String fooString = "My String Is Here!"; - - // \n - это экранированный символ, который означает начало новой строки. - String barString = "Printing on a new line?\nNo Problem!"; - // \t - это экранированный символ, который добавляет символ табуляции. - String bazString = "Do you want to add a tab?\tNo Problem!"; - System.out.println(fooString); - System.out.println(barString); - System.out.println(bazString); - - // Массивы - // Размер массива должен быть указан при объявлении. - // Объявлять массив можно в следующих форматах: - //<тип данных> [] <имя> = new <тип данных>[<размер массива>]; - //<тип данных> <имя>[] = new <тип данных>[<размер массива>]; - int [] intArray = new int[10]; - String [] stringArray = new String[1]; - boolean boolArray [] = new boolean[100]; - - // Другой способ объявления и инициализации массива: - int [] y = {9000, 1000, 1337}; - String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; - boolean bools[] = new boolean[] {true, false, false}; - - // Индексация массива - доступ к элементу. - System.out.println("intArray @ 0: " + intArray[0]); - - // Массивы изменяемы и индекс в них начинается с 0. - intArray[1] = 1; - System.out.println("intArray @ 1: " + intArray[1]); // => 1 - - // Дополнительно. - // ArrayLists - похож на массив, но предлагает больше возможностей, - // его размер изменяемый. - // LinkedLists - реализация двусвязного списка. Все операции - // выполняются так, как ожидается от двусвязного - // списка. - // Maps - набор объектов, в которых присутствует связь - // ключ-значение. В Map ключ не может дублироваться. - // Каждый ключ связан только с одним значением. - // HashMaps - этот класс использует хэш-таблицу для реализации - // интерфейса Map. Это позволяет сохранить постоянной - // скорость выполнения базовых операций, таких как - // добавление и удаление элементов, вне зависимости - // от размера множества. - - /////////////////////////////////////// - // Операторы - /////////////////////////////////////// - System.out.println("\n->Операторы"); - - int i1 = 1, i2 = 2; // Сокращение для множественного объявления. - - // Арифметика в Java проста. - System.out.println("1+2 = " + (i1 + i2)); // => 3 - System.out.println("2-1 = " + (i2 - i1)); // => 1 - System.out.println("2*1 = " + (i2 * i1)); // => 2 - System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 округлено) - - // Остаток от деления - System.out.println("11%3 = "+(11 % 3)); // => 2 - - // Операторы сравнения. - System.out.println("3 == 2? " + (3 == 2)); // => false - System.out.println("3 != 2? " + (3 != 2)); // => true - System.out.println("3 > 2? " + (3 > 2)); // => true - System.out.println("3 < 2? " + (3 < 2)); // => false - System.out.println("2 <= 2? " + (2 <= 2)); // => true - System.out.println("2 >= 2? " + (2 >= 2)); // => true - - // Побитовые операторы! - /* - ~ Унарное побитовое дополнение. - << Знаковый сдвиг влево. - >> Знаковый сдвиг вправо. - >>> Беззнаковый сдвиг вправо. - & Побитовое И. - ^ Побитовое исключающее ИЛИ. - | Побитовое ИЛИ. - */ - - // Операторы инкремента. - int i = 0; - System.out.println("\n->Inc/Dec-rementation"); - // Операторы ++ и -- увеличивают и уменьшают значение на 1 соответственно. - // Если они находятся перед переменной, сначала происходит - // увеличение/уменьшение, затем операция, если после, - // то сначала выполняется операция, затем увеличение/уменьшение. - System.out.println(i++); //i = 1, напечатает 0 (пре-инкремент) - System.out.println(++i); //i = 2, напечатает 2 (пре-инкремент) - System.out.println(i--); //i = 1, напечатает 2 (пост-декремент) - System.out.println(--i); //i = 0, напечатает 0 (пре-декремент) - - /////////////////////////////////////// - // Контролирующие операторы. - /////////////////////////////////////// - System.out.println("\n->Контролирующие операторы"); - - // Оператор if такой же, как и в С. - int j = 10; - if (j == 10){ - System.out.println("Я напечатаюсь!"); - } else if (j > 10) { - System.out.println("Я нет."); - } else { - System.out.println("И я тоже нет."); - } - - // Цикл while. - int fooWhile = 0; - while(fooWhile < 100) - { - // System.out.println(fooWhile); - // Увеличить счетчик. - // Будет пройдено 100 итераций, fooWhile 0,1,2...99 - fooWhile++; - } - System.out.println("Значение fooWhile: " + fooWhile); - - // Цикл Do While. - int fooDoWhile = 0; - do - { - // System.out.println(fooDoWhile); - // Увеличить счетчик. - // Будет пройдено 100 итераций, fooDoWhile 0->99 - fooDoWhile++; - } while(fooDoWhile < 100); - System.out.println("Значение fooDoWhile: " + fooDoWhile); - - // Цикл for. - int fooFor; - // Структура цикла for => for(<начальное_состояние>; <условие>; <шаг>) - for(fooFor=0; fooFor<10; fooFor++){ - // System.out.println(fooFor); - // Пройдет 10 итераций., fooFor 0->9 - } - System.out.println("Значение fooFor: " + fooFor); - - // Цикл For Each - // Автоматический проход через массив или список объектов. - int[] fooList = {1,2,3,4,5,6,7,8,9}; - // Структура цикла for each => for(<объект> : <объект_массив>) - // читается как: для каждого объекта в массиве - // заметка: тип объекта должен совпадать с типом массива. - - for( int bar : fooList ){ - System.out.println(bar); - //Пройдет 9 итераций и напечатает 1-9 на новых строках. - } - - // Switch Case - // switch работает с типами byte, short, char и int. - // Также он работает с перечислениями, - // классом String и с некоторыми классами-обертками над - // примитивными типами: Character, Byte, Short и Integer. - int month = 3; - String monthString; - switch (month){ - case 1: - monthString = "Январь"; - break; - case 2: - monthString = "Февраль"; - break; - case 3: - monthString = "Март"; - break; - default: - monthString = "Другой месяц"; - break; - } - System.out.println("Результат Switch Case: " + monthString); - - // Сокращенный синтаксис условного оператора. - // Вы можете использовать этот синтаксис для быстрого присвоения - // или логических переходов. - // Читается так: "Если (условие) истинно, использовать <значение 1>, - // в ином случае, использовать <значение 2>" - int foo = 5; - String bar = (foo < 10) ? "A" : "B"; - System.out.println(bar); // Напечатает А, потому что условие истинно - - - /////////////////////////////////////// - // Преобразование и приведение типов данных. - /////////////////////////////////////// - - // Преобразование данных. - - // Преобразование строки в число. - Integer.parseInt("123"); // Вернет числовое представление "123". - - // Преобразование числа в строку - Integer.toString(123); // Вернет строковое представление 123. - - // Для других преобразований смотрите следующие классы: - // Double - // Long - // String - - // Приведение типов - // Вы так же можете приводить типы в Java. - // Подробнее об этом можно узнать по ссылке: - // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html - - - /////////////////////////////////////// - // Классы и Функции - /////////////////////////////////////// - - System.out.println("\n->Классы и Функции"); - - // (Класс Bicycle определен ниже) - - // Для создания экземпляра класса используется new. - Bicycle trek = new Bicycle(); - - // Вызов методов объекта. - trek.speedUp(3); // Вы должны всегда использовать сеттеры и геттеры. - trek.setCadence(100); - - // toString возвращает строковое представление объекта. - System.out.println("trek info: " + trek.toString()); - - } // Конец метода main. -} // Конец класса LearnJava. - - -// Вы можете включать другие, не публичные классы в .java файл. - - -// Синтаксис объявления класса: -// class <имя класса>{ -// // Поля с данными, конструкторы, функции, все внутри. -// // Функции называют методами в Java. -// } - -class Bicycle { - - // Поля/Переменные класса Bicycle. - public int cadence;// Публичные(public): Доступны из любого места. - private int speed; // Приватные(private): Доступны только внутри класса. - protected int gear;// Защищенные(protected): Доступ из класса и наследников. - String name; // по умолчанию: Доступны только внутри пакета. - - // Конструкторы - способ создания класса. - // Это конструктор: - public Bicycle() { - gear = 1; - cadence = 50; - speed = 5; - name = "Bontrager"; - } - - // Это конструктор, который принимает аргументы: - public Bicycle(int startCadence, int startSpeed, int startGear, String name) { - this.gear = startGear; - this.cadence = startCadence; - this.speed = startSpeed; - this.name = name; - } - - // Синтаксис функций: - // <тип возвращаемого значения> <имя>(<аргументы>) - - // Классы в Java часто реализуют сеттеры и геттеры для своих полей. - - // Синтаксис определения метода: - // <модификатор> <тип возвращаемого значения> <имя>(<аргументы>) - public int getCadence() { - return cadence; - } - - // void-методы не возвращают значений. - public void setCadence(int newValue) { - cadence = newValue; - } - - public void setGear(int newValue) { - gear = newValue; - } - - public void speedUp(int increment) { - speed += increment; - } - - public void slowDown(int decrement) { - speed -= decrement; - } - - public void setName(String newName) { - name = newName; - } - - public String getName() { - return name; - } - - //Метод для отображения значений атрибутов объекта. - @Override - public String toString() { - return "gear: " + gear + - " cadence: " + cadence + - " speed: " + speed + - " name: " + name; - } -} // конец класса Bicycle. - -// PennyFarthing - это класс, наследованный от Bicycle -class PennyFarthing extends Bicycle { - // (Penny Farthings - это такие велосипеды с большим передним колесом, - // у них нет передач.) - - public PennyFarthing(int startCadence, int startSpeed){ - // Вызов конструктора родительского класса. - super(startCadence, startSpeed, 0, "PennyFarthing"); - } - - // Вы должны пометить метод, который переопределяете, при помощи @аннотации - // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте: - // http://docs.oracle.com/javase/tutorial/java/annotations/ - @Override - public void setGear(int gear) { - gear = 0; - } - -} - -// Интерфейсы -// Синтаксис определения интерфейса: -// <модификатор доступа> interface <имя> extends <базовый интерфейс> { -// // Константы -// // Определение методов. -//} - -// Пример - Еда: -public interface Edible { - // Любой класс, реализующий этот интерфейс, должен реализовать этот метод. - public void eat(); -} - -public interface Digestible { - public void digest(); -} - - -// Сейчас мы можем создать класс, реализующий оба эти интерфейса. -public class Fruit implements Edible, Digestible { - public void eat() { - //... - } - - public void digest() { - //... - } -} - -// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать -// несколько интерфейсов. Например: -public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { - public void InterfaceOneMethod() { - - } - - public void InterfaceTwoMethod() { - - } -} - -``` - -## Почитать еще - -Здесь приведены ссылки только для того, чтобы получить общее представление о Java. Гуглите, чтобы найти какие-либо конкретные примеры. - -**Официальные руководства Oracle**: - -* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) - -* [Модификаторы доступа в Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) - -* [Концепции объектно-ориентированного программирования](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): - * [Наследование](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) - * [Полиморфизм](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) - * [Абстракция](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) - -* [Исключения](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) - -* [Интерфейсы](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) - -* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) - -* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) - -**Уроки онлайн** - -* [Learneroo.com - Изучение Java](http://www.learneroo.com) - -* [Codingbat.com](http://codingbat.com/java) - - -**Книги**: - -* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) - -* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) - -* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) - - -- cgit v1.2.3 From cd4c3a4ad8de2668ed6caad2df40dc470a80a4a0 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Wed, 5 Nov 2014 13:05:47 -0700 Subject: Done with Chinese, mostly --- zh-cn/python3-cn.html.markdown | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index 1f294ebb..4059c876 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -123,8 +123,7 @@ False or True #=> True # None是一个对象 None # => None -# Don't use the equality "==" symbol to compare objects to None -# Use "is" instead. This checks for equality of object identity. +# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。 "etc" is None # => False None is None # => True @@ -482,52 +481,50 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] #################################################### -# We subclass from object to get a class. +# 定义一个继承object的类 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. You should not invent such names on your own. + # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属 + # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这 + # 种格式。 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 + # 实例方法,第一个参数总是self,就是这个实例对象 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" +print(i.say("hi")) # 印出 "Ian: hi" j = Human("Joel") -print(j.say("hello")) # prints out "Joel: hello" +print(j.say("hello")) # 印出 "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*" -- cgit v1.2.3 From 1d665b9c0734ac606c2f8fa8b71c22c1d7ac377b Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Wed, 5 Nov 2014 13:12:35 -0700 Subject: Missed a few lines --- zh-cn/python3-cn.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index 4059c876..1b3f5086 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -184,8 +184,8 @@ li[:3] # => [1, 2, 4] li[::2] # =>[1, 4] # 倒排列表 li[::-1] # => [3, 4, 2, 1] -# Use any combination of these to make advanced slices -# li[start:end:step] +# 可以用三个参数的任何组合来构建切割 +# li[始:终:步伐] # 用del删除任何一个元素 del li[2] # li is now [1, 2, 3] @@ -433,9 +433,9 @@ all_the_args(1, 2, a=3, b=4) prints: # 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。 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) +all_the_args(*args) # 相当于 foo(1, 2, 3, 4) +all_the_args(**kwargs) # 相当于 foo(a=3, b=4) +all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4) # 函数作用域 -- cgit v1.2.3 From af29a504c0eb02e9eb575d5cace38676f7cf1ef1 Mon Sep 17 00:00:00 2001 From: Bonnie Barrilleaux Date: Wed, 5 Nov 2014 14:06:34 -0800 Subject: Added a few clarifying lines to Scala so that the examples can be run as given. Removed a duplicate example. --- scala.html.markdown | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5a0cc0ff..201a51ab 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -189,6 +189,8 @@ sSquared.reduce (_+_) // The filter function takes a predicate (a function from A -> Boolean) and // selects all elements which satisfy the 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) @@ -197,6 +199,7 @@ List( // Scala a foreach method defined on certain collections that takes a type // returning Unit (a void method) +val aListOfNumbers = Set(1,2,3,45,234) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println @@ -255,6 +258,7 @@ def showNumbersInRange(a:Int, b:Int):Unit = { if (a < b) showNumbersInRange(a + 1, b) } +showNumbersInRange(1,14) @@ -270,15 +274,13 @@ if (x == 11) println ("yeah") else println("nay") println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" -var i = 0 -while (i < 10) { println("i " + i); i+=1 } - // Object oriented features // Classname is Dog -class Dog { +class Dog (br: String) { + var breed: String = br //A method called bark, returning a String def bark: String = { // the body of the method @@ -286,6 +288,11 @@ class Dog { } } +val mydog = new Dog("greyhound") +println(mydog.breed) // => "greyhound" +println(mydog.bark) // => "Woof, woof!" + + // Classes can contain nearly any other construct, including other classes, // functions, methods, objects, case classes, traits etc. -- cgit v1.2.3 From e45b3f5bdbcbbb02fa304beafda8676a7227354c Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 6 Nov 2014 16:09:45 +0200 Subject: Update python3-cn.html.markdown --- zh-cn/python3-cn.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index 1b3f5086..c223297c 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -6,7 +6,8 @@ contributors: - ["Andre Polykanine", "https://github.com/Oire"] translators: - ["Geoff Liu", "http://geoffliu.me"] -filename: learnpython3.py +filename: learnpython3-cn.py +lang: zh-cn --- Python是由吉多·范罗苏姆(Guido Van Rossum)在90年代早期设计。它是如今最常用的编程 -- cgit v1.2.3 From a32a8e140153d5ffd341bb38515660f80da37575 Mon Sep 17 00:00:00 2001 From: Bonnie Date: Thu, 6 Nov 2014 18:47:38 -0800 Subject: Remove an extraneous space. --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 201a51ab..775956cb 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -279,7 +279,7 @@ val text = if (x == 10) "yeah" else "nope" // Object oriented features // Classname is Dog -class Dog (br: String) { +class Dog(br: String) { var breed: String = br //A method called bark, returning a String def bark: String = { -- cgit v1.2.3 From e3c13dd8ce6166b69e8085caea11da963d215d74 Mon Sep 17 00:00:00 2001 From: Peter Mortensen Date: Sun, 9 Nov 2014 10:25:00 +0100 Subject: Update README.markdown Copy edited (e.g. ref. , , , http://en.wikipedia.org/wiki/Python_%28programming_language%29, , and ). --- README.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.markdown b/README.markdown index dc379a9b..4e24bbe6 100644 --- a/README.markdown +++ b/README.markdown @@ -14,12 +14,12 @@ properly! ## Contributing -All contributions welcome, from the tiniest typo to a brand new article. Translations +All contributions are welcome, from the tiniest typo to a brand new article. Translations in all languages are welcome (or, for that matter, original articles in any language). Send a pull request or open an issue any time of day or night. **Please tag your issues pull requests with [language/lang-code] at the beginning** -**(e.g. [python/en] for english python).** This will help everyone pick out things they +**(e.g. [python/en] for English Python).** This will help everyone pick out things they care about. ### Style Guidelines @@ -27,7 +27,7 @@ care about. * **Keep lines under 80 chars** * **Prefer example to exposition** * **Eschew surplusage** -* **Use utf-8** +* **Use UTF-8** Long version: @@ -38,28 +38,28 @@ Long version: * We welcome newcomers, but the target audience for this site is programmers with some experience. So, try to avoid explaining basic concepts except for those specific to the language in question, - to keep articles succinct and scannable. We all know how to use google here. + to keep articles succinct and scannable. We all know how to use Google here. -* For translations (or english articles with non-ASCII characters), please make sure your file is - utf-8 encoded, and try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in vim) +* For translations (or English articles with non-ASCII characters), please make sure your file is + UTF-8 encoded, and try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in Vim) ### Header configuration -The actual site uses Middleman to generate HTML files from these markdown ones. Middleman, or at least +The actual site uses Middleman to generate HTML files from these Markdown ones. Middleman, or at least the custom scripts underpinning the site, required that some key information be defined in the header. -The following fields are necessary for english articles about programming languages: +The following fields are necessary for English articles about programming languages: * **language** The *programming language* in question -* **contributors** A list of [author, url] lists to credit +* **contributors** A list of [author, URL] lists to credit Other fields: * **filename**: The filename for this article's code. It will be fetched, mashed together, and made downloadable. - For non-english articles, *filename* should have a language-specific suffix. + For non-English articles, *filename* should have a language-specific suffix. * **lang**: For translations, the human language this article is in. For categorization, mostly. -Here's an example header for an esperanto translation of Ruby: +Here's an example header for an Esperanto translation of Ruby: ```yaml --- -- cgit v1.2.3 From 9576d80b75a025740775b7a16ee327403df25e88 Mon Sep 17 00:00:00 2001 From: Kishore Relangi Date: Mon, 10 Nov 2014 15:50:47 +0530 Subject: Update perl6.html.markdown It is actually generating fibonacci series --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 52625bc2..9f3a03ba 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1149,7 +1149,7 @@ my @list = 1, 3, 9 ... * > 30; # you can use a predicate # (with the Whatever Star, here). my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above) -my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers, +my @fib = 1, 1, *+* ... *; # lazy infinite list of fibonacci series, # computed using a closure! my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above) my @fib = 1, 1, { $^a + $^b } ... *; #(... also equivalent to the above) -- cgit v1.2.3 From 9ddc2d0a5b92974ac1614024b4586354a395482e Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 10 Nov 2014 19:45:17 -0600 Subject: Add Ruby exceptions. --- ruby.html.markdown | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 3c67de2e..a1a2c77b 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -10,6 +10,7 @@ contributors: - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] - ["Ariel Krakowski", "http://www.learneroo.com"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] --- @@ -271,6 +272,19 @@ else end #=> "OK job" +# exception handling +begin + # code here that might raise an exception + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end # Functions -- cgit v1.2.3 From 57c9f704170cd4d3adf49623c9f1b7a7a9670925 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:24:00 -0700 Subject: A huge re-organization of the Scala file --- scala.html.markdown | 358 ++++++++++++++++++++++++++++------------------------ 1 file changed, 193 insertions(+), 165 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5a0cc0ff..a55e1f0e 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -4,6 +4,7 @@ filename: learnscala.scala contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] filename: learn.scala --- @@ -20,16 +21,16 @@ Scala - the scalable language scala> - This is the so called REPL. You can run commands in the REPL. Let's do just - that: + This is the so called REPL (Read-Eval-Print Loop). You may type any valid + Scala expression into it, and the result will be printed. We will explain what + Scala files look like further into this tutorial, but for now, let's start + with some basics. */ -println(10) // prints the integer 10 -println("Boo!") // printlns the string Boo! - - -// Some basics +################################################# +## 1. Basics +################################################# // Printing, and forcing a new line on the next print println("Hello world!") @@ -37,15 +38,15 @@ println("Hello world!") print("Hello world") // Declaring values is done using either var or val -// val declarations are immutable, whereas var's are mutable. Immutability is +// val declarations are immutable, whereas var's are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -var x = 10 +var x = 10 x = 20 // x is now 20 // Single line comments start with two forward slashes -/* +/* Multi line comments look like this. */ @@ -82,149 +83,83 @@ true == false // false */ -// Everything is an object, including a function. Type these in the REPL: - -7 // results in res30: Int = 7 (res30 is just a generated var name for the result) - -// The next line gives you a function that takes an Int and returns it squared -(x:Int) => x * x - -// You can assign this function to an identifier, like this: -val sq = (x:Int) => x * x - -/* The above says this - - sq: Int => Int = - - Which means that this time we gave an explicit name to the value - sq is a - function that take an Int and returns Int. - - sq can be executed as follows: -*/ - -sq(10) // Gives you this: res33: Int = 100. - -// The colon explicitly defines the type of a value, in this case a function -// taking an Int and returning an Int. -val add10: Int => Int = _ + 10 - -// Scala allows methods and functions to return, or take as parameters, other -// functions or methods. - -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: -List(1, 2, 3) map (x => x + 10) - -// And the underscore symbol, can be used if there is just one argument to the -// anonymous function. It gets bound as the variable -List(1, 2, 3) map (_ + 10) - -// If the anonymous block AND the function you are applying both take one -// argument, you can even omit the underscore -List("Dom", "Bob", "Natalia") foreach println - - - -// Data structures - -val a = Array(1, 2, 3, 5, 8, 13) -a(0) -a(3) -a(21) // Throws an exception - -val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") -m("fork") -m("spoon") -m("bottle") // Throws an exception - -val safeM = m.withDefaultValue("no lo se") -safeM("bottle") - -val s = Set(1, 3, 7) -s(0) -s(1) - -/* Look up the documentation of map here - - * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map - * and make sure you can read it - */ - - -// Tuples - -(1, 2) - -(4, 3, 2) - -(1, 2, "three") - -(a, 2, "three") - -// Why have this? -val divideInts = (x:Int, y:Int) => (x / y, x % y) - -divideInts(10,3) // The function divideInts gives you the result and the remainder - -// To access the elements of a tuple, use _._n where n is the 1-based index of -// the element -val d = divideInts(10,3) - -d._1 - -d._2 - +// Strings +"Scala strings are surrounded by double quotes" // +'a' // A Scala Char +'Single quote strings don't exist' // Error +"Strings have the usual Java methods defined on them".length +"They also have some extra Scala methods.".reverse -// Combinators +// Seealso: scala.collection.immutable.StringOps -s.map(sq) +println("ABCDEF".length) +println("ABCDEF".substring(2, 6)) +println("ABCDEF".replace("C", "3")) -val sSquared = s. map(sq) +// String interpolation +val n = 45 +println(s"We have $n apples") // => "We have 45 apples" -sSquared.filter(_ < 10) +// Expressions inside interpolated strings are also possible +val a = Array(11, 9, 6) +println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." +println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." +println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" -sSquared.reduce (_+_) +// Formatting with interpolated strings (note the prefixed f) +println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" +println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" -// The filter function takes a predicate (a function from A -> Boolean) and -// selects all elements which satisfy the predicate -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)) +// Ignoring special characters. +println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." +// Some characters need to be 'escaped', e.g. a double quote inside a string: +val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" -// Scala a foreach method defined on certain collections that takes a type -// returning Unit (a void method) -aListOfNumbers foreach (x => println(x)) -aListOfNumbers foreach println +// Triple double-quotes let strings span multiple rows and contain quotes +val html = """ +

Press belo', Joe

+ | + """ +################################################# +## 2. Functions +################################################# +// The next line gives you a function that takes an Int and returns it squared +(x:Int) => x * x -// For comprehensions +// You can assign this function to an identifier, like this: +val sq = (x:Int) => x * x -for { n <- s } yield sq(n) +/* The above says this -val nSquared2 = for { n <- s } yield sq(n) + sq: Int => Int = -for { n <- nSquared2 if n < 10 } yield n + Which means that this time we gave an explicit name to the value - sq is a + function that take an Int and returns Int. -for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + sq can be executed as follows: +*/ -/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas - a for-comprehension defines a relationship between two sets of data. */ +sq(10) // Gives you this: res33: Int = 100. +// The colon explicitly defines the type of a value, in this case a function +// taking an Int and returning an Int. +val add10: Int => Int = _ + 10 -// Loops and iteration +################################################# +## 3. Flow Control +################################################# 1 to 5 val r = 1 to 5 r.foreach( println ) -r foreach println +r foreach println // NB: Scala is quite lenient when it comes to dots and brackets - study the // rules separately. This helps write DSLs and APIs that read like English @@ -243,7 +178,7 @@ i // Show the value of i. Note that while is a loop in the classical sense - // A do while loop do { - println("x is still less than 10"); + println("x is still less than 10"); x += 1 } while (x < 10) @@ -257,7 +192,6 @@ def showNumbersInRange(a:Int, b:Int):Unit = { } - // Conditionals val x = 10 @@ -274,10 +208,76 @@ var i = 0 while (i < 10) { println("i " + i); i+=1 } +################################################# +## 4. Data Structures +################################################# -// Object oriented features +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Throws an exception + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Throws an exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Look up the documentation of map here - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * and make sure you can read it + */ + + +// Tuples + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(a, 2, "three") + +// Why have this? +val divideInts = (x:Int, y:Int) => (x / y, x % y) + +divideInts(10,3) // The function divideInts gives you the result and the remainder + +// To access the elements of a tuple, use _._n where n is the 1-based index of +// the element +val d = divideInts(10,3) + +d._1 + +d._2 + + +################################################# +## 5. Object Oriented Programming +################################################# + +/* + Aside: Everything we've done so far in this tutorial has been simple + expressions (values, functions, etc). These expressions are fine to type into + the command-line interpreter for quick tests, but they cannot exist by + themselves in a Scala file. For example, you cannot have just "val x = 5" in + a Scala file. Instead, the only top-level constructs allowed in Scala are: + + - objects + - classes + - case classes + - traits + + And now we will explain what these are. +*/ -// Classname is Dog class Dog { //A method called bark, returning a String def bark: String = { @@ -289,8 +289,6 @@ class Dog { // Classes can contain nearly any other construct, including other classes, // functions, methods, objects, case classes, traits etc. - - // Case classes case class Person(name:String, phoneNumber:String) @@ -298,8 +296,12 @@ case class Person(name:String, phoneNumber:String) Person("George", "1234") == Person("Kate", "1236") +// Objects and traits coming soon! + -// Pattern matching +################################################# +## 6. Pattern Matching +################################################# val me = Person("George", "1234") @@ -338,49 +340,75 @@ matcher("52917") // => "No match on '52917'" matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" -// Strings +################################################# +## 7. Functional Programming +################################################# -"Scala strings are surrounded by double quotes" // -'a' // A Scala Char -'Single quote strings don't exist' // Error -"Strings have the usual Java methods defined on them".length -"They also have some extra Scala methods.".reverse +// Scala allows methods and functions to return, or take as parameters, other +// functions or methods. -// Seealso: scala.collection.immutable.StringOps +List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element -println("ABCDEF".length) -println("ABCDEF".substring(2, 6)) -println("ABCDEF".replace("C", "3")) +// Anonymous functions can be used instead of named functions: +List(1, 2, 3) map (x => x + 10) -// String interpolation -val n = 45 -println(s"We have $n apples") // => "We have 45 apples" +// And the underscore symbol, can be used if there is just one argument to the +// anonymous function. It gets bound as the variable +List(1, 2, 3) map (_ + 10) -// Expressions inside interpolated strings are also possible -val a = Array(11, 9, 6) -println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." -println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." -println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" +// If the anonymous block AND the function you are applying both take one +// argument, you can even omit the underscore +List("Dom", "Bob", "Natalia") foreach println -// Formatting with interpolated strings (note the prefixed f) -println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" -println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" -// Ignoring special characters. -println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." +// Combinators -// Some characters need to be 'escaped', e.g. a double quote inside a string: -val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" +s.map(sq) -// Triple double-quotes let strings span multiple rows and contain quotes -val html = """
-

Press belo', Joe

- | -
""" +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + +// The filter function takes a predicate (a function from A -> Boolean) and +// selects all elements which satisfy the predicate +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)) + + +// Scala a foreach method defined on certain collections that takes a type +// returning Unit (a void method) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// For comprehensions + +for { n <- s } yield sq(n) + +val nSquared2 = for { n <- s } yield sq(n) + +for { n <- nSquared2 if n < 10 } yield n + +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + +/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas + a for-comprehension defines a relationship between two sets of data. */ + + +################################################# +## 8. Implicits +################################################# +Coming soon! -// Application structure and organization +################################################# +## 9. Misc +################################################# // Importing things import scala.collection.immutable.List -- cgit v1.2.3 From 761f150b4bb0374e71aa16a2323a96a89603aaf7 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:38:48 -0700 Subject: Clean up of section 1 --- scala.html.markdown | 73 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 43 insertions(+), 30 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index a55e1f0e..a0983bdb 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -32,23 +32,36 @@ Scala - the scalable language ## 1. Basics ################################################# +// Single line comments start with two forward slashes + +/* + Multi line comments, as you can already see from above, look like this. +*/ + // Printing, and forcing a new line on the next print println("Hello world!") +println(10) + // Printing, without forcing a new line on next print print("Hello world") -// Declaring values is done using either var or val +// Declaring values is done using either var or val. // val declarations are immutable, whereas var's are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -var x = 10 -x = 20 // x is now 20 +var y = 10 +y = 20 // y is now 20 -// Single line comments start with two forward slashes /* -Multi line comments look like this. + Scala is a statically typed language, yet note that in the above declarations, we did not specify + a type. This is due to a language feature called type inference. In most cases, Scala compiler can + guess what the type of a variable is, so you don't have to type it every time. We can explicitly + declare the type of a variable like so: */ +val z: Int = 10 +val a: Double = 1.0 +val b: Double = 10 // Notice automatic conversion from Int to Double, result is 10.0, not 10 // Boolean values true @@ -65,9 +78,11 @@ true == false // false 2 - 1 // 1 5 * 3 // 15 6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 -// Evaluating a command in the REPL gives you the type and value of the result +// Evaluating an expression in the REPL gives you the type and value of the result 1 + 7 @@ -79,48 +94,46 @@ true == false // false This means the result of evaluating 1 + 7 is an object of type Int with a value of 8 - 1+7 will give you the same result + Note that "res29" is a sequentially generated variable name to store the results of the + expressions you typed, your output may differ. */ - -// Strings - -"Scala strings are surrounded by double quotes" // +"Scala strings are surrounded by double quotes" 'a' // A Scala Char 'Single quote strings don't exist' // Error -"Strings have the usual Java methods defined on them".length -"They also have some extra Scala methods.".reverse -// Seealso: scala.collection.immutable.StringOps +// Strings have the usual Java methods defined on them +"hello world".length +"ABCDEF".substring(2, 6) +"ABCDEF".replace("C", "3") -println("ABCDEF".length) -println("ABCDEF".substring(2, 6)) -println("ABCDEF".replace("C", "3")) +// They also have some extra Scala methods. See also: scala.collection.immutable.StringOps +"hello world".take(5) -// String interpolation +// String interpolation: notice the prefix "s" val n = 45 -println(s"We have $n apples") // => "We have 45 apples" +s"We have $n apples" // => "We have 45 apples" // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." -println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." -println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" +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" -// Formatting with interpolated strings (note the prefixed f) -println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" -println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" +// Formatting with interpolated strings with the prefix "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" -// Ignoring special characters. -println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." +// Raw strings, ignoring special characters. +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." -// Some characters need to be 'escaped', e.g. a double quote inside a string: -val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" +// Some characters need to be "escaped", e.g. a double quote inside a string: +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" // Triple double-quotes let strings span multiple rows and contain quotes val html = """

Press belo', Joe

- | +
""" -- cgit v1.2.3 From 45bc0f19a0e52d5ccc58db555cb3823c1a00e973 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:46:26 -0700 Subject: Minor fix --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index a0983bdb..6311dba4 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -122,7 +122,7 @@ s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" // Formatting with interpolated strings with the prefix "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" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" // Raw strings, ignoring special characters. raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." -- cgit v1.2.3 From e784f52d33475b0cba059a0c07ad01b0e63578a9 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:58:14 -0700 Subject: Minor consistency edit --- scala.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 6311dba4..c8932c86 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -104,11 +104,12 @@ true == false // false // Strings have the usual Java methods defined on them "hello world".length -"ABCDEF".substring(2, 6) -"ABCDEF".replace("C", "3") +"hello world".substring(2, 6) +"hello world".replace("C", "3") // They also have some extra Scala methods. See also: scala.collection.immutable.StringOps "hello world".take(5) +"hello world".drop(5) // String interpolation: notice the prefix "s" val n = 45 -- cgit v1.2.3 From 0698ed27c1c63100fabf01be654a412186982042 Mon Sep 17 00:00:00 2001 From: Jack Hooper Date: Wed, 12 Nov 2014 00:28:03 +1100 Subject: There's no apostrophe in 90s Apostrophes are for indicating an abbreviation or for denoting possession. '90s' is merely a plural. It is an abbreviation of 1990s, so technically it ought to be '90s, but for all intents and purposes this is optional. --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index ba236fb3..411194f4 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -7,7 +7,7 @@ contributors: filename: learnpython.py --- -Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular +Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular languages in existence. I fell in love with Python for its syntactic clarity. It's basically executable pseudocode. -- cgit v1.2.3 From 0429c31d6d640889cd40ad0fba89a476bf1e7480 Mon Sep 17 00:00:00 2001 From: Jack Hooper Date: Wed, 12 Nov 2014 00:30:19 +1100 Subject: Updated note regarding Python 3 tutorial. --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 411194f4..961d0965 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. Look for another tour of Python 3 soon! +to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial. ```python -- cgit v1.2.3 From 4d85f161d8399f80e3c7ca93eb7ad8ed8018a327 Mon Sep 17 00:00:00 2001 From: Jack Hooper Date: Wed, 12 Nov 2014 02:03:50 +1100 Subject: More apostrophe fixes I hate to be that guy, but... I found a couple more. --- python.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 961d0965..f7b0082c 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -21,7 +21,7 @@ to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial. # Single line comments start with a number symbol. """ Multiline strings can be written - using three "'s, and are often used + using three "s, and are often used as comments """ @@ -55,7 +55,7 @@ to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial. # Modulo operation 7 % 3 # => 1 -# Exponentiation (x to the y'th power) +# Exponentiation (x to the yth power) 2**4 # => 16 # Enforce precedence with parentheses -- cgit v1.2.3 From 38cf765079a3bd7ea8a2493857b7d2bc26d5fe30 Mon Sep 17 00:00:00 2001 From: Jack Hooper Date: Wed, 12 Nov 2014 02:04:50 +1100 Subject: Apostrophe fixes as per Python 2 tutorial --- python3.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index e478e57f..0b4feccc 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -7,7 +7,7 @@ contributors: filename: learnpython3.py --- -Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular +Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular languages in existence. I fell in love with Python for its syntactic clarity. It's basically executable pseudocode. @@ -20,7 +20,7 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Single line comments start with a number symbol. """ Multiline strings can be written - using three "'s, and are often used + using three "s, and are often used as comments """ @@ -51,7 +51,7 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Modulo operation 7 % 3 # => 1 -# Exponentiation (x to the y'th power) +# Exponentiation (x to the yth power) 2**4 # => 16 # Enforce precedence with parentheses -- cgit v1.2.3 From 1c4cbd279e740f4782c62e75d1f4659447dc464a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 11 Nov 2014 13:06:57 -0600 Subject: Add colon to introduce the exception handling section --- ruby.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index a1a2c77b..e58c513d 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -272,7 +272,7 @@ else end #=> "OK job" -# exception handling +# exception handling: begin # code here that might raise an exception raise NoMemoryError, 'You ran out of memory.' -- cgit v1.2.3 From 29bc9a14495a433536a5aaeb1278e56708a81bb7 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Wed, 12 Nov 2014 00:36:19 -0800 Subject: Use the right comment style for Scala... oops --- scala.html.markdown | 54 ++++++++++++++++++++++++++--------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 6964b9a0..dc039f0c 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -28,9 +28,9 @@ Scala - the scalable language */ -################################################# -## 1. Basics -################################################# +///////////////////////////////////////////////// +// 1. Basics +///////////////////////////////////////////////// // Single line comments start with two forward slashes @@ -138,9 +138,9 @@ val html = """
""" -################################################# -## 2. Functions -################################################# +///////////////////////////////////////////////// +// 2. Functions +///////////////////////////////////////////////// // The next line gives you a function that takes an Int and returns it squared (x:Int) => x * x @@ -165,9 +165,9 @@ sq(10) // Gives you this: res33: Int = 100. val add10: Int => Int = _ + 10 -################################################# -## 3. Flow Control -################################################# +///////////////////////////////////////////////// +// 3. Flow Control +///////////////////////////////////////////////// 1 to 5 val r = 1 to 5 @@ -220,9 +220,9 @@ println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" -################################################# -## 4. Data Structures -################################################# +///////////////////////////////////////////////// +// 4. Data Structures +///////////////////////////////////////////////// val a = Array(1, 2, 3, 5, 8, 13) a(0) @@ -271,9 +271,9 @@ d._1 d._2 -################################################# -## 5. Object Oriented Programming -################################################# +///////////////////////////////////////////////// +// 5. Object Oriented Programming +///////////////////////////////////////////////// /* Aside: Everything we've done so far in this tutorial has been simple @@ -317,9 +317,9 @@ Person("George", "1234") == Person("Kate", "1236") // Objects and traits coming soon! -################################################# -## 6. Pattern Matching -################################################# +///////////////////////////////////////////////// +// 6. Pattern Matching +///////////////////////////////////////////////// val me = Person("George", "1234") @@ -358,9 +358,9 @@ matcher("52917") // => "No match on '52917'" matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" -################################################# -## 7. Functional Programming -################################################# +///////////////////////////////////////////////// +// 7. Functional Programming +///////////////////////////////////////////////// // Scala allows methods and functions to return, or take as parameters, other // functions or methods. @@ -419,16 +419,16 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared a for-comprehension defines a relationship between two sets of data. */ -################################################# -## 8. Implicits -################################################# +///////////////////////////////////////////////// +// 8. Implicits +///////////////////////////////////////////////// Coming soon! -################################################# -## 9. Misc -################################################# +///////////////////////////////////////////////// +// 9. Misc +///////////////////////////////////////////////// // Importing things import scala.collection.immutable.List -- cgit v1.2.3 From aea5e2eb1b255457a2411358a4275d473d191536 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Wed, 12 Nov 2014 18:22:02 +0000 Subject: Add basic outline of Forth and explaination of simple concepts. --- forth.html.markdown | 136 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 forth.html.markdown diff --git a/forth.html.markdown b/forth.html.markdown new file mode 100644 index 00000000..de0e18c2 --- /dev/null +++ b/forth.html.markdown @@ -0,0 +1,136 @@ +--- +language: forth +contributors: + - ["Horse M.D.", "http://github.com/HorseMD/"] +filename: learnforth.fs +--- + +Forth was created by Charles H. Moore in the 70s. + +Note: This article focuses predominantly on the Gforth implementation of Forth, but most +of what is written here should work elsewhere. + +> If Lisp is the ultimate high level language, Forth is the ultimate low level language. + +```forth + +\ Forth is an interactive programming language which is comprised of *words*. These are +\ Forth subroutines which are executed once you press , from left to right. + +\ ------------------------------ Precursor ------------------------------ + +\ It's important to know how forth processes instructions. All programming in Forth is +\ done by manipulating what's known as the parameter stack (more commonly just referred +\ to as "the stack"). The stack is a typical last-in-first-out (LIFO) stack. Typing: + +5 2 3 56 76 23 65 + +\ Means 5 gets put on the stack first, then 2, then 3, etc all the way to 65, which +\ is now at the top of the stack. We can see the length and contents of the stack by +\ passing forth the word `.s`: + +.s <7> 5 2 3 56 76 23 65 \ ok + +\ Forth's interpreter interprets what you type in one of two ways: as *words* (i.e. the +\ name of subroutines) or as *numbers*. Words are essentially "symbols that do things". + +\ Finally, as the stack is LIFO, we obviously must use postfix notation to manipulate +\ the stack. This should become clear shortly. + +\ ------------------------------ Basic Arithmetic ------------------------------ + +\ Lets do a simple equation: adding 5 and 4. In infix notation this would be 5 + 4, +\ but as forth works in postfix (see above about stack manipulation) we input it like so: + +5 4 + \ ok + +\ However, this alone yields "ok", yet no answer. Why? The way forth interprets what +\ we typed is as such: 5 gets added to the top of the stack, and then 4. Finally, +\ it runs word `+` on the stack (which pops the top and second value, and adds them), +\ and inserts the result at the top of the stack. Typing the word `.` will yield +\ the result. + +. \ 9 ok + +\ This should illustrate the fundamentals of forth. Lets do a few more arithmetic +\ tests: + +6 7 * . \ 42 ok +1360 23 - . \ 1337 ok +12 12 / . \ 1 ok + +\ And so on. + +\ ------------------------------ More Advanced Stack Maniulation ------------------------------ + +\ Naturally, as we do so much work with the stack, we'll want some useful methods. + +drop \ drop (remove) the item at the top of the stack (note the difference between this and `.`) +dup \ duplicate the item on top the stack +rot \ rotate the top three items (third -> first, first -> second, second -> third) +swap \ swaps the top item with the second item + +\ Examples: + +dup * \ square the top item +2 5 dup * swap / \ half the top item squared +6 4 5 rot * - \ sometimes we just want to reorganize +4 0 drop 2 / \ add 4 and 0, remove 0 and divide the top by 2 + +\ ------------------------------ Extra Stack Manipulation ------------------------------ + +tuck \ acts like dup, except it duplicates the top item into the 3rd* position in the stack +over \ duplicate the second item to the top of the stack +n roll \ where n is a number, *move* the stack item at that position to the top of the stack +n pick \ where n is a number, *duplicate* the item at that position to the top of the stack + +\ 3rd*: when referring to stack indexes, they are zero-based - i.e. the first element is at +\ position 0, the second element is at position 1, etc... Just like indexing arrays in +\ most other languages. + +\ ------------------------------ Creating Words ------------------------------ + +\ Quite often one will want to write their own words. + +: square ( n -- n ) dup * ; \ ok + +\ Lets break this down. The `:` word says to Forth to enter "compile" mode. After that, +\ we tell Forth what our word is called - "square". Between the parentheses we have a +\ comment depicting what this word does to the stack - it takes a number and adds a +\ number. Finally, we have what the word does, until we reach the `;` word which +\ says that you've finished your definition, Forth will add this to the dictionary and +\ switch back into interpret mode. + +\ We can check the definition of a word with the `see` word: + +see square \ dup * ; ok + +\ ------------------------------ Conditionals ------------------------------ + +\ TODO + +\ ------------------------------ Loops ------------------------------ + +\ TODO + +\ ------------------------------ The Return Stack ------------------------------ + +\ TODO + +\ ------------------------------ Variables and Memory ------------------------------ + +\ TODO + +\ ------------------------------ Final Notes ------------------------------ + +\ Booleans +\ Floats +\ Commenting (types) +\ bye + +``` + +##Ready For More? + +* [Starting Forth](http://www.forth.com/starting-forth/) +* [Thinking Forth](http://thinking-forth.sourceforge.net/) -- cgit v1.2.3 From 8f7ad2af1ebab9ebffe5aee1c7f6325acb8ddd3e Mon Sep 17 00:00:00 2001 From: Baptiste Fontaine Date: Wed, 12 Nov 2014 21:40:15 +0100 Subject: [bash/fr] A couple formatting/phrasing issues fixed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thanks to @vendethiel’s feedback on #824. --- fr-fr/bash-fr.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/fr-fr/bash-fr.html.markdown b/fr-fr/bash-fr.html.markdown index 4678237d..0e764d7d 100644 --- a/fr-fr/bash-fr.html.markdown +++ b/fr-fr/bash-fr.html.markdown @@ -45,18 +45,19 @@ VARIABLE = "Du texte" # Bash va penser que VARIABLE est une commande qu’il doit exécuter et va # afficher une erreur parce qu’elle est introuvable. -# Utiliser la variable : +# Utiliser une variable : echo $VARIABLE echo "$VARIABLE" echo '$VARIABLE' # Quand vous utilisez la variable en elle-même – en lui assignant une valeur, # en l’exportant ou autre – vous écrivez son nom sans $. Si vous voulez # utiliser sa valeur, vous devez utiliser $. -# Notez que ' (guillemet droit simple) empêche l’expansion des variables ! +# Notez qu’entourer une variable de deux guillemets simples (') empêche +# l’expansion des variables ! -# Substitution de chaîne de caractères dans les variables +# Substitution de chaîne de caractères dans une variable echo ${VARIABLE/Some/A} -# Ceci va remplacer la première occurrence de « Some » par « A » +# Ceci va remplacer la première occurrence de « Some » par « A » # Sous-chaîne d’une variable echo ${VARIABLE:0:7} @@ -77,7 +78,7 @@ echo "Arguments du script séparés en plusieurs variables : $1 $2..." # Lire une valeur depuis l’entrée standard : echo "Quel est votre nom ?" -read NAME # Notez que l’on a pas eu à déclarer une nouvelle variable +read NAME # Notez que l’on n’a pas eu à déclarer une nouvelle variable echo Bonjour, $NAME! # Nous avons l’habituelle structure « if » : @@ -128,7 +129,7 @@ python2 hello.py < "entrée.in" python2 hello.py > "sortie.out" python2 hello.py 2> "erreur.err" # Ceci va écraser le fichier s'il existe; si vous préférez écrire à la fin de -celui-ci, utilisez >> à la place. +# celui-ci, utilisez >> à la place. # Les commandes peuvent se substituer à l’intérieur d’autres commandes en # utilisant $( ) : -- cgit v1.2.3 From 5b91f96781a153faa5a129514cce8dcca3f24c54 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Wed, 12 Nov 2014 21:56:13 +0000 Subject: Finished conditionals section for now. --- forth.html.markdown | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index de0e18c2..bea7cf38 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -61,7 +61,7 @@ of what is written here should work elsewhere. \ And so on. -\ ------------------------------ More Advanced Stack Maniulation ------------------------------ +\ ------------------------------ Stack Maniulation ------------------------------ \ Naturally, as we do so much work with the stack, we'll want some useful methods. @@ -77,7 +77,7 @@ dup * \ square the top item 6 4 5 rot * - \ sometimes we just want to reorganize 4 0 drop 2 / \ add 4 and 0, remove 0 and divide the top by 2 -\ ------------------------------ Extra Stack Manipulation ------------------------------ +\ ------------------------------ More Advanced Stack Manipulation ------------------------------ tuck \ acts like dup, except it duplicates the top item into the 3rd* position in the stack over \ duplicate the second item to the top of the stack @@ -107,7 +107,28 @@ see square \ dup * ; ok \ ------------------------------ Conditionals ------------------------------ -\ TODO +\ Booleans: +\ In forth, -1 is used to represent truth, and 0 is used to represent false. +\ The idea behind this is that -1 is 11111111 in binary, whereas 0 is obviously 0 in binary. +\ However, any non-zero value is usually treated as being true. + +42 42 = / -1 ok +12 53 = / 0 ok + +\ `if` is a compile-only word. This means that it can *only* be used when we're compiling a word. +\ when creating conditionals, the format is `if` `then` . + +: ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" then ; \ ok +100 ?>64 \ Greater than 64! ok + +\ This unimaginative example displays "Greater than 64!" when the number on the stack is greater +\ than 64. However, it does nothing when the test is false. Let's fix that with the `else` word! + +: ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" else ." Less than 64!" then ; \ ok +100 ?>64 \ Greater than 64! ok +20 ?>64 \ Less than 64! ok + +\ As you can see, conditionals behave more or less like they do in most programming languages. \ ------------------------------ Loops ------------------------------ -- cgit v1.2.3 From c63b9d0153710077d48c3c7ab16b3d848c97f8e9 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Wed, 12 Nov 2014 22:33:04 +0000 Subject: Add outline of loops. --- forth.html.markdown | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index bea7cf38..ee491e7a 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -110,12 +110,12 @@ see square \ dup * ; ok \ Booleans: \ In forth, -1 is used to represent truth, and 0 is used to represent false. \ The idea behind this is that -1 is 11111111 in binary, whereas 0 is obviously 0 in binary. -\ However, any non-zero value is usually treated as being true. +\ However, any non-zero value is usually treated as being true: 42 42 = / -1 ok 12 53 = / 0 ok -\ `if` is a compile-only word. This means that it can *only* be used when we're compiling a word. +\ `if` is a *compile-only word*. This means that it can *only* be used when we're compiling a word. \ when creating conditionals, the format is `if` `then` . : ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" then ; \ ok @@ -132,7 +132,41 @@ see square \ dup * ; ok \ ------------------------------ Loops ------------------------------ -\ TODO +\ `do` is like `if` in that it is also a compile-only word, though it uses `loop` as its +\ terminator. + +: myloop ( -- ) 5 0 do cr ." Hello!" loop ; \ ok +test +\ Hello! +\ Hello! +\ Hello! +\ Hello! +\ Hello! ok + +\ `do` expects two numbers before it: the end number and the index number, respectively. +\ (cr means carraige-return, essentially it a newline). This is equivalent to a for-loop +\ in other languages, with a definite number of times to loop. + +\ So what if we want to get the value of the index as we loop? We use `i`. + +: one-to-15 ( -- ) 15 0 do i . loop ; \ ok +one-to-15 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ok +: squares ( -- ) 10 0 do i DUP * . loop ; \ ok +squares \ 0 1 4 9 16 25 36 49 64 81 ok + +\ Thidly, we can also change how large the step is between each loop iteration with `+loop`. +\ `+loop` reads the number on the top of the stack for how far to move each iteration. + +: threes ( -- ) 15 0 do i . 3 +loop ; \ ok +threes \ 0 3 6 9 12 ok + +\ Finally, while loops: + +: death ( -- ) begin ." Are we there yet?" 0 until ; + +\ Will print "Are we there yet?" forever. While loops are constructed in the format +\ of `begin` `until`. The loop will run until flag is a +\ truthy value (not 0). \ ------------------------------ The Return Stack ------------------------------ -- cgit v1.2.3 From e53b98a1187633c09d0b702464efbb435fe3f1c0 Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Wed, 12 Nov 2014 23:59:32 +0100 Subject: yaml-fr fixes --- fr-fr/yaml-fr.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown index 7f962f61..0b4ba032 100644 --- a/fr-fr/yaml-fr.html.markdown +++ b/fr-fr/yaml-fr.html.markdown @@ -81,7 +81,7 @@ une_map_imbriquée: # YAML autorise aussi l'usage des collections à l'intérieur des clés, # mais certains langages de programmation ne le tolère pas si bien. -# les Séquences ( équivalent des listes ou tableaux ) ressemblent à cela: +# les Séquences( équivalent des listes ou tableaux )ressemblent à cela: une_séquence: - Item 1 - Item 2 @@ -99,7 +99,7 @@ json_map: {"clé": "valeur"} json_seq: [1, 2, 3, "soleil"] ################################# -# AUTRES FONCTIONNALITEES YAML # +# AUTRES FONCTIONNALITÉES YAML # ################################# # YAML possède une fonctionnalité fort utile nommée 'ancres'. Celle-ci @@ -120,14 +120,14 @@ python_complex_number: !!python/complex 1+2j # AUTRES TYPES YAML # ##################### -# YAML comprends aussi les données formatées ISO de type date et datetime, +# YAML interprète également les données formatées ISO de type date et datetime, # pas seulement les chaînes et nombres. datetime: 2001-12-15T02:59:43.1Z datetime_avec_espaces: 2001-12-14 21:59:43.10 -5 date: 2002-12-14 # Le tag !!binary indique que la chaîne à suivre est la représentation binaire -# d'un blob encodé en base64. En clair ? Une image! +# d'un blob encodé en base64. En clair ? Une image ! fichier_gif: !!binary | R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ @@ -140,7 +140,7 @@ set: ? item2 ? item3 -# Comme dans Python, les sets ne sont que des maps contenant des valeurs null; +# Comme dans Python, les sets ne sont que des maps contenant des valeurs null ; # le set précédent est l'équivalent du suivant: set2: item1: null -- cgit v1.2.3 From 9d0aa8abf6f5824272c84adf814d2d7a2c5608fe Mon Sep 17 00:00:00 2001 From: Andrei Curelaru Date: Thu, 13 Nov 2014 00:18:42 +0100 Subject: yaml-fr fixes --- fr-fr/yaml-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown index 0b4ba032..d9b94aa6 100644 --- a/fr-fr/yaml-fr.html.markdown +++ b/fr-fr/yaml-fr.html.markdown @@ -81,7 +81,7 @@ une_map_imbriquée: # YAML autorise aussi l'usage des collections à l'intérieur des clés, # mais certains langages de programmation ne le tolère pas si bien. -# les Séquences( équivalent des listes ou tableaux )ressemblent à cela: +# les Séquences (équivalent des listes ou tableaux) ressemblent à cela: une_séquence: - Item 1 - Item 2 -- cgit v1.2.3 From cc8eb6fed6476f1f387b7a3a31d69c61e6e2efb3 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Wed, 12 Nov 2014 23:55:50 +0000 Subject: Finished outline of Variables and Memory. Must be more vague, this is a whirlwind tour! --- forth.html.markdown | 55 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index ee491e7a..06c2c6dc 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -168,17 +168,64 @@ threes \ 0 3 6 9 12 ok \ of `begin` `until`. The loop will run until flag is a \ truthy value (not 0). -\ ------------------------------ The Return Stack ------------------------------ +\ ------------------------------ Variables and Memory ------------------------------ -\ TODO +\ Sometimes we'll be in a situation where we want more permanent variables: +\ First, we use `variable` to declare `age` to be a variable. +variable age -\ ------------------------------ Variables and Memory ------------------------------ +\ Then we write 21 to age with the word `!`. +21 age ! + +\ Finally we can print our variable using the "read" word '@', which adds the value +\ to the stack, or use a handy word called `?` that reads and prints it in one go. +age @ . \ 12 ok +age ? \ 12 ok + +\ What's happening here is that `age` stores the memory address, and we use `!` +\ and `@` to manipulate it. + +\ Constants are quite simiar, except we don't bother with memory addresses: +100 constant WATER-BOILING-POINT \ ok +WATER-BOILING-POINT . \ 100 ok + +\ Arrays! + +\ Set up an array of length 3: +variable mynumbers 2 cells allot + +\ Initialize all the values to 0 +mynumbers 3 cells erase +\ (alternatively we could do `0 fill` instead of `erase`, but as we're setting +\ them to 0 we just use `erase`). + +\ or we can just skip all the above and initialize with specific values: + +create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! + +\ ...which is equivalent to: + +\ [64, 9001, 1337] +64 mynumbers 0 cells + ! +9001 mynumbers 1 cells + ! +1337 mynumbers 2 cells + ! + +\ Reading values at certain array indexes: +0 cells mynumbers + ? \ 64 ok +1 cells mynumbers + ? \ 9001 ok +2 cells mynumbers + ? \ 1337 ok + +\ Of course, you'll probably want to define your own words to manipulate arrays: +: ?mynumbers ( n -- n ) cells mynumbers + ; \ ok +64 mynumbers 2 cells + ! \ ok +2 ?mynumbers ? \ 64 ok + +\ ------------------------------ The Return Stack ------------------------------ \ TODO \ ------------------------------ Final Notes ------------------------------ -\ Booleans \ Floats \ Commenting (types) \ bye -- cgit v1.2.3 From ae2728d58009abfd7d50c2fbc346e46a58e0c2fc Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 00:02:44 +0000 Subject: Be more brief! --- forth.html.markdown | 51 ++++++++++++--------------------------------------- 1 file changed, 12 insertions(+), 39 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 06c2c6dc..7b805057 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -22,13 +22,11 @@ of what is written here should work elsewhere. \ It's important to know how forth processes instructions. All programming in Forth is \ done by manipulating what's known as the parameter stack (more commonly just referred \ to as "the stack"). The stack is a typical last-in-first-out (LIFO) stack. Typing: - 5 2 3 56 76 23 65 \ Means 5 gets put on the stack first, then 2, then 3, etc all the way to 65, which \ is now at the top of the stack. We can see the length and contents of the stack by \ passing forth the word `.s`: - .s <7> 5 2 3 56 76 23 65 \ ok \ Forth's interpreter interprets what you type in one of two ways: as *words* (i.e. the @@ -41,20 +39,13 @@ of what is written here should work elsewhere. \ Lets do a simple equation: adding 5 and 4. In infix notation this would be 5 + 4, \ but as forth works in postfix (see above about stack manipulation) we input it like so: - 5 4 + \ ok -\ However, this alone yields "ok", yet no answer. Why? The way forth interprets what -\ we typed is as such: 5 gets added to the top of the stack, and then 4. Finally, -\ it runs word `+` on the stack (which pops the top and second value, and adds them), -\ and inserts the result at the top of the stack. Typing the word `.` will yield +\ However, this alone yields "ok", yet no answer. Typing the word `.` will yield \ the result. - . \ 9 ok -\ This should illustrate the fundamentals of forth. Lets do a few more arithmetic -\ tests: - +\ This should illustrate how Forth's stack works. Lets do a few more arithmetic tests: 6 7 * . \ 42 ok 1360 23 - . \ 1337 ok 12 12 / . \ 1 ok @@ -84,14 +75,11 @@ over \ duplicate the second item to the top of the stack n roll \ where n is a number, *move* the stack item at that position to the top of the stack n pick \ where n is a number, *duplicate* the item at that position to the top of the stack -\ 3rd*: when referring to stack indexes, they are zero-based - i.e. the first element is at -\ position 0, the second element is at position 1, etc... Just like indexing arrays in -\ most other languages. +\ When referring to stack indexes, they are zero-based. \ ------------------------------ Creating Words ------------------------------ \ Quite often one will want to write their own words. - : square ( n -- n ) dup * ; \ ok \ Lets break this down. The `:` word says to Forth to enter "compile" mode. After that, @@ -102,39 +90,34 @@ n pick \ where n is a number, *duplicate* the item at that position to the top o \ switch back into interpret mode. \ We can check the definition of a word with the `see` word: - see square \ dup * ; ok \ ------------------------------ Conditionals ------------------------------ \ Booleans: \ In forth, -1 is used to represent truth, and 0 is used to represent false. -\ The idea behind this is that -1 is 11111111 in binary, whereas 0 is obviously 0 in binary. +\ The idea is that -1 is 11111111 in binary, whereas 0 is obviously 0 in binary. \ However, any non-zero value is usually treated as being true: 42 42 = / -1 ok 12 53 = / 0 ok -\ `if` is a *compile-only word*. This means that it can *only* be used when we're compiling a word. -\ when creating conditionals, the format is `if` `then` . +\ `if` is a *compile-only word*. This means that it can only be used when we're compiling a word. +\ when creating conditionals, the format is `if` `then` . : ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" then ; \ ok 100 ?>64 \ Greater than 64! ok -\ This unimaginative example displays "Greater than 64!" when the number on the stack is greater -\ than 64. However, it does nothing when the test is false. Let's fix that with the `else` word! +\ Else: : ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" else ." Less than 64!" then ; \ ok 100 ?>64 \ Greater than 64! ok 20 ?>64 \ Less than 64! ok -\ As you can see, conditionals behave more or less like they do in most programming languages. - \ ------------------------------ Loops ------------------------------ \ `do` is like `if` in that it is also a compile-only word, though it uses `loop` as its -\ terminator. - +\ terminator: : myloop ( -- ) 5 0 do cr ." Hello!" loop ; \ ok test \ Hello! @@ -143,31 +126,21 @@ test \ Hello! \ Hello! ok -\ `do` expects two numbers before it: the end number and the index number, respectively. -\ (cr means carraige-return, essentially it a newline). This is equivalent to a for-loop -\ in other languages, with a definite number of times to loop. - -\ So what if we want to get the value of the index as we loop? We use `i`. +\ `do` expects two numbers on the stack: the end number and the index number, respectively. +\ Get the value of the index as we loop with `i`: : one-to-15 ( -- ) 15 0 do i . loop ; \ ok one-to-15 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ok : squares ( -- ) 10 0 do i DUP * . loop ; \ ok squares \ 0 1 4 9 16 25 36 49 64 81 ok -\ Thidly, we can also change how large the step is between each loop iteration with `+loop`. -\ `+loop` reads the number on the top of the stack for how far to move each iteration. - +\ Change the "step" with `+loop`: : threes ( -- ) 15 0 do i . 3 +loop ; \ ok threes \ 0 3 6 9 12 ok -\ Finally, while loops: - +\ Finally, while loops with `begin` `unil`: : death ( -- ) begin ." Are we there yet?" 0 until ; -\ Will print "Are we there yet?" forever. While loops are constructed in the format -\ of `begin` `until`. The loop will run until flag is a -\ truthy value (not 0). - \ ------------------------------ Variables and Memory ------------------------------ \ Sometimes we'll be in a situation where we want more permanent variables: -- cgit v1.2.3 From e5fbd94af0455cfcac15e398c41a0686b69d38ec Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 00:13:54 +0000 Subject: Refactor section Stack Manipulation. --- forth.html.markdown | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 7b805057..91591ac9 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -56,17 +56,10 @@ of what is written here should work elsewhere. \ Naturally, as we do so much work with the stack, we'll want some useful methods. -drop \ drop (remove) the item at the top of the stack (note the difference between this and `.`) -dup \ duplicate the item on top the stack -rot \ rotate the top three items (third -> first, first -> second, second -> third) -swap \ swaps the top item with the second item - -\ Examples: - -dup * \ square the top item -2 5 dup * swap / \ half the top item squared -6 4 5 rot * - \ sometimes we just want to reorganize -4 0 drop 2 / \ add 4 and 0, remove 0 and divide the top by 2 +3 dup - \ duplicate the top item (1st now equals 2nd): 3 - 3 +2 5 swap / \ swap the top with the second element: 5 / 2 +6 4 5 rot .s \ rotate the top 3 elements: 4 5 6 ok +4 0 drop 2 / \ remove the top item (dont print to screen): 4 / 2 \ ------------------------------ More Advanced Stack Manipulation ------------------------------ @@ -173,7 +166,6 @@ mynumbers 3 cells erase \ them to 0 we just use `erase`). \ or we can just skip all the above and initialize with specific values: - create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! \ ...which is equivalent to: -- cgit v1.2.3 From ba3bc070c5db0b24f485a1a742c0b3944b3bb7e8 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 00:19:20 +0000 Subject: Improve section Advanced Stack Manipulation's examples. --- forth.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 91591ac9..c61633c2 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -52,7 +52,7 @@ of what is written here should work elsewhere. \ And so on. -\ ------------------------------ Stack Maniulation ------------------------------ +\ ------------------------------ Stack Manipulation ------------------------------ \ Naturally, as we do so much work with the stack, we'll want some useful methods. @@ -63,10 +63,10 @@ of what is written here should work elsewhere. \ ------------------------------ More Advanced Stack Manipulation ------------------------------ -tuck \ acts like dup, except it duplicates the top item into the 3rd* position in the stack -over \ duplicate the second item to the top of the stack -n roll \ where n is a number, *move* the stack item at that position to the top of the stack -n pick \ where n is a number, *duplicate* the item at that position to the top of the stack +1 2 3 4 tuck \ duplicate the top item into the second slot: 1 2 4 3 4 ok +1 2 3 4 over \ duplicate the second item to the top: 1 2 3 4 3 ok +1 2 3 4 2 roll \ *move* the item at that position to the top: 1 3 4 2 ok +1 2 3 4 2 pick \ *duplicate* the item at that position to the top: 1 2 3 4 2 ok \ When referring to stack indexes, they are zero-based. -- cgit v1.2.3 From 1482bfc52b65c028c364670ab9f2561e7660a932 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 18:04:56 +0300 Subject: Add not translated verson of javasript --- ru-ru/javascript-ru.html.markdown | 529 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 529 insertions(+) create mode 100644 ru-ru/javascript-ru.html.markdown diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown new file mode 100644 index 00000000..7e2c0cca --- /dev/null +++ b/ru-ru/javascript-ru.html.markdown @@ -0,0 +1,529 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +translators: + - ["--mynamehere--", "http://github.com/--mynamehere--"] +filename: javascript-ru.js +lang: ru-ru +--- + +JavaScript was created by Netscape's Brendan Eich in 1995. It was originally +intended as a simpler scripting language for websites, complementing the use of +Java for more complex web applications, but its tight integration with Web pages +and built-in support in browsers has caused it to become far more common than +Java in web frontends. + +JavaScript isn't just limited to web browsers, though: Node.js, a project that +provides a standalone runtime for Google Chrome's V8 JavaScript engine, is +becoming more and more popular. + +Feedback would be highly appreciated! You can reach me at +[@adambrenecki](https://twitter.com/adambrenecki), or +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// Comments are like C. Single-line comments start with two slashes, +/* and multiline comments start with slash-star + and end with star-slash */ + +// Statements can be terminated by ; +doStuff(); + +// ... but they don't have to be, as semicolons are automatically inserted +// wherever there's a newline, except in certain cases. +doStuff() + +// Because those cases can cause unexpected results, we'll keep on using +// semicolons in this guide. + +/////////////////////////////////// +// 1. Numbers, Strings and Operators + +// JavaScript has one number type (which is a 64-bit IEEE 754 double). +// Doubles have a 52-bit mantissa, which is enough to store integers +// up to about 9✕10¹⁵ precisely. +3; // = 3 +1.5; // = 1.5 + +// Some basic arithmetic works as you'd expect. +1 + 1; // = 2 +.1 + .2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Including uneven division. +5 / 2; // = 2.5 + +// Bitwise operations also work; when you perform a bitwise operation your float +// is converted to a signed int *up to* 32 bits. +1 << 2; // = 4 + +// Precedence is enforced with parentheses. +(1 + 3) * 2; // = 8 + +// There are three special not-a-real-number values: +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0 + +// There's also a boolean type. +true; +false; + +// Strings are created with ' or ". +'abc'; +"Hello, world"; + +// Negation uses the ! symbol +!true; // = false +!false; // = 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 + +// Strings are concatenated with + +"Hello " + "world!"; // = "Hello world!" + +// and are compared with < and > +"a" < "b"; // = true + +// Type coercion is performed for comparisons with double equals... +"5" == 5; // = true +null == undefined; // = true + +// ...unless you use === +"5" === 5; // = false +null === undefined; // = false + +// You can access characters in a string with charAt +"This is a string".charAt(0); // = 'T' + +// ...or use substring to get larger pieces +"Hello world".substring(0, 5); // = "Hello" + +// length is a property, so don't use () +"Hello".length; // = 5 + +// There's also null and undefined +null; // used to indicate a deliberate non-value +undefined; // used to indicate a value is not currently present (although + // undefined is actually a value itself) + +// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. +// Note that 0 is falsy and "0" is truthy, even though 0 == "0". + +/////////////////////////////////// +// 2. Variables, Arrays and Objects + +// Variables are declared with the var keyword. JavaScript is dynamically typed, +// so you don't need to specify type. Assignment uses a single = character. +var someVar = 5; + +// if you leave the var keyword off, you won't get an error... +someOtherVar = 10; + +// ...but your variable will be created in the global scope, not in the scope +// you defined it in. + +// Variables declared without being assigned to are set to undefined. +var someThirdVar; // = undefined + +// There's shorthand for performing math operations on variables: +someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now +someVar *= 10; // now someVar is 100 + +// and an even-shorter-hand for adding or subtracting 1 +someVar++; // now someVar is 101 +someVar--; // back to 100 + +// Arrays are ordered lists of values, of any type. +var myArray = ["Hello", 45, true]; + +// Their members can be accessed using the square-brackets subscript syntax. +// Array indices start at zero. +myArray[1]; // = 45 + +// Arrays are mutable and of variable length. +myArray.push("World"); +myArray.length; // = 4 + +// Add/Modify at specific index +myArray[3] = "Hello"; + +// JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other +// languages: an unordered collection of key-value pairs. +var myObj = {key1: "Hello", key2: "World"}; + +// Keys are strings, but quotes aren't required if they're a valid +// JavaScript identifier. Values can be any type. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Object attributes can also be accessed using the subscript syntax, +myObj["my other key"]; // = 4 + +// ... or using the dot syntax, provided the key is a valid identifier. +myObj.myKey; // = "myValue" + +// Objects are mutable; values can be changed and new keys added. +myObj.myThirdKey = true; + +// If you try to access a value that's not yet set, you'll get undefined. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Logic and Control Structures + +// The syntax for this section is almost identical to Java's. + +// The if structure works as you'd expect. +var count = 1; +if (count == 3){ + // evaluated if count is 3 +} else if (count == 4){ + // evaluated if count is 4 +} else { + // evaluated if it's not either 3 or 4 +} + +// As does while. +while (true){ + // An infinite loop! +} + +// Do-while loops are like while loops, except they always run at least once. +var input +do { + input = getInput(); +} while (!isValid(input)) + +// the for loop is the same as C and Java: +// initialisation; continue condition; iteration. +for (var i = 0; i < 5; i++){ + // will run 5 times +} + +// && is logical and, || is logical or +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // colour is either red or blue +} + +// && and || "short circuit", which is useful for setting default values. +var name = otherName || "default"; + + +// switch statement checks for equality with === +// use 'break' after each case +// or the cases after the correct one will be executed too. +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + +/////////////////////////////////// +// 4. Functions, Scope and Closures + +// JavaScript functions are declared with the function keyword. +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Note that the value to be returned must start on the same line as the +// 'return' keyword, otherwise you'll always return 'undefined' due to +// automatic semicolon insertion. Watch out for this when using Allman style. +function myFunction() +{ + return // <- semicolon automatically inserted here + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// JavaScript functions are first class objects, so they can be reassigned to +// different variable names and passed to other functions as arguments - for +// example, when supplying an event handler: +function myFunction(){ + // this code will be called in 5 seconds' time +} +setTimeout(myFunction, 5000); +// Note: setTimeout isn't part of the JS language, but is provided by browsers +// and Node.js. + +// Function objects don't even have to be declared with a name - you can write +// an anonymous function definition directly into the arguments of another. +setTimeout(function(){ + // this code will be called in 5 seconds' time +}, 5000); + +// JavaScript has function scope; functions get their own scope but other blocks +// do not. +if (true){ + var i = 5; +} +i; // = 5 - not undefined as you'd expect in a block-scoped language + +// This has led to a common pattern of "immediately-executing anonymous +// functions", which prevent temporary variables from leaking into the global +// scope. +(function(){ + var temporary = 5; + // We can access the global scope by assiging to the 'global object', which + // in a web browser is always 'window'. The global object may have a + // different name in non-browser environments such as Node.js. + window.permanent = 10; +})(); +temporary; // raises ReferenceError +permanent; // = 10 + +// One of JavaScript's most powerful features is closures. If a function is +// defined inside another function, the inner function has access to all the +// outer function's variables, even after the outer function exits. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // Inner functions are put in the local scope by default, as if they were + // declared with 'var'. + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will + // exit immediately, and setTimeout will call inner afterwards. However, + // because inner is "closed over" sayHelloInFiveSeconds, inner still has + // access to the 'prompt' variable when it is finally called. +} +sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s + +/////////////////////////////////// +// 5. More about Objects; Constructors and Prototypes + +// Objects can contain functions. +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +// When functions attached to an object are called, they can access the object +// they're attached to using the this keyword. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +// What this is set to has to do with how the function is called, not where +// it's defined. So, our function doesn't work if it isn't called in the +// context of the object. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Inversely, a function can be assigned to the object and gain access to it +// through this, even if it wasn't attached when it was defined. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +// We can also specify a context for a function to execute in when we invoke it +// using 'call' or 'apply'. + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// The 'apply' function is nearly identical, but takes an array for an argument list. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// This is useful when working with a function that accepts a sequence of arguments +// and you want to pass an array. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// But, 'call' and 'apply' are only temporary. When we want it to stick, we can use +// bind. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// Bind can also be used to partially apply (curry) a function. + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// When you call a function with the new keyword, a new object is created, and +// made available to the function via the this keyword. Functions designed to be +// called like that are called constructors. + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Every JavaScript object has a 'prototype'. When you go to access a property +// on an object that doesn't exist on the actual object, the interpreter will +// look at its prototype. + +// Some JS implementations let you access an object's prototype on the magic +// property __proto__. While this is useful for explaining prototypes it's not +// part of the standard; we'll get to standard ways of using prototypes later. +var myObj = { + myString: "Hello world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// This works for functions, too. +myObj.myFunc(); // = "hello world!" + +// Of course, if your property isn't on your prototype, the prototype's +// prototype is searched, and so on. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// There's no copying involved here; each object stores a reference to its +// prototype. This means we can alter the prototype and our changes will be +// reflected everywhere. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// We mentioned that __proto__ was non-standard, and there's no standard way to +// change the prototype of an existing object. However, there are two ways to +// create a new object with a given prototype. + +// The first is Object.create, which is a recent addition to JS, and therefore +// not available in all implementations yet. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// The second way, which works anywhere, has to do with constructors. +// Constructors have a property called prototype. This is *not* the prototype of +// 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; + } +}; +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. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Except, they aren't exactly equivalent. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // This code won't execute, because 0 is falsy. +} +if (Number(0)){ + // This code *will* execute, because Number(0) is truthy. +} + +// However, the wrapper objects and the regular builtins share a prototype, so +// you can actually add functionality to a string, for instance. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// This fact is often used in "polyfilling", which is implementing newer +// features of JavaScript in an older subset of JavaScript, so that they can be +// used in older environments such as outdated browsers. + +// For instance, we mentioned that Object.create isn't yet available in all +// implementations, but we can still use it with this polyfill: +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){}; + Constructor.prototype = proto; + // then use it to create a new, appropriately-prototyped object + return new Constructor(); + } +} +``` + +## Further Reading + +The [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides +excellent documentation for JavaScript as it's used in browsers. Plus, it's a +wiki, so as you learn more you can help others out by sharing your own +knowledge. + +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +covers much of the concepts covered here in more detail. This guide has quite +deliberately only covered the JavaScript language itself; if you want to learn +more about how to use JavaScript in web pages, start by learning about the +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +guide of all the counter-intuitive parts of the language. + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. + +In addition to direct contributors to this article, some content is adapted +from Louie Dinh's Python tutorial on this site, and the [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +on the Mozilla Developer Network. -- cgit v1.2.3 From 3c0733f45ce2de89888ea3dd2a16401df1a4a6b7 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 21:41:16 +0300 Subject: Translate preamble --- ru-ru/javascript-ru.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 7e2c0cca..963805f9 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,16 +9,28 @@ filename: javascript-ru.js lang: ru-ru --- +Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально +предполагалось, что он станет простым вариантом скриптового языка для сайтов, +дополняющий к Java, который в свою очередь использовался бы для более сложных +web-приложений. Но тонкая интегрированность javascript с web-страницей и +встроенная поддержка в браузерах привели к тому, чтобы он стал более +распространен в web-разработке, чем Java. JavaScript was created by Netscape's Brendan Eich in 1995. It was originally intended as a simpler scripting language for websites, complementing the use of Java for more complex web applications, but its tight integration with Web pages and built-in support in browsers has caused it to become far more common than Java in web frontends. +Использование Javascript не ограничивается браузерами. Проект Node.js, +предоставляющий независимую среду выполнения на движке Google Chrome V8 +JavaScript, становится все более популярным. JavaScript isn't just limited to web browsers, though: Node.js, a project that provides a standalone runtime for Google Chrome's V8 JavaScript engine, is becoming more and more popular. +Обратная связь важна и нужна! Вы можете написаться мне +на [@_remedy]() или +[mymail](). Feedback would be highly appreciated! You can reach me at [@adambrenecki](https://twitter.com/adambrenecki), or [adam@brenecki.id.au](mailto:adam@brenecki.id.au). -- cgit v1.2.3 From 89ac5d6b77e84517e8844d694676f9e25d171538 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 21:44:21 +0300 Subject: Translate 1st part --- ru-ru/javascript-ru.html.markdown | 56 ++++++++++++++++++++++++++++++--------- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 963805f9..aa1d1f3c 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -36,29 +36,43 @@ Feedback would be highly appreciated! You can reach me at [adam@brenecki.id.au](mailto:adam@brenecki.id.au). ```js +// Комментарии оформляются как в C. +// Обнострочнные комментарии начинаются с двух слешей, // Comments are like C. Single-line comments start with two slashes, +/* а многострочные с слеша и звездочки + и заканчиваются звездочеий и слешом */ /* and multiline comments start with slash-star and end with star-slash */ +// Выражения разделяются с помощью ; // Statements can be terminated by ; doStuff(); +// ... но этого можно и делать, разделители подставляются автоматически +// после перехода на новую строку за исключением особых случаев // ... but they don't have to be, as semicolons are automatically inserted // wherever there's a newline, except in certain cases. doStuff() +// Это может приводить к непредсказуемому результату и поэтому мы будем +// использовать разделители в этом туре. // Because those cases can cause unexpected results, we'll keep on using // semicolons in this guide. /////////////////////////////////// +// 1. Числа, Строки и Операторы // 1. Numbers, Strings and Operators +// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой стандарта +// IEEE 754) +// todo: сформулировать // JavaScript has one number type (which is a 64-bit IEEE 754 double). // Doubles have a 52-bit mantissa, which is enough to store integers // up to about 9✕10¹⁵ precisely. 3; // = 3 1.5; // = 1.5 +// В основном базовая арифметика работает предсказуемо // Some basic arithmetic works as you'd expect. 1 + 1; // = 2 .1 + .2; // = 0.30000000000000004 @@ -66,76 +80,92 @@ doStuff() 10 * 2; // = 20 35 / 5; // = 7 +// Включая нецелочисленное деление (todo:уточнить!) // Including uneven division. 5 / 2; // = 2.5 +// Двоичные операции тоже есть. Если применить двоичную операцию к float-числу, +// оно будет приведено к 32-битному целому со знаком. // Bitwise operations also work; when you perform a bitwise operation your float // is converted to a signed int *up to* 32 bits. 1 << 2; // = 4 +// (todo:перевести) // Precedence is enforced with parentheses. (1 + 3) * 2; // = 8 +// Есть три особых не реальных числовых значения: // There are three special not-a-real-number values: -Infinity; // result of e.g. 1/0 --Infinity; // result of e.g. -1/0 -NaN; // result of e.g. 0/0 +Infinity; // допустим, результат операции 1/0 +-Infinity; // допустим, результат операции -1/0 +NaN; // допустим, результат операции 0/0 +// Так же есть тип булевых данных. // There's also a boolean type. true; false; +// Строки создаются с помощью ' или ". // Strings are created with ' or ". 'abc'; "Hello, world"; -// Negation uses the ! symbol +// Оператор ! означает отрицание !true; // = false !false; // = 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 -// Strings are concatenated with + +// Строки складываются с помощью + "Hello " + "world!"; // = "Hello world!" -// and are compared with < and > +// и сравниваются с помощью < и > "a" < "b"; // = true +// Приведение типов выполняется при сравнении с ==... // Type coercion is performed for comparisons with double equals... "5" == 5; // = true null == undefined; // = true -// ...unless you use === +// ...в отличие от === "5" === 5; // = false null === undefined; // = false +// Для доступа к конкретному символу строки используйте charAt // You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' +// ... или используйте substring для получения подстроки // ...or use substring to get larger pieces "Hello world".substring(0, 5); // = "Hello" +// length(длина) - свойство, не используйте () // length is a property, so don't use () "Hello".length; // = 5 +// Есть null и undefined // There's also null and undefined -null; // used to indicate a deliberate non-value -undefined; // used to indicate a value is not currently present (although - // undefined is actually a value itself) +null; // используется что бы указать явно, что значения нет +undefined; // испрользуется чтобы показать, что значения не было установлено + // собственно, undefined так и переводится +// false, null, undefined, NaN, 0 и "" являются falsy-значениями(при приведении +// в булеву типу становятся false) // false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. +// Обратите внимание что 0 приводится к false, а "0" к true, не смотря на то, +// что "0"==0 // Note that 0 is falsy and "0" is truthy, even though 0 == "0". /////////////////////////////////// -- cgit v1.2.3 From 27825265f397087a60e597d5a0a1ae44d180ddc5 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 21:58:59 +0300 Subject: Translate part 3 --- ru-ru/javascript-ru.html.markdown | 41 +++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index aa1d1f3c..1369d0d7 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,6 +9,8 @@ filename: javascript-ru.js lang: ru-ru --- +todo: привести все названия языка к коректному написанию + Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально предполагалось, что он станет простым вариантом скриптового языка для сайтов, дополняющий к Java, который в свою очередь использовался бы для более сложных @@ -169,60 +171,83 @@ undefined; // испрользуется чтобы показать, что з // Note that 0 is falsy and "0" is truthy, even though 0 == "0". /////////////////////////////////// -// 2. Variables, Arrays and Objects +// 2. Переменные, массивы и объекты +// Переменные объявляются ключевым словом var. Javascript динамически +// типизируемый, так что указывать тип не нужно. +// Присвоение значения описывается с помощью оператора = // Variables are declared with the var keyword. JavaScript is dynamically typed, // so you don't need to specify type. Assignment uses a single = character. var someVar = 5; +// если не указать ключевого слова var, ошибки не будет... // if you leave the var keyword off, you won't get an error... someOtherVar = 10; +// ...но переменная будет создана в глобальном контексте, в не области +// видимости, в которой она была объявлена. // ...but your variable will be created in the global scope, not in the scope // you defined it in. +// Переменные объявленные без присвоения значения, содержать undefined // Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined +// Для математических операций над числами есть короткая запись: // There's shorthand for performing math operations on variables: -someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now -someVar *= 10; // now someVar is 100 +someVar += 5; // тоже что someVar = someVar + 5; someVar равно 10 теперь +someVar *= 10; // а теперь -- 100 -// and an even-shorter-hand for adding or subtracting 1 -someVar++; // now someVar is 101 -someVar--; // back to 100 +// еще более короткая запись для добавления и вычитания 1 +someVar++; // теперь someVar равно 101 +someVar--; // обратно к 100 +// Массивы -- упорядоченные списки значений любых типов. // Arrays are ordered lists of values, of any type. var myArray = ["Hello", 45, true]; +// Для доступу к элементам массивов используйте квадратные скобки. +// Индексы массивов начинаются с 0 // Their members can be accessed using the square-brackets subscript syntax. // Array indices start at zero. myArray[1]; // = 45 +// Массивы мутабельны(изменяемы) и имеют переменную длину. // Arrays are mutable and of variable length. -myArray.push("World"); +myArray.push("World"); // добавить элемент myArray.length; // = 4 -// Add/Modify at specific index +// Добавить или изменить значение по конкретному индексу myArray[3] = "Hello"; +// Объёкты javascript похожи на dictionary или map из других языков +// программирования. Это неупорядочнные коллекции пар ключ-значение. // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; +// Ключи -- это строки, но кавычки не требуются если названия явлюятся +// корректными javascript идентификаторами. Значения могут быть любого типа. // Keys are strings, but quotes aren't required if they're a valid // JavaScript identifier. Values can be any type. var myObj = {myKey: "myValue", "my other key": 4}; +// Доступ к атрибту объекта можно получить с помощью квадратных скобок // Object attributes can also be accessed using the subscript syntax, myObj["my other key"]; // = 4 +// ... или используя точечную нотацию, при условии что ключ является +// корректным идентификатором // ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey; // = "myValue" +// Объекты мутабельны. В существуюещем объекте можно изменить значние +// или добавить новый атрибут // Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true; +// При попытке доступа к атрибуту, который до этого не был создан, будет +// возвращен undefined // If you try to access a value that's not yet set, you'll get undefined. myObj.myFourthKey; // = undefined -- cgit v1.2.3 From 4fefe7ac06d2cfc87c0de263ea87475daa96248e Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sat, 1 Nov 2014 22:54:49 +0300 Subject: Translate Logic and Control Structures --- ru-ru/javascript-ru.html.markdown | 44 ++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 1369d0d7..c0e4c0fa 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -252,65 +252,79 @@ myObj.myThirdKey = true; myObj.myFourthKey; // = undefined /////////////////////////////////// +// 3. Логика и управляющие структуры // 3. Logic and Control Structures +// +// Синтаксис управляющих структур очень похож на его реализацию в Java. // The syntax for this section is almost identical to Java's. +// if работает так как вы ожидаете. // The if structure works as you'd expect. var count = 1; if (count == 3){ - // evaluated if count is 3 + // выполнится, если значение count равно 3 } else if (count == 4){ - // evaluated if count is 4 + // выполнится, если значение count равно 4 } else { - // evaluated if it's not either 3 or 4 + // выполнится, если значение countне будет равно ни 3 ни 4 } -// As does while. +// Поведение while тоже вполне предсказуемо while (true){ - // An infinite loop! + // Бесконечный цикл } +// Циклы do-while похожи на while, но они всегда выполняются хотябы 1 раз. // Do-while loops are like while loops, except they always run at least once. var input do { input = getInput(); } while (!isValid(input)) +// Цикл for такой же как в C b Java: +// инициализация; условие продолжения; итерация // the for loop is the same as C and Java: // initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ + // выполнится 5 раз // will run 5 times } +// && - логическое и, || - логическое или // && is logical and, || is logical or -if (house.size == "big" && house.colour == "blue"){ +if (house.size == "big" && house.color == "blue"){ house.contains = "bear"; } -if (colour == "red" || colour == "blue"){ +if (color == "red" || color == "blue"){ + // если цвет или красный или синий // colour is either red or blue } +// && и || удобны для установки значений по умолчанию. // && and || "short circuit", which is useful for setting default values. var name = otherName || "default"; +// выражение switch проверяет равество с помощью === +// используйте 'break' после каждого case +// иначе помимо правильного case выполнятся и все последующие. // switch statement checks for equality with === // use 'break' after each case // or the cases after the correct one will be executed too. -grade = 'B'; +grade = '4'; // оценка switch (grade) { - case 'A': - console.log("Great job"); + case '5': + console.log("Великолепно"); break; - case 'B': - console.log("OK job"); + case '4': + console.log("Неплохо"); break; - case 'C': - console.log("You can do better"); + case '3': + console.log("Можно и лучше"); break; default: - console.log("Oy vey"); + console.log("Да уж."); break; } -- cgit v1.2.3 From b1ec17dae0827b4c17d18399d4bd666a9e617bc4 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sat, 1 Nov 2014 22:55:18 +0300 Subject: Fix grammar --- 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 c0e4c0fa..a22055ef 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -237,12 +237,12 @@ var myObj = {myKey: "myValue", "my other key": 4}; myObj["my other key"]; // = 4 // ... или используя точечную нотацию, при условии что ключ является -// корректным идентификатором +// корректным идентификатором. // ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey; // = "myValue" // Объекты мутабельны. В существуюещем объекте можно изменить значние -// или добавить новый атрибут +// или добавить новый атрибут. // Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true; -- cgit v1.2.3 From 44615813763e218e4f1140ff6c9dbcdd6948d858 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sat, 1 Nov 2014 23:21:54 +0300 Subject: Translate 4. Functions, Scope and Closures --- ru-ru/javascript-ru.html.markdown | 50 ++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index a22055ef..b5556f49 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -330,79 +330,117 @@ switch (grade) { /////////////////////////////////// +// 4. Функции, Область видимости и Замыкания // 4. Functions, Scope and Closures +// Функции в JavaScript объявляются с помощью ключевого слова function. // JavaScript functions are declared with the function keyword. function myFunction(thing){ - return thing.toUpperCase(); + return thing.toUpperCase(); // приведение к верхнему регистру } myFunction("foo"); // = "FOO" +// Помните, что значение, которое должно быть возкращено должно начинаться +// на той же строке, где расположено ключевое слово 'return'. В противном случае +// будет возвращено undefined. Такое поведения объясняется автоматической +// вставкой разделителей ';'. Оглядывйтесь на этот факт, если используете +// BSD стиль оформления кода. // Note that the value to be returned must start on the same line as the // 'return' keyword, otherwise you'll always return 'undefined' due to // automatic semicolon insertion. Watch out for this when using Allman style. function myFunction() { - return // <- semicolon automatically inserted here + return // <- разделитель автоматически будет вставлен здесь { thisIsAn: 'object literal' } } myFunction(); // = undefined +// Функции в JavaScript являются объектами, поэтому их можно назначить в +// переменные с разными названиями и передавать в другие функции, как аргументы, +// на пример, при указании обработчика события. // JavaScript functions are first class objects, so they can be reassigned to // different variable names and passed to other functions as arguments - for // example, when supplying an event handler: function myFunction(){ + // этот фрагмент кода будет вызван через 5 секунд // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000); +// Обратите внимание, что setTimeout не является частью языка, однако он +// доступен в API браузеров и Node.js. // Note: setTimeout isn't part of the JS language, but is provided by browsers // and Node.js. +// Объект функции на самом деле не обязательно объявлять с именем - можно +// создать анонимную функцию прямо в аргументах другой функции. // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. setTimeout(function(){ + // этот фрагмент кода будет вызван через 5 секунд // this code will be called in 5 seconds' time }, 5000); +// В JavaScript есть области видимости. У функций есть собственные области +// видимости, у других блоков их нет. // JavaScript has function scope; functions get their own scope but other blocks // do not. if (true){ var i = 5; } -i; // = 5 - not undefined as you'd expect in a block-scoped language +i; // = 5, а не undefined, как это было бы ожидаемо(todo: поправить) + // в языке, создающем области видисти для блоков " +// Это привело к появлению паттерна общего назначения "immediately-executing +// anonymous functions" (сразу выполняющиеся анонимные функции), который +// позволяет предотвратить запись временных переменных в общую облать видимости. // This has led to a common pattern of "immediately-executing anonymous // functions", which prevent temporary variables from leaking into the global // scope. (function(){ var temporary = 5; + // Для доступа к глобальной области видимости можно использовать запись в + // некоторый 'глобальный объект', для браузеров это 'window'. Глобальный + // объект может называться по-разному в небраузерных средах, таких Node.js. // We can access the global scope by assiging to the 'global object', which // in a web browser is always 'window'. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10; })(); -temporary; // raises ReferenceError +temporary; // вызывает исключение ReferenceError permanent; // = 10 +// Одной из сильных сторон JavaScript являются замыкания. Если функция +// объявлена в вниутри другой функции, внутренняя функция имеет доступ ко всем +// переменным внешней функции, даже после того, как внешняя функции завершила +// свое выполнение // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the // outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!"; + var prompt = "Привет, " + name + "!"; + // Внутренние фунции помещаются в локальную область видимости, как-будто они + // объявлены с ключевым словом 'var'. // Inner functions are put in the local scope by default, as if they were // declared with 'var'. function inner(){ alert(prompt); } setTimeout(inner, 5000); + // setTimeout является асинхроннной, и поэтому функция sayHelloInFiveSeconds + // завершит свое выполнение сразу и setTimeout вызовет inner позже. + // Однако, так как inner "замкнута"(todo: уточнить "закрыта внутри") + // sayHelloInFiveSeconds, inner все еще будет иметь доступ к переменной + // prompt, когда будет вызвана. // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will // exit immediately, and setTimeout will call inner afterwards. However, // because inner is "closed over" sayHelloInFiveSeconds, inner still has // access to the 'prompt' variable when it is finally called. } -sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s +sayHelloInFiveSeconds("Вася"); // откроет модальное окно с сообщением + // "Привет, Вася" по истечении 5 секунд. + /////////////////////////////////// // 5. More about Objects; Constructors and Prototypes -- cgit v1.2.3 From 6e694a82b2503a2cce524df96c1c59af6d4ecdea Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sun, 2 Nov 2014 01:12:22 +0300 Subject: Translate last chapter --- ru-ru/javascript-ru.html.markdown | 59 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 4 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index b5556f49..f0c91278 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -443,8 +443,10 @@ sayHelloInFiveSeconds("Вася"); // откроет модальное окно /////////////////////////////////// +// 5. Немного об Объектах. Конструкторы и Прототипы // 5. More about Objects; Constructors and Prototypes +// Объекты погут содержать функции // Objects can contain functions. var myObj = { myFunc: function(){ @@ -453,6 +455,8 @@ var myObj = { }; myObj.myFunc(); // = "Hello world!" +// Когда функции прикрепленные к объекту вызываются, они могут получить доступ +// к данным объекта, ипользую ключевое слово this. // When functions attached to an object are called, they can access the object // they're attached to using the this keyword. myObj = { @@ -463,12 +467,17 @@ myObj = { }; myObj.myFunc(); // = "Hello world!" +// Содержание this определяется исходя из того, как была вызвана функция, а +// не места её определения. По этой причине наша функция не будет работать вне +// контекста объекта. // What this is set to has to do with how the function is called, not where // it's defined. So, our function doesn't work if it isn't called in the // context of the object. var myFunc = myObj.myFunc; myFunc(); // = undefined +// И напротив, функция может быть присвоена объекту и получить доступ к нему +// через this, даже если она не была прикреплена к объекту в момент её создания. // Inversely, a function can be assigned to the object and gain access to it // through this, even if it wasn't attached when it was defined. var myOtherFunc = function(){ @@ -477,6 +486,7 @@ var myOtherFunc = function(){ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" +// Также можно указать контекс выполнения фунции с помощью 'call' или 'apply'. // We can also specify a context for a function to execute in when we invoke it // using 'call' or 'apply'. @@ -485,10 +495,13 @@ var anotherFunc = function(s){ } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" +// Функция 'apply' очень похожа, но принимает массив со списком аргументов. // The 'apply' function is nearly identical, but takes an array for an argument list. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" +// Это может быть удобно, когда работаешь с фунцией принимающей на вход +// последовательность аргументов и нужно передать их в виде массива. // This is useful when working with a function that accepts a sequence of arguments // and you want to pass an array. @@ -496,18 +509,25 @@ Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) Math.min.apply(Math, [42, 6, 27]); // = 6 +// Однако, 'call' и 'apply' не имеют постоянного эффекта. Если вы хотите +// зафиксировать контекст для функции, используйте bind. // But, 'call' and 'apply' are only temporary. When we want it to stick, we can use // bind. var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" +// bind можно использовать чтобы частично передать аргументы в +// функцию (каррировать). // Bind can also be used to partially apply (curry) a function. var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 +// Когда функция вызывается с ключевым словом new, создается новый объект. +// Данный объект становится доступным функции через ключевое слово this. +// Функции спроектированные вызываться таким способом называются конструкторами. // When you call a function with the new keyword, a new object is created, and // made available to the function via the this keyword. Functions designed to be // called like that are called constructors. @@ -518,10 +538,17 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 +// Любой объект в JavaScript имеет 'прототип'. Когда выпытаетесь получить доступ +// к свойству не объявленному в данном объекте, интерпретатор будет искать его +// в прототипе. // Every JavaScript object has a 'prototype'. When you go to access a property // on an object that doesn't exist on the actual object, the interpreter will // look at its prototype. +// Некоторые реализации JS позволяют получить доступ к прототипу с помощью +// волшебного свойства __proto__. До момента пока оно не являются стандартным, +// __proto__ полезно лишь для изучения прототипов в JavaScript. Мы разберемся +// со стандартными способами работы с прототипом несколько позже. // Some JS implementations let you access an object's prototype on the magic // property __proto__. While this is useful for explaining prototypes it's not // part of the standard; we'll get to standard ways of using prototypes later. @@ -537,10 +564,10 @@ var myPrototype = { myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 - -// This works for functions, too. myObj.myFunc(); // = "hello world!" +// Естествно, если в свойства нет в прототипе, поиск будет продолжен в прототипе +// прототипа и так далее. // Of course, if your property isn't on your prototype, the prototype's // prototype is searched, and so on. myPrototype.__proto__ = { @@ -548,21 +575,32 @@ myPrototype.__proto__ = { }; myObj.myBoolean; // = true +// Ничего не копируется, каждый объект хранит ссылку на свой прототип. Если +// изменить прототип, все изменения отразятся во всех его потомках. // There's no copying involved here; each object stores a reference to its // prototype. This means we can alter the prototype and our changes will be // reflected everywhere. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 +// Как было сказано выше, __proto__ не является стандартом, и нет стандартного +// способа изменить прототип у созданного объекта. Однако, есть два способа +// создать объект с заданным прототипом. // We mentioned that __proto__ was non-standard, and there's no standard way to // change the prototype of an existing object. However, there are two ways to // create a new object with a given prototype. +// Первый способ - Object.create, был добавлен в JS относительно недавно, и +// потому не доступен в более ранних реализациях языка. // The first is Object.create, which is a recent addition to JS, and therefore // not available in all implementations yet. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 +// Второй вариан доступен везде и связан с конструкторами. Конструкторы имеют +// свойство prototype. Это воовсе не прототип функции конструктора, напротив, +// это прототип, который присваевается новым объектам, созданным с этим +// конструктором с помощью ключевого слова new. // The second way, which works anywhere, has to do with constructors. // Constructors have a property called prototype. This is *not* the prototype of // the constructor function itself; instead, it's the prototype that new objects @@ -578,23 +616,30 @@ myNewObj2.getMyNumber(); // = 5 myNewObj2.myNumber = 6 myNewObj2.getMyNumber(); // = 6 +// У встроенных типов таких, как строки и числа, тоже есть конструкторы, +// создающие эквивалентные объекты-обертки. // Built-in types like strings and numbers also have constructors that create // equivalent wrapper objects. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true +// Правда, они не совсем эквивалентны. // Except, they aren't exactly equivalent. typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ + // Этот фрагмент кода не будет выпонен, так как 0 приводится к false // This code won't execute, because 0 is falsy. } if (Number(0)){ + // Этот фрагмент кода *будет* выпонен, так как Number(0) приводится к true. // This code *will* execute, because Number(0) is truthy. } +// Однако, оберточные объекты и обычные встроенные типы имеют общие прототипы, +// следовательно вы можете расширить функциональность строки, например. // However, the wrapper objects and the regular builtins share a prototype, so // you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ @@ -602,17 +647,23 @@ String.prototype.firstCharacter = function(){ } "abc".firstCharacter(); // = "a" +// Этот факт часто используется для создания полифилов(polyfill) - реализации +// новых возможностей JS в его болле старых версиях для того чтобы их можно было +// использовать в устаревших браузерах. // This fact is often used in "polyfilling", which is implementing newer // features of JavaScript in an older subset of JavaScript, so that they can be // used in older environments such as outdated browsers. +// Например, мы упомянули, что Object.create не доступен во всех версиях +// JavaScript, но мы може создать полифилл. // For instance, we mentioned that Object.create isn't yet available in all // implementations, but we can still use it with this polyfill: -if (Object.create === undefined){ // don't overwrite it if it exists +if (Object.create === undefined){ // не переопределяем если есть Object.create = function(proto){ - // make a temporary constructor with the right prototype + // создаем временный конструктор с заданным прототипом var Constructor = function(){}; Constructor.prototype = proto; + // создаём новый объект с правильным прототипом // then use it to create a new, appropriately-prototyped object return new Constructor(); } -- cgit v1.2.3 From 821880e95f4b61cdb89eebc7d0077a069b43a2a6 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 13 Nov 2014 11:32:51 +0300 Subject: =?UTF-8?q?=C2=A0Add=20Further=20Reading?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ru-ru/javascript-ru.html.markdown | 39 ++++++++++++++++----------------------- 1 file changed, 16 insertions(+), 23 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index f0c91278..1f0cfb3f 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -655,7 +655,7 @@ String.prototype.firstCharacter = function(){ // used in older environments such as outdated browsers. // Например, мы упомянули, что Object.create не доступен во всех версиях -// JavaScript, но мы може создать полифилл. +// JavaScript, но мы можем создать полифилл. // For instance, we mentioned that Object.create isn't yet available in all // implementations, but we can still use it with this polyfill: if (Object.create === undefined){ // не переопределяем если есть @@ -670,30 +670,23 @@ if (Object.create === undefined){ // не переопределяем если } ``` -## Further Reading +## Что еще почитать -The [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides -excellent documentation for JavaScript as it's used in browsers. Plus, it's a -wiki, so as you learn more you can help others out by sharing your own -knowledge. +[Современный учебник JavaScript](http://learn.javascript.ru/) от Ильи Кантора +является довольно качественным и глубоким учебным материалом, освещающим все +особенности современного языка. Помимо учебника на том же домене можно найти +[перевод спецификации ECMAScript 5.1](http://es5.javascript.ru/) и справочник по +возможностям языка. -MDN's [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -covers much of the concepts covered here in more detail. This guide has quite -deliberately only covered the JavaScript language itself; if you want to learn -more about how to use JavaScript in web pages, start by learning about the -[Document Object -Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) позволяет +довольно быстро изучить основные тонкие места в работе с JS, но фокусируется +только на таких моментах -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. +[Справочник](https://developer.mozilla.org/ru/docs/JavaScript) от MDN +(Mozilla Development Network) содержит информацию о возможностях языка на +английском. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth -guide of all the counter-intuitive parts of the language. +Название проекта ["Принципы написания консистентного, идиоматического кода на +JavaScript"](https://github.com/rwaldron/idiomatic.js/tree/master/translations/ru_RU) +говорит само за себя. -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. - -In addition to direct contributors to this article, some content is adapted -from Louie Dinh's Python tutorial on this site, and the [JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -on the Mozilla Developer Network. -- cgit v1.2.3 From 958ba0d69e9c4ac21a39d37b61f7dea1b5a155de Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 13 Nov 2014 12:28:49 +0300 Subject: Remove comments with english + fix some typo --- ru-ru/javascript-ru.html.markdown | 235 +++++++------------------------------- 1 file changed, 44 insertions(+), 191 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 1f0cfb3f..abbafc8d 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - - ["--mynamehere--", "http://github.com/--mynamehere--"] + - ["Maxim Koretskiy", "http://github.com/maximkoretskiy"] filename: javascript-ru.js lang: ru-ru --- @@ -13,47 +13,30 @@ todo: привести все названия языка к коректном Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально предполагалось, что он станет простым вариантом скриптового языка для сайтов, -дополняющий к Java, который в свою очередь использовался бы для более сложных +дополняющий к Java, который бы в свою очередь использовался для более сложных web-приложений. Но тонкая интегрированность javascript с web-страницей и встроенная поддержка в браузерах привели к тому, чтобы он стал более -распространен в web-разработке, чем Java. -JavaScript was created by Netscape's Brendan Eich in 1995. It was originally -intended as a simpler scripting language for websites, complementing the use of -Java for more complex web applications, but its tight integration with Web pages -and built-in support in browsers has caused it to become far more common than -Java in web frontends. - -Использование Javascript не ограничивается браузерами. Проект Node.js, +распространен в frontend-разработке, чем Java. + +Использование JavaScript не ограничивается браузерами. Проект Node.js, предоставляющий независимую среду выполнения на движке Google Chrome V8 JavaScript, становится все более популярным. -JavaScript isn't just limited to web browsers, though: Node.js, a project that -provides a standalone runtime for Google Chrome's V8 JavaScript engine, is -becoming more and more popular. Обратная связь важна и нужна! Вы можете написаться мне -на [@_remedy]() или -[mymail](). -Feedback would be highly appreciated! You can reach me at -[@adambrenecki](https://twitter.com/adambrenecki), or +на [@adambrenecki](https://twitter.com/adambrenecki) или [adam@brenecki.id.au](mailto:adam@brenecki.id.au). ```js // Комментарии оформляются как в C. -// Обнострочнные комментарии начинаются с двух слешей, -// Comments are like C. Single-line comments start with two slashes, +// Однострочнные коментарии начинаются с двух слешей, /* а многострочные с слеша и звездочки и заканчиваются звездочеий и слешом */ -/* and multiline comments start with slash-star - and end with star-slash */ // Выражения разделяются с помощью ; -// Statements can be terminated by ; doStuff(); -// ... но этого можно и делать, разделители подставляются автоматически +// ... но этого можно и не делать, разделители подставляются автоматически // после перехода на новую строку за исключением особых случаев -// ... but they don't have to be, as semicolons are automatically inserted -// wherever there's a newline, except in certain cases. doStuff() // Это может приводить к непредсказуемому результату и поэтому мы будем @@ -65,50 +48,41 @@ doStuff() // 1. Числа, Строки и Операторы // 1. Numbers, Strings and Operators -// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой стандарта -// IEEE 754) -// todo: сформулировать -// JavaScript has one number type (which is a 64-bit IEEE 754 double). -// Doubles have a 52-bit mantissa, which is enough to store integers -// up to about 9✕10¹⁵ precisely. +// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой +// стандарта IEEE 754) +// Числа имеют 52-битную мантиссу, чего достаточно для хранения хранения целых +// чисел до 9✕10¹⁵ приблизительно. 3; // = 3 1.5; // = 1.5 // В основном базовая арифметика работает предсказуемо -// Some basic arithmetic works as you'd expect. 1 + 1; // = 2 .1 + .2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 -// Включая нецелочисленное деление (todo:уточнить!) -// Including uneven division. +// Включая нецелочисленное деление 5 / 2; // = 2.5 // Двоичные операции тоже есть. Если применить двоичную операцию к float-числу, // оно будет приведено к 32-битному целому со знаком. -// Bitwise operations also work; when you perform a bitwise operation your float -// is converted to a signed int *up to* 32 bits. 1 << 2; // = 4 // (todo:перевести) -// Precedence is enforced with parentheses. +// Приоритет выполнения операций можно менять с помощью скобок. (1 + 3) * 2; // = 8 // Есть три особых не реальных числовых значения: -// There are three special not-a-real-number values: Infinity; // допустим, результат операции 1/0 -Infinity; // допустим, результат операции -1/0 NaN; // допустим, результат операции 0/0 // Так же есть тип булевых данных. -// There's also a boolean type. true; false; // Строки создаются с помощью ' или ". -// Strings are created with ' or ". 'abc'; "Hello, world"; @@ -137,7 +111,6 @@ false; "a" < "b"; // = true // Приведение типов выполняется при сравнении с ==... -// Type coercion is performed for comparisons with double equals... "5" == 5; // = true null == undefined; // = true @@ -146,29 +119,23 @@ null == undefined; // = true null === undefined; // = false // Для доступа к конкретному символу строки используйте charAt -// You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' // ... или используйте substring для получения подстроки -// ...or use substring to get larger pieces "Hello world".substring(0, 5); // = "Hello" // length(длина) - свойство, не используйте () -// length is a property, so don't use () "Hello".length; // = 5 // Есть null и undefined -// There's also null and undefined null; // используется что бы указать явно, что значения нет undefined; // испрользуется чтобы показать, что значения не было установлено // собственно, undefined так и переводится // false, null, undefined, NaN, 0 и "" являются falsy-значениями(при приведении // в булеву типу становятся false) -// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. -// Обратите внимание что 0 приводится к false, а "0" к true, не смотря на то, -// что "0"==0 -// Note that 0 is falsy and "0" is truthy, even though 0 == "0". +// Обратите внимание что 0 приводится к false, а "0" к true, +// не смотря на то, что "0"==0 /////////////////////////////////// // 2. Переменные, массивы и объекты @@ -176,25 +143,18 @@ undefined; // испрользуется чтобы показать, что з // Переменные объявляются ключевым словом var. Javascript динамически // типизируемый, так что указывать тип не нужно. // Присвоение значения описывается с помощью оператора = -// Variables are declared with the var keyword. JavaScript is dynamically typed, -// so you don't need to specify type. Assignment uses a single = character. var someVar = 5; // если не указать ключевого слова var, ошибки не будет... -// if you leave the var keyword off, you won't get an error... someOtherVar = 10; // ...но переменная будет создана в глобальном контексте, в не области // видимости, в которой она была объявлена. -// ...but your variable will be created in the global scope, not in the scope -// you defined it in. // Переменные объявленные без присвоения значения, содержать undefined -// Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined -// Для математических операций над числами есть короткая запись: -// There's shorthand for performing math operations on variables: +// Для математических операций над переменными есть короткая запись: someVar += 5; // тоже что someVar = someVar + 5; someVar равно 10 теперь someVar *= 10; // а теперь -- 100 @@ -203,71 +163,55 @@ someVar++; // теперь someVar равно 101 someVar--; // обратно к 100 // Массивы -- упорядоченные списки значений любых типов. -// Arrays are ordered lists of values, of any type. var myArray = ["Hello", 45, true]; // Для доступу к элементам массивов используйте квадратные скобки. // Индексы массивов начинаются с 0 -// Their members can be accessed using the square-brackets subscript syntax. -// Array indices start at zero. myArray[1]; // = 45 // Массивы мутабельны(изменяемы) и имеют переменную длину. -// Arrays are mutable and of variable length. myArray.push("World"); // добавить элемент myArray.length; // = 4 // Добавить или изменить значение по конкретному индексу myArray[3] = "Hello"; -// Объёкты javascript похожи на dictionary или map из других языков +// Объекты javascript похожи на dictionary или map из других языков // программирования. Это неупорядочнные коллекции пар ключ-значение. -// JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other -// languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; // Ключи -- это строки, но кавычки не требуются если названия явлюятся // корректными javascript идентификаторами. Значения могут быть любого типа. -// Keys are strings, but quotes aren't required if they're a valid -// JavaScript identifier. Values can be any type. var myObj = {myKey: "myValue", "my other key": 4}; // Доступ к атрибту объекта можно получить с помощью квадратных скобок -// Object attributes can also be accessed using the subscript syntax, myObj["my other key"]; // = 4 // ... или используя точечную нотацию, при условии что ключ является // корректным идентификатором. -// ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey; // = "myValue" // Объекты мутабельны. В существуюещем объекте можно изменить значние // или добавить новый атрибут. -// Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true; // При попытке доступа к атрибуту, который до этого не был создан, будет // возвращен undefined -// If you try to access a value that's not yet set, you'll get undefined. myObj.myFourthKey; // = undefined /////////////////////////////////// -// 3. Логика и управляющие структуры -// 3. Logic and Control Structures +// 3. Логика и Управляющие структуры -// // Синтаксис управляющих структур очень похож на его реализацию в Java. -// The syntax for this section is almost identical to Java's. // if работает так как вы ожидаете. -// The if structure works as you'd expect. var count = 1; if (count == 3){ // выполнится, если значение count равно 3 } else if (count == 4){ // выполнится, если значение count равно 4 } else { - // выполнится, если значение countне будет равно ни 3 ни 4 + // выполнится, если значение count не будет равно ни 3 ни 4 } // Поведение while тоже вполне предсказуемо @@ -282,36 +226,27 @@ do { input = getInput(); } while (!isValid(input)) -// Цикл for такой же как в C b Java: +// Цикл for такой же как в C и Java: // инициализация; условие продолжения; итерация -// the for loop is the same as C and Java: -// initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ // выполнится 5 раз - // will run 5 times } // && - логическое и, || - логическое или -// && is logical and, || is logical or if (house.size == "big" && house.color == "blue"){ house.contains = "bear"; } if (color == "red" || color == "blue"){ // если цвет или красный или синий - // colour is either red or blue } // && и || удобны для установки значений по умолчанию. // && and || "short circuit", which is useful for setting default values. var name = otherName || "default"; - -// выражение switch проверяет равество с помощью === -// используйте 'break' после каждого case +// выражение switch проверяет равество с помощью === +// используйте 'break' после каждого case, // иначе помимо правильного case выполнятся и все последующие. -// switch statement checks for equality with === -// use 'break' after each case -// or the cases after the correct one will be executed too. grade = '4'; // оценка switch (grade) { case '5': @@ -331,10 +266,8 @@ switch (grade) { /////////////////////////////////// // 4. Функции, Область видимости и Замыкания -// 4. Functions, Scope and Closures // Функции в JavaScript объявляются с помощью ключевого слова function. -// JavaScript functions are declared with the function keyword. function myFunction(thing){ return thing.toUpperCase(); // приведение к верхнему регистру } @@ -343,7 +276,7 @@ myFunction("foo"); // = "FOO" // Помните, что значение, которое должно быть возкращено должно начинаться // на той же строке, где расположено ключевое слово 'return'. В противном случае // будет возвращено undefined. Такое поведения объясняется автоматической -// вставкой разделителей ';'. Оглядывйтесь на этот факт, если используете +// вставкой разделителей ';'. Помните этот факт, если используете // BSD стиль оформления кода. // Note that the value to be returned must start on the same line as the // 'return' keyword, otherwise you'll always return 'undefined' due to @@ -360,94 +293,66 @@ myFunction(); // = undefined // Функции в JavaScript являются объектами, поэтому их можно назначить в // переменные с разными названиями и передавать в другие функции, как аргументы, // на пример, при указании обработчика события. -// JavaScript functions are first class objects, so they can be reassigned to -// different variable names and passed to other functions as arguments - for -// example, when supplying an event handler: function myFunction(){ // этот фрагмент кода будет вызван через 5 секунд - // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000); // Обратите внимание, что setTimeout не является частью языка, однако он // доступен в API браузеров и Node.js. -// Note: setTimeout isn't part of the JS language, but is provided by browsers -// and Node.js. // Объект функции на самом деле не обязательно объявлять с именем - можно // создать анонимную функцию прямо в аргументах другой функции. -// Function objects don't even have to be declared with a name - you can write -// an anonymous function definition directly into the arguments of another. setTimeout(function(){ // этот фрагмент кода будет вызван через 5 секунд - // this code will be called in 5 seconds' time }, 5000); // В JavaScript есть области видимости. У функций есть собственные области // видимости, у других блоков их нет. -// JavaScript has function scope; functions get their own scope but other blocks -// do not. if (true){ var i = 5; } -i; // = 5, а не undefined, как это было бы ожидаемо(todo: поправить) - // в языке, создающем области видисти для блоков " +i; // = 5, а не undefined, как это было бы в языке, создающем + // области видисти для блоков кода // Это привело к появлению паттерна общего назначения "immediately-executing // anonymous functions" (сразу выполняющиеся анонимные функции), который // позволяет предотвратить запись временных переменных в общую облать видимости. -// This has led to a common pattern of "immediately-executing anonymous -// functions", which prevent temporary variables from leaking into the global -// scope. (function(){ var temporary = 5; // Для доступа к глобальной области видимости можно использовать запись в // некоторый 'глобальный объект', для браузеров это 'window'. Глобальный // объект может называться по-разному в небраузерных средах, таких Node.js. - // We can access the global scope by assiging to the 'global object', which - // in a web browser is always 'window'. The global object may have a - // different name in non-browser environments such as Node.js. window.permanent = 10; })(); temporary; // вызывает исключение ReferenceError permanent; // = 10 // Одной из сильных сторон JavaScript являются замыкания. Если функция -// объявлена в вниутри другой функции, внутренняя функция имеет доступ ко всем +// объявлена в внутри другой функции, внутренняя функция имеет доступ ко всем // переменным внешней функции, даже после того, как внешняя функции завершила -// свое выполнение -// One of JavaScript's most powerful features is closures. If a function is -// defined inside another function, the inner function has access to all the -// outer function's variables, even after the outer function exits. +// свое выполнение. function sayHelloInFiveSeconds(name){ var prompt = "Привет, " + name + "!"; - // Внутренние фунции помещаются в локальную область видимости, как-будто они - // объявлены с ключевым словом 'var'. - // Inner functions are put in the local scope by default, as if they were - // declared with 'var'. + // Внутренние функции помещаются в локальную область видимости, как-будто + // они объявлены с ключевым словом 'var'. function inner(){ alert(prompt); } setTimeout(inner, 5000); // setTimeout является асинхроннной, и поэтому функция sayHelloInFiveSeconds // завершит свое выполнение сразу и setTimeout вызовет inner позже. - // Однако, так как inner "замкнута"(todo: уточнить "закрыта внутри") + // Однако, так как inner "закрыта внутри" или "замкнута в" // sayHelloInFiveSeconds, inner все еще будет иметь доступ к переменной // prompt, когда будет вызвана. - // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will - // exit immediately, and setTimeout will call inner afterwards. However, - // because inner is "closed over" sayHelloInFiveSeconds, inner still has - // access to the 'prompt' variable when it is finally called. } sayHelloInFiveSeconds("Вася"); // откроет модальное окно с сообщением // "Привет, Вася" по истечении 5 секунд. /////////////////////////////////// -// 5. Немного об Объектах. Конструкторы и Прототипы -// 5. More about Objects; Constructors and Prototypes +// 5. Немного еще об Объектах. Конструкторы и Прототипы -// Объекты погут содержать функции -// Objects can contain functions. +// Объекты могут содержать функции var myObj = { myFunc: function(){ return "Hello world!"; @@ -456,9 +361,7 @@ var myObj = { myObj.myFunc(); // = "Hello world!" // Когда функции прикрепленные к объекту вызываются, они могут получить доступ -// к данным объекта, ипользую ключевое слово this. -// When functions attached to an object are called, they can access the object -// they're attached to using the this keyword. +// к данным объекта, ипользуя ключевое слово this. myObj = { myString: "Hello world!", myFunc: function(){ @@ -470,16 +373,11 @@ myObj.myFunc(); // = "Hello world!" // Содержание this определяется исходя из того, как была вызвана функция, а // не места её определения. По этой причине наша функция не будет работать вне // контекста объекта. -// What this is set to has to do with how the function is called, not where -// it's defined. So, our function doesn't work if it isn't called in the -// context of the object. var myFunc = myObj.myFunc; myFunc(); // = undefined // И напротив, функция может быть присвоена объекту и получить доступ к нему // через this, даже если она не была прикреплена к объекту в момент её создания. -// Inversely, a function can be assigned to the object and gain access to it -// through this, even if it wasn't attached when it was defined. var myOtherFunc = function(){ return this.myString.toUpperCase(); } @@ -487,23 +385,17 @@ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" // Также можно указать контекс выполнения фунции с помощью 'call' или 'apply'. -// We can also specify a context for a function to execute in when we invoke it -// using 'call' or 'apply'. - var anotherFunc = function(s){ return this.myString + s; } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" // Функция 'apply' очень похожа, но принимает массив со списком аргументов. -// The 'apply' function is nearly identical, but takes an array for an argument list. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" // Это может быть удобно, когда работаешь с фунцией принимающей на вход // последовательность аргументов и нужно передать их в виде массива. -// This is useful when working with a function that accepts a sequence of arguments -// and you want to pass an array. Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) @@ -511,15 +403,12 @@ Math.min.apply(Math, [42, 6, 27]); // = 6 // Однако, 'call' и 'apply' не имеют постоянного эффекта. Если вы хотите // зафиксировать контекст для функции, используйте bind. -// But, 'call' and 'apply' are only temporary. When we want it to stick, we can use -// bind. var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" -// bind можно использовать чтобы частично передать аргументы в +// bind также можно использовать чтобы частично передать аргументы в // функцию (каррировать). -// Bind can also be used to partially apply (curry) a function. var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); @@ -528,9 +417,6 @@ doubler(8); // = 16 // Когда функция вызывается с ключевым словом new, создается новый объект. // Данный объект становится доступным функции через ключевое слово this. // Функции спроектированные вызываться таким способом называются конструкторами. -// When you call a function with the new keyword, a new object is created, and -// made available to the function via the this keyword. Functions designed to be -// called like that are called constructors. var MyConstructor = function(){ this.myNumber = 5; @@ -538,20 +424,14 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Любой объект в JavaScript имеет 'прототип'. Когда выпытаетесь получить доступ -// к свойству не объявленному в данном объекте, интерпретатор будет искать его -// в прототипе. -// Every JavaScript object has a 'prototype'. When you go to access a property -// on an object that doesn't exist on the actual object, the interpreter will -// look at its prototype. +// Любой объект в JavaScript имеет 'прототип'. Когда вы пытаетесь получить +// доступ к свойству не объявленному в данном объекте, интерпретатор будет +// искать его в прототипе. // Некоторые реализации JS позволяют получить доступ к прототипу с помощью -// волшебного свойства __proto__. До момента пока оно не являются стандартным, +// "волшебного" свойства __proto__. До момента пока оно не являются стандартным, // __proto__ полезно лишь для изучения прототипов в JavaScript. Мы разберемся // со стандартными способами работы с прототипом несколько позже. -// Some JS implementations let you access an object's prototype on the magic -// property __proto__. While this is useful for explaining prototypes it's not -// part of the standard; we'll get to standard ways of using prototypes later. var myObj = { myString: "Hello world!" }; @@ -566,10 +446,8 @@ myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 myObj.myFunc(); // = "hello world!" -// Естествно, если в свойства нет в прототипе, поиск будет продолжен в прототипе -// прототипа и так далее. -// Of course, if your property isn't on your prototype, the prototype's -// prototype is searched, and so on. +// Естественно, если в свойства нет в прототипе, поиск будет продолжен в +// прототипе прототипа и так далее. myPrototype.__proto__ = { myBoolean: true }; @@ -577,34 +455,22 @@ myObj.myBoolean; // = true // Ничего не копируется, каждый объект хранит ссылку на свой прототип. Если // изменить прототип, все изменения отразятся во всех его потомках. -// There's no copying involved here; each object stores a reference to its -// prototype. This means we can alter the prototype and our changes will be -// reflected everywhere. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 // Как было сказано выше, __proto__ не является стандартом, и нет стандартного // способа изменить прототип у созданного объекта. Однако, есть два способа // создать объект с заданным прототипом. -// We mentioned that __proto__ was non-standard, and there's no standard way to -// change the prototype of an existing object. However, there are two ways to -// create a new object with a given prototype. // Первый способ - Object.create, был добавлен в JS относительно недавно, и // потому не доступен в более ранних реализациях языка. -// The first is Object.create, which is a recent addition to JS, and therefore -// not available in all implementations yet. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 // Второй вариан доступен везде и связан с конструкторами. Конструкторы имеют -// свойство prototype. Это воовсе не прототип функции конструктора, напротив, +// свойство prototype. Это вовсе не прототип функции конструктора, напротив, // это прототип, который присваевается новым объектам, созданным с этим // конструктором с помощью ключевого слова new. -// The second way, which works anywhere, has to do with constructors. -// Constructors have a property called prototype. This is *not* the prototype of -// 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(){ @@ -618,53 +484,40 @@ myNewObj2.getMyNumber(); // = 6 // У встроенных типов таких, как строки и числа, тоже есть конструкторы, // создающие эквивалентные объекты-обертки. -// Built-in types like strings and numbers also have constructors that create -// equivalent wrapper objects. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true // Правда, они не совсем эквивалентны. -// Except, they aren't exactly equivalent. typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ // Этот фрагмент кода не будет выпонен, так как 0 приводится к false - // This code won't execute, because 0 is falsy. } if (Number(0)){ // Этот фрагмент кода *будет* выпонен, так как Number(0) приводится к true. - // This code *will* execute, because Number(0) is truthy. } // Однако, оберточные объекты и обычные встроенные типы имеют общие прототипы, // следовательно вы можете расширить функциональность строки, например. -// However, the wrapper objects and the regular builtins share a prototype, so -// you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ return this.charAt(0); } "abc".firstCharacter(); // = "a" // Этот факт часто используется для создания полифилов(polyfill) - реализации -// новых возможностей JS в его болле старых версиях для того чтобы их можно было +// новых возможностей JS в его более старых версиях для того чтобы их можно было // использовать в устаревших браузерах. -// This fact is often used in "polyfilling", which is implementing newer -// features of JavaScript in an older subset of JavaScript, so that they can be -// used in older environments such as outdated browsers. // Например, мы упомянули, что Object.create не доступен во всех версиях // JavaScript, но мы можем создать полифилл. -// For instance, we mentioned that Object.create isn't yet available in all -// implementations, but we can still use it with this polyfill: -if (Object.create === undefined){ // не переопределяем если есть +if (Object.create === undefined){ // не переопределяем, если есть Object.create = function(proto){ // создаем временный конструктор с заданным прототипом var Constructor = function(){}; Constructor.prototype = proto; // создаём новый объект с правильным прототипом - // then use it to create a new, appropriately-prototyped object return new Constructor(); } } -- cgit v1.2.3 From c689f9f8218dfa95fe655364301326f8dbd369b7 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 13 Nov 2014 12:34:19 +0300 Subject: Remove todos --- ru-ru/javascript-ru.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index abbafc8d..ad66b501 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,8 +9,6 @@ filename: javascript-ru.js lang: ru-ru --- -todo: привести все названия языка к коректному написанию - Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально предполагалось, что он станет простым вариантом скриптового языка для сайтов, дополняющий к Java, который бы в свою очередь использовался для более сложных -- cgit v1.2.3 From c0774dc8217fc86025a25936bff2f2981ef12026 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 16:10:56 +0000 Subject: Remove/refactor the descriptions. --- forth.html.markdown | 31 +++++++++++-------------------- 1 file changed, 11 insertions(+), 20 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index c61633c2..34416878 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -21,31 +21,26 @@ of what is written here should work elsewhere. \ It's important to know how forth processes instructions. All programming in Forth is \ done by manipulating what's known as the parameter stack (more commonly just referred -\ to as "the stack"). The stack is a typical last-in-first-out (LIFO) stack. Typing: +\ to as "the stack"). Typing: 5 2 3 56 76 23 65 -\ Means 5 gets put on the stack first, then 2, then 3, etc all the way to 65, which -\ is now at the top of the stack. We can see the length and contents of the stack by -\ passing forth the word `.s`: -.s <7> 5 2 3 56 76 23 65 \ ok +\ Makes those numbers get added to the stack, from left to right. +.s \ <7> 5 2 3 56 76 23 65 ok \ Forth's interpreter interprets what you type in one of two ways: as *words* (i.e. the \ name of subroutines) or as *numbers*. Words are essentially "symbols that do things". -\ Finally, as the stack is LIFO, we obviously must use postfix notation to manipulate -\ the stack. This should become clear shortly. - \ ------------------------------ Basic Arithmetic ------------------------------ -\ Lets do a simple equation: adding 5 and 4. In infix notation this would be 5 + 4, -\ but as forth works in postfix (see above about stack manipulation) we input it like so: +\ Arithmetic (in fact most words requiring data) works by manipulating data on +\ the stack. 5 4 + \ ok -\ However, this alone yields "ok", yet no answer. Typing the word `.` will yield -\ the result. +\ This adds 5 and 4 to the stack and then `+` is called, which removes them and +\ adds the result to the stack. We can see it with `.`: . \ 9 ok -\ This should illustrate how Forth's stack works. Lets do a few more arithmetic tests: +\ A few more examples of arithmetic 6 7 * . \ 42 ok 1360 23 - . \ 1337 ok 12 12 / . \ 1 ok @@ -75,19 +70,15 @@ of what is written here should work elsewhere. \ Quite often one will want to write their own words. : square ( n -- n ) dup * ; \ ok -\ Lets break this down. The `:` word says to Forth to enter "compile" mode. After that, -\ we tell Forth what our word is called - "square". Between the parentheses we have a -\ comment depicting what this word does to the stack - it takes a number and adds a -\ number. Finally, we have what the word does, until we reach the `;` word which -\ says that you've finished your definition, Forth will add this to the dictionary and -\ switch back into interpret mode. +\ The `:` word sets forth into compile mode. `(` and `)` are both words which +\ tell forth to ignore between them. Up until the `;` word is what our word +\ does. \ We can check the definition of a word with the `see` word: see square \ dup * ; ok \ ------------------------------ Conditionals ------------------------------ -\ Booleans: \ In forth, -1 is used to represent truth, and 0 is used to represent false. \ The idea is that -1 is 11111111 in binary, whereas 0 is obviously 0 in binary. \ However, any non-zero value is usually treated as being true: -- cgit v1.2.3 From ade01b4ad8258c9e12f86e2bb9aa5426f60bc500 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 16:26:38 +0000 Subject: More refactoring, get lines below 80 chars. --- forth.html.markdown | 61 +++++++++++++++++++++++++++-------------------------- 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 34416878..8cfa46e4 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -7,28 +7,29 @@ filename: learnforth.fs Forth was created by Charles H. Moore in the 70s. -Note: This article focuses predominantly on the Gforth implementation of Forth, but most -of what is written here should work elsewhere. +Note: This article focuses predominantly on the Gforth implementation of +Forth, but most of what is written here should work elsewhere. -> If Lisp is the ultimate high level language, Forth is the ultimate low level language. +> If Lisp is the ultimate high level lang, Forth is the ultimate low level lang. ```forth -\ Forth is an interactive programming language which is comprised of *words*. These are -\ Forth subroutines which are executed once you press , from left to right. +\ Forth is an interactive programming language which is comprised of +\ *words*. These are Forth subroutines which are executed once you press +, from left to right. \ ------------------------------ Precursor ------------------------------ -\ It's important to know how forth processes instructions. All programming in Forth is -\ done by manipulating what's known as the parameter stack (more commonly just referred -\ to as "the stack"). Typing: +\ It's important to know how forth processes instructions. All +\ programming in Forth is done by manipulating what's known as the parameter +\ stack (more commonly just referred to as "the stack"). Typing: 5 2 3 56 76 23 65 \ Makes those numbers get added to the stack, from left to right. .s \ <7> 5 2 3 56 76 23 65 ok -\ Forth's interpreter interprets what you type in one of two ways: as *words* (i.e. the -\ name of subroutines) or as *numbers*. Words are essentially "symbols that do things". +\ Forth's interpreter interprets what you type in one of two ways: as *words* +\ (i.e. the name of subroutines) or as *numbers*. \ ------------------------------ Basic Arithmetic ------------------------------ @@ -47,16 +48,16 @@ of what is written here should work elsewhere. \ And so on. -\ ------------------------------ Stack Manipulation ------------------------------ +\ ----------------------------- Stack Manipulation ----------------------------- -\ Naturally, as we do so much work with the stack, we'll want some useful methods. +\ Naturally, as we work with the stack, we'll want some useful methods: 3 dup - \ duplicate the top item (1st now equals 2nd): 3 - 3 2 5 swap / \ swap the top with the second element: 5 / 2 6 4 5 rot .s \ rotate the top 3 elements: 4 5 6 ok 4 0 drop 2 / \ remove the top item (dont print to screen): 4 / 2 -\ ------------------------------ More Advanced Stack Manipulation ------------------------------ +\ ---------------------- More Advanced Stack Manipulation ---------------------- 1 2 3 4 tuck \ duplicate the top item into the second slot: 1 2 4 3 4 ok 1 2 3 4 over \ duplicate the second item to the top: 1 2 3 4 3 ok @@ -65,7 +66,7 @@ of what is written here should work elsewhere. \ When referring to stack indexes, they are zero-based. -\ ------------------------------ Creating Words ------------------------------ +\ ------------------------------ Creating Words -------------------------------- \ Quite often one will want to write their own words. : square ( n -- n ) dup * ; \ ok @@ -77,7 +78,7 @@ of what is written here should work elsewhere. \ We can check the definition of a word with the `see` word: see square \ dup * ; ok -\ ------------------------------ Conditionals ------------------------------ +\ -------------------------------- Conditionals -------------------------------- \ In forth, -1 is used to represent truth, and 0 is used to represent false. \ The idea is that -1 is 11111111 in binary, whereas 0 is obviously 0 in binary. @@ -86,22 +87,22 @@ see square \ dup * ; ok 42 42 = / -1 ok 12 53 = / 0 ok -\ `if` is a *compile-only word*. This means that it can only be used when we're compiling a word. -\ when creating conditionals, the format is `if` `then` . +\ `if` is a *compile-only word*. This means that it can only be used when we're +\ compiling a word. The format is `if` `then` . : ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" then ; \ ok 100 ?>64 \ Greater than 64! ok \ Else: -: ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" else ." Less than 64!" then ; \ ok -100 ?>64 \ Greater than 64! ok -20 ?>64 \ Less than 64! ok +: ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" else ." Less than 64!" then ; +100 ?>64 \ Greater than 64! ok +20 ?>64 \ Less than 64! ok -\ ------------------------------ Loops ------------------------------ +\ ------------------------------------ Loops ----------------------------------- -\ `do` is like `if` in that it is also a compile-only word, though it uses `loop` as its -\ terminator: +\ `do` is like `if` in that it is also a compile-only word, though it uses +\ `loop` as its terminator: : myloop ( -- ) 5 0 do cr ." Hello!" loop ; \ ok test \ Hello! @@ -110,11 +111,11 @@ test \ Hello! \ Hello! ok -\ `do` expects two numbers on the stack: the end number and the index number, respectively. +\ `do` expects two numbers on the stack: the end number and the index number: \ Get the value of the index as we loop with `i`: -: one-to-15 ( -- ) 15 0 do i . loop ; \ ok -one-to-15 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ok +: one-to-12 ( -- ) 12 0 do i . loop ; \ ok +one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok : squares ( -- ) 10 0 do i DUP * . loop ; \ ok squares \ 0 1 4 9 16 25 36 49 64 81 ok @@ -125,7 +126,7 @@ threes \ 0 3 6 9 12 ok \ Finally, while loops with `begin` `unil`: : death ( -- ) begin ." Are we there yet?" 0 until ; -\ ------------------------------ Variables and Memory ------------------------------ +\ ---------------------------- Variables and Memory ---------------------------- \ Sometimes we'll be in a situation where we want more permanent variables: \ First, we use `variable` to declare `age` to be a variable. @@ -134,8 +135,8 @@ variable age \ Then we write 21 to age with the word `!`. 21 age ! -\ Finally we can print our variable using the "read" word '@', which adds the value -\ to the stack, or use a handy word called `?` that reads and prints it in one go. +\ Finally we can print our variable using the "read" word '@', which adds the +\ value to the stack, or use `?` that reads and prints it in one go. age @ . \ 12 ok age ? \ 12 ok @@ -180,7 +181,7 @@ create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! \ TODO -\ ------------------------------ Final Notes ------------------------------ +\ --------------------------------- Final Notes -------------------------------- \ Floats \ Commenting (types) -- cgit v1.2.3 From b2c704deaf460e97e89895f409368879e3f46f60 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 16:29:40 +0000 Subject: Fix missing comment, pull up a few lines. --- forth.html.markdown | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 8cfa46e4..11300159 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -16,7 +16,7 @@ Forth, but most of what is written here should work elsewhere. \ Forth is an interactive programming language which is comprised of \ *words*. These are Forth subroutines which are executed once you press -, from left to right. +\ , from left to right. \ ------------------------------ Precursor ------------------------------ @@ -46,8 +46,6 @@ Forth, but most of what is written here should work elsewhere. 1360 23 - . \ 1337 ok 12 12 / . \ 1 ok -\ And so on. - \ ----------------------------- Stack Manipulation ----------------------------- \ Naturally, as we work with the stack, we'll want some useful methods: @@ -83,18 +81,15 @@ see square \ dup * ; ok \ In forth, -1 is used to represent truth, and 0 is used to represent false. \ The idea is that -1 is 11111111 in binary, whereas 0 is obviously 0 in binary. \ However, any non-zero value is usually treated as being true: - 42 42 = / -1 ok 12 53 = / 0 ok \ `if` is a *compile-only word*. This means that it can only be used when we're \ compiling a word. The format is `if` `then` . - : ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" then ; \ ok 100 ?>64 \ Greater than 64! ok \ Else: - : ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" else ." Less than 64!" then ; 100 ?>64 \ Greater than 64! ok 20 ?>64 \ Less than 64! ok -- cgit v1.2.3 From b1c2d9ef792251b8683b189dd5f24c9c53e4587c Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 22:16:48 +0000 Subject: Add section Return Stack, add Floating Point Operations section. --- forth.html.markdown | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 11300159..2c2c480e 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -18,7 +18,7 @@ Forth, but most of what is written here should work elsewhere. \ *words*. These are Forth subroutines which are executed once you press \ , from left to right. -\ ------------------------------ Precursor ------------------------------ +\ --------------------------------- Precursor --------------------------------- \ It's important to know how forth processes instructions. All \ programming in Forth is done by manipulating what's known as the parameter @@ -174,12 +174,34 @@ create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! \ ------------------------------ The Return Stack ------------------------------ -\ TODO +\ The return stack is used by Forth to the hold pointers to things when +\ words are executing other words, e.g. loops. + +\ We've already seen one use of it: `i`, which duplicates the top of the return +\ stack. `i` is equivalent to `r@`. +: myloop ( -- ) 5 0 do r@ . loop ; + +\ As well as reading, we can add to the return stack and remove from it: +5 6 4 >r swap r> .s \ 6 5 4 + +\ NOTE: Because forth uses the return stack for word pointers, it's essential +\ that you set the return stack back to how it was at the end of your +\ definition. `>r` should always be followed by `r>`. + +\ ------------------------- Floating Point Operations ------------------------- + +\ Most forths tend to dislike the use of floating point operations. We write +\ floating point operations with scientific notation. +8.3e 0.8e f+ f. \ 9.1 ok + +\ Usually we can just prepend arithmetic words with 'f' to use floating point +\ arithmetic: +variable myfloatingvar +4.4e myfloatingvar f! +myfloatingvar f@ f. \ --------------------------------- Final Notes -------------------------------- -\ Floats -\ Commenting (types) \ bye ``` -- cgit v1.2.3 From 70b03c18683f298a8c4b3eb7045c740c9882f343 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 22:25:37 +0000 Subject: Make Arrays its own section, comment float examples. --- forth.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 2c2c480e..76fdf425 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -18,7 +18,7 @@ Forth, but most of what is written here should work elsewhere. \ *words*. These are Forth subroutines which are executed once you press \ , from left to right. -\ --------------------------------- Precursor --------------------------------- +\ --------------------------------- Precursor ---------------------------------- \ It's important to know how forth processes instructions. All \ programming in Forth is done by manipulating what's known as the parameter @@ -142,7 +142,7 @@ age ? \ 12 ok 100 constant WATER-BOILING-POINT \ ok WATER-BOILING-POINT . \ 100 ok -\ Arrays! +\ ----------------------------------- Arrays ----------------------------------- \ Set up an array of length 3: variable mynumbers 2 cells allot @@ -188,7 +188,7 @@ create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! \ that you set the return stack back to how it was at the end of your \ definition. `>r` should always be followed by `r>`. -\ ------------------------- Floating Point Operations ------------------------- +\ ------------------------- Floating Point Operations -------------------------- \ Most forths tend to dislike the use of floating point operations. We write \ floating point operations with scientific notation. @@ -196,9 +196,9 @@ create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! \ Usually we can just prepend arithmetic words with 'f' to use floating point \ arithmetic: -variable myfloatingvar -4.4e myfloatingvar f! -myfloatingvar f@ f. +variable myfloatingvar \ ok +4.4e myfloatingvar f! \ ok +myfloatingvar f@ f. \ 4.4 ok \ --------------------------------- Final Notes -------------------------------- -- cgit v1.2.3 From 4d80a56d2c3311b56e2ccee873bb970abe82e9c4 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 22:51:40 +0000 Subject: Capitalize instances of 'forth'. --- forth.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 76fdf425..77358dcd 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -20,7 +20,7 @@ Forth, but most of what is written here should work elsewhere. \ --------------------------------- Precursor ---------------------------------- -\ It's important to know how forth processes instructions. All +\ It's important to know how Forth processes instructions. All \ programming in Forth is done by manipulating what's known as the parameter \ stack (more commonly just referred to as "the stack"). Typing: 5 2 3 56 76 23 65 @@ -69,8 +69,8 @@ Forth, but most of what is written here should work elsewhere. \ Quite often one will want to write their own words. : square ( n -- n ) dup * ; \ ok -\ The `:` word sets forth into compile mode. `(` and `)` are both words which -\ tell forth to ignore between them. Up until the `;` word is what our word +\ The `:` word sets Forth into compile mode. `(` and `)` are both words which +\ tell Forth to ignore between them. Up until the `;` word is what our word \ does. \ We can check the definition of a word with the `see` word: @@ -78,7 +78,7 @@ see square \ dup * ; ok \ -------------------------------- Conditionals -------------------------------- -\ In forth, -1 is used to represent truth, and 0 is used to represent false. +\ In Forth, -1 is used to represent truth, and 0 is used to represent false. \ The idea is that -1 is 11111111 in binary, whereas 0 is obviously 0 in binary. \ However, any non-zero value is usually treated as being true: 42 42 = / -1 ok @@ -184,13 +184,13 @@ create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! \ As well as reading, we can add to the return stack and remove from it: 5 6 4 >r swap r> .s \ 6 5 4 -\ NOTE: Because forth uses the return stack for word pointers, it's essential +\ NOTE: Because Forth uses the return stack for word pointers, it's essential \ that you set the return stack back to how it was at the end of your \ definition. `>r` should always be followed by `r>`. \ ------------------------- Floating Point Operations -------------------------- -\ Most forths tend to dislike the use of floating point operations. We write +\ Most Forths tend to dislike the use of floating point operations. We write \ floating point operations with scientific notation. 8.3e 0.8e f+ f. \ 9.1 ok -- cgit v1.2.3 From 879da6be51557b1acba811954bc341afba502edd Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 23:01:42 +0000 Subject: Fix typos. --- forth.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 77358dcd..9c95f66b 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -81,8 +81,8 @@ see square \ dup * ; ok \ In Forth, -1 is used to represent truth, and 0 is used to represent false. \ The idea is that -1 is 11111111 in binary, whereas 0 is obviously 0 in binary. \ However, any non-zero value is usually treated as being true: -42 42 = / -1 ok -12 53 = / 0 ok +42 42 = \ -1 ok +12 53 = \ 0 ok \ `if` is a *compile-only word*. This means that it can only be used when we're \ compiling a word. The format is `if` `then` . @@ -99,7 +99,7 @@ see square \ dup * ; ok \ `do` is like `if` in that it is also a compile-only word, though it uses \ `loop` as its terminator: : myloop ( -- ) 5 0 do cr ." Hello!" loop ; \ ok -test +myloop \ Hello! \ Hello! \ Hello! -- cgit v1.2.3 From edba1b39c8dee9f383b4b1dd1732e2b1afc55a40 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 23:16:26 +0000 Subject: Add a few misc ideas to section Final Notes. --- forth.html.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/forth.html.markdown b/forth.html.markdown index 9c95f66b..aec74333 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -202,11 +202,18 @@ myfloatingvar f@ f. \ 4.4 ok \ --------------------------------- Final Notes -------------------------------- -\ bye +\ Loading Forth files: +s" forthfile.fs" included + +\ If you find yourself wanting to clear the stack, typing something that's not +\ a defined word or a number will work. + +\ `bye` closes gforth. ``` ##Ready For More? * [Starting Forth](http://www.forth.com/starting-forth/) +* [Simple Forth](http://www.murphywong.net/hello/simple.htm) * [Thinking Forth](http://thinking-forth.sourceforge.net/) -- cgit v1.2.3 From e001c352caa7babb52c53673a52fffe6a5482da9 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 23:25:48 +0000 Subject: Slim down comments. --- forth.html.markdown | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index aec74333..04804b60 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -10,18 +10,15 @@ Forth was created by Charles H. Moore in the 70s. Note: This article focuses predominantly on the Gforth implementation of Forth, but most of what is written here should work elsewhere. -> If Lisp is the ultimate high level lang, Forth is the ultimate low level lang. - ```forth -\ Forth is an interactive programming language which is comprised of +\ Forth is a low level interactive programming language which is comprised of \ *words*. These are Forth subroutines which are executed once you press \ , from left to right. \ --------------------------------- Precursor ---------------------------------- -\ It's important to know how Forth processes instructions. All -\ programming in Forth is done by manipulating what's known as the parameter +\ All programming in Forth is done by manipulating what's known as the parameter \ stack (more commonly just referred to as "the stack"). Typing: 5 2 3 56 76 23 65 @@ -78,9 +75,8 @@ see square \ dup * ; ok \ -------------------------------- Conditionals -------------------------------- -\ In Forth, -1 is used to represent truth, and 0 is used to represent false. -\ The idea is that -1 is 11111111 in binary, whereas 0 is obviously 0 in binary. -\ However, any non-zero value is usually treated as being true: +\ -1 == true, 0 == false. However, any non-zero value is usually treated as +\ being true: 42 42 = \ -1 ok 12 53 = \ 0 ok @@ -123,21 +119,17 @@ threes \ 0 3 6 9 12 ok \ ---------------------------- Variables and Memory ---------------------------- -\ Sometimes we'll be in a situation where we want more permanent variables: -\ First, we use `variable` to declare `age` to be a variable. +\ Use `variable` to declare `age` to be a variable. variable age \ Then we write 21 to age with the word `!`. 21 age ! -\ Finally we can print our variable using the "read" word '@', which adds the +\ Finally we can print our variable using the "read" word `@`, which adds the \ value to the stack, or use `?` that reads and prints it in one go. age @ . \ 12 ok age ? \ 12 ok -\ What's happening here is that `age` stores the memory address, and we use `!` -\ and `@` to manipulate it. - \ Constants are quite simiar, except we don't bother with memory addresses: 100 constant WATER-BOILING-POINT \ ok WATER-BOILING-POINT . \ 100 ok @@ -174,8 +166,8 @@ create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! \ ------------------------------ The Return Stack ------------------------------ -\ The return stack is used by Forth to the hold pointers to things when -\ words are executing other words, e.g. loops. +\ The return stack is used to the hold pointers to things when words are +\ executing other words, e.g. loops. \ We've already seen one use of it: `i`, which duplicates the top of the return \ stack. `i` is equivalent to `r@`. @@ -190,12 +182,11 @@ create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! \ ------------------------- Floating Point Operations -------------------------- -\ Most Forths tend to dislike the use of floating point operations. We write +\ Most Forths tend to eschew the use of floating point operations. We write \ floating point operations with scientific notation. 8.3e 0.8e f+ f. \ 9.1 ok -\ Usually we can just prepend arithmetic words with 'f' to use floating point -\ arithmetic: +\ Usually we simply prepend words with 'f' when dealing with floats: variable myfloatingvar \ ok 4.4e myfloatingvar f! \ ok myfloatingvar f@ f. \ 4.4 ok -- cgit v1.2.3 From 00d03a4cbee3fc87c54b03a2a7d25b82c84ac2ef Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 23:37:07 +0000 Subject: Tidying up. --- forth.html.markdown | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 04804b60..c60b8d67 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -5,13 +5,14 @@ contributors: filename: learnforth.fs --- -Forth was created by Charles H. Moore in the 70s. +Forth was created by Charles H. Moore in the 70s. It is an imperative, +stack-based language and programming environment, being used in projects +such as Open Firmware. It's also used by NASA. Note: This article focuses predominantly on the Gforth implementation of Forth, but most of what is written here should work elsewhere. ```forth - \ Forth is a low level interactive programming language which is comprised of \ *words*. These are Forth subroutines which are executed once you press \ , from left to right. @@ -39,9 +40,9 @@ Forth, but most of what is written here should work elsewhere. . \ 9 ok \ A few more examples of arithmetic -6 7 * . \ 42 ok -1360 23 - . \ 1337 ok -12 12 / . \ 1 ok +6 7 * . \ 42 ok +1360 23 - . \ 1337 ok +12 12 / . \ 1 ok \ ----------------------------- Stack Manipulation ----------------------------- -- cgit v1.2.3 From e4229c618bfc5ad4c0ed1939322e698eb45546c8 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 23:49:06 +0000 Subject: Add a 'returns' comment for every line of Forth. --- forth.html.markdown | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index c60b8d67..5ffdfbfc 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -50,7 +50,7 @@ Forth, but most of what is written here should work elsewhere. 3 dup - \ duplicate the top item (1st now equals 2nd): 3 - 3 2 5 swap / \ swap the top with the second element: 5 / 2 -6 4 5 rot .s \ rotate the top 3 elements: 4 5 6 ok +6 4 5 rot .s \ rotate the top 3 elements: 4 5 6 4 0 drop 2 / \ remove the top item (dont print to screen): 4 / 2 \ ---------------------- More Advanced Stack Manipulation ---------------------- @@ -103,9 +103,9 @@ myloop \ Hello! \ Hello! ok -\ `do` expects two numbers on the stack: the end number and the index number: +\ `do` expects two numbers on the stack: the end number and the index number. -\ Get the value of the index as we loop with `i`: +\ We can get the value of the index as we loop with `i`: : one-to-12 ( -- ) 12 0 do i . loop ; \ ok one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok : squares ( -- ) 10 0 do i DUP * . loop ; \ ok @@ -116,49 +116,49 @@ squares \ 0 1 4 9 16 25 36 49 64 81 ok threes \ 0 3 6 9 12 ok \ Finally, while loops with `begin` `unil`: -: death ( -- ) begin ." Are we there yet?" 0 until ; +: death ( -- ) begin ." Are we there yet?" 0 until ; \ ok \ ---------------------------- Variables and Memory ---------------------------- \ Use `variable` to declare `age` to be a variable. -variable age +variable age \ ok \ Then we write 21 to age with the word `!`. -21 age ! +21 age ! \ ok \ Finally we can print our variable using the "read" word `@`, which adds the \ value to the stack, or use `?` that reads and prints it in one go. -age @ . \ 12 ok -age ? \ 12 ok +age @ . \ 12 ok +age ? \ 12 ok \ Constants are quite simiar, except we don't bother with memory addresses: -100 constant WATER-BOILING-POINT \ ok -WATER-BOILING-POINT . \ 100 ok +100 constant WATER-BOILING-POINT \ ok +WATER-BOILING-POINT . \ 100 ok \ ----------------------------------- Arrays ----------------------------------- \ Set up an array of length 3: -variable mynumbers 2 cells allot +variable mynumbers 2 cells allot \ ok \ Initialize all the values to 0 -mynumbers 3 cells erase +mynumbers 3 cells erase \ ok \ (alternatively we could do `0 fill` instead of `erase`, but as we're setting \ them to 0 we just use `erase`). \ or we can just skip all the above and initialize with specific values: -create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! +create mynumbers 64 , 9001 , 1337 , \ ok (the last `,` is important!) \ ...which is equivalent to: \ [64, 9001, 1337] -64 mynumbers 0 cells + ! -9001 mynumbers 1 cells + ! -1337 mynumbers 2 cells + ! +64 mynumbers 0 cells + ! \ ok +9001 mynumbers 1 cells + ! \ ok +1337 mynumbers 2 cells + ! \ ok \ Reading values at certain array indexes: -0 cells mynumbers + ? \ 64 ok -1 cells mynumbers + ? \ 9001 ok -2 cells mynumbers + ? \ 1337 ok +0 cells mynumbers + ? \ 64 ok +1 cells mynumbers + ? \ 9001 ok +2 cells mynumbers + ? \ 1337 ok \ Of course, you'll probably want to define your own words to manipulate arrays: : ?mynumbers ( n -- n ) cells mynumbers + ; \ ok @@ -172,10 +172,10 @@ create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! \ We've already seen one use of it: `i`, which duplicates the top of the return \ stack. `i` is equivalent to `r@`. -: myloop ( -- ) 5 0 do r@ . loop ; +: myloop ( -- ) 5 0 do r@ . loop ; \ ok \ As well as reading, we can add to the return stack and remove from it: -5 6 4 >r swap r> .s \ 6 5 4 +5 6 4 >r swap r> .s \ 6 5 4 ok \ NOTE: Because Forth uses the return stack for word pointers, it's essential \ that you set the return stack back to how it was at the end of your @@ -188,9 +188,9 @@ create mynumbers 64 , 9001 , 1337 , \ the last `,` is important! 8.3e 0.8e f+ f. \ 9.1 ok \ Usually we simply prepend words with 'f' when dealing with floats: -variable myfloatingvar \ ok -4.4e myfloatingvar f! \ ok -myfloatingvar f@ f. \ 4.4 ok +variable myfloatingvar \ ok +4.4e myfloatingvar f! \ ok +myfloatingvar f@ f. \ 4.4 ok \ --------------------------------- Final Notes -------------------------------- -- cgit v1.2.3 From 11313c9c005be9979883ca866e4da9aeb3413091 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 23:50:54 +0000 Subject: Whoops, missed a return comment. --- forth.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forth.html.markdown b/forth.html.markdown index 5ffdfbfc..8a24dccc 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -21,7 +21,7 @@ Forth, but most of what is written here should work elsewhere. \ All programming in Forth is done by manipulating what's known as the parameter \ stack (more commonly just referred to as "the stack"). Typing: -5 2 3 56 76 23 65 +5 2 3 56 76 23 65 \ ok \ Makes those numbers get added to the stack, from left to right. .s \ <7> 5 2 3 56 76 23 65 ok -- cgit v1.2.3 From 481261458cf3dad917ae3bdc46b25540b2ca3d05 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 23:57:02 +0000 Subject: Mention word . Also comment-out the file-include line. --- forth.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 8a24dccc..55286c21 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -195,10 +195,11 @@ myfloatingvar f@ f. \ 4.4 ok \ --------------------------------- Final Notes -------------------------------- \ Loading Forth files: -s" forthfile.fs" included +\ s" forthfile.fs" included -\ If you find yourself wanting to clear the stack, typing something that's not -\ a defined word or a number will work. +\ Typing a non-existent word will empty the stack. However, there's also a word +\ specifically for that: +clearstack \ `bye` closes gforth. -- cgit v1.2.3 From 6cf6ce36684e38a5aaacde58be1cd83d58cebd8f Mon Sep 17 00:00:00 2001 From: HorseMD Date: Thu, 13 Nov 2014 23:59:37 +0000 Subject: Reorder final notes section. --- forth.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 55286c21..0e3cdd2a 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -194,14 +194,15 @@ myfloatingvar f@ f. \ 4.4 ok \ --------------------------------- Final Notes -------------------------------- -\ Loading Forth files: -\ s" forthfile.fs" included - \ Typing a non-existent word will empty the stack. However, there's also a word \ specifically for that: clearstack -\ `bye` closes gforth. +\ Loading Forth files: +\ s" forthfile.fs" included + +\ Exiting Gforth: +\ bye ``` -- cgit v1.2.3 From 601f06e72d48ce0d16f9d34dc1f74418eddae654 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Fri, 14 Nov 2014 00:05:48 +0000 Subject: Whoops, make lowercase. --- forth.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 0e3cdd2a..e799655b 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -83,11 +83,11 @@ see square \ dup * ; ok \ `if` is a *compile-only word*. This means that it can only be used when we're \ compiling a word. The format is `if` `then` . -: ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" then ; \ ok +: ?>64 ( n -- n ) dup 64 > if ." Greater than 64!" then ; \ ok 100 ?>64 \ Greater than 64! ok \ Else: -: ?>64 ( n -- n ) DUP 64 > if ." Greater than 64!" else ." Less than 64!" then ; +: ?>64 ( n -- n ) dup 64 > if ." Greater than 64!" else ." Less than 64!" then ; 100 ?>64 \ Greater than 64! ok 20 ?>64 \ Less than 64! ok @@ -108,7 +108,7 @@ myloop \ We can get the value of the index as we loop with `i`: : one-to-12 ( -- ) 12 0 do i . loop ; \ ok one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok -: squares ( -- ) 10 0 do i DUP * . loop ; \ ok +: squares ( -- ) 10 0 do i dup * . loop ; \ ok squares \ 0 1 4 9 16 25 36 49 64 81 ok \ Change the "step" with `+loop`: -- cgit v1.2.3 From f1688b8000eeb39bc1e89b06c6a55eb74a081b96 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Fri, 14 Nov 2014 00:14:38 +0000 Subject: Illustrate parameters via loops. --- forth.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index e799655b..a6b17a5d 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -108,12 +108,12 @@ myloop \ We can get the value of the index as we loop with `i`: : one-to-12 ( -- ) 12 0 do i . loop ; \ ok one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok -: squares ( -- ) 10 0 do i dup * . loop ; \ ok -squares \ 0 1 4 9 16 25 36 49 64 81 ok +: squares ( -- ) 0 do i dup * . loop ; \ ok +10 squares \ 0 1 4 9 16 25 36 49 64 81 ok \ Change the "step" with `+loop`: -: threes ( -- ) 15 0 do i . 3 +loop ; \ ok -threes \ 0 3 6 9 12 ok +: threes ( -- ) do i . 3 +loop ; \ ok +15 0 threes \ 0 3 6 9 12 ok \ Finally, while loops with `begin` `unil`: : death ( -- ) begin ." Are we there yet?" 0 until ; \ ok -- cgit v1.2.3 From eb83f36015e6e666603645394aa61d1bd8153dac Mon Sep 17 00:00:00 2001 From: HorseMD Date: Fri, 14 Nov 2014 10:24:39 +0000 Subject: Trim down explainations. --- forth.html.markdown | 55 +++++++++++++++++++++++++---------------------------- 1 file changed, 26 insertions(+), 29 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index a6b17a5d..46b912b4 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -13,21 +13,19 @@ Note: This article focuses predominantly on the Gforth implementation of Forth, but most of what is written here should work elsewhere. ```forth -\ Forth is a low level interactive programming language which is comprised of -\ *words*. These are Forth subroutines which are executed once you press -\ , from left to right. +\ This is a comment +( This is also a comment but it's only used when defining words ) \ --------------------------------- Precursor ---------------------------------- -\ All programming in Forth is done by manipulating what's known as the parameter -\ stack (more commonly just referred to as "the stack"). Typing: +\ All programming in Forth is done by manipulating the parameter stack (more +\ commonly just referred to as "the stack"). 5 2 3 56 76 23 65 \ ok -\ Makes those numbers get added to the stack, from left to right. +\ Those numbers get added to the stack, from left to right. .s \ <7> 5 2 3 56 76 23 65 ok -\ Forth's interpreter interprets what you type in one of two ways: as *words* -\ (i.e. the name of subroutines) or as *numbers*. +\ In Forth, everything is either a word or a number. \ ------------------------------ Basic Arithmetic ------------------------------ @@ -35,14 +33,19 @@ Forth, but most of what is written here should work elsewhere. \ the stack. 5 4 + \ ok -\ This adds 5 and 4 to the stack and then `+` is called, which removes them and -\ adds the result to the stack. We can see it with `.`: +\ `.` pops the top result from the stack: . \ 9 ok -\ A few more examples of arithmetic +\ More examples of arithmetic: 6 7 * . \ 42 ok 1360 23 - . \ 1337 ok 12 12 / . \ 1 ok +13 2 mod . \ 1 ok + +99 negate . \ -99 ok +-99 abs . \ 99 ok +52 23 max . \ 52 ok +52 23 min . \ 23 ok \ ----------------------------- Stack Manipulation ----------------------------- @@ -67,11 +70,8 @@ Forth, but most of what is written here should work elsewhere. \ Quite often one will want to write their own words. : square ( n -- n ) dup * ; \ ok -\ The `:` word sets Forth into compile mode. `(` and `)` are both words which -\ tell Forth to ignore between them. Up until the `;` word is what our word -\ does. +\ The `:` word sets Forth into compile mode until it sees the `;` word. -\ We can check the definition of a word with the `see` word: see square \ dup * ; ok \ -------------------------------- Conditionals -------------------------------- @@ -81,8 +81,7 @@ see square \ dup * ; ok 42 42 = \ -1 ok 12 53 = \ 0 ok -\ `if` is a *compile-only word*. This means that it can only be used when we're -\ compiling a word. The format is `if` `then` . +\ `if` is a compile-only word. `if` `then` . : ?>64 ( n -- n ) dup 64 > if ." Greater than 64!" then ; \ ok 100 ?>64 \ Greater than 64! ok @@ -93,8 +92,7 @@ see square \ dup * ; ok \ ------------------------------------ Loops ----------------------------------- -\ `do` is like `if` in that it is also a compile-only word, though it uses -\ `loop` as its terminator: +\ `do` is also a compile-only word. : myloop ( -- ) 5 0 do cr ." Hello!" loop ; \ ok myloop \ Hello! @@ -108,12 +106,12 @@ myloop \ We can get the value of the index as we loop with `i`: : one-to-12 ( -- ) 12 0 do i . loop ; \ ok one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok -: squares ( -- ) 0 do i dup * . loop ; \ ok +: squares ( n -- ) 0 do i dup * . loop ; \ ok 10 squares \ 0 1 4 9 16 25 36 49 64 81 ok \ Change the "step" with `+loop`: -: threes ( -- ) do i . 3 +loop ; \ ok -15 0 threes \ 0 3 6 9 12 ok +: threes ( n n -- ) do i . 3 +loop ; \ ok +15 0 threes \ 0 3 6 9 12 ok \ Finally, while loops with `begin` `unil`: : death ( -- ) begin ." Are we there yet?" 0 until ; \ ok @@ -142,8 +140,9 @@ variable mynumbers 2 cells allot \ ok \ Initialize all the values to 0 mynumbers 3 cells erase \ ok -\ (alternatively we could do `0 fill` instead of `erase`, but as we're setting -\ them to 0 we just use `erase`). + +\ Alternatively we could use `fill`: +mynumbers 3 cells 0 fill \ or we can just skip all the above and initialize with specific values: create mynumbers 64 , 9001 , 1337 , \ ok (the last `,` is important!) @@ -177,14 +176,12 @@ create mynumbers 64 , 9001 , 1337 , \ ok (the last `,` is important!) \ As well as reading, we can add to the return stack and remove from it: 5 6 4 >r swap r> .s \ 6 5 4 ok -\ NOTE: Because Forth uses the return stack for word pointers, it's essential -\ that you set the return stack back to how it was at the end of your -\ definition. `>r` should always be followed by `r>`. +\ NOTE: Because Forth uses the return stack for word pointers, `>r` should +\ always be followed by `r>`. \ ------------------------- Floating Point Operations -------------------------- -\ Most Forths tend to eschew the use of floating point operations. We write -\ floating point operations with scientific notation. +\ Most Forths tend to eschew the use of floating point operations. 8.3e 0.8e f+ f. \ 9.1 ok \ Usually we simply prepend words with 'f' when dealing with floats: -- cgit v1.2.3 From 13a3c113940c74f9e0847dd2cfd767c07ac0a7b9 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Fri, 14 Nov 2014 10:51:22 +0000 Subject: More rewording, mention ?do. --- forth.html.markdown | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 46b912b4..b8b751d9 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -67,11 +67,10 @@ Forth, but most of what is written here should work elsewhere. \ ------------------------------ Creating Words -------------------------------- -\ Quite often one will want to write their own words. -: square ( n -- n ) dup * ; \ ok - \ The `:` word sets Forth into compile mode until it sees the `;` word. +: square ( n -- n ) dup * ; \ ok +\ We can view what a word does too: see square \ dup * ; ok \ -------------------------------- Conditionals -------------------------------- @@ -101,19 +100,22 @@ myloop \ Hello! \ Hello! ok -\ `do` expects two numbers on the stack: the end number and the index number. +\ `do` expects two numbers on the stack: the end number and the start number. \ We can get the value of the index as we loop with `i`: : one-to-12 ( -- ) 12 0 do i . loop ; \ ok one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok -: squares ( n -- ) 0 do i dup * . loop ; \ ok -10 squares \ 0 1 4 9 16 25 36 49 64 81 ok + +\ `?do` works similarly, except it will skip the loop if the end and start +\ numbers are equal. +: squares ( n -- ) 0 ?do i dup * . loop ; \ ok +10 squares \ 0 1 4 9 16 25 36 49 64 81 ok \ Change the "step" with `+loop`: -: threes ( n n -- ) do i . 3 +loop ; \ ok +: threes ( n n -- ) ?do i . 3 +loop ; \ ok 15 0 threes \ 0 3 6 9 12 ok -\ Finally, while loops with `begin` `unil`: +\ Indefinite loops with `begin` `unil`: : death ( -- ) begin ." Are we there yet?" 0 until ; \ ok \ ---------------------------- Variables and Memory ---------------------------- @@ -195,9 +197,15 @@ myfloatingvar f@ f. \ 4.4 ok \ specifically for that: clearstack +\ Clear the screen: +page + \ Loading Forth files: \ s" forthfile.fs" included +\ You can list every word that's in Forth's dictionary (but it's a huge list!): +\ words + \ Exiting Gforth: \ bye -- cgit v1.2.3 From a49ab049a54f3961f3e491d48678b421c7662ee1 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Fri, 14 Nov 2014 11:13:39 +0000 Subject: Mention nip, rework Arrays section. --- forth.html.markdown | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index b8b751d9..847895c3 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -55,6 +55,7 @@ Forth, but most of what is written here should work elsewhere. 2 5 swap / \ swap the top with the second element: 5 / 2 6 4 5 rot .s \ rotate the top 3 elements: 4 5 6 4 0 drop 2 / \ remove the top item (dont print to screen): 4 / 2 +1 2 3 nip .s \ remove the second item (similar to drop): 1 3 \ ---------------------- More Advanced Stack Manipulation ---------------------- @@ -151,7 +152,7 @@ create mynumbers 64 , 9001 , 1337 , \ ok (the last `,` is important!) \ ...which is equivalent to: -\ [64, 9001, 1337] +\ Manually writing values to each index: 64 mynumbers 0 cells + ! \ ok 9001 mynumbers 1 cells + ! \ ok 1337 mynumbers 2 cells + ! \ ok @@ -159,12 +160,14 @@ create mynumbers 64 , 9001 , 1337 , \ ok (the last `,` is important!) \ Reading values at certain array indexes: 0 cells mynumbers + ? \ 64 ok 1 cells mynumbers + ? \ 9001 ok -2 cells mynumbers + ? \ 1337 ok -\ Of course, you'll probably want to define your own words to manipulate arrays: -: ?mynumbers ( n -- n ) cells mynumbers + ; \ ok -64 mynumbers 2 cells + ! \ ok -2 ?mynumbers ? \ 64 ok +\ We can simplify it by making a helper word for manipulating arrays: +: arr ( n n -- n ) cells swap + ; +mynumbers 2 arr ? \ 1337 ok + +\ Which we can use for writing too: +20 mynumbers 1 arr ! \ ok +mynumbers 1 arr ? \ 20 ok \ ------------------------------ The Return Stack ------------------------------ -- cgit v1.2.3 From 6b5c06d45a8ee067fcb62bb6e02b6dd95c634292 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Fri, 14 Nov 2014 11:23:14 +0000 Subject: Remove unnecessary swap, give array helper word a better name. --- forth.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 847895c3..0521a3ab 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -161,13 +161,13 @@ create mynumbers 64 , 9001 , 1337 , \ ok (the last `,` is important!) 0 cells mynumbers + ? \ 64 ok 1 cells mynumbers + ? \ 9001 ok -\ We can simplify it by making a helper word for manipulating arrays: -: arr ( n n -- n ) cells swap + ; -mynumbers 2 arr ? \ 1337 ok +\ We can simplify it a little by making a helper word for manipulating arrays: +: of-arr ( n n -- n ) cells + ; \ ok +mynumbers 2 of-arr ? \ 1337 ok \ Which we can use for writing too: -20 mynumbers 1 arr ! \ ok -mynumbers 1 arr ? \ 20 ok +20 mynumbers 1 of-arr ! \ ok +mynumbers 1 of-arr ? \ 20 ok \ ------------------------------ The Return Stack ------------------------------ -- cgit v1.2.3 From ce1d44b308150c88ee61c819ed4b2242af4fcf14 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Fri, 14 Nov 2014 12:12:30 +0000 Subject: Use our word 'square' in the loop example word 'squares'. --- forth.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 0521a3ab..25a9f3b8 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -70,9 +70,10 @@ Forth, but most of what is written here should work elsewhere. \ The `:` word sets Forth into compile mode until it sees the `;` word. : square ( n -- n ) dup * ; \ ok +5 square . \ 25 ok \ We can view what a word does too: -see square \ dup * ; ok +see square \ : square dup * ; ok \ -------------------------------- Conditionals -------------------------------- @@ -109,7 +110,7 @@ one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok \ `?do` works similarly, except it will skip the loop if the end and start \ numbers are equal. -: squares ( n -- ) 0 ?do i dup * . loop ; \ ok +: squares ( n -- ) 0 ?do i square . loop ; \ ok 10 squares \ 0 1 4 9 16 25 36 49 64 81 ok \ Change the "step" with `+loop`: -- cgit v1.2.3 From 453b6254c5809c2227de29b2b6f99f7db5a8c6de Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 14 Nov 2014 17:07:42 +0200 Subject: Update markdown-cn.html.markdown --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index eecb8c5b..1c577efb 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: Markdown +language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: -- cgit v1.2.3 From bfabbc0923a22d42dabc8e5516955d2cb789c358 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 14 Nov 2014 17:08:27 +0200 Subject: Update yaml-fr.html.markdown --- fr-fr/yaml-fr.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown index d9b94aa6..43b1df54 100644 --- a/fr-fr/yaml-fr.html.markdown +++ b/fr-fr/yaml-fr.html.markdown @@ -3,6 +3,7 @@ language: yaml filename: learnyaml.yaml contributors: - ["Andrei Curelaru", "http://www.infinidad.fr"] +lang: fr-fr --- Proposé à l'origine par Clark Evans en Mai 2001, YAML est un un format de @@ -153,4 +154,4 @@ Quelques références et outils : - Doc officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*, - Une [Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) très bien construite et claire, -- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples. \ No newline at end of file +- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples. -- cgit v1.2.3 From 6e912f4b46b02fbed110502e5b1cf1ecd600ab4c Mon Sep 17 00:00:00 2001 From: HorseMD Date: Fri, 14 Nov 2014 16:49:25 +0000 Subject: Fix return-comment indentation. --- forth.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 25a9f3b8..4c89a5ec 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -110,8 +110,8 @@ one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok \ `?do` works similarly, except it will skip the loop if the end and start \ numbers are equal. -: squares ( n -- ) 0 ?do i square . loop ; \ ok -10 squares \ 0 1 4 9 16 25 36 49 64 81 ok +: squares ( n -- ) 0 ?do i square . loop ; \ ok +10 squares \ 0 1 4 9 16 25 36 49 64 81 ok \ Change the "step" with `+loop`: : threes ( n n -- ) ?do i . 3 +loop ; \ ok -- cgit v1.2.3 From 651e1e90d2da18ee0dd225ef78631c90d519af9d Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 14 Nov 2014 15:01:16 -0800 Subject: Some work on the Scala page --- scala.html.markdown | 152 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 118 insertions(+), 34 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index dc039f0c..529347be 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -54,14 +54,17 @@ var y = 10 y = 20 // y is now 20 /* - Scala is a statically typed language, yet note that in the above declarations, we did not specify - a type. This is due to a language feature called type inference. In most cases, Scala compiler can - guess what the type of a variable is, so you don't have to type it every time. We can explicitly - declare the type of a variable like so: + Scala is a statically typed language, yet note that in the above declarations, + we did not specify a type. This is due to a language feature called type + inference. In most cases, Scala compiler can guess what the type of a variable + is, so you don't have to type it every time. We can explicitly declare the + type of a variable like so: */ val z: Int = 10 val a: Double = 1.0 -val b: Double = 10 // Notice automatic conversion from Int to Double, result is 10.0, not 10 + +// Notice automatic conversion from Int to Double, result is 10.0, not 10 +val b: Double = 10 // Boolean values true @@ -94,8 +97,8 @@ true == false // false This means the result of evaluating 1 + 7 is an object of type Int with a value of 8 - Note that "res29" is a sequentially generated variable name to store the results of the - expressions you typed, your output may differ. + Note that "res29" is a sequentially generated variable name to store the + results of the expressions you typed, your output may differ. */ "Scala strings are surrounded by double quotes" @@ -142,27 +145,69 @@ val html = """
// 2. Functions ///////////////////////////////////////////////// -// The next line gives you a function that takes an Int and returns it squared -(x:Int) => x * x +// Functions are defined like so: +// +// def functionName(args...): ReturnType = { body... } +// +// If you come from more traditional languages, notice the omission of the +// return keyword. In Scala, the last expression in the function block is the +// return value. +def sumOfSquares(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} -// You can assign this function to an identifier, like this: -val sq = (x:Int) => x * x +// The { } can be omitted if the function body is a single expression: +def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y -/* The above says this +// Syntax for calling functions is familiar: +sumOfSquares(3, 4) // => 25 - sq: Int => Int = +// In most cases (with recursive functions the most notable exception), function +// return type can be omitted, and the same type inference we saw with variables +// will work with function return values: +def sq(x: Int) = x * x // Compiler can guess return type is Int - Which means that this time we gave an explicit name to the value - sq is a - function that take an Int and returns Int. +// Functions can have default parameters: +def addWithDefault(x: Int, y: Int = 5) = x + y +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 - sq can be executed as follows: -*/ -sq(10) // Gives you this: res33: Int = 100. +// Anonymous functions look like this: +(x:Int) => x * x -// The colon explicitly defines the type of a value, in this case a function -// taking an Int and returning an Int. -val add10: Int => Int = _ + 10 +// Unlike defs, even the input type of anonymous functions can be omitted if the +// context makes it clear. Notice the type "Int => Int" which means a function +// that takes Int and returns Int. +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 +// 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. +val addOne: Int => Int = _ + 1 +val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) + +addOne(5) // => 6 +weirdSum(2, 4) // => 16 + + +// The return keyword exists in Scala, but it only returns from the inner-most +// def that surrounds it. It has no effect on anonymous functions. For example: +def foo(x: Int) = { + val anonFunc: Int => Int = { z => + if (z > 5) + return z // This line makes z the return value of foo! + else + z + 2 // This line is the return value of anonFunc + } + anonFunc(x) // This line is the return value of foo +} ///////////////////////////////////////////////// @@ -187,7 +232,7 @@ while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why i // Show the value of i. Note that while is a loop in the classical sense - // it executes sequentially while changing the loop variable. while is very - // fast, faster that Java // loops, but using the combinators and + // fast, faster that Java loops, but using the combinators and // comprehensions above is easier to understand and parallelize // A do while loop @@ -290,13 +335,24 @@ d._2 And now we will explain what these are. */ +// classes are similar to classes in other languages. Constructor arguments are +// declared after the class name, and initialization is done in the class body. class Dog(br: String) { + // Constructor code here var breed: String = br - //A method called bark, returning a String - def bark: String = { - // the body of the method - "Woof, woof!" - } + + // Define a method called bark, returning a String + def bark = "Woof, woof!" + + // Values and methods are assumed public. "protected" and "private" keywords + // are also available. + private def sleep(hours: Int) = + println(s"I'm sleeping for $hours hours") + + // Abstract methods are simply methods with no body. If we uncomment the next + // line, class Dog would need to be declared abstract + // abstract class Dog(...) { ... } + // def chaseAfter(what: String): String } val mydog = new Dog("greyhound") @@ -304,17 +360,45 @@ println(mydog.breed) // => "greyhound" println(mydog.bark) // => "Woof, woof!" -// Classes can contain nearly any other construct, including other classes, -// functions, methods, objects, case classes, traits etc. +// The "object" keyword creates a type AND a singleton instance of it. It is +// common for Scala classes to have a "companion object", where the per-instance +// behavior is captured in the classes themselves, but behavior related to all +// instance of that class go in objects. The difference is similar to class +// methods vs static methods in other languages. Note that objects and classes +// can have the same name. +object Dog { + def allKnownBreeds = List("pitbull", "shepherd", "retriever") + def createDog(breed: String) = new Dog(breed) +} -// Case classes -case class Person(name:String, phoneNumber:String) +// Case classes are classes that have extra functionality built in. A common +// question for Scala beginners is when to use classes and when to use case +// classes. The line is quite fuzzy, but in general, classes tend to focus on +// encapsulation, polymorphism, and behavior. The values in these classes tend +// to be private, and only methods are exposed. The primary purpose of case +// classes is to hold immutable data. They often have few methods, and the +// methods rarely have side-effects. +case class Person(name: String, phoneNumber: String) + +// Create a new instance. Note cases classes don't need "new" +val george = Person("George", "1234") +val kate = Person("Kate", "4567") + +// With case classes, you get a few perks for free, like getters: +george.phoneNumber // => "1234" + +// Per field equality (no need to override .equals) +Person("George", "1234") == Person("Kate", "1236") // => false + +// Easy way to copy +// otherGeorge == Person("george", "9876") +val otherGeorge = george.copy(phoneNumber = "9876") -Person("George", "1234") == Person("Kate", "1236") +// And many others. Case classes also get pattern matching for free, see below. -// Objects and traits coming soon! +// Traits coming soon! ///////////////////////////////////////////////// @@ -423,7 +507,7 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared // 8. Implicits ///////////////////////////////////////////////// -Coming soon! +// Coming soon! ///////////////////////////////////////////////// -- cgit v1.2.3 From bd728a065afd343f47429ae9f88d7d3b877e5ea5 Mon Sep 17 00:00:00 2001 From: anatoly burtsev Date: Sat, 15 Nov 2014 16:55:39 +0300 Subject: Update java-ru.html.markdown fix mistake in pre/post-increment --- ru-ru/java-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 460086e3..005495cc 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -181,7 +181,7 @@ public class LearnJavaRu { // Если они находятся перед переменной, сначала происходит // увеличение/уменьшение, затем операция, если после, // то сначала выполняется операция, затем увеличение/уменьшение. - System.out.println(i++); //i = 1, напечатает 0 (пре-инкремент) + System.out.println(i++); //i = 1, напечатает 0 (пост-инкремент) System.out.println(++i); //i = 2, напечатает 2 (пре-инкремент) System.out.println(i--); //i = 1, напечатает 2 (пост-декремент) System.out.println(--i); //i = 0, напечатает 0 (пре-декремент) -- cgit v1.2.3 From 337fb88da9b5e4009c95c818cef0610da0d841db Mon Sep 17 00:00:00 2001 From: CoolDark Date: Sat, 15 Nov 2014 22:12:40 +0300 Subject: Update --- ru-ru/lua-ru.html.markdown | 51 ++++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index 3fd478ef..c7d6a121 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -45,7 +45,7 @@ end if num > 40 then print('больше 40') elseif s ~= 'walternate' then -- ~= обозначает "не равно". - -- Проверка равенства это == как в Python; ok для строк. + -- Проверка равенства это == как в Python; работает для строк. io.write('не больше 40\n') -- По умолчанию стандартный вывод. else -- По умолчанию переменные являются глобальными. @@ -54,7 +54,7 @@ else -- Как сделать локальную переменную: local line = io.read() -- Считывает введённую строку. - -- Конкатенация строк использует .. оператор: + -- Для конкатенации строк используется оператор .. : print('Зима пришла, ' .. line) end @@ -133,10 +133,10 @@ f = function (x) return x * x end -- Эти тоже: local function g(x) return math.sin(x) end local g = function(x) return math.sin(x) end --- Equivalent to local function g(x)..., except referring to g in the function --- body won't work as expected. +-- Эквивалентно для local function g(x)..., кроме ссылки на g в теле функции +-- не будет работать как ожидалось. local g; g = function (x) return math.sin(x) end --- the 'local g' decl makes g-self-references ok. +-- 'local g' будет прототипом функции. -- Trig funcs work in radians, by the way. @@ -151,32 +151,34 @@ print {} -- Тоже сработает. -------------------------------------------------------------------------------- -- Таблицы = структура данных, свойственная только для Lua; это ассоциативные массивы. --- Similar to php arrays or js objects, they are hash-lookup dicts that can --- also be used as lists. +-- Похоже на массивы в PHP или объекты в JS +-- Так же может использоваться как список. --- Using tables as dictionaries / maps: --- Dict literals have string keys by default: +-- Использование словарей: + +-- Литералы имеют ключ по умолчанию: t = {key1 = 'value1', key2 = false} --- String keys can use js-like dot notation: +-- Строковые ключи выглядят как точечная нотация в JS: print(t.key1) -- Печатает 'value1'. t.newKey = {} -- Добавляет новую пару ключ-значение. t.key2 = nil -- Удаляет key2 из таблицы. --- Literal notation for any (non-nil) value as key: +-- Литеральная нотация для любого (не пустой) значения ключа: u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} print(u[6.28]) -- пишет "tau" --- Key matching is basically by value for numbers and strings, but by identity --- for tables. +-- Ключ соответствует нужен не только для значения чисел и строк, но и для +-- идентификации таблиц. a = u['@!#'] -- Теперь a = 'qbert'. -b = u[{}] -- We might expect 1729, but it's nil: --- b = nil since the lookup fails. It fails because the key we used is not the --- same object as the one used to store the original value. So strings & --- numbers are more portable keys. +b = u[{}] -- Мы ожидали 1729, но получили nil: +-- b = nil вышла неудача. Потому что за ключ мы использовали +-- не тот же объект, который использовали в оригинальном значении. +-- Поэтому строки и числа больше подходят под ключ. --- A one-table-param function call needs no parens: +-- Вызов фукцнии с одной таблицей в качестве аргумента +-- не нуждается в кавычках: function h(x) print(x.key1) end h{key1 = 'Sonmi~451'} -- Печатает 'Sonmi~451'. @@ -187,15 +189,16 @@ end -- _G - это таблица со всеми глобалями. print(_G['_G'] == _G) -- Печатает 'true'. --- Using tables as lists / arrays: +-- Использование таблиц как списков / массивов: --- List literals implicitly set up int keys: +-- Список значений с неявно заданными целочисленными ключами: v = {'value1', 'value2', 1.21, 'gigawatts'} -for i = 1, #v do -- #v is the size of v for lists. - print(v[i]) -- Indices start at 1 !! SO CRAZY! +for i = 1, #v do -- #v это размер списка v. + print(v[i]) -- Начинается с ОДНОГО! end --- A 'list' is not a real type. v is just a table with consecutive integer --- keys, treated as a list. + +-- Список это таблица. v Это таблица с последовательными целочисленными +-- ключами, созданными в списке. -------------------------------------------------------------------------------- -- 3.1 Мета-таблицы и мета-методы. -- cgit v1.2.3 From 423d6373820896083160686cc9ced1cf842b6daa Mon Sep 17 00:00:00 2001 From: CoolDark Date: Sun, 16 Nov 2014 11:27:29 +0300 Subject: Translate 3 part --- ru-ru/lua-ru.html.markdown | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index c7d6a121..6ff6ddd7 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -138,7 +138,7 @@ local g = function(x) return math.sin(x) end local g; g = function (x) return math.sin(x) end -- 'local g' будет прототипом функции. --- Trig funcs work in radians, by the way. +-- Так же тригонометрические функции работсют с радианами. -- Вызов функции с одним текстовым параметром не требует круглых скобок: print 'hello' -- Работает без ошибок. @@ -204,10 +204,10 @@ end -- 3.1 Мета-таблицы и мета-методы. -------------------------------------------------------------------------------- --- A table can have a metatable that gives the table operator-overloadish --- behavior. Later we'll see how metatables support js-prototypey behavior. - -f1 = {a = 1, b = 2} -- Represents the fraction a/b. +-- Таблицы могут быть метатаблицами, что дает им поведение +-- перегрузки-оператора. Позже мы увидим, что метатаблицы поддерживают поведение +-- js-прототипов. +f1 = {a = 1, b = 2} -- Представляет фракцию a/b. f2 = {a = 2, b = 3} -- Это не сработает: @@ -226,29 +226,29 @@ setmetatable(f2, metafraction) s = f1 + f2 -- вызывает __add(f1, f2) на мета-таблице f1 --- f1, f2 have no key for their metatable, unlike prototypes in js, so you must --- retrieve it as in getmetatable(f1). The metatable is a normal table with --- keys that Lua knows about, like __add. +-- f1, f2 не имеют ключей для своих метатаблиц в отличии от прототипов в js, поэтому +-- ты можешь извлечь данные через getmetatable(f1). Метатаблицы это обычные таблицы с +-- ключем, который в Lua известен как __add. --- But the next line fails since s has no metatable: +-- Но следущая строка будет ошибочной т.к s не мета-таблица: -- t = s + s --- Class-like patterns given below would fix this. +-- Шаблоны классов приведенные ниже смогут это исправить. --- An __index on a metatable overloads dot lookups: +-- __index перегружет в мета-таблице просмотр через точку: defaultFavs = {animal = 'gru', food = 'donuts'} myFavs = {food = 'pizza'} setmetatable(myFavs, {__index = defaultFavs}) eatenBy = myFavs.animal -- работает! спасибо, мета-таблица. -------------------------------------------------------------------------------- --- Direct table lookups that fail will retry using the metatable's __index --- value, and this recurses. +-- Прямой табличный поиск не будет пытаться передавать с помощью __index +-- значения, и её рекурсии. --- An __index value can also be a function(tbl, key) for more customized --- lookups. +-- __index значения так же могут быть function(tbl, key) для настроенного +-- просмотра. --- Values of __index,add, .. are called metamethods. --- Full list. Here a is a table with the metamethod. +-- Значения типа __index,add, ... называются метаметодами. +-- Полный список. Здесь таблицы с метаметодами. -- __add(a, b) для a + b -- __sub(a, b) для a - b -- cgit v1.2.3 From a281e7d0ffa57e0ee11b5980adc41a58b10c50a0 Mon Sep 17 00:00:00 2001 From: CoolDark Date: Sun, 16 Nov 2014 12:48:02 +0300 Subject: Full --- ru-ru/lua-ru.html.markdown | 134 ++++++++++++++++++++++----------------------- 1 file changed, 66 insertions(+), 68 deletions(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index 6ff6ddd7..7b0946e3 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -267,13 +267,14 @@ eatenBy = myFavs.animal -- работает! спасибо, мета-табл -- __call(a, ...) для a(...) -------------------------------------------------------------------------------- --- 3.2 Class-like tables and inheritance. +-- 3.2 Классы и наследования. -------------------------------------------------------------------------------- --- Classes aren't built in; there are different ways to make them using --- tables and metatables. +-- В Lua нет поддержки классов на уровне языка; +-- Однако существуют разные способы их создания с помощью +-- таблиц и метатаблиц. --- Explanation for this example is below it. +-- Пример классам находится ниже. Dog = {} -- 1. @@ -290,23 +291,22 @@ end mrDog = Dog:new() -- 7. mrDog:makeSound() -- 'I say woof' -- 8. --- 1. Dog acts like a class; it's really a table. --- 2. "function tablename:fn(...)" is the same as --- "function tablename.fn(self, ...)", The : just adds a first arg called --- self. Read 7 & 8 below for how self gets its value. --- 3. newObj will be an instance of class Dog. --- 4. "self" is the class being instantiated. Often self = Dog, but inheritance --- can change it. newObj gets self's functions when we set both newObj's --- metatable and self's __index to self. --- 5. Reminder: setmetatable returns its first arg. --- 6. The : works as in 2, but this time we expect self to be an instance --- instead of a class. --- 7. Same as Dog.new(Dog), so self = Dog in new(). --- 8. Same as mrDog.makeSound(mrDog); self = mrDog. - +-- 1. Dog похоже на класс; но это таблица. +-- 2. "function tablename:fn(...)" как и +-- "function tablename.fn(self, ...)", Просто : добавляет первый аргумент +-- перед собой. Читай 7 и 8 чтоб понять как self получает значение. +-- 3. newObj это экземпляр класса Dog. +-- 4. "self" есть класс являющийся экземпляром. Зачастую self = Dog, но экземляр +-- может поменять это. newObj получит свои функции, когда мы установим newObj как +-- метатаблицу и __index на себя. +-- 5. Помни: setmetatable возвращает первый аргумент. +-- 6. ":" Работает в 2 стороны, но в этот раз мы ожидмаем, что self будет экземпляром +-- а не классом. +-- 7. Dog.new(Dog), тоже самое что self = Dog in new(). +-- 8. mrDog.makeSound(mrDog) будет self = mrDog. -------------------------------------------------------------------------------- --- Inheritance example: +-- Пример наследования: LoudDog = Dog:new() -- 1. @@ -319,17 +319,16 @@ seymour = LoudDog:new() -- 3. seymour:makeSound() -- 'woof woof woof' -- 4. -------------------------------------------------------------------------------- --- 1. LoudDog gets Dog's methods and variables. --- 2. self has a 'sound' key from new(), see 3. --- 3. Same as "LoudDog.new(LoudDog)", and converted to "Dog.new(LoudDog)" as --- LoudDog has no 'new' key, but does have "__index = Dog" on its metatable. --- Result: seymour's metatable is LoudDog, and "LoudDog.__index = Dog". So --- seymour.key will equal seymour.key, LoudDog.key, Dog.key, whichever --- table is the first with the given key. --- 4. The 'makeSound' key is found in LoudDog; this is the same as --- "LoudDog.makeSound(seymour)". - --- If needed, a subclass's new() is like the base's: +-- 1. LoudDog получит методы и переменные класса Dog. +-- 2. self будет 'sound' ключ для new(), смотри 3й пункт. +-- 3. Так же как "LoudDog.new(LoudDog)" и переделанный в "Dog.new(LoudDog)" +-- LoudDog не имеет ключ 'new', но может выполнить "__index = Dog" в этой метатаблице +-- Результат: Метатаблица seymour стала LoudDog и "LoudDog.__index = Dog" +-- Так же seymour.key будет равна seymour.key, LoudDog.key, Dog.key, +-- в зависимости от того какая таблица будет с первым ключем. +-- 4. 'makeSound' ключ найден в LoudDog; и выглдяит как "LoudDog.makeSound(seymour)". + +-- При необходимости, подкласс new() будет базовым. function LoudDog:new() local newObj = {} -- set up newObj @@ -342,12 +341,12 @@ end -------------------------------------------------------------------------------- ---[[ I'm commenting out this section so the rest of this script remains --- runnable. +--[[ Я закомментировал этот раздел так как часть скрипта остается +-- работоспособной. ``` ```lua --- Suppose the file mod.lua looks like this: +-- Предположим файл mod.lua будет выглядеть так: local M = {} local function sayMyName() @@ -361,57 +360,55 @@ end return M --- Another file can use mod.lua's functionality: -local mod = require('mod') -- Run the file mod.lua. +-- Иные файлы могут использовать функционал mod.lua: +local mod = require('mod') -- Запустим файл mod.lua. --- require is the standard way to include modules. --- require acts like: (if not cached; see below) +-- require - подключает модули. +-- require выглядит так: (если не кешируется; смотри ниже) local mod = (function () end)() --- It's like mod.lua is a function body, so that locals inside mod.lua are --- invisible outside it. +-- Тело функции mod.lua является локальным, поэтому +-- содержимое не видимо за телом функции. --- This works because mod here = M in mod.lua: -mod.sayHello() -- Says hello to Hrunkner. +-- Это работает так как mod здесь = M в mod.lua: +mod.sayHello() -- Скажет слово Hrunkner. --- This is wrong; sayMyName only exists in mod.lua: -mod.sayMyName() -- error +-- Это будет ошибочным; sayMyName доступен только в mod.lua: +mod.sayMyName() -- ошибка --- require's return values are cached so a file is run at most once, even when --- require'd many times. +-- require возвращает значения кеша файла вызванного не более одного раза, даже когда +-- требуется много раз. --- Suppose mod2.lua contains "print('Hi!')". -local a = require('mod2') -- Prints Hi! -local b = require('mod2') -- Doesn't print; a=b. +-- Предположим mod2.lua содержит "print('Hi!')". +local a = require('mod2') -- Напишет Hi! +local b = require('mod2') -- Не напишет; a=b. --- dofile is like require without caching: +-- dofile работает без кэша: dofile('mod2') --> Hi! -dofile('mod2') --> Hi! (runs again, unlike require) +dofile('mod2') --> Hi! (напишет снова) --- loadfile loads a lua file but doesn't run it yet. -f = loadfile('mod2') -- Calling f() runs mod2.lua. +-- loadfile загружает lua файл, но не запускает его. +f = loadfile('mod2') -- Вызовет f() запустит mod2.lua. --- loadstring is loadfile for strings. -g = loadstring('print(343)') -- Returns a function. -g() -- Prints out 343; nothing printed before now. +-- loadstring это loadfile для строк. +g = loadstring('print(343)') -- Вернет функцию. +g() -- Напишет 343. --]] ``` -## References +## Примечание (от автора) -I was excited to learn Lua so I could make games -with the Love 2D game engine. That's the why. +Я был взволнован, когда узнал что с Lua я могу делать игры при помощи Love 2D game engine. Вот почему. -I started with BlackBulletIV's Lua for programmers. -Next I read the official Programming in Lua book. -That's the how. +Я начинал с BlackBulletIV's Lua for programmers. +Затем я прочитал официальную Документацию по Lua. -It might be helpful to check out the Lua short -reference on lua-users.org. +Так же может быть полезнымLua short +reference на lua-users.org. -The main topics not covered are standard libraries: +Основные темы не охваченные стандартной библиотекой: * string library * table library @@ -419,8 +416,9 @@ The main topics not covered are standard libraries: * io library * os library -By the way, the entire file is valid Lua; save it -as learn.lua and run it with "lua learn.lua" ! +Весь файл написан на Lua; сохрани его как learn.lua и запусти при помощи "lua learn.lua" ! + +Это была моя первая статья для tylerneylon.com, которая так же доступна тут github gist. + +Удачи с Lua! -This was first written for tylerneylon.com, and is -also available as a github gist. Have fun with Lua! -- cgit v1.2.3 From 3c9988a7e437eb4368a22525f49dfb14aaa5f127 Mon Sep 17 00:00:00 2001 From: CoolDark Date: Sun, 16 Nov 2014 12:50:41 +0300 Subject: oops --- ru-ru/lua-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index 7b0946e3..50aa5910 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -405,7 +405,7 @@ g() -- Напишет 343. Я начинал с BlackBulletIV's Lua for programmers. Затем я прочитал официальную Документацию по Lua. -Так же может быть полезнымLua short +Так же может быть полезным Lua short reference на lua-users.org. Основные темы не охваченные стандартной библиотекой: -- cgit v1.2.3 From 9e811629c263c3d04ae39a9d69d8b2de8a0bd7f7 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 16 Nov 2014 12:59:08 +0300 Subject: Update lua-ru.html.markdown --- ru-ru/lua-ru.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index 50aa5910..7f30edbd 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -6,6 +6,7 @@ contributors: translators: - ["Max Solomonov", "https://vk.com/solomonovmaksim"] - ["Max Truhonin", "https://vk.com/maximmax42"] + - ["Konstantin Gromyko", "https://vk.com/id0x1765d79"] lang: ru-ru --- -- cgit v1.2.3 From dd76dc0c491b080e94c770698ab0dbd913dfe890 Mon Sep 17 00:00:00 2001 From: Daniel-Cortez Date: Sun, 16 Nov 2014 20:02:27 +0700 Subject: Fix some translation mistakes --- ru-ru/lua-ru.html.markdown | 274 ++++++++++++++++++++++----------------------- 1 file changed, 135 insertions(+), 139 deletions(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index 7f30edbd..b9af61b4 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -5,8 +5,9 @@ contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] translators: - ["Max Solomonov", "https://vk.com/solomonovmaksim"] - - ["Max Truhonin", "https://vk.com/maximmax42"] + - ["Max Truhonin", "https://vk.com/maximmax42"] - ["Konstantin Gromyko", "https://vk.com/id0x1765d79"] + - ["Stanislav Gromov", "https://vk.com/id156354391"] lang: ru-ru --- @@ -21,33 +22,30 @@ lang: ru-ru -- 1. Переменные, циклы и условия. -------------------------------------------------------------------------------- -num = 42 -- Все числа являются типом double. ---[[ - Не волнуйся, 64-битные double имеют 52 бита - для хранения именно целочисленных значений; - точность не является проблемой для - целочисленных значений, занимающих меньше - 52 бит. ---]] +num = 42 -- Все числа имеют тип double. +-- Не волнуйтесь, в 64-битных double 52 бита +-- отведено под хранение целой части числа; +-- точность не является проблемой для +-- целочисленных значений, занимающих меньше 52 бит. -s = 'walternate' -- Неизменные строки как в Python. +s = 'walternate' -- Неизменные строки, как в Python. t = "Двойные кавычки также приветствуются" u = [[ Двойные квадратные скобки начинают и заканчивают многострочные значения.]] -t = nil -- Удаляет определение переменной t; Lua имеет мусорку. +t = nil -- Удаляет определение переменной t; в Lua есть сборка мусора. --- Циклы и условия имеют ключевые слова, такие как do/end: +-- Блоки обозначаются ключевыми слоавми, такими как do/end: while num < 50 do num = num + 1 -- Здесь нет ++ или += операторов. end --- Условие "если": +-- Ветвление "если": if num > 40 then print('больше 40') elseif s ~= 'walternate' then -- ~= обозначает "не равно". -- Проверка равенства это == как в Python; работает для строк. - io.write('не больше 40\n') -- По умолчанию стандартный вывод. + io.write('не больше 40\n') -- По умолчанию вывод в stdout. else -- По умолчанию переменные являются глобальными. thisIsGlobal = 5 -- Стиль CamelСase является общим. @@ -68,11 +66,8 @@ aBoolValue = false -- Только значения nil и false являются ложными; 0 и '' являются истинными! if not aBoolValue then print('это значение ложно') end ---[[ - Для 'or' и 'and' действует принцип "какой оператор дальше, - тот и применяется". Это действует аналогично a?b:c - операторам в C/js: ---]] +-- Для 'or' и 'and' действует принцип "какой оператор дальше, +-- тот и применяется". Это действует аналогично оператору a?b:c в C/js: ans = aBoolValue and 'yes' or 'no' --> 'no' karlSum = 0 @@ -103,8 +98,8 @@ end -- Вложенные и анонимные функции являются нормой: function adder(x) - -- Возращаемая функция создаётся когда adder вызывается, тот в свою очередь - -- запоминает значение переменной x: + -- Возращаемая функция создаётся, когда вызывается функция adder, + -- и запоминает значение переменной x: return function (y) return x + y end end a1 = adder(9) @@ -112,12 +107,11 @@ a2 = adder(36) print(a1(16)) --> 25 print(a2(64)) --> 100 --- Возвраты, вызовы функций и присвоения, вся работа с перечисленным может иметь --- неодинаковое кол-во аргументов/элементов. Неиспользуемые аргументы являются nil и --- отбрасываются на приёме. +-- Возвраты, вызовы функций и присвоения работают со списками, которые могут иметь разную длину. +-- Лишние получатели принимают значение nil, а лишние значения игнорируются. x, y, z = 1, 2, 3, 4 --- Теперь x = 1, y = 2, z = 3, и 4 просто отбрасывается. +-- Теперь x = 1, y = 2, z = 3, а 4 просто отбрасывается. function bar(a, b, c) print(a, b, c) @@ -134,12 +128,12 @@ f = function (x) return x * x end -- Эти тоже: local function g(x) return math.sin(x) end local g = function(x) return math.sin(x) end --- Эквивалентно для local function g(x)..., кроме ссылки на g в теле функции --- не будет работать как ожидалось. +-- Эквивалентно для local function g(x)..., однако ссылки на g +-- в теле функции не будут работать, как ожидалось. local g; g = function (x) return math.sin(x) end -- 'local g' будет прототипом функции. --- Так же тригонометрические функции работсют с радианами. +-- Кстати, тригонометрические функции работают с радианами. -- Вызов функции с одним текстовым параметром не требует круглых скобок: print 'hello' -- Работает без ошибок. @@ -151,9 +145,10 @@ print {} -- Тоже сработает. -- 3. Таблицы. -------------------------------------------------------------------------------- --- Таблицы = структура данных, свойственная только для Lua; это ассоциативные массивы. --- Похоже на массивы в PHP или объекты в JS --- Так же может использоваться как список. +-- Таблица = единственная составная структура данных в Lua; +-- представляет собой ассоциативный массив. +-- Похоже на массивы в PHP или объекты в JS. +-- Также может использоваться, как список. -- Использование словарей: @@ -161,53 +156,54 @@ print {} -- Тоже сработает. -- Литералы имеют ключ по умолчанию: t = {key1 = 'value1', key2 = false} --- Строковые ключи выглядят как точечная нотация в JS: +-- Строковые ключи используются, как в точечной нотации в JS: print(t.key1) -- Печатает 'value1'. -t.newKey = {} -- Добавляет новую пару ключ-значение. +t.newKey = {} -- Добавляет новую пару ключ/значение. t.key2 = nil -- Удаляет key2 из таблицы. --- Литеральная нотация для любого (не пустой) значения ключа: +-- Литеральная нотация для любого значения ключа (кроме nil): u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} print(u[6.28]) -- пишет "tau" --- Ключ соответствует нужен не только для значения чисел и строк, но и для --- идентификации таблиц. +-- Ключ соответствует значению для чисел и строк, но при +-- использовании таблицы в качестве ключа берётся её экземпляр. a = u['@!#'] -- Теперь a = 'qbert'. -b = u[{}] -- Мы ожидали 1729, но получили nil: --- b = nil вышла неудача. Потому что за ключ мы использовали --- не тот же объект, который использовали в оригинальном значении. --- Поэтому строки и числа больше подходят под ключ. +b = u[{}] -- Вы могли ожидать 1729, но получится nil: +-- b = nil, т.к. ключ не будет найден. +-- Это произойдёт, потому что за ключ мы использовали не тот же самый объект, +-- который использовали для сохранения оригинального значения. +-- Поэтому строки и числа удобнее использовать в качестве ключей. --- Вызов фукцнии с одной таблицей в качестве аргумента +-- Вызов функции с одной таблицей в качестве аргумента -- не нуждается в кавычках: function h(x) print(x.key1) end h{key1 = 'Sonmi~451'} -- Печатает 'Sonmi~451'. -for key, val in pairs(u) do -- Итерация цикла с таблицей. +for key, val in pairs(u) do -- Цикл по таблице. print(key, val) end -- _G - это таблица со всеми глобалями. print(_G['_G'] == _G) -- Печатает 'true'. --- Использование таблиц как списков / массивов: +-- Использование таблиц, как списков / массивов: -- Список значений с неявно заданными целочисленными ключами: v = {'value1', 'value2', 1.21, 'gigawatts'} for i = 1, #v do -- #v это размер списка v. - print(v[i]) -- Начинается с ОДНОГО! + print(v[i]) -- Нумерация начинается с ОДНОГО !! end --- Список это таблица. v Это таблица с последовательными целочисленными --- ключами, созданными в списке. +-- Список не является отдельным типом. v - всего лишь таблица +-- с последовательными целочисленными ключами, воспринимаемая как список. -------------------------------------------------------------------------------- --- 3.1 Мета-таблицы и мета-методы. +-- 3.1 Метатаблицы и метаметоды. -------------------------------------------------------------------------------- --- Таблицы могут быть метатаблицами, что дает им поведение --- перегрузки-оператора. Позже мы увидим, что метатаблицы поддерживают поведение --- js-прототипов. +-- Таблицу можно связать с метатаблицей, задав ей поведение, как при +-- перегрузке операторов. Позже мы увидим, что метатаблицы поддерживают поведение, +-- как в js-прототипах. f1 = {a = 1, b = 2} -- Представляет фракцию a/b. f2 = {a = 2, b = 3} @@ -225,57 +221,57 @@ end setmetatable(f1, metafraction) setmetatable(f2, metafraction) -s = f1 + f2 -- вызывает __add(f1, f2) на мета-таблице f1 +s = f1 + f2 -- вызвать __add(f1, f2) на метатаблице от f1 --- f1, f2 не имеют ключей для своих метатаблиц в отличии от прототипов в js, поэтому --- ты можешь извлечь данные через getmetatable(f1). Метатаблицы это обычные таблицы с --- ключем, который в Lua известен как __add. +-- f1, f2 не имеют ключа для своих метатаблиц в отличии от прототипов в js, поэтому +-- нужно получить его через getmetatable(f1). Метатаблица - обычная таблица +-- с ключами, известными для Lua (например, __add). --- Но следущая строка будет ошибочной т.к s не мета-таблица: +-- Но следущая строка будет ошибочной т.к в s нет метатаблицы: -- t = s + s --- Шаблоны классов приведенные ниже смогут это исправить. +-- Похожий на классы подход, приведенный ниже, поможет это исправить. --- __index перегружет в мета-таблице просмотр через точку: +-- __index перегружет в метатаблице просмотр через точку: defaultFavs = {animal = 'gru', food = 'donuts'} myFavs = {food = 'pizza'} setmetatable(myFavs, {__index = defaultFavs}) eatenBy = myFavs.animal -- работает! спасибо, мета-таблица. -------------------------------------------------------------------------------- --- Прямой табличный поиск не будет пытаться передавать с помощью __index --- значения, и её рекурсии. - --- __index значения так же могут быть function(tbl, key) для настроенного --- просмотра. - --- Значения типа __index,add, ... называются метаметодами. --- Полный список. Здесь таблицы с метаметодами. - --- __add(a, b) для a + b --- __sub(a, b) для a - b --- __mul(a, b) для a * b --- __div(a, b) для a / b --- __mod(a, b) для a % b --- __pow(a, b) для a ^ b --- __unm(a) для -a --- __concat(a, b) для a .. b --- __len(a) для #a --- __eq(a, b) для a == b --- __lt(a, b) для a < b --- __le(a, b) для a <= b --- __index(a, b) для a.b --- __newindex(a, b, c) для a.b = c --- __call(a, ...) для a(...) +-- При неудаче прямой табличный поиск попытается использовать +-- значение __index в метатаблице, причём это рекурсивно. + +-- Значение __index также может быть функцией +-- function(tbl, key) для настраиваемого поиска. + +-- Значения типа __index, __add, ... называются метаметодами. +-- Ниже приведён полный список метаметодов. + +-- __add(a, b) для a + b +-- __sub(a, b) для a - b +-- __mul(a, b) для a * b +-- __div(a, b) для a / b +-- __mod(a, b) для a % b +-- __pow(a, b) для a ^ b +-- __unm(a) для -a +-- __concat(a, b) для a .. b +-- __len(a) для #a +-- __eq(a, b) для a == b +-- __lt(a, b) для a < b +-- __le(a, b) для a <= b +-- __index(a, b) <функция или таблица> для a.b +-- __newindex(a, b, c) для a.b = c +-- __call(a, ...) для a(...) -------------------------------------------------------------------------------- --- 3.2 Классы и наследования. +-- 3.2 Классоподобные таблицы и наследование. -------------------------------------------------------------------------------- --- В Lua нет поддержки классов на уровне языка; --- Однако существуют разные способы их создания с помощью +-- В Lua нет поддержки классов на уровне языка, +-- однако существуют разные способы их создания с помощью -- таблиц и метатаблиц. --- Пример классам находится ниже. +-- Ниже приведён один из таких способов. Dog = {} -- 1. @@ -292,19 +288,19 @@ end mrDog = Dog:new() -- 7. mrDog:makeSound() -- 'I say woof' -- 8. --- 1. Dog похоже на класс; но это таблица. --- 2. "function tablename:fn(...)" как и --- "function tablename.fn(self, ...)", Просто : добавляет первый аргумент --- перед собой. Читай 7 и 8 чтоб понять как self получает значение. --- 3. newObj это экземпляр класса Dog. --- 4. "self" есть класс являющийся экземпляром. Зачастую self = Dog, но экземляр --- может поменять это. newObj получит свои функции, когда мы установим newObj как --- метатаблицу и __index на себя. --- 5. Помни: setmetatable возвращает первый аргумент. --- 6. ":" Работает в 2 стороны, но в этот раз мы ожидмаем, что self будет экземпляром --- а не классом. --- 7. Dog.new(Dog), тоже самое что self = Dog in new(). --- 8. mrDog.makeSound(mrDog) будет self = mrDog. +-- 1. Dog похоже на класс, но на самом деле это таблица. +-- 2. "function tablename:fn(...)" - то же самое, что и +-- "function tablename.fn(self, ...)", просто : добавляет первый аргумент +-- перед собой. См. пункты 7 и 8, чтобы понять, как self получает значение. +-- 3. newObj - это экземпляр класса Dog. +-- 4. "self" - экземпляр класса. Зачастую self = Dog, но с помощью наследования +-- это можно изменить. newObj получит свои функции, когда мы установим +-- метатаблицу для newObj и __index для self на саму себя. +-- 5. Напоминание: setmetatable возвращает первый аргумент. +-- 6. : работает, как в пункте 2, но в этот раз мы ожидмаем, +-- что self будет экземпляром, а не классом. +-- 7. То же самое, что и Dog.new(Dog), поэтому self = Dog в new(). +-- 8. То же самое, что mrDog.makeSound(mrDog); self = mrDog. -------------------------------------------------------------------------------- -- Пример наследования: @@ -321,18 +317,19 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -------------------------------------------------------------------------------- -- 1. LoudDog получит методы и переменные класса Dog. --- 2. self будет 'sound' ключ для new(), смотри 3й пункт. --- 3. Так же как "LoudDog.new(LoudDog)" и переделанный в "Dog.new(LoudDog)" --- LoudDog не имеет ключ 'new', но может выполнить "__index = Dog" в этой метатаблице --- Результат: Метатаблица seymour стала LoudDog и "LoudDog.__index = Dog" --- Так же seymour.key будет равна seymour.key, LoudDog.key, Dog.key, --- в зависимости от того какая таблица будет с первым ключем. +-- 2. В self будет ключ 'sound' из new(), см. пункт 3. +-- 3. То же самое, что и "LoudDog.new(LoudDog)", конвертированное в "Dog.new(LoudDog)", +-- поскольку в LoudDog нет ключа 'new', но в его метатаблице есть "__index = Dog". +-- Результат: Метатаблицей для seymour стала LoudDog и "LoudDog.__index = Dog", +-- поэтому seymour.key будет равно seymour.key, LoudDog.key, Dog.key, +-- в зависимости от того какая таблица будет первой с заданным ключом. -- 4. 'makeSound' ключ найден в LoudDog; и выглдяит как "LoudDog.makeSound(seymour)". --- При необходимости, подкласс new() будет базовым. +-- При необходимости функция new() в подклассе +-- может быть похожа на аналог в базовом классе. function LoudDog:new() local newObj = {} - -- set up newObj + -- установить newObj self.__index = self return setmetatable(newObj, self) end @@ -342,12 +339,12 @@ end -------------------------------------------------------------------------------- ---[[ Я закомментировал этот раздел так как часть скрипта остается +--[[ Я закомментировал этот раздел, чтобы остальная часть скрипта осталась -- работоспособной. ``` ```lua --- Предположим файл mod.lua будет выглядеть так: +-- Предположим, файл mod.lua будет выглядеть так: local M = {} local function sayMyName() @@ -355,44 +352,44 @@ local function sayMyName() end function M.sayHello() - print('Why hello there') + print('Привет, ') sayMyName() end return M --- Иные файлы могут использовать функционал mod.lua: +-- Другой файл может использовать функционал mod.lua: local mod = require('mod') -- Запустим файл mod.lua. --- require - подключает модули. --- require выглядит так: (если не кешируется; смотри ниже) +-- require - стандартный способ подключения модулей. +-- require ведёт себя так: (если не кешировано, см. ниже) local mod = (function () - + <содержимое mod.lua> end)() --- Тело функции mod.lua является локальным, поэтому --- содержимое не видимо за телом функции. +-- Файл mod.lua воспринимается, как тело функции, поэтому +-- все локальные переменные и функции внутри него не видны за его пределами. --- Это работает так как mod здесь = M в mod.lua: -mod.sayHello() -- Скажет слово Hrunkner. +-- Это работает, так как здесь mod = M в mod.lua: +mod.sayHello() -- Выведет "Привет, Hrunkner". --- Это будет ошибочным; sayMyName доступен только в mod.lua: +-- Это будет ошибочным; sayMyName доступна только в mod.lua: mod.sayMyName() -- ошибка --- require возвращает значения кеша файла вызванного не более одного раза, даже когда --- требуется много раз. +-- Значения, возвращаемые require, кэшируются, поэтому содержимое файла +-- выполняется только 1 раз, даже если он подключается с помощью require много раз. --- Предположим mod2.lua содержит "print('Hi!')". -local a = require('mod2') -- Напишет Hi! -local b = require('mod2') -- Не напишет; a=b. +-- Предположим, mod2.lua содержит "print('Hi!')". +local a = require('mod2') -- Выведет "Hi!" +local b = require('mod2') -- Ничего не выведет; a=b. --- dofile работает без кэша: +-- dofile, в отличии от require, работает без кэширования: dofile('mod2') --> Hi! -dofile('mod2') --> Hi! (напишет снова) +dofile('mod2') --> Hi! (запустится снова) --- loadfile загружает lua файл, но не запускает его. -f = loadfile('mod2') -- Вызовет f() запустит mod2.lua. +-- loadfile загружает файл, но не запускает его. +f = loadfile('mod2') -- Вызов f() запустит содержимое mod2.lua. --- loadstring это loadfile для строк. +-- loadstring - это loadfile для строк. g = loadstring('print(343)') -- Вернет функцию. g() -- Напишет 343. @@ -401,25 +398,24 @@ g() -- Напишет 343. ``` ## Примечание (от автора) -Я был взволнован, когда узнал что с Lua я могу делать игры при помощи Love 2D game engine. Вот почему. +Мне было интересно изучить Lua, чтобы делать игры при помощи Love 2D game engine. Я начинал с BlackBulletIV's Lua for programmers. Затем я прочитал официальную Документацию по Lua. -Так же может быть полезным Lua short -reference на lua-users.org. +Так же может быть полезным Краткая справка по Lua на lua-users.org. -Основные темы не охваченные стандартной библиотекой: +Основные темы, не охваченные стандартной библиотекой: -* string library -* table library -* math library -* io library -* os library +* библиотека string +* библиотека table +* библиотека math +* библиотека io +* библиотека os -Весь файл написан на Lua; сохрани его как learn.lua и запусти при помощи "lua learn.lua" ! +Весь файл написан на Lua; сохраните его, как learn.lua, и запустите при помощи "lua learn.lua" ! -Это была моя первая статья для tylerneylon.com, которая так же доступна тут github gist. +Это была моя первая статья для tylerneylon.com, которая также доступна как github gist. Удачи с Lua! -- cgit v1.2.3 From acbea221a4037ff34ebf8a9b76b47aaec3c0c755 Mon Sep 17 00:00:00 2001 From: ugexe Date: Sun, 16 Nov 2014 12:16:26 -0500 Subject: 0 // 5 = 0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 11:59 < nebuchadnezzar> m: say Any // Nil // 0 // 5 11:59 <+camelia> rakudo-moar 38e77b: OUTPUT«0␤» 11:59 < nebuchadnezzar> shouldn't it be 5? 12:00 < ugexe> 0 is a defined value 12:00 < ugexe> m: say Any || Nil || 0 || 5; 12:00 <+camelia> rakudo-moar 38e77b: OUTPUT«5␤» --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 9f3a03ba..b178de1e 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1177,7 +1177,7 @@ $obj eqv $obj2; # sort comparison using eqv semantics ## * Short-circuit default operator # Like `or` and `||`, but instead returns the first *defined* value : -say Any // Nil // 0 // 5; #=> 5 +say Any // Nil // 0 // 5; #=> 0 ## * Short-circuit exclusive or (XOR) # Returns `True` if one (and only one) of its arguments is true -- cgit v1.2.3 From d886036b59f14da678536b1a2a57c6ad2fadee08 Mon Sep 17 00:00:00 2001 From: Doug Ilijev Date: Mon, 17 Nov 2014 01:26:19 -0600 Subject: [python/en] Fix 80 col limit and clarify a few points. --- python.html.markdown | 60 ++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 16 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index f7b0082c..53381f32 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -102,6 +102,9 @@ not False # => True # Strings can be added too! "Hello " + "world!" # => "Hello world!" +# ... or multiplied +"Hello" * 3 # => "HelloHelloHello" + # A string can be treated like a list of characters "This is a string"[0] # => 'T' @@ -136,11 +139,12 @@ bool("") # => False ## 2. Variables and Collections #################################################### -# 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!" - +# Python has a print statement, in all 2.x versions but removed from 3. +print "I'm Python. Nice to meet you!" +# Python also has a print function, available in versions 2.7 and 3... +# but for 2.7 you need to add the import (uncommented): +# from __future__ import print_function +print("I'm also Python! ") # No need to declare variables before assigning to them. some_var = 5 # Convention is to use lower_case_with_underscores @@ -170,6 +174,10 @@ li.append(3) # li is now [1, 2, 4, 3] again. # Access a list like you would any array li[0] # => 1 +# Assign new values to indexes that have already been initialized with = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Note: setting it back to the original value # Look at the last element li[-1] # => 3 @@ -194,7 +202,8 @@ li[::-1] # => [3, 4, 2, 1] del li[2] # li is now [1, 2, 3] # You can add lists -li + other_li # => [1, 2, 3, 4, 5, 6] - Note: values for li and for other_li are not modified. +li + other_li # => [1, 2, 3, 4, 5, 6] +# Note: values for li and for other_li are not modified. # Concatenate lists with "extend()" li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] @@ -255,17 +264,25 @@ 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 +# note that filled_dict.get("four") is still => 4 +# (get doesn't set the value in the dictionary) + +# set the value of a key with a syntax similar to lists +filled_dict["four"] = 4 # now, filled_dict["four"] => 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 -# Sets store ... well sets +# Sets store ... well sets (which are like lists but can contain no duplicates) empty_set = set() # Initialize a "set()" with a bunch of values some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4]) +# order is not guaranteed, even though it may sometimes look sorted +another_set = set([4, 3, 2, 2, 1]) # another_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} @@ -371,7 +388,7 @@ add(y=6, x=5) # Keyword arguments can arrive in any order. # You can define functions that take a variable number of -# positional arguments +# positional args, which will be interpreted as a tuple if you do not use the * def varargs(*args): return args @@ -379,7 +396,7 @@ varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of -# keyword arguments, as well +# keyword args, as well, which will be interpreted as a map if you do not use ** def keyword_args(**kwargs): return kwargs @@ -398,26 +415,33 @@ all_the_args(1, 2, a=3, b=4) prints: """ # When calling functions, you can do the opposite of args/kwargs! -# Use * to expand tuples and use ** to expand kwargs. +# Use * to expand positional args and use ** to expand keyword args. 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) +# you can pass args and kwargs along to other functions that take args/kwargs +# by expanding them with * and ** respectively +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + # Function Scope x = 5 def setX(num): # Local var x not the same as global variable x x = num # => 43 - print (x) # => 43 + print x # => 43 def setGlobalX(num): global x - print (x) # => 5 + print x # => 5 x = num # global var x is now set to 6 - print (x) # => 6 + print x # => 6 setX(43) setGlobalX(6) @@ -442,11 +466,11 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] [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): @@ -516,6 +540,9 @@ from math import * # You can shorten module names import math as m math.sqrt(16) == m.sqrt(16) # => True +# you can also test that the functions are equivalent +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True # Python modules are just ordinary python files. You # can write your own, and import them. The name of the @@ -542,8 +569,9 @@ def double_numbers(iterable): # double_numbers. # Note xrange is a generator that does the same thing range does. # Creating a list 1-900000000 would take lot of time and space to be made. -# xrange creates an xrange generator object instead of creating the entire list like range does. -# We use a trailing underscore in variable names when we want to use a name that +# xrange creates an xrange generator object instead of creating the entire list +# like range does. +# We use a trailing underscore in variable names when we want to use a name that # would normally collide with a python keyword xrange_ = xrange(1, 900000000) -- cgit v1.2.3 From 41633c28aab59a9ddcbfdddbd59f284140142f46 Mon Sep 17 00:00:00 2001 From: Daniel-Cortez Date: Tue, 18 Nov 2014 01:54:01 +0700 Subject: Another portion of fixes --- ru-ru/lua-ru.html.markdown | 58 +++++++++++++++++++++++++--------------------- 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index b9af61b4..89d0c8d7 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -37,20 +37,20 @@ t = nil -- Удаляет определение переменной t; в Lua -- Блоки обозначаются ключевыми слоавми, такими как do/end: while num < 50 do - num = num + 1 -- Здесь нет ++ или += операторов. + num = num + 1 -- Операторов ++ и += нет. end -- Ветвление "если": if num > 40 then print('больше 40') elseif s ~= 'walternate' then -- ~= обозначает "не равно". - -- Проверка равенства это == как в Python; работает для строк. + -- Проверка равенства это ==, как в Python; работает для строк. io.write('не больше 40\n') -- По умолчанию вывод в stdout. else -- По умолчанию переменные являются глобальными. thisIsGlobal = 5 -- Стиль CamelСase является общим. - -- Как сделать локальную переменную: + -- Как сделать переменную локальной: local line = io.read() -- Считывает введённую строку. -- Для конкатенации строк используется оператор .. : @@ -107,7 +107,8 @@ a2 = adder(36) print(a1(16)) --> 25 print(a2(64)) --> 100 --- Возвраты, вызовы функций и присвоения работают со списками, которые могут иметь разную длину. +-- Возвраты, вызовы функций и присвоения работают со списками, +-- которые могут иметь разную длину. -- Лишние получатели принимают значение nil, а лишние значения игнорируются. x, y, z = 1, 2, 3, 4 @@ -135,10 +136,11 @@ local g; g = function (x) return math.sin(x) end -- Кстати, тригонометрические функции работают с радианами. --- Вызов функции с одним текстовым параметром не требует круглых скобок: +-- Вызов функции с одним строковым параметром не требует круглых скобок: print 'hello' -- Работает без ошибок. --- Вызов функции с одним табличным параметром так же не требуют круглых скобок (про таблицы в след.части): +-- Вызов функции с одним табличным параметром так же +-- не требует круглых скобок (про таблицы в след.части): print {} -- Тоже сработает. -------------------------------------------------------------------------------- @@ -147,8 +149,8 @@ print {} -- Тоже сработает. -- Таблица = единственная составная структура данных в Lua; -- представляет собой ассоциативный массив. --- Похоже на массивы в PHP или объекты в JS. --- Также может использоваться, как список. +-- Подобно массивам в PHP или объектам в JS, они представляют собой +-- хеш-таблицы, которые также можно использовать в качестве списков. -- Использование словарей: @@ -170,12 +172,12 @@ print(u[6.28]) -- пишет "tau" a = u['@!#'] -- Теперь a = 'qbert'. b = u[{}] -- Вы могли ожидать 1729, но получится nil: -- b = nil, т.к. ключ не будет найден. --- Это произойдёт, потому что за ключ мы использовали не тот же самый объект, --- который использовали для сохранения оригинального значения. +-- Это произойдёт потому, что за ключ мы использовали не тот же самый объект, +-- который был использован для сохранения оригинального значения. -- Поэтому строки и числа удобнее использовать в качестве ключей. -- Вызов функции с одной таблицей в качестве аргумента --- не нуждается в кавычках: +-- не требует круглых скобок: function h(x) print(x.key1) end h{key1 = 'Sonmi~451'} -- Печатает 'Sonmi~451'. @@ -190,8 +192,8 @@ print(_G['_G'] == _G) -- Печатает 'true'. -- Список значений с неявно заданными целочисленными ключами: v = {'value1', 'value2', 1.21, 'gigawatts'} -for i = 1, #v do -- #v это размер списка v. - print(v[i]) -- Нумерация начинается с ОДНОГО !! +for i = 1, #v do -- #v - размер списка v. + print(v[i]) -- Нумерация начинается с 1 !! end -- Список не является отдельным типом. v - всего лишь таблица @@ -202,8 +204,8 @@ end -------------------------------------------------------------------------------- -- Таблицу можно связать с метатаблицей, задав ей поведение, как при --- перегрузке операторов. Позже мы увидим, что метатаблицы поддерживают поведение, --- как в js-прототипах. +-- перегрузке операторов. Позже мы увидим, что метатаблицы поддерживают +-- поведение, как в js-прототипах. f1 = {a = 1, b = 2} -- Представляет фракцию a/b. f2 = {a = 2, b = 3} @@ -223,9 +225,9 @@ setmetatable(f2, metafraction) s = f1 + f2 -- вызвать __add(f1, f2) на метатаблице от f1 --- f1, f2 не имеют ключа для своих метатаблиц в отличии от прототипов в js, поэтому +-- f1, f2 не имеют ключа для своих метатаблиц в отличии от прототипов в js, -- нужно получить его через getmetatable(f1). Метатаблица - обычная таблица --- с ключами, известными для Lua (например, __add). +-- поэтому с ключами, известными для Lua (например, __add). -- Но следущая строка будет ошибочной т.к в s нет метатаблицы: -- t = s + s @@ -318,12 +320,15 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -------------------------------------------------------------------------------- -- 1. LoudDog получит методы и переменные класса Dog. -- 2. В self будет ключ 'sound' из new(), см. пункт 3. --- 3. То же самое, что и "LoudDog.new(LoudDog)", конвертированное в "Dog.new(LoudDog)", --- поскольку в LoudDog нет ключа 'new', но в его метатаблице есть "__index = Dog". --- Результат: Метатаблицей для seymour стала LoudDog и "LoudDog.__index = Dog", --- поэтому seymour.key будет равно seymour.key, LoudDog.key, Dog.key, --- в зависимости от того какая таблица будет первой с заданным ключом. --- 4. 'makeSound' ключ найден в LoudDog; и выглдяит как "LoudDog.makeSound(seymour)". +-- 3. То же самое, что и "LoudDog.new(LoudDog)", конвертированное +-- в "Dog.new(LoudDog)", поскольку в LoudDog нет ключа 'new', +-- но в его метатаблице есть "__index = Dog". +-- Результат: Метатаблицей для seymour стала LoudDog, +-- а "LoudDog.__index = Dog". Поэтому seymour.key будет равно +-- seymour.key, LoudDog.key, Dog.key, в зависимости от того, +-- какая таблица будет первой с заданным ключом. +-- 4. Ключ 'makeSound' находится в LoudDog; +-- то же самое, что и "LoudDog.makeSound(seymour)". -- При необходимости функция new() в подклассе -- может быть похожа на аналог в базовом классе. @@ -375,8 +380,9 @@ mod.sayHello() -- Выведет "Привет, Hrunkner". -- Это будет ошибочным; sayMyName доступна только в mod.lua: mod.sayMyName() -- ошибка --- Значения, возвращаемые require, кэшируются, поэтому содержимое файла --- выполняется только 1 раз, даже если он подключается с помощью require много раз. +-- Значения, возвращаемые require, кэшируются, +-- поэтому содержимое файла выполняется только 1 раз, +-- даже если он подключается с помощью require много раз. -- Предположим, mod2.lua содержит "print('Hi!')". local a = require('mod2') -- Выведет "Hi!" @@ -403,7 +409,7 @@ g() -- Напишет 343. Я начинал с BlackBulletIV's Lua for programmers. Затем я прочитал официальную Документацию по Lua. -Так же может быть полезным Краткая справка по Lua на lua-users.org. +Также может быть полезной Краткая справка по Lua на lua-users.org. Основные темы, не охваченные стандартной библиотекой: -- cgit v1.2.3 From 1992190cd010c21115c00c84ae168d0c004023e2 Mon Sep 17 00:00:00 2001 From: Harry Mumford-Turner Date: Tue, 18 Nov 2014 10:19:11 +0000 Subject: Temp fix for Matlab syntax highlighting The single quote messed up the rest of the file. --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 2b9077d5..9de41275 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -200,7 +200,7 @@ A(1, :) =[] % Delete the first row of the matrix A(:, 1) =[] % Delete the first column of the matrix transpose(A) % Transpose the matrix, which is the same as: -A' +A one ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) -- cgit v1.2.3 From 1e1ff8bd10990e81cd18b2393a781c5061538bc0 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Tue, 18 Nov 2014 12:01:59 +0000 Subject: Fix typo when demonstrating variables. --- forth.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/forth.html.markdown b/forth.html.markdown index 4c89a5ec..5db7b51f 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -130,8 +130,8 @@ variable age \ ok \ Finally we can print our variable using the "read" word `@`, which adds the \ value to the stack, or use `?` that reads and prints it in one go. -age @ . \ 12 ok -age ? \ 12 ok +age @ . \ 21 ok +age ? \ 21 ok \ Constants are quite simiar, except we don't bother with memory addresses: 100 constant WATER-BOILING-POINT \ ok -- cgit v1.2.3 From 39ac935c4f2fefa0d63ed8e87bb7142a9c458188 Mon Sep 17 00:00:00 2001 From: HorseMD Date: Tue, 18 Nov 2014 12:19:12 +0000 Subject: Reword arrays introduction. --- forth.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/forth.html.markdown b/forth.html.markdown index 5db7b51f..570e12ed 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -139,7 +139,10 @@ WATER-BOILING-POINT . \ 100 ok \ ----------------------------------- Arrays ----------------------------------- -\ Set up an array of length 3: +\ Creating arrays is similar to variables, except we need to allocate more +\ memory to them. + +\ You can use `2 cells allot` to create an array that's 3 cells long: variable mynumbers 2 cells allot \ ok \ Initialize all the values to 0 -- cgit v1.2.3 From f25d54b06bd8ae17cf8e9fc9d966fc728cb593e0 Mon Sep 17 00:00:00 2001 From: Kevin Busby Date: Thu, 20 Nov 2014 16:26:56 +0000 Subject: Typo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Typo: “addition” corrected to “edition”. --- ruby.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index e58c513d..7cf5bdc7 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -518,5 +518,5 @@ Something.new.qux # => 'qux' - [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. - [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) -- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. - [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. -- cgit v1.2.3 From 458bbd063ad78c3ba6b0d114226f94edf0dab708 Mon Sep 17 00:00:00 2001 From: Julien Cretel Date: Fri, 21 Nov 2014 17:28:38 +0000 Subject: Fix some inaccuracies in haskell.html.markdown - The bottom of the "List and Tuples" section may mislead the reader into thinking that the `fst` and `snd` functions can be applied to any tuple; it's worth mentioning that those functions only apply to pairs. - The example demonstrating the use of the function-application operator (`$`) in combination with the function-composition operator (`.`) seems a bit contrived. For completeness, I've added an example that uses `$` alone. - "If statements" and "case statements" are actually expressions, in Haskell; I've replaced all occurences of the word "statement" appearing in that context by the word "expression". - Minor wording improvement (replaced "because" by a semicolon). --- haskell.html.markdown | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 2785405c..748a29da 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -110,7 +110,7 @@ last [1..5] -- 5 -- A tuple: ("haskell", 1) --- accessing elements of a tuple +-- accessing elements of a pair (i.e. a tuple of length 2) fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 @@ -195,8 +195,8 @@ 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 `.` and `$` to get rid of a lot --- of parentheses: +-- to everything on the right. You can use `$` (often in combination with `.`) +-- to get rid of a lot of parentheses: -- before (even (fib 7)) -- true @@ -204,6 +204,9 @@ foo 5 -- 75 -- after even . fib $ 7 -- true +-- equivalently +even $ fib 7 -- true + ---------------------------------------------------- -- 5. Type signatures ---------------------------------------------------- @@ -227,24 +230,24 @@ double :: Integer -> Integer double x = x * 2 ---------------------------------------------------- --- 6. Control Flow and If Statements +-- 6. Control Flow and If Expressions ---------------------------------------------------- --- if statements +-- if expressions haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" --- if statements can be on multiple lines too, indentation is important +-- if expressions can be on multiple lines too, indentation is important haskell = if 1 == 1 then "awesome" else "awful" --- case statements: Here's how you could parse command line arguments +-- case expressions: Here's how you could parse command line arguments case args of "help" -> printHelp "start" -> startProgram _ -> putStrLn "bad args" --- Haskell doesn't have loops because it uses recursion instead. +-- Haskell doesn't have loops; it uses recursion instead. -- map applies a function over every element in an array map (*2) [1..5] -- [2, 4, 6, 8, 10] -- cgit v1.2.3 From d179669f3985f8cab479778a1a32f7e02ea3f182 Mon Sep 17 00:00:00 2001 From: Martin Thoresen Date: Mon, 24 Nov 2014 17:37:55 +0100 Subject: fix #873 --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 874197d3..f44da38e 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -629,7 +629,7 @@ typedef void (*my_fnp_type)(char *); ## Further Reading Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) -It is *the* book about C, written by the creators of C. Be careful, though - it's ancient and it contains some +It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some inaccuracies (well, ideas that are not considered good anymore) or now-changed practices. Another good resource is [Learn C the hard way](http://c.learncodethehardway.org/book/). -- cgit v1.2.3 From 3a8b9f0fc5397fb824cb49ecf6efd4a0c916b339 Mon Sep 17 00:00:00 2001 From: LOZORD Date: Mon, 24 Nov 2014 19:32:40 -0600 Subject: Added 'git stash'! --- git.html.markdown | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index 618d1906..e064122d 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -334,6 +334,55 @@ $ git push -u origin master $ git push ``` +### stash + +Stashing takes the dirty state of your working directory and saves it on a +stack of unfinished changes that you can reapply at any time. + +```bash +# Let's say you've been doing some work in your git repo, but you want to pull from the remote. +# Since you have dirty (uncommited) changes to some files, you are not able to run 'git pull'. +# Instead, you can run 'git stash' to save your changes onto a stack! + +$ git stash +Saved working directory and index state \ + "WIP on master: 049d078 added the index file" + HEAD is now at 049d078 added the index file + (To restore them type "git stash apply") + +# Now you can pull! +git pull +# ...changes apply... + +# Now check that everything is OK + +$ git status +# On branch master +nothing to commit, working directory clean + +# You can see what 'hunks' you've stashed so far: +# Since the 'hunks' are stored in a Last-In-First-Out stack +# our most recent change will be at top +$ git stash list +stash@{0}: WIP on master: 049d078 added the index file +stash@{1}: WIP on master: c264051 Revert "added file_size" +stash@{2}: WIP on master: 21d80a5 added number to log + +# Now let's apply our dirty changes back by popping them off the stack +# 'git stash apply' also works too +$ git stash pop +# On branch master +# Changes not staged for commit: +# (use "git add ..." to update what will be committed) +# +# modified: index.html +# modified: lib/simplegit.rb +# + +# Now you're good to go! + +[Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) + ### rebase (caution) Take all changes that were committed on one branch, and replay them onto another branch. @@ -396,4 +445,4 @@ $ git rm /pather/to/the/file/HelloWorld.c * [GitGuys](http://www.gitguys.com/) -* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) \ No newline at end of file +* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) -- cgit v1.2.3 From 8b442c2497962b3b47844da74a416075313dc428 Mon Sep 17 00:00:00 2001 From: LOZORD Date: Mon, 24 Nov 2014 19:39:44 -0600 Subject: Only bashified the code sections --- git.html.markdown | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/git.html.markdown b/git.html.markdown index e064122d..7778fdd4 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -336,40 +336,45 @@ $ git push ### stash -Stashing takes the dirty state of your working directory and saves it on a -stack of unfinished changes that you can reapply at any time. +Stashing takes the dirty state of your working directory and saves it on a stack of unfinished changes that you can reapply at any time. -```bash -# Let's say you've been doing some work in your git repo, but you want to pull from the remote. -# Since you have dirty (uncommited) changes to some files, you are not able to run 'git pull'. -# Instead, you can run 'git stash' to save your changes onto a stack! +Let's say you've been doing some work in your git repo, but you want to pull from the remote. +Since you have dirty (uncommited) changes to some files, you are not able to run 'git pull'. +Instead, you can run 'git stash' to save your changes onto a stack! +```bash $ git stash Saved working directory and index state \ "WIP on master: 049d078 added the index file" HEAD is now at 049d078 added the index file (To restore them type "git stash apply") +``` -# Now you can pull! +Now you can pull! +```bash git pull -# ...changes apply... +``` +...changes apply... -# Now check that everything is OK +Now check that everything is OK +```bash $ git status # On branch master nothing to commit, working directory clean +``` -# You can see what 'hunks' you've stashed so far: -# Since the 'hunks' are stored in a Last-In-First-Out stack -# our most recent change will be at top +You can see what 'hunks' you've stashed so far: +Since the 'hunks' are stored in a Last-In-First-Out stack our most recent change will be at top +```bash $ git stash list stash@{0}: WIP on master: 049d078 added the index file stash@{1}: WIP on master: c264051 Revert "added file_size" stash@{2}: WIP on master: 21d80a5 added number to log +``` -# Now let's apply our dirty changes back by popping them off the stack -# 'git stash apply' also works too +Now let's apply our dirty changes back by popping them off the stack +```bash $ git stash pop # On branch master # Changes not staged for commit: @@ -378,9 +383,10 @@ $ git stash pop # modified: index.html # modified: lib/simplegit.rb # +``` +'git stash apply' also works too -# Now you're good to go! - +Now you're ready to get back to work on your stuff! [Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) ### rebase (caution) -- cgit v1.2.3 From 295b40d2724a24e046f75da71b4e43124168b535 Mon Sep 17 00:00:00 2001 From: LOZORD Date: Mon, 24 Nov 2014 19:41:02 -0600 Subject: Small formatting changes --- git.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index 7778fdd4..7e9e70de 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -384,9 +384,10 @@ $ git stash pop # modified: lib/simplegit.rb # ``` -'git stash apply' also works too +`git stash apply` does the same thing Now you're ready to get back to work on your stuff! + [Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) ### rebase (caution) -- cgit v1.2.3 From b7f4ca7ea8e831426eeced7b37b09ed1d81a8190 Mon Sep 17 00:00:00 2001 From: LOZORD Date: Mon, 24 Nov 2014 19:44:25 -0600 Subject: Added ourselves to the contributor section --- git.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index 7e9e70de..f94fadee 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -3,6 +3,8 @@ category: tool tool: git contributors: - ["Jake Prather", "http://github.com/JakeHP"] + - ["Leo Rudberg" , "http://github.com/LOZORD"] + - ["Betsy Lorton" , "http://github.com/schbetsy"] filename: LearnGit.txt --- -- cgit v1.2.3 From 0e42f4c928b1414102467f539b313c1646e91093 Mon Sep 17 00:00:00 2001 From: Leo Rudberg Date: Tue, 25 Nov 2014 13:47:03 -0600 Subject: Fixed some markdown formatting issuses --- git.html.markdown | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/git.html.markdown b/git.html.markdown index f94fadee..04350dd5 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -341,8 +341,8 @@ $ git push Stashing takes the dirty state of your working directory and saves it on a stack of unfinished changes that you can reapply at any time. Let's say you've been doing some work in your git repo, but you want to pull from the remote. -Since you have dirty (uncommited) changes to some files, you are not able to run 'git pull'. -Instead, you can run 'git stash' to save your changes onto a stack! +Since you have dirty (uncommited) changes to some files, you are not able to run `git pull`. +Instead, you can run `git stash` to save your changes onto a stack! ```bash $ git stash @@ -353,10 +353,11 @@ Saved working directory and index state \ ``` Now you can pull! + ```bash git pull ``` -...changes apply... +`...changes apply...` Now check that everything is OK @@ -366,8 +367,9 @@ $ git status nothing to commit, working directory clean ``` -You can see what 'hunks' you've stashed so far: -Since the 'hunks' are stored in a Last-In-First-Out stack our most recent change will be at top +You can see what "hunks" you've stashed so far using `git stash list`. +Since the "hunks" are stored in a Last-In-First-Out stack, our most recent change will be at top. + ```bash $ git stash list stash@{0}: WIP on master: 049d078 added the index file @@ -375,7 +377,8 @@ stash@{1}: WIP on master: c264051 Revert "added file_size" stash@{2}: WIP on master: 21d80a5 added number to log ``` -Now let's apply our dirty changes back by popping them off the stack +Now let's apply our dirty changes back by popping them off the stack. + ```bash $ git stash pop # On branch master @@ -386,6 +389,7 @@ $ git stash pop # modified: lib/simplegit.rb # ``` + `git stash apply` does the same thing Now you're ready to get back to work on your stuff! -- cgit v1.2.3 From d6ce2aa25941317de46d02567d2b2c7c2127393c Mon Sep 17 00:00:00 2001 From: Pedro Pisandelli Date: Tue, 25 Nov 2014 20:02:54 -0300 Subject: Fixed some misspelling words for pt-br language --- pt-br/ruby-pt.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 4a8a1b5c..89a051d4 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -33,7 +33,7 @@ Você não deve usar também 10 * 2 #=> 20 35 / 5 #=> 7 -# Aritimética é apenas açúcar sintático +# Aritmética é apenas açúcar sintático # para chamar um método de um objeto 1.+(3) #=> 4 10.* 5 #=> 50 @@ -129,7 +129,7 @@ array = [1, "Oi", false] #=> => [1, "Oi", false] array[0] #=> 1 array[12] #=> nil -# Como aritimética, o acesso via [var] +# Como aritmética, o acesso via [var] # é apenas açúcar sintático # para chamar o método [] de um objeto array.[] 0 #=> 1 @@ -171,7 +171,7 @@ end # Desde o Ruby 1.9, temos uma sintaxe especial quando usamos símbolos como chaves (keys) -novo_hash = { defcon: 3, acao: true} +novo_hash = {defcon: 3, acao: true} novo_hash.keys #=> [:defcon, :acao] @@ -183,9 +183,9 @@ novo_hash.keys #=> [:defcon, :acao] if true "Se verdadeiro" elsif false - "else if, opicional" + "else if, opcional" else - "else, também é opicional" + "else, também é opcional" end for contador in 1..5 @@ -259,7 +259,7 @@ end # Argumentos de métodos são separados por uma vírgula somar 3, 4 #=> 7 -somar somar(3,4), 5 #=> 12 +somar(3,4), 5 #=> 12 # yield # Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco -- cgit v1.2.3 From fa2a8209062a3005744a17f3d0912981b43f8942 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Thu, 27 Nov 2014 00:38:54 -0700 Subject: Implicits --- scala.html.markdown | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 529347be..f481f04f 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -507,7 +507,60 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared // 8. Implicits ///////////////////////////////////////////////// -// Coming soon! +/* WARNING WARNING: Implicits are a set of powerful features of Scala, and + * therefore it is easy to abuse them. Beginners to Scala should resist the + * temptation to use them until they understand not only how they work, but also + * best practices around them. We only include this section in the tutorial + * because they are so commonplace in Scala libraries that it is impossible to + * do anything meaningful without using a library that has implicits. This is + * meant for you to understand and work with implicts, not declare your own. + */ + +// Any value (vals, functions, objects, etc) can be declared to be implicit by +// using the, you guessed it, "implicit" keyword. Note we are using the Dog +// class from section 5 in these examples. +implicit val myImplicitInt = 100 +implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) + +// By itself, implicit keyword doesn't change the behavior of the value, so +// above values can be used as usual. +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" + +// The difference is that these values are now elligible to be used when another +// piece of code "needs" an implicit value. One such situation is implicit +// function arguments: +def sendGreetings(toWhom: String)(implicit howMany: Int) = + s"Hello $toWhom, $howMany blessings to you and yours!" + +// If we supply a value for "howMany", the function behaves as usual +sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" + +// But if we omit the implicit parameter, an implicit value of the same type is +// used, in this case, "myImplicitInt": +sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" + +// Implicit function parameters enable us to simulate type classes in other +// functional languages. It is so often used that it gets its own shorthand. The +// following two lines mean the same thing: +def foo[T](implicit c: C[T]) = ... +def foo[T : C] = ... + + +// Another situation in which the compiler looks for an implicit is if you have +// obj.method(...) +// but "obj" doesn't have "method" as a method. In this case, if there is an +// implicit conversion of type A => B, where A is the type of obj, and B has a +// method called "method", that conversion is applied. So having +// myImplicitFunction above in scope, we can say: +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" + +// Here the String is first converted to Dog using our function above, and then +// the appropriate method is called. This is an extremely powerful feature, but +// again, it is not to be used lightly. In fact, when you defined the implicit +// function above, your compiler should have given you a warning, that you +// shouldn't do this unless you really know what you're doing. ///////////////////////////////////////////////// -- cgit v1.2.3 From 448aee0ed7b68d1ad029d78f3ac157eeba8c3555 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Thu, 27 Nov 2014 00:40:32 -0700 Subject: Fix a typo --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index f481f04f..5a478f2a 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -527,7 +527,7 @@ implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) myImplicitInt + 2 // => 102 myImplicitFunction("Pitbull").breed // => "Golden Pitbull" -// The difference is that these values are now elligible to be used when another +// The difference is that these values are now eligible to be used when another // piece of code "needs" an implicit value. One such situation is implicit // function arguments: def sendGreetings(toWhom: String)(implicit howMany: Int) = -- cgit v1.2.3 From 8ea39ded5c746628ae74ad3706752410de5273cd Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 1 Dec 2014 21:39:49 -0700 Subject: Reassignment to reference doesn't cause error --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 9f357b08..d81ca4fc 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -238,7 +238,7 @@ string& fooRef = foo; // This creates a reference to foo. fooRef += ". Hi!"; // Modifies foo through the reference cout << fooRef; // Prints "I am foo. Hi!" -fooRef = bar; // Error: references cannot be reassigned. +fooRef = bar; // Doesn't reassign `fooRef`. This is the same as `foo = bar` const string& barRef = bar; // Create a const reference to bar. // Like C, const values (and pointers and references) cannot be modified. -- cgit v1.2.3 From bf493c07ed519cc3d41198a0720a5919f67f3ff0 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 1 Dec 2014 21:39:49 -0700 Subject: Reassignment to reference doesn't cause error --- c++.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 9f357b08..5f80f26f 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -238,7 +238,10 @@ string& fooRef = foo; // This creates a reference to foo. fooRef += ". Hi!"; // Modifies foo through the reference cout << fooRef; // Prints "I am foo. Hi!" -fooRef = bar; // Error: references cannot be reassigned. +// Doesn't reassign "fooRef". This is the same as "foo = bar", and +// foo == "I am bar" +// after this line. +fooRef = bar; const string& barRef = bar; // Create a const reference to bar. // Like C, const values (and pointers and references) cannot be modified. -- cgit v1.2.3 From 493812180f1e368ec8788cc02620bcd1f10e290e Mon Sep 17 00:00:00 2001 From: Mariane Siqueira Machado Date: Thu, 4 Dec 2014 14:38:45 -0200 Subject: Clojure translation into pt-br --- pt-br/clojure-pt.html.markdown | 381 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 381 insertions(+) create mode 100644 pt-br/clojure-pt.html.markdown diff --git a/pt-br/clojure-pt.html.markdown b/pt-br/clojure-pt.html.markdown new file mode 100644 index 00000000..a2b53726 --- /dev/null +++ b/pt-br/clojure-pt.html.markdown @@ -0,0 +1,381 @@ +--- +language: clojure +filename: learnclojure-pt.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Mariane Siqueira Machado", "https://twitter.com/mariane_sm"] +lang: pt-br +--- + +Clojure é uma linguagem da família do Lisp desenvolvida para a JVM (máquina virtual Java). Possui uma ênfase muito mais forte em [programação funcional] (https://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_funcional) pura do que Common Lisp, mas inclui diversas utilidades [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) para lidar com estado a medida que isso se torna necessário. + +Essa combinação permite gerenciar processamento concorrente de maneira muito simples e frequentemente de maneira automática. + +(Sua versão de clojure precisa ser pelo menos 1.2) + + +```clojure +; Comentários começam por ponto e vírgula + +; Clojure é escrito em "forms" (padrões), os quais são simplesmente +; listas de coisas dentro de parênteses, separados por espaços em branco. + +; O "reader" (leitor) de clojure presume que o primeiro elemento de +; uma par de parênteses é uma função ou macro, e que os resto são argumentos. + +: A primeira chamada de um arquivo deve ser ns, para configurar o namespace (espaço de nomes) +(ns learnclojure) + +; Alguns exemplos básicos: + +; str cria uma string concatenando seus argumentos +(str "Hello" " " "World") ; => "Hello World" + +; Math é direta e intuitiva +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 + +; Igualdade é = +(= 1 1) ; => true +(= 2 1) ; => false + +; Negação para operações lógicas +(not true) ; => false + +; Aninhar forms (padrões) funciona como esperado +(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 + +; Tipos +;;;;;;;;;;;;; + +; Clojure usa os tipos de objetos de Java para booleanos, strings e números. +; Use `class` para inspecioná-los +(class 1) ; Literais Integer são java.lang.Long por padrão +(class 1.); Literais Float são java.lang.Double +(class ""); Strings são sempre com aspas duplas, e são java.lang.String +(class false) ; Booleanos são java.lang.Boolean +(class nil); O valor "null" é chamado nil + +; Se você quiser criar um lista de literais, use aspa simples para +; ela não ser avaliada +'(+ 1 2) ; => (+ 1 2) +; (que é uma abreviação de (quote (+ 1 2))) + +; É possível avaliar uma lista com aspa simples +(eval '(+ 1 2)) ; => 3 + +; Coleções e sequências +;;;;;;;;;;;;;;;;;;; + +; Listas são estruturas encadeadas, enquanto vetores são implementados como arrays. +; Listas e Vetores são classes Java também! +(class [1 2 3]); => clojure.lang.PersistentVector +(class '(1 2 3)); => clojure.lang.PersistentList + +; Uma lista é escrita como (1 2 3), mas temos que colocar a aspa +; simples para impedir o leitor (reader) de pensar que é uma função. +; Também, (list 1 2 3) é o mesmo que '(1 2 3) + +; "Coleções" são apenas grupos de dados +; Listas e vetores são ambos coleções: +(coll? '(1 2 3)) ; => true +(coll? [1 2 3]) ; => true + +; "Sequências" (seqs) são descrições abstratas de listas de dados. +; Apenas listas são seqs. +(seq? '(1 2 3)) ; => true +(seq? [1 2 3]) ; => false + +; Um seq precisa apenas prover uma entrada quando é acessada. +; Portanto, já que seqs podem ser avaliadas sob demanda (lazy) -- elas podem definir séries infinitas: +(range 4) ; => (0 1 2 3) +(range) ; => (0 1 2 3 4 ...) (uma série infinita) +(take 4 (range)) ; (0 1 2 3) + +; Use cons para adicionar um item no início de uma lista ou vetor +(cons 4 [1 2 3]) ; => (4 1 2 3) +(cons 4 '(1 2 3)) ; => (4 1 2 3) + +; Conj adiciona um item em uma coleção sempre do jeito mais eficiente. +; Para listas, elas inserem no início. Para vetores, é inserido no final. +(conj [1 2 3] 4) ; => [1 2 3 4] +(conj '(1 2 3) 4) ; => (4 1 2 3) + +; Use concat para concatenar listas e vetores +(concat [1 2] '(3 4)) ; => (1 2 3 4) + +; Use filter, map para interagir com coleções +(map inc [1 2 3]) ; => (2 3 4) +(filter even? [1 2 3]) ; => (2) + +; Use reduce para reduzi-los +(reduce + [1 2 3 4]) +; = (+ (+ (+ 1 2) 3) 4) +; => 10 + +; Reduce pode receber um argumento para o valor inicial +(reduce conj [] '(3 2 1)) +; = (conj (conj (conj [] 3) 2) 1) +; => [3 2 1] + +; Funções +;;;;;;;;;;;;;;;;;;;;; + +; Use fn para criar novas funções. Uma função sempre retorna +; sua última expressão. +(fn [] "Hello World") ; => fn + +; (É necessário colocar parênteses para chamá-los) +((fn [] "Hello World")) ; => "Hello World" + +; Você pode criar variáveis (var) usando def +(def x 1) +x ; => 1 + +; Atribua uma função para uma var +(def hello-world (fn [] "Hello World")) +(hello-world) ; => "Hello World" + +; Você pode abreviar esse processo usando defn +(defn hello-world [] "Hello World") + +; O [] é uma lista de argumentos para um função. +(defn hello [name] + (str "Hello " name)) +(hello "Steve") ; => "Hello Steve" + +; Você pode ainda usar essa abreviação para criar funcões: +(def hello2 #(str "Hello " %1)) +(hello2 "Fanny") ; => "Hello Fanny" + +; Vocé pode ter funções multi-variadic, isto é, com um número variável de argumentos +(defn hello3 + ([] "Hello World") + ([name] (str "Hello " name))) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" + +; Funções podem agrupar argumentos extras em uma seq +(defn count-args [& args] + (str "You passed " (count args) " args: " args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" + +; Você pode misturar argumentos regulares e argumentos em seq +(defn hello-count [name & args] + (str "Hello " name ", you passed " (count args) " extra args")) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" + + +; Mapas +;;;;;;;;;; + +; Hash maps e array maps compartilham uma mesma interface. Hash maps são mais +; rápidos para pesquisa mas não mantém a ordem da chave. +(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap +(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap + +; Arraymaps pode automaticamente se tornar hashmaps através da maioria das +; operações se eles ficarem grandes o suficiente, portanto não há necessida de +; se preocupar com isso. + +; Maps podem usar qualquer tipo "hasheavel" como chave, mas normalmente +; keywords (palavras chave) são melhores. +; Keywords são como strings mas com algumas vantagens. +(class :a) ; => clojure.lang.Keyword + +(def stringmap {"a" 1, "b" 2, "c" 3}) +stringmap ; => {"a" 1, "b" 2, "c" 3} + +(def keymap {:a 1, :b 2, :c 3}) +keymap ; => {:a 1, :c 3, :b 2} + +; A propósito, vírgulas são sempre tratadas como espaçoes em branco e não fazem nada. + +; Recupere o valor de um mapa chamando ele como uma função +(stringmap "a") ; => 1 +(keymap :a) ; => 1 + +; Uma palavra chave pode ser usada pra recuperar os valores de um mapa +(:b keymap) ; => 2 + +; Não tente isso com strings +;("a" stringmap) +; => Exception: java.lang.String cannot be cast to clojure.lang.IFn + +; Buscar uma chave não presente retorna nil +(stringmap "d") ; => nil + +; Use assoc para adicionar novas chaves para hash-maps +(def newkeymap (assoc keymap :d 4)) +newkeymap ; => {:a 1, :b 2, :c 3, :d 4} + +; Mas lembre-se, tipos em clojure são sempre imutáveis! +keymap ; => {:a 1, :b 2, :c 3} + +; Use dissoc para remover chaves +(dissoc keymap :a :b) ; => {:c 3} + +; Conjuntos +;;;;;; + +(class #{1 2 3}) ; => clojure.lang.PersistentHashSet +(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} + +; Adicione um membro com conj +(conj #{1 2 3} 4) ; => #{1 2 3 4} + +; Remove um com disj +(disj #{1 2 3} 1) ; => #{2 3} + +; Test por existência usando set como função: +(#{1 2 3} 1) ; => 1 +(#{1 2 3} 4) ; => nil + +; Existem muitas outras funções no namespace clojure.sets + +; Forms (padrões) úteis +;;;;;;;;;;;;;;;;; + +; Construções lógicas em clojure são como macros, e +; se parecem com as demais +(if false "a" "b") ; => "b" +(if false "a") ; => nil + +; Use let para criar amarramentos (bindings) temporários +(let [a 1 b 2] + (> a b)) ; => false + +; Agrupe comandos juntos com do +(do + (print "Hello") + "World") ; => "World" (prints "Hello") + +; Funções tem um do implícito +(defn print-and-say-hello [name] + (print "Saying hello to " name) + (str "Hello " name)) +(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") + +; Assim como let +(let [name "Urkel"] + (print "Saying hello to " name) + (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Módulos +;;;;;;;;;;;;;;; + +; Use "use" para poder usar todas as funções de um modulo +(use 'clojure.set) + +; Agora nós podemos usar operações com conjuntos +(intersection #{1 2 3} #{2 3 4}) ; => #{2 3} +(difference #{1 2 3} #{2 3 4}) ; => #{1} + +; Você pode escolher um subconjunto de funções para importar +(use '[clojure.set :only [intersection]]) + +; Use require para importar um módulo +(require 'clojure.string) + +; USe / para chamar funções de um módulo +; Aqui, o módulo é clojure.string e a função é blank? +(clojure.string/blank? "") ; => true + +; Você pode dar para um módulo um nome mais curto no import +(require '[clojure.string :as str]) +(str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." +; (#"" denota uma expressão regular literal) + +; Você pode usar require (e até "use", mas escolha require) de um namespace utilizando :require. +; Não é necessário usar aspa simples nos seus módulos se você usar desse jeito. +(ns test + (:require + [clojure.string :as str] + [clojure.set :as set])) + +; Java +;;;;;;;;;;;;;;;;; + +; Java tem uma biblioteca padrão enorme e muito útil, +; portanto é importante aprender como utiliza-la. + +; Use import para carregar um modulo java +(import java.util.Date) + +; Você pode importar usando ns também. +(ns test + (:import java.util.Date + java.util.Calendar)) + +; Use o nome da clase com um "." no final para criar uma nova instância +(Date.) ; + +; Use . para chamar métodos. Ou, use o atalho ".method" +(. (Date.) getTime) ; +(.getTime (Date.)) ; exactly the same thing. + +; Use / para chamar métodos estáticos +(System/currentTimeMillis) ; (system is always present) + +; Use doto para pode lidar com classe (mutáveis) de forma mais tolerável +(import java.util.Calendar) +(doto (Calendar/getInstance) + (.set 2000 1 1 0 0 0) + .getTime) ; => A Date. set to 2000-01-01 00:00:00 + +; STM +;;;;;;;;;;;;;;;;; + +; Software Transactional Memory é o mecanismo que clojure usa para gerenciar +; estado persistente. Tem algumas construções em clojure que o utilizam. + +; O atom é o mais simples. Passe pra ele um valor inicial +(def my-atom (atom {})) + +; Atualize o atom com um swap!. +; swap! pega uma funçnao and chama ela com o valor atual do atom +; como primeiro argumento, e qualquer argumento restante como o segundo +(swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2) + +; Use '@' para desreferenciar um atom e acessar seu valor +my-atom ;=> Atom<#...> (Retorna o objeto do Atom) +@my-atom ; => {:a 1 :b 2} + +; Abaixo um contador simples usando um atom +(def counter (atom 0)) +(defn inc-counter [] + (swap! counter inc)) + +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) + +@counter ; => 5 + +; Outras construção STM são refs e agents. +; Refs: http://clojure.org/refs +; Agents: http://clojure.org/agents +``` + +### Leitura adicional + +Esse tutorial está longe de ser exaustivo, mas deve ser suficiente para que você possa começar. + +Clojure.org tem vários artigos: +[http://clojure.org/](http://clojure.org/) + +Clojuredocs.org tem documentação com exemplos para quase todas as funções principais (pertecentes ao core): +[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) + +4Clojure é um grande jeito de aperfeiçoar suas habilidades em Clojure/Programação Funcional: +[http://www.4clojure.com/](http://www.4clojure.com/) + +Clojure-doc.org tem um bom número de artigos para iniciantes: +[http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From 283973e99da0dee0bc811b62280d1a3db77b0b52 Mon Sep 17 00:00:00 2001 From: Mariane Siqueira Machado Date: Thu, 4 Dec 2014 19:43:12 -0200 Subject: Swift translation to pt-br --- pt-br/swift-pt.html.markdown | 500 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 500 insertions(+) create mode 100644 pt-br/swift-pt.html.markdown diff --git a/pt-br/swift-pt.html.markdown b/pt-br/swift-pt.html.markdown new file mode 100644 index 00000000..a29490b0 --- /dev/null +++ b/pt-br/swift-pt.html.markdown @@ -0,0 +1,500 @@ +--- +language: swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"], + - ["Christopher Bess", "http://github.com/cbess"] +translators: + - ["Mariane Siqueira Machado", "https://twitter.com/mariane_sm"] +lang: pt-br +filename: learnswift.swift +--- + +Swift é uma linguagem de programação para desenvolvimento de aplicações no iOS e OS X criada pela Apple. Criada para +coexistir com Objective-C e para ser mais resiliente a código com erros, Swift foi apresentada em 2014 na Apple's +developer conference WWDC. Foi construída com o compilador LLVM já incluído no Xcode 6 beta. + +O livro oficial [Swift Programming Language] (https://itunes.apple.com/us/book/swift-programming-language/id881256329) da +Apple já está disponível via IBooks (apenas em inglês). + +Confira também o tutorial completo de Swift da Apple [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), também disponível apenas em inglês. + +```swift +// importa um módulo +import UIKit + +// +// MARK: Noções básicas +// + +// Xcode supporta anotações para seu código e lista elas na barra de atalhos +// MARK: Marca uma sessão +// TODO: Faça algo logo +// FIXME: Conserte esse código + +println("Hello, world") + +// Valores em variáveis (var) podem ter seu valor alterado depois de declarados. +// Valores em constantes (let) NÃO podem ser alterados depois de declarados. + +var myVariable = 42 +let øπΩ = "value" // nomes de variáveis em unicode +let π = 3.1415926 +let convenience = "keyword" // nome de variável contextual +let weak = "keyword"; let override = "another keyword" // comandos podem ser separados por uma ponto e vírgula +let `class` = "keyword" // Crases permitem que palavras-chave seja usadas como nome de variáveis +let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "some text " + String(myVariable) // Coerção +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolação de strings + +// Constrói valores específicos +// Utiliza configuração de build -D +#if false + println("Not printed") + let buildValue = 3 +#else + let buildValue = 7 +#endif +println("Build value: \(buildValue)") // Build value: 7 + +/* + Optionals fazem parte da linguagem e permitem que você armazene um + valor `Some` (algo) ou `None` (nada). + + Como Swift requer que todas as propriedades tenham valores, até mesmo nil deve + ser explicitamente armazenado como um valor Optional. + + Optional é uma enum. +*/ +var someOptionalString: String? = "optional" // Pode ser nil +// o mesmo acima, mas ? é um operador pós-fixado (açúcar sintático) +var someOptionalString2: Optional = "optional" + +if someOptionalString != nil { + // Eu não sou nil + if someOptionalString!.hasPrefix("opt") { + println("has the prefix") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +// Optional implicitamente desempacotado (unwrapped) +var unwrappedString: String! = "Valor é esperado." +// o mesmo acima, mas ? é um operador pósfixado (açúcar sintático) +var unwrappedString2: ImplicitlyUnwrappedOptional = "Valor é esperado." + +if let someOptionalStringConstant = someOptionalString { + // Tem `Some` (algum) valor, não nil + if !someOptionalStringConstant.hasPrefix("ok") { + // não possui o prefixo + } +} + +// Swift tem suporte para armazenar um valor de qualquer tipo. +// AnyObject == id +// Ao contrário de Objective-C `id`, AnyObject funciona com qualquer valor (Class, Int, struct, etc) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Mudou o valor para string, não é uma boa prática, mas é possível." + +/* +Comentário aqui + /* + Comentários aninhados também são suportados + */ +*/ + +// +// MARK: Coleções +// + +/* + Tipos Array e Dicionário são structs. Portanto `let` e `var` + também indicam se são mutáveis (var) ou imutáveis (let) quando declarados + com esses tipos. +*/ + +// Array +var shoppingList = ["catfish", "water", "lemons"] +shoppingList[1] = "bottle of water" +let emptyArray = [String]() // imutável +var emptyMutableArray = [String]() // mutável + + +// Dicionário +var occupations = [ + "Malcolm": "Captain", + "kaylee": "Mechanic" +] +occupations["Jayne"] = "Public Relations" +let emptyDictionary = [String: Float]() // imutável +var emptyMutableDictionary = [String: Float]() // mutável + + +// +// MARK: Controle de fluxo +// + +// laço for (array) +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + println("One!") + } else { + println("Not one!") + } +} + +// laço for (dicionário) +var dict = ["one": 1, "two": 2] +for (key, value) in dict { + println("\(key): \(value)") +} + +// laço for (alcance) +for i in -1...shoppingList.count { + println(i) +} +shoppingList[1...2] = ["steak", "peacons"] +// use ..< para excluir o último número + +// laço while (enquanto) +var i = 1 +while i < 1000 { + i *= 2 +} + +// laço do-while +do { + println("hello") +} while 1 == 2 + +// Switch +let vegetable = "red pepper" +switch vegetable { +case "celery": + let vegetableComment = "Add some raisins and make ants on a log." +case "cucumber", "watercress": + let vegetableComment = "That would make a good tea sandwich." +case let x where x.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(x)?" +default: // required (in order to cover all possible input) + let vegetableComment = "Everything tastes good in soup." +} + + +// +// MARK: Funções +// + +// Funções são tipos de primeira classe, o que significa que eles podem ser aninhados +// em funções e podem ser passados como parâmetros + +// Funções Swift com cabeçalhos doc (formato como reStructedText) +/** +Uma operação de saudação + +- Um bullet em documentos +- Outro bullet + +:param: nome A nome +:param: dia A dia +:returns: Uma string contendo o nome e o dia. +*/ +func greet(name: String, day: String) -> String { + return "Hello \(name), today is \(day)." +} +greet("Bob", "Tuesday") + +// Função que retorna múltiplos items em uma tupla +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// Ignore valores de Tuplas (ou outros valores) usando _ (underscore) +let (_, price1, _) = pricesTuple // price1 == 3.69 +println(price1 == pricesTuple.1) // true +println("Gas price: \(price)") + +// Número variável de argumentos +func setup(numbers: Int...) { + // its an array + let number = numbers[0] + let argCount = numbers.count +} + +// Passando e retornando funções +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + +// passagem por referência +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +println(someIntB) // 7 + + +// +// MARK: Closures +// +var numbers = [1, 2, 6] + +// Funções são casos especiais de closures ({}) + +// Exemplo de closure. +// `->` separa argumentos e tipo de retorno +// `in` separa o cabeçalho do closure do seu corpo +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result +}) + +// Quando o tipo é conhecido, como abaixo, nós podemos fazer o seguinte +numbers = numbers.map({ number in 3 * number }) +// Ou até mesmo isso +//numbers = numbers.map({ $0 * 3 }) + +print(numbers) // [3, 6, 18] + +// Closure restante +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super atalho, já que o operador < infere os tipos + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] + +// +// MARK: Estruturas +// + +// Estruturas e classes tem funcionalidades muito similares +struct NamesTable { + let names: [String] + + // Custom subscript + subscript(index: Int) -> String { + return names[index] + } +} + +// Estruturas possuem um inicializador auto-gerado automático (implícito) +let namesTable = NamesTable(names: ["Me", "Them"]) +//let name = namesTable[2] +//println("Name is \(name)") // Name is Them + +// +// MARK: Classes +// + +// Classes, Estruturas e seus membros possuem três níveis de modificadores de acesso +// Eles são: internal (default), public, private + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + +// Todos os métodos e propriedades de uma classe são públicos. +// Se você só precisa armazenar dados em um objeto estruturado, use `struct` + +internal class Rect: Shape { + var sideLength: Int = 1 + + // Getter e setter personalizado + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` é uma variável implicita disponível para os setters + sideLength = newValue / 4 + } + } + + // Carregue uma propriedade sob demanda (lazy) + // subShape permanece nil (não inicializado) até seu getter ser chamado + lazy var subShape = Rect(sideLength: 4) + + // Se você não precisa de um getter e setter personalizado, + // mas ainda quer roda código antes e depois de configurar + // uma propriedade, você pode usar `willSet` e `didSet` + var identifier: String = "defaultID" { + // o argumento `willSet` será o nome da variável para o novo valor + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(sideLength: Int) { + self.sideLength = sideLength + // sempre chame super.init por último quand inicializar propriedades personalizadas (custom) + super.init() + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} + +// Uma classe básica `Square` que estende `Rect` +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } +} + +var mySquare = Square() +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// Compara instâncias, não é o mesmo que == o qual compara objetos +if mySquare === mySquare { + println("Yep, it's mySquare") +} + + +// +// MARK: Enums +// + +// Enums podem opcionalmente ser de um tipo específico ou não. +// Podem conter métodos do mesmo jeito que classes. + +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + + +// +// MARK: Protocolos +// + +// `protocol` pode requerer que os tipos que se adequam tenham +// propriedades de instância, métodos, operadores e subscripts. +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +// Protocolos declarados com @objc permitem funções opcionais, +// que permitem verificar a confomidade +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + if let allow = self.delegate?.canReshape?() { + // test for delegate then for method + // testa por delegação e então por método + self.delegate?.reshaped?() + } + } +} + + +// +// MARK: Outros +// + +// `extension`s: Adicionam uma funcionalidade extra para um tipo já existente. + +// Square agora "segue" o protocolo `Printable` +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +println("Square: \(mySquare)") + +// Você pode também estender tipos embutidos (built-in) +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +println(7.customProperty) // "This is 7" +println(14.multiplyBy(2)) // 42 + +// Generics: Similar com Java e C#. Use a palavra-chave `where` para +// especificar os requisitos do generics. + +func findIndex(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +println(foundAtIndex == 2) // true + +// Operadores: +// Operadores personalizados (custom) podem começar com os seguintes caracteres: +// / = - + * % < > ! & | ^ . ~ +// ou +// Unicode math, símbolo, seta, e caracteres tipográficos ou de desenho. +prefix operator !!! {} + +// Um operador de prefixo que triplica o comprimento do lado do quadrado +// quando usado +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// valor atual +println(mySquare.sideLength) // 4 + +// Troca o comprimento do lado usando um operador personalizado !!!, aumenta o lado por 3 +!!!mySquare +println(mySquare.sideLength) // 12 + +``` -- cgit v1.2.3 From acaefff543c04e9cf3f63625193c1383254b6ee3 Mon Sep 17 00:00:00 2001 From: Daniel-Cortez Date: Fri, 5 Dec 2014 17:59:04 +0700 Subject: And the last(?) one --- ru-ru/lua-ru.html.markdown | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index 89d0c8d7..99607ebc 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -35,7 +35,7 @@ u = [[ Двойные квадратные скобки многострочные значения.]] t = nil -- Удаляет определение переменной t; в Lua есть сборка мусора. --- Блоки обозначаются ключевыми слоавми, такими как do/end: +-- Блоки обозначаются ключевыми словами, такими как do/end: while num < 50 do num = num + 1 -- Операторов ++ и += нет. end @@ -139,8 +139,8 @@ local g; g = function (x) return math.sin(x) end -- Вызов функции с одним строковым параметром не требует круглых скобок: print 'hello' -- Работает без ошибок. --- Вызов функции с одним табличным параметром так же --- не требует круглых скобок (про таблицы в след.части): +-- Вызов функции с одним табличным параметром также +-- не требует круглых скобок (про таблицы в след. части): print {} -- Тоже сработает. -------------------------------------------------------------------------------- @@ -206,7 +206,7 @@ end -- Таблицу можно связать с метатаблицей, задав ей поведение, как при -- перегрузке операторов. Позже мы увидим, что метатаблицы поддерживают -- поведение, как в js-прототипах. -f1 = {a = 1, b = 2} -- Представляет фракцию a/b. +f1 = {a = 1, b = 2} -- Представляет дробь a/b. f2 = {a = 2, b = 3} -- Это не сработает: @@ -233,7 +233,7 @@ s = f1 + f2 -- вызвать __add(f1, f2) на метатаблице от f1 -- t = s + s -- Похожий на классы подход, приведенный ниже, поможет это исправить. --- __index перегружет в метатаблице просмотр через точку: +-- __index перегружает в метатаблице просмотр через точку: defaultFavs = {animal = 'gru', food = 'donuts'} myFavs = {food = 'pizza'} setmetatable(myFavs, {__index = defaultFavs}) @@ -299,7 +299,7 @@ mrDog:makeSound() -- 'I say woof' -- 8. -- это можно изменить. newObj получит свои функции, когда мы установим -- метатаблицу для newObj и __index для self на саму себя. -- 5. Напоминание: setmetatable возвращает первый аргумент. --- 6. : работает, как в пункте 2, но в этот раз мы ожидмаем, +-- 6. : работает, как в пункте 2, но в этот раз мы ожидаем, -- что self будет экземпляром, а не классом. -- 7. То же самое, что и Dog.new(Dog), поэтому self = Dog в new(). -- 8. То же самое, что mrDog.makeSound(mrDog); self = mrDog. @@ -367,7 +367,7 @@ return M local mod = require('mod') -- Запустим файл mod.lua. -- require - стандартный способ подключения модулей. --- require ведёт себя так: (если не кешировано, см. ниже) +-- require ведёт себя так: (если не кэшировано, см. ниже) local mod = (function () <содержимое mod.lua> end)() @@ -404,14 +404,14 @@ g() -- Напишет 343. ``` ## Примечание (от автора) -Мне было интересно изучить Lua, чтобы делать игры при помощи Love 2D game engine. +Мне было интересно изучить Lua, чтобы делать игры при помощи игрового движка LÖVE. Я начинал с BlackBulletIV's Lua for programmers. Затем я прочитал официальную Документацию по Lua. Также может быть полезной Краткая справка по Lua на lua-users.org. -Основные темы, не охваченные стандартной библиотекой: +Ещё из основных тем не охвачены стандартные библиотеки: * библиотека string * библиотека table @@ -419,9 +419,7 @@ g() -- Напишет 343. * библиотека io * библиотека os -Весь файл написан на Lua; сохраните его, как learn.lua, и запустите при помощи "lua learn.lua" ! - -Это была моя первая статья для tylerneylon.com, которая также доступна как github gist. - -Удачи с Lua! +Кстати, весь файл написан на Lua; сохраните его, как learn.lua, и запустите при помощи "lua learn.lua" ! +Изначально эта статья была написана для tylerneylon.com. +Также она доступна как github gist. Удачи с Lua! -- cgit v1.2.3 From d3d7a7c76288318f5be62690b74776ff0e9a1c0e Mon Sep 17 00:00:00 2001 From: Daniel-Cortez Date: Fri, 5 Dec 2014 18:37:50 +0700 Subject: Forgot to remove commas --- ru-ru/lua-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index 99607ebc..6f515975 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -419,7 +419,7 @@ g() -- Напишет 343. * библиотека io * библиотека os -Кстати, весь файл написан на Lua; сохраните его, как learn.lua, и запустите при помощи "lua learn.lua" ! +Кстати, весь файл написан на Lua; сохраните его как learn.lua и запустите при помощи "lua learn.lua" ! Изначально эта статья была написана для tylerneylon.com. Также она доступна как github gist. Удачи с Lua! -- cgit v1.2.3 From c5723d5e2a6302b3047569aa94c7974cad868287 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 5 Dec 2014 22:45:17 +0100 Subject: Fixes #882 --- fr-fr/brainfuck-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/brainfuck-fr.html.markdown b/fr-fr/brainfuck-fr.html.markdown index 3882734d..545e407e 100644 --- a/fr-fr/brainfuck-fr.html.markdown +++ b/fr-fr/brainfuck-fr.html.markdown @@ -13,7 +13,7 @@ Brainfuck (sans majuscule à part au début d’une phrase) est un langage Turing-complet extrêmement simple avec seulement 8 commandes. ``` -Tout caractère en dehors de "><+-.,[]" (en dehors des guillements) est ignoré. +Tout caractère en dehors de "><+-.,[]" (en dehors des guillemets) est ignoré. Brainfuck est représenté par un tableau de 30 000 cellules initialisées à 0 et un pointeur de données pointant sur la cellule courante. -- cgit v1.2.3 From b3e0d276987dca1cb97aad2b39999ce7e63da6be Mon Sep 17 00:00:00 2001 From: Mariane Siqueira Machado Date: Fri, 5 Dec 2014 20:15:08 -0200 Subject: Improving a little bit more --- pt-br/clojure-pt.html.markdown | 49 ++++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/pt-br/clojure-pt.html.markdown b/pt-br/clojure-pt.html.markdown index a2b53726..7e8b3f7b 100644 --- a/pt-br/clojure-pt.html.markdown +++ b/pt-br/clojure-pt.html.markdown @@ -10,7 +10,7 @@ lang: pt-br Clojure é uma linguagem da família do Lisp desenvolvida para a JVM (máquina virtual Java). Possui uma ênfase muito mais forte em [programação funcional] (https://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_funcional) pura do que Common Lisp, mas inclui diversas utilidades [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) para lidar com estado a medida que isso se torna necessário. -Essa combinação permite gerenciar processamento concorrente de maneira muito simples e frequentemente de maneira automática. +Essa combinação permite gerenciar processamento concorrente de maneira muito simples, e frequentemente de maneira automática. (Sua versão de clojure precisa ser pelo menos 1.2) @@ -18,10 +18,10 @@ Essa combinação permite gerenciar processamento concorrente de maneira muito s ```clojure ; Comentários começam por ponto e vírgula -; Clojure é escrito em "forms" (padrões), os quais são simplesmente +; Clojure é escrito em "forms", os quais são simplesmente ; listas de coisas dentro de parênteses, separados por espaços em branco. -; O "reader" (leitor) de clojure presume que o primeiro elemento de +; O "reader" (leitor) de Clojure presume que o primeiro elemento de ; uma par de parênteses é uma função ou macro, e que os resto são argumentos. : A primeira chamada de um arquivo deve ser ns, para configurar o namespace (espaço de nomes) @@ -32,20 +32,20 @@ Essa combinação permite gerenciar processamento concorrente de maneira muito s ; str cria uma string concatenando seus argumentos (str "Hello" " " "World") ; => "Hello World" -; Math é direta e intuitiva +; Cálculos são feitos de forma direta e intuitiva (+ 1 1) ; => 2 (- 2 1) ; => 1 (* 1 2) ; => 2 (/ 2 1) ; => 2 -; Igualdade é = +; Você pode comparar igualdade utilizando = (= 1 1) ; => true (= 2 1) ; => false ; Negação para operações lógicas (not true) ; => false -; Aninhar forms (padrões) funciona como esperado +; Aninhar "forms" funciona como esperado (+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 ; Tipos @@ -131,7 +131,7 @@ Essa combinação permite gerenciar processamento concorrente de maneira muito s ; (É necessário colocar parênteses para chamá-los) ((fn [] "Hello World")) ; => "Hello World" -; Você pode criar variáveis (var) usando def +; Você pode atribuir valores a variáveis utilizando def (def x 1) x ; => 1 @@ -182,8 +182,11 @@ x ; => 1 ; operações se eles ficarem grandes o suficiente, portanto não há necessida de ; se preocupar com isso. -; Maps podem usar qualquer tipo "hasheavel" como chave, mas normalmente -; keywords (palavras chave) são melhores. +;Mapas podem usar qualquer valor que se pode derivar um hash como chave + + +; Mapas podem usar qualquer valor em que se pode derivar um hash como chave, +; mas normalmente palavras-chave (keywords) são melhores. ; Keywords são como strings mas com algumas vantagens. (class :a) ; => clojure.lang.Keyword @@ -199,7 +202,7 @@ keymap ; => {:a 1, :c 3, :b 2} (stringmap "a") ; => 1 (keymap :a) ; => 1 -; Uma palavra chave pode ser usada pra recuperar os valores de um mapa +; Uma palavra-chave pode ser usada pra recuperar os valores de um mapa (:b keymap) ; => 2 ; Não tente isso com strings @@ -213,7 +216,7 @@ keymap ; => {:a 1, :c 3, :b 2} (def newkeymap (assoc keymap :d 4)) newkeymap ; => {:a 1, :b 2, :c 3, :d 4} -; Mas lembre-se, tipos em clojure são sempre imutáveis! +; Mas lembre-se, tipos em Clojure são sempre imutáveis! keymap ; => {:a 1, :b 2, :c 3} ; Use dissoc para remover chaves @@ -228,7 +231,7 @@ keymap ; => {:a 1, :b 2, :c 3} ; Adicione um membro com conj (conj #{1 2 3} 4) ; => #{1 2 3 4} -; Remove um com disj +; Remova um membro com disj (disj #{1 2 3} 1) ; => #{2 3} ; Test por existência usando set como função: @@ -237,19 +240,19 @@ keymap ; => {:a 1, :b 2, :c 3} ; Existem muitas outras funções no namespace clojure.sets -; Forms (padrões) úteis +; Forms úteis ;;;;;;;;;;;;;;;;; -; Construções lógicas em clojure são como macros, e +; Construções lógicas em Clojure são como macros, e ; se parecem com as demais (if false "a" "b") ; => "b" (if false "a") ; => nil -; Use let para criar amarramentos (bindings) temporários +; Use let para criar um novo escopo associando sîmbolos a valores (bindings) (let [a 1 b 2] (> a b)) ; => false -; Agrupe comandos juntos com do +; Agrupe comandos juntos com "do" (do (print "Hello") "World") ; => "World" (prints "Hello") @@ -281,7 +284,7 @@ keymap ; => {:a 1, :b 2, :c 3} ; Use require para importar um módulo (require 'clojure.string) -; USe / para chamar funções de um módulo +; Use / para chamar funções de um módulo ; Aqui, o módulo é clojure.string e a função é blank? (clojure.string/blank? "") ; => true @@ -316,10 +319,10 @@ keymap ; => {:a 1, :b 2, :c 3} ; Use . para chamar métodos. Ou, use o atalho ".method" (. (Date.) getTime) ; -(.getTime (Date.)) ; exactly the same thing. +(.getTime (Date.)) ; exatamente a mesma coisa. ; Use / para chamar métodos estáticos -(System/currentTimeMillis) ; (system is always present) +(System/currentTimeMillis) ; (o módulo System está sempre presente) ; Use doto para pode lidar com classe (mutáveis) de forma mais tolerável (import java.util.Calendar) @@ -330,8 +333,8 @@ keymap ; => {:a 1, :b 2, :c 3} ; STM ;;;;;;;;;;;;;;;;; -; Software Transactional Memory é o mecanismo que clojure usa para gerenciar -; estado persistente. Tem algumas construções em clojure que o utilizam. +; Software Transactional Memory é o mecanismo que Clojure usa para gerenciar +; estado persistente. Tem algumas construções em Clojure que o utilizam. ; O atom é o mais simples. Passe pra ele um valor inicial (def my-atom (atom {})) @@ -339,8 +342,8 @@ keymap ; => {:a 1, :b 2, :c 3} ; Atualize o atom com um swap!. ; swap! pega uma funçnao and chama ela com o valor atual do atom ; como primeiro argumento, e qualquer argumento restante como o segundo -(swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1) -(swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2) +(swap! my-atom assoc :a 1) ; Coloca o valor do átomo my-atom como o resultado de (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Coloca o valor do átomo my-atom como o resultado de (assoc {:a 1} :b 2) ; Use '@' para desreferenciar um atom e acessar seu valor my-atom ;=> Atom<#...> (Retorna o objeto do Atom) -- cgit v1.2.3 From 8291fb2d7d376186a19e643e92aacb9ed9412395 Mon Sep 17 00:00:00 2001 From: Ruben Date: Mon, 8 Dec 2014 13:27:06 +0100 Subject: Update c.html.markdown --- c.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index f44da38e..b5b804af 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -26,13 +26,15 @@ Multi-line comments look like this. They work in C89 as well. Multi-line comments don't nest /* Be careful */ // comment ends on this line... */ // ...not this one! - // Constants: #define +// Constants: #define #define DAYS_IN_YEAR 365 - // Enumeration constants are also ways to declare constants. - enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; +// Enumeration constants are also ways to declare constants. +// All statements must end with a semicolon +enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; // MON gets 2 automatically, TUE gets 3, etc. + // Import headers with #include #include #include @@ -57,7 +59,6 @@ int main() { // print output using printf, for "print formatted" // %d is an integer, \n is a newline printf("%d\n", 0); // => Prints 0 - // All statements must end with a semicolon /////////////////////////////////////// // Types -- cgit v1.2.3 From 658c09f6e4263e834153907cca87df00e4d9ab3b Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 8 Dec 2014 23:42:24 +0100 Subject: Update README.markdown --- README.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.markdown b/README.markdown index 4e24bbe6..774797d5 100644 --- a/README.markdown +++ b/README.markdown @@ -22,6 +22,11 @@ Send a pull request or open an issue any time of day or night. **(e.g. [python/en] for English Python).** This will help everyone pick out things they care about. +We're happy for any contribution in any form, but if you're making more than one major change +(i.e. translations for two different languages) it would be super cool of you to make a +separate pull request for each one so that someone can review them more effectively and/or +individually. + ### Style Guidelines * **Keep lines under 80 chars** -- cgit v1.2.3 From 9a8d8f0e5da4af6ddf18124f2cc203dcf57b52e5 Mon Sep 17 00:00:00 2001 From: Adrian Cooney Date: Wed, 10 Dec 2014 12:48:45 +0000 Subject: Added an example of custom Indexers in C-Sharp [en] --- csharp.html.markdown | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index f6708590..47dd9683 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -678,6 +678,23 @@ on a new line! ""Wow!"", the masses cried"; private set; } + // It's also possible to define custom Indexers on objects. + // All though this is not entirely useful in this example, you + // could do bicycle[0] which yields "chris" to get the first passenger or + // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) + private string[] passengers = { "chris", "phil", "darren", "regina" } + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + return passengers[i] = value; + } + } + //Method to display the attribute values of this Object. public virtual string Info() { -- cgit v1.2.3 From 4f2f0116edb8b4a83dba19e9fe61229e8d88d29e Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Wed, 10 Dec 2014 22:57:59 +0800 Subject: lua-cn: typos and refinements. --- zh-cn/lua-cn.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 53a603a2..098d0ab5 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -63,8 +63,8 @@ foo = anUnknownVariable -- 现在 foo = nil. aBoolValue = false ---只有nil和false为假; 0和 ''都均为真! -if not aBoolValue then print('twas false') end +--只有nil和false为假; 0和 ''均为真! +if not aBoolValue then print('false') end -- 'or'和 'and'短路 -- 类似于C/js里的 a?b:c 操作符: @@ -149,7 +149,7 @@ print {} -- 一样可以工作。 -- Table = Lua唯一的组合数据结构; -- 它们是关联数组。 -- 类似于PHP的数组或者js的对象, --- 它们是哈希表或者字典,也可以当初列表使用。 +-- 它们是哈希表或者字典,也可以当列表使用。 -- 按字典/map的方式使用Table: -- cgit v1.2.3 From 3a7e00127fef6f72b36f9b86083928623d3a1ab8 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sat, 13 Dec 2014 20:01:08 -0600 Subject: - update examples, update comments - add another Switch example - add more complex func example - fix playground error - add another casting example --- swift.html.markdown | 69 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 47 insertions(+), 22 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 005e511c..0d1d2df4 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -6,7 +6,7 @@ contributors: filename: learnswift.swift --- -Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta. +Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+. The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. @@ -23,7 +23,7 @@ import UIKit // Xcode supports landmarks to annotate your code and lists them in the jump bar // MARK: Section mark // TODO: Do something soon -// FIXME Fix this code +// FIXME: Fix this code println("Hello, world") @@ -55,8 +55,8 @@ println("Build value: \(buildValue)") // Build value: 7 /* Optionals are a Swift language feature that allows you to store a `Some` or `None` value. - - Because Swift requires every property to have a value, even nil must be + + Because Swift requires every property to have a value, even nil must be explicitly stored as an Optional value. Optional is an enum. @@ -94,7 +94,8 @@ var anyObjectVar: AnyObject = 7 anyObjectVar = "Changed value to a string, not good practice, but possible." /* -Comment here + Comment here + /* Nested comments are also supported */ @@ -112,8 +113,9 @@ Comment here // Array var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" -let emptyArray = [String]() // immutable -var emptyMutableArray = [String]() // mutable +let emptyArray = [String]() // let == immutable +let emptyArray2 = Array() // same as above +var emptyMutableArray = [String]() // var == mutable // Dictionary @@ -122,8 +124,9 @@ var occupations = [ "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" -let emptyDictionary = [String: Float]() // immutable -var emptyMutableDictionary = [String: Float]() // mutable +let emptyDictionary = [String: Float]() // let == immutable +let emptyDictionary2 = Dictionary() // same as above +var emptyMutableDictionary = [String: Float]() // var == mutable // @@ -165,14 +168,16 @@ do { } while 1 == 2 // Switch +// Very powerful, think `if` statements with syntax candy +// They support String, object instances, and primitives (Int, Double, etc) let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." -case let x where x.hasSuffix("pepper"): - let vegetableComment = "Is it a spicy \(x)?" +case let localScopeValue where localScopeValue.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(localScopeValue)?" default: // required (in order to cover all possible input) let vegetableComment = "Everything tastes good in soup." } @@ -186,21 +191,28 @@ default: // required (in order to cover all possible input) // in functions and can be passed around // Function with Swift header docs (format as reStructedText) + /** -A greet operation + A greet operation -- A bullet in docs -- Another bullet in the docs + - A bullet in docs + - Another bullet in the docs -:param: name A name -:param: day A day -:returns: A string containing the name and day value. + :param: name A name + :param: day A day + :returns: A string containing the name and day value. */ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } greet("Bob", "Tuesday") +// similar to above except for the function parameter behaviors +func greet2(#requiredName: String, externalParamName localParamName: String) -> String { + return "Hello \(requiredName), the day is \(localParamName)" +} +greet2(requiredName:"John", externalParamName: "Sunday") + // Function that returns multiple items in a tuple func getGasPrices() -> (Double, Double, Double) { return (3.59, 3.69, 3.79) @@ -281,7 +293,7 @@ print(numbers) // [3, 6, 18] // Structures and classes have very similar capabilites struct NamesTable { - let names: [String] + let names = [String]() // Custom subscript subscript(index: Int) -> String { @@ -291,8 +303,8 @@ struct NamesTable { // Structures have an auto-generated (implicit) designated initializer let namesTable = NamesTable(names: ["Me", "Them"]) -//let name = namesTable[2] -//println("Name is \(name)") // Name is Them +let name = namesTable[1] +println("Name is \(name)") // Name is Them // // MARK: Classes @@ -341,7 +353,7 @@ internal class Rect: Shape { init(sideLength: Int) { self.sideLength = sideLength - // always super.init last when init custom properties + // always super.init last when init custom properties super.init() } @@ -368,6 +380,9 @@ print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 +// cast instance +let aShape = mySquare as Shape + // compare instances, not the same as == which compares objects (equal to) if mySquare === mySquare { println("Yep, it's mySquare") @@ -393,6 +408,17 @@ enum Suit { } } +// Enum values allow short hand syntax, no need to type the enum type +// when the variable is explicitly declared +var suitValue: Suit = .Hearts + +// Non-Integer enums require direct raw value assignments +enum BookName: String { + case John = "John" + case Luke = "Luke" +} +println("Name: \(BookName.John.rawValue)") + // // MARK: Protocols @@ -490,5 +516,4 @@ println(mySquare.sideLength) // 4 // change side length using custom !!! operator, increases size by 3 !!!mySquare println(mySquare.sideLength) // 12 - ``` -- cgit v1.2.3 From 12e01249b37d65d8e7cf95b311782531978552d5 Mon Sep 17 00:00:00 2001 From: Swapnil Joshi Date: Tue, 16 Dec 2014 22:33:08 +0530 Subject: Changed function name to match function call --- hy.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hy.html.markdown b/hy.html.markdown index 04bd05c9..9beaff0c 100644 --- a/hy.html.markdown +++ b/hy.html.markdown @@ -83,7 +83,7 @@ True ; => True (greet "bilbo") ;=> "hello bilbo" ; functions can take optional arguments as well as keyword arguments -(defn foolist [arg1 &optional [arg2 2]] +(defn foolists [arg1 &optional [arg2 2]] [arg1 arg2]) (foolists 3) ;=> [3 2] -- cgit v1.2.3 From c43b73a369526a922282f429ba7b1472b64c4f8e Mon Sep 17 00:00:00 2001 From: Yuichi Motoyama Date: Sat, 20 Dec 2014 09:52:43 +0900 Subject: start translating julia into japanese --- ja-jp/julia-jp.html.markdown | 747 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 747 insertions(+) create mode 100644 ja-jp/julia-jp.html.markdown diff --git a/ja-jp/julia-jp.html.markdown b/ja-jp/julia-jp.html.markdown new file mode 100644 index 00000000..3a52018c --- /dev/null +++ b/ja-jp/julia-jp.html.markdown @@ -0,0 +1,747 @@ +--- +language: Julia +contributors: + - ["Leah Hanson", "http://leahhanson.us"] +filename: learnjulia.jl +--- + +Julia is a new homoiconic functional language focused on technical computing. +While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. + +This is based on the current development version of Julia, as of October 18th, 2013. + +```ruby + +# Single line comments start with a hash (pound) symbol. +#= Multiline comments can be written + by putting '#=' before the text and '=#' + after the text. They can also be nested. +=# + +#################################################### +## 1. Primitive Datatypes and Operators +#################################################### + +# Everything in Julia is a expression. + +# There are several basic types of numbers. +3 # => 3 (Int64) +3.2 # => 3.2 (Float64) +2 + 1im # => 2 + 1im (Complex{Int64}) +2//3 # => 2//3 (Rational{Int64}) + +# All of the normal infix operators are available. +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 +5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float +div(5, 2) # => 2 # for a truncated result, use div +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # power, not bitwise xor +12 % 10 # => 2 + +# Enforce precedence with parentheses +(1 + 3) * 2 # => 8 + +# Bitwise Operators +~2 # => -3 # bitwise not +3 & 5 # => 1 # bitwise and +2 | 4 # => 6 # bitwise or +2 $ 4 # => 6 # bitwise xor +2 >>> 1 # => 1 # logical shift right +2 >> 1 # => 1 # arithmetic shift right +2 << 1 # => 4 # logical/arithmetic shift left + +# You can use the bits function to see the binary representation of a number. +bits(12345) +# => "0000000000000000000000000000000000000000000000000011000000111001" +bits(12345.0) +# => "0100000011001000000111001000000000000000000000000000000000000000" + +# Boolean values are primitives +true +false + +# Boolean operators +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +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 " +"This is a string." + +# Character literals are written with ' +'a' + +# A string can be indexed like an array of characters +"This is a string"[1] # => 'T' # Julia indexes from 1 +# However, this is will not work well for UTF8 strings, +# so iterating over strings is recommended (map, for loops, etc). + +# $ can be used for string interpolation: +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" +# You can put any Julia expression inside the parenthesis. + +# Another way to format strings is the printf macro. +@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 + +# Printing is easy +println("I'm Julia. Nice to meet you!") + +#################################################### +## 2. Variables and Collections +#################################################### + +# You don't declare variables before assigning to them. +some_var = 5 # => 5 +some_var # => 5 + +# Accessing a previously unassigned variable is an error +try + some_other_var # => ERROR: some_other_var not defined +catch e + println(e) +end + +# Variable names start with a letter. +# After that, you can use letters, digits, underscores, and exclamation points. +SomeOtherVar123! = 6 # => 6 + +# You can also use unicode characters +☃ = 8 # => 8 +# These are especially handy for mathematical notation +2 * π # => 6.283185307179586 + +# A note on naming conventions in Julia: +# +# * Word separation can be indicated by underscores ('_'), but use of +# underscores is discouraged unless the name would be hard to read +# otherwise. +# +# * Names of Types begin with a capital letter and word separation is shown +# with CamelCase instead of underscores. +# +# * Names of functions and macros are in lower case, without underscores. +# +# * Functions that modify their inputs have names that end in !. These +# functions are sometimes called mutating functions or in-place functions. + +# Arrays store a sequence of values indexed by integers 1 through n: +a = Int64[] # => 0-element Int64 Array + +# 1-dimensional array literals can be written with comma-separated values. +b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] +b[1] # => 4 +b[end] # => 6 + +# 2-dimentional arrays use space-separated values and semicolon-separated rows. +matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] + +# Add stuff to the end of a list with push! and append! +push!(a,1) # => [1] +push!(a,2) # => [1,2] +push!(a,4) # => [1,2,4] +push!(a,3) # => [1,2,4,3] +append!(a,b) # => [1,2,4,3,4,5,6] + +# Remove from the end with pop +pop!(b) # => 6 and b is now [4,5] + +# Let's put it back +push!(b,6) # b is now [4,5,6] again. + +a[1] # => 1 # remember that Julia indexes from 1, not 0! + +# end is a shorthand for the last index. It can be used in any +# indexing expression +a[end] # => 6 + +# we also have shift and unshift +shift!(a) # => 1 and a is now [2,4,3,4,5,6] +unshift!(a,7) # => [7,2,4,3,4,5,6] + +# Function names that end in exclamations points indicate that they modify +# their argument. +arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] +sort(arr) # => [4,5,6]; arr is still [5,4,6] +sort!(arr) # => [4,5,6]; arr is now [4,5,6] + +# Looking out of bounds is a BoundsError +try + a[0] # => ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 +catch e + println(e) +end + +# Errors list the line and file they came from, even if it's in the standard +# library. If you built Julia from source, you can look in the folder base +# inside the julia folder to find these files. + +# You can initialize arrays from ranges +a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] + +# You can look at ranges with slice syntax. +a[1:3] # => [1, 2, 3] +a[2:end] # => [2, 3, 4, 5] + +# Remove elements from an array by index with splice! +arr = [3,4,5] +splice!(arr,2) # => 4 ; arr is now [3,5] + +# Concatenate lists with append! +b = [1,2,3] +append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] + +# Check for existence in a list with in +in(1, a) # => true + +# Examine the length with length +length(a) # => 8 + +# Tuples are immutable. +tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. +tup[1] # => 1 +try: + tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +catch e + println(e) +end + +# Many list functions also work on tuples +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true + +# You can unpack tuples into variables +a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 + +# Tuples are created even if you leave out the parentheses +d, e, f = 4, 5, 6 # => (4,5,6) + +# A 1-element tuple is distinct from the value it contains +(1,) == 1 # => false +(1) == 1 # => true + +# Look how easy it is to swap two values +e, d = d, e # => (5,4) # d is now 5 and e is now 4 + + +# Dictionaries store mappings +empty_dict = Dict() # => Dict{Any,Any}() + +# You can create a dictionary using a literal +filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +# => Dict{ASCIIString,Int64} + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys +keys(filled_dict) +# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# Note - dictionary keys are not sorted or in the order you inserted them. + +# Get all values +values(filled_dict) +# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# Note - Same as above regarding key ordering. + +# Check for existence of keys in a dictionary with in, haskey +in(("one", 1), filled_dict) # => true +in(("two", 3), filled_dict) # => false +haskey(filled_dict, "one") # => true +haskey(filled_dict, 1) # => false + +# Trying to look up a non-existant key will raise an error +try + filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 +catch e + println(e) +end + +# Use the get method to avoid that error by providing a default value +# get(dictionary,key,default_value) +get(filled_dict,"one",4) # => 1 +get(filled_dict,"four",4) # => 4 + +# Use Sets to represent collections of unordered, unique values +empty_set = Set() # => Set{Any}() +# Initialize a set with values +filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) + +# Add more values to a set +push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) + +# Check if the values are in the set +in(2, filled_set) # => true +in(10, filled_set) # => false + +# There are functions for set intersection, union, and difference. +other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) +intersect(filled_set, other_set) # => Set{Int64}(3,4,5) +union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) +setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) + + +#################################################### +## 3. Control Flow +#################################################### + +# Let's make a variable +some_var = 5 + +# Here is an if statement. Indentation is not meaningful in Julia. +if some_var > 10 + println("some_var is totally bigger than 10.") +elseif some_var < 10 # This elseif clause is optional. + println("some_var is smaller than 10.") +else # The else clause is optional too. + println("some_var is indeed 10.") +end +# => prints "some var is smaller than 10" + + +# For loops iterate over iterables. +# Iterable types include Range, Array, Set, Dict, and String. +for animal=["dog", "cat", "mouse"] + println("$animal is a mammal") + # You can use $ to interpolate variables or expression into strings +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# You can use 'in' instead of '='. +for animal in ["dog", "cat", "mouse"] + println("$animal is a mammal") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$(a[1]) is a $(a[2])") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$k is a $v") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# While loops loop while a condition is true +x = 0 +while x < 4 + println(x) + x += 1 # Shorthand for x = x + 1 +end +# prints: +# 0 +# 1 +# 2 +# 3 + +# Handle exceptions with a try/catch block +try + error("help") +catch e + println("caught it $e") +end +# => caught it ErrorException("help") + + +#################################################### +## 4. Functions +#################################################### + +# The keyword 'function' creates new functions +#function name(arglist) +# body... +#end +function add(x, y) + println("x is $x and y is $y") + + # Functions return the value of their last statement + x + y +end + +add(5, 6) # => 11 after printing out "x is 5 and y is 6" + +# You can define functions that take a variable number of +# positional arguments +function varargs(args...) + return args + # use the keyword return to return anywhere in the function +end +# => varargs (generic function with 1 method) + +varargs(1,2,3) # => (1,2,3) + +# The ... is called a splat. +# We just used it in a function definition. +# It can also be used in a fuction call, +# where it will splat an Array or Tuple's contents into the argument list. +Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays +Set([1,2,3]...) # => Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) + +x = (1,2,3) # => (1,2,3) +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples +Set(x...) # => Set{Int64}(2,3,1) + + +# You can define functions with optional positional arguments +function defaults(a,b,x=5,y=6) + return "$a $b and $x $y" +end + +defaults('h','g') # => "h g and 5 6" +defaults('h','g','j') # => "h g and j 6" +defaults('h','g','j','k') # => "h g and j k" +try + defaults('h') # => ERROR: no method defaults(Char,) + defaults() # => ERROR: no methods defaults() +catch e + println(e) +end + +# You can define functions that take keyword arguments +function keyword_args(;k1=4,name2="hello") # note the ; + return ["k1"=>k1,"name2"=>name2] +end + +keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] +keyword_args() # => ["name2"=>"hello","k1"=>4] + +# You can combine all kinds of arguments in the same function +function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") + println("normal arg: $normal_arg") + println("optional arg: $optional_positional_arg") + println("keyword arg: $keyword_arg") +end + +all_the_args(1, 3, keyword_arg=4) +# prints: +# normal arg: 1 +# optional arg: 3 +# keyword arg: 4 + +# Julia has first class functions +function create_adder(x) + adder = function (y) + return x + y + end + return adder +end + +# This is "stabby lambda syntax" for creating anonymous functions +(x -> x > 2)(3) # => true + +# This function is identical to create_adder implementation above. +function create_adder(x) + y -> x + y +end + +# You can also name the internal function, if you want +function create_adder(x) + function adder(y) + x + y + end + adder +end + +add_10 = create_adder(10) +add_10(3) # => 13 + + +# There are built-in higher order functions +map(add_10, [1,2,3]) # => [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# We can use list comprehensions for nicer maps +[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] + +#################################################### +## 5. Types +#################################################### + +# Julia has a type system. +# Every value has a type; variables do not have types themselves. +# You can use the `typeof` function to get the type of a value. +typeof(5) # => Int64 + +# Types are first-class values +typeof(Int64) # => DataType +typeof(DataType) # => DataType +# DataType is the type that represents types, including itself. + +# Types are used for documentation, optimizations, and dispatch. +# They are not statically checked. + +# Users can define types +# They are like records or structs in other languages. +# New types are defined using the `type` keyword. + +# type Name +# field::OptionalType +# ... +# end +type Tiger + taillength::Float64 + coatcolor # not including a type annotation is the same as `::Any` +end + +# The default constructor's arguments are the properties +# of the type, in the order they are listed in the definition +tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") + +# The type doubles as the constructor function for values of that type +sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") + +# These struct-style types are called concrete types +# They can be instantiated, but cannot have subtypes. +# The other kind of types is abstract types. + +# abstract Name +abstract Cat # just a name and point in the type hierarchy + +# Abstract types cannot be instantiated, but can have subtypes. +# For example, Number is an abstract type +subtypes(Number) # => 6-element Array{Any,1}: + # Complex{Float16} + # Complex{Float32} + # Complex{Float64} + # Complex{T<:Real} + # ImaginaryUnit + # Real +subtypes(Cat) # => 0-element Array{Any,1} + +# Every type has a super type; use the `super` function to get it. +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Number +super(Any) # => Any +# All of these type, except for Int64, are abstract. + +# <: is the subtyping operator +type Lion <: Cat # Lion is a subtype of Cat + mane_color + roar::String +end + +# You can define more constructors for your type +# Just define a function of the same name as the type +# and call an existing constructor to get a value of the correct type +Lion(roar::String) = Lion("green",roar) +# This is an outer constructor because it's outside the type definition + +type Panther <: Cat # Panther is also a subtype of Cat + eye_color + Panther() = new("green") + # Panthers will only have this constructor, and no default constructor. +end +# Using inner constructors, like Panther does, gives you control +# over how values of the type can be created. +# When possible, you should use outer constructors rather than inner ones. + +#################################################### +## 6. Multiple-Dispatch +#################################################### + +# In Julia, all named functions are generic functions +# This means that they are built up from many small methods +# Each constructor for Lion is a method of the generic function Lion. + +# For a non-constructor example, let's make a function meow: + +# Definitions for Lion, Panther, Tiger +function meow(animal::Lion) + animal.roar # access type properties using dot notation +end + +function meow(animal::Panther) + "grrr" +end + +function meow(animal::Tiger) + "rawwwr" +end + +# Testing the meow function +meow(tigger) # => "rawwr" +meow(Lion("brown","ROAAR")) # => "ROAAR" +meow(Panther()) # => "grrr" + +# Review the local type hierarchy +issubtype(Tiger,Cat) # => false +issubtype(Lion,Cat) # => true +issubtype(Panther,Cat) # => true + +# Defining a function that takes Cats +function pet_cat(cat::Cat) + println("The cat says $(meow(cat))") +end + +pet_cat(Lion("42")) # => prints "The cat says 42" +try + pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) +catch e + println(e) +end + +# In OO languages, single dispatch is common; +# this means that the method is picked based on the type of the first argument. +# In Julia, all of the argument types contribute to selecting the best method. + +# Let's define a function with more arguments, so we can see the difference +function fight(t::Tiger,c::Cat) + println("The $(t.coatcolor) tiger wins!") +end +# => fight (generic function with 1 method) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! + +# Let's change the behavior when the Cat is specifically a Lion +fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") +# => fight (generic function with 2 methods) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! + +# We don't need a Tiger in order to fight +fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +# => fight (generic function with 3 methods) + +fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr +try + fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) +catch +end + +# Also let the cat go first +fight(c::Cat,l::Lion) = println("The cat beats the Lion") +# => Warning: New definition +# fight(Cat,Lion) at none:1 +# is ambiguous with +# fight(Lion,Cat) at none:2. +# Make sure +# fight(Lion,Lion) +# is defined first. +#fight (generic function with 4 methods) + +# This warning is because it's unclear which fight will be called in: +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr +# The result may be different in other versions of Julia + +fight(l::Lion,l2::Lion) = println("The lions come to a tie") +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie + + +# Under the hood +# You can take a look at the llvm and the assembly code generated. + +square_area(l) = l * l # square_area (generic function with 1 method) + +square_area(5) #25 + +# What happens when we feed square_area an integer? +code_native(square_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 # Prologue + # push RBP + # mov RBP, RSP + # Source line: 1 + # movsxd RAX, EDI # Fetch l from memory? + # imul RAX, RAX # Square l and store the result in RAX + # pop RBP # Restore old base pointer + # ret # Result will still be in RAX + +code_native(square_area, (Float32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) + # pop RBP + # ret + +code_native(square_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) + # pop RBP + # ret + # +# Note that julia will use floating point instructions if any of the +# arguements are floats. +# Let's calculate the area of a circle +circle_area(r) = pi * r * r # circle_area (generic function with 1 method) +circle_area(5) # 78.53981633974483 + +code_native(circle_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory + # movabs RAX, 4593140240 # Load pi + # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r + # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r + # pop RBP + # ret + # + +code_native(circle_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # movabs RAX, 4593140496 + # Source line: 1 + # vmulsd XMM1, XMM0, QWORD PTR [RAX] + # vmulsd XMM0, XMM1, XMM0 + # pop RBP + # ret + # +``` + +## Further Reading + +You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) + +The best place to get help with Julia is the (very friendly) [mailing list](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From 09ab1c3aee929fd9336cecdff6ff2c5d3cd4f06a Mon Sep 17 00:00:00 2001 From: Yuichi Motoyama Date: Sat, 20 Dec 2014 12:33:17 +0900 Subject: finish translating (original english remains for review) --- ja-jp/julia-jp.html.markdown | 232 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 212 insertions(+), 20 deletions(-) diff --git a/ja-jp/julia-jp.html.markdown b/ja-jp/julia-jp.html.markdown index 3a52018c..0c596c99 100644 --- a/ja-jp/julia-jp.html.markdown +++ b/ja-jp/julia-jp.html.markdown @@ -2,9 +2,17 @@ language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] -filename: learnjulia.jl +translators: + - ["Yuichi Motoyama", "https://github.com/yomichi"] +filename: learnjulia-jp.jl --- +Julia は科学技術計算向けに作られた、同図像性を持った(homoiconic) プログラミング言語です。 +マクロによる同図像性や第一級関数をもち、なおかつ低階層も扱えるにもかかわらず、 +Julia はPython 並に学習しやすく、使いやすい言語となっています。 + +この文章は、Julia の2013年10月18日現在の開発バージョンを元にしています。 + Julia is a new homoiconic functional language focused on technical computing. While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. @@ -12,6 +20,12 @@ This is based on the current development version of Julia, as of October 18th, 2 ```ruby +# ハッシュ(シャープ)記号から改行までは単一行コメントとなります。 +#= 複数行コメントは、 + '#=' と '=#' とで囲むことで行えます。 + 入れ子構造にすることもできます。 +=# + # Single line comments start with a hash (pound) symbol. #= Multiline comments can be written by putting '#=' before the text and '=#' @@ -20,49 +34,61 @@ This is based on the current development version of Julia, as of October 18th, 2 #################################################### ## 1. Primitive Datatypes and Operators +## 1. 基本的な型と演算子 #################################################### +# Julia ではすべて式となります。 # Everything in Julia is a expression. +# 基本となる数値型がいくつかあります。 # There are several basic types of numbers. 3 # => 3 (Int64) 3.2 # => 3.2 (Float64) 2 + 1im # => 2 + 1im (Complex{Int64}) 2//3 # => 2//3 (Rational{Int64}) +# 一般的な中置演算子が使用可能です。 # All of the normal infix operators are available. 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7.0 +5 / 2 # => 2.5 # 整数型同士の割り算の結果は、浮動小数点数型になります 5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float +div(5, 2) # => 2 # 整数のまま割り算するには、 div を使います div(5, 2) # => 2 # for a truncated result, use div 5 \ 35 # => 7.0 +2 ^ 2 # => 4 # べき乗です。排他的論理和ではありません 2 ^ 2 # => 4 # power, not bitwise xor 12 % 10 # => 2 +# 丸括弧で演算の優先順位をコントロールできます # Enforce precedence with parentheses (1 + 3) * 2 # => 8 +# ビット演算 # Bitwise Operators -~2 # => -3 # bitwise not -3 & 5 # => 1 # bitwise and -2 | 4 # => 6 # bitwise or -2 $ 4 # => 6 # bitwise xor -2 >>> 1 # => 1 # logical shift right -2 >> 1 # => 1 # arithmetic shift right -2 << 1 # => 4 # logical/arithmetic shift left - +~2 # => -3 # ビット反転 +3 & 5 # => 1 # ビット積 +2 | 4 # => 6 # ビット和 +2 $ 4 # => 6 # 排他的論理和 +2 >>> 1 # => 1 # 右論理シフト +2 >> 1 # => 1 # 右算術シフト +2 << 1 # => 4 # 左シフト + +# bits 関数を使うことで、数の二進表現を得られます。 # You can use the bits function to see the binary representation of a number. bits(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" bits(12345.0) # => "0100000011001000000111001000000000000000000000000000000000000000" +# ブール値が用意されています # Boolean values are primitives true false +# ブール代数 # Boolean operators !true # => false !false # => true @@ -74,39 +100,51 @@ false 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 " "This is a string." +# 文字リテラルは ' で作れます # Character literals are written with ' 'a' +# 文字列は文字の配列のように添字アクセスできます # A string can be indexed like an array of characters -"This is a string"[1] # => 'T' # Julia indexes from 1 +"This is a string"[1] # => 'T' # Julia では添字は 1 から始まります +# ただし、UTF8 文字列の場合は添字アクセスではうまくいかないので、 +# その場合はイテレーションを行ってください(map 関数や for ループなど) # However, this is will not work well for UTF8 strings, # so iterating over strings is recommended (map, for loops, etc). +# $ を使うことで、文字列に変数や、任意の式を埋め込めます。 # $ can be used for string interpolation: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" # You can put any Julia expression inside the parenthesis. +# 他にも、printf マクロを使うことでも変数を埋め込めます。 # Another way to format strings is the printf macro. @printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 +# 出力も簡単です # Printing is easy println("I'm Julia. Nice to meet you!") #################################################### ## 2. Variables and Collections +## 2. 変数と配列 #################################################### +# 変数の宣言は不要で、いきなり変数に値を代入・束縛できます。 # You don't declare variables before assigning to them. some_var = 5 # => 5 some_var # => 5 +# 値の束縛されていない変数を使おうとするとエラーになります。 # Accessing a previously unassigned variable is an error try some_other_var # => ERROR: some_other_var not defined @@ -114,40 +152,62 @@ catch e println(e) end +# 変数名は文字から始めます。 +# その後は、文字だけでなく数字やアンダースコア(_), 感嘆符(!)が使えます。 # Variable names start with a letter. # After that, you can use letters, digits, underscores, and exclamation points. SomeOtherVar123! = 6 # => 6 +# Unicode 文字も使えます。 # You can also use unicode characters ☃ = 8 # => 8 +# ギリシャ文字などを使うことで数学的な記法が簡単にかけます。 # These are especially handy for mathematical notation 2 * π # => 6.283185307179586 +# Julia における命名習慣について: # A note on naming conventions in Julia: # +# * 変数名における単語の区切りにはアンダースコアを使っても良いですが、 +# 使わないと読みにくくなる、というわけではない限り、 +# 推奨はされません。 +# # * Word separation can be indicated by underscores ('_'), but use of # underscores is discouraged unless the name would be hard to read # otherwise. # +# * 型名は大文字で始め、単語の区切りはキャメルケースを使います。 +# # * Names of Types begin with a capital letter and word separation is shown # with CamelCase instead of underscores. # +# * 関数やマクロの名前は小文字で書きます。 +# 分かち書きにアンダースコアをつかわず、直接つなげます。 +# # * Names of functions and macros are in lower case, without underscores. # +# * 内部で引数を変更する関数は、名前の最後に ! をつけます。 +# この手の関数は、しばしば「破壊的な関数」とか「in-place な関数」とか呼ばれます。 +# # * Functions that modify their inputs have names that end in !. These # functions are sometimes called mutating functions or in-place functions. +# 配列は、1 から始まる整数によって添字付けられる、値の列です。 # Arrays store a sequence of values indexed by integers 1 through n: a = Int64[] # => 0-element Int64 Array +# 一次元配列は、角括弧 [] のなかにカンマ , 区切りで値を並べることで作ります。 # 1-dimensional array literals can be written with comma-separated values. b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] b[1] # => 4 b[end] # => 6 +# 二次元配列は、空白区切りで作った行を、セミコロンで区切ることで作ります。 # 2-dimentional arrays use space-separated values and semicolon-separated rows. matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] +# 配列の終端に値を追加するには push! を、 +# 他の配列を追加するには append! を使います。 # Add stuff to the end of a list with push! and append! push!(a,1) # => [1] push!(a,2) # => [1,2] @@ -155,28 +215,36 @@ push!(a,4) # => [1,2,4] push!(a,3) # => [1,2,4,3] append!(a,b) # => [1,2,4,3,4,5,6] +# 配列の終端から値を削除するには pop! を使います。 # Remove from the end with pop pop!(b) # => 6 and b is now [4,5] +# もう一度戻しましょう。 # Let's put it back push!(b,6) # b is now [4,5,6] again. +a[1] # => 1 # Julia では添字は0 ではなく1 から始まること、お忘れなく! a[1] # => 1 # remember that Julia indexes from 1, not 0! +# end は最後の添字を表す速記法です。 +# 添字を書く場所ならどこにでも使えます。 # end is a shorthand for the last index. It can be used in any # indexing expression a[end] # => 6 +# 先頭に対する追加・削除は shift!, unshift! です。 # we also have shift and unshift shift!(a) # => 1 and a is now [2,4,3,4,5,6] unshift!(a,7) # => [7,2,4,3,4,5,6] +# ! で終わる関数名は、その引数を変更するということを示します。 # Function names that end in exclamations points indicate that they modify # their argument. arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] sort(arr) # => [4,5,6]; arr is still [5,4,6] sort!(arr) # => [4,5,6]; arr is now [4,5,6] +# 配列の範囲外アクセスをすると BoundsError が発生します。 # Looking out of bounds is a BoundsError try a[0] # => ERROR: BoundsError() in getindex at array.jl:270 @@ -185,31 +253,40 @@ catch e println(e) end +# エラーが発生すると、どのファイルのどの行で発生したかが表示されます。 # Errors list the line and file they came from, even if it's in the standard # library. If you built Julia from source, you can look in the folder base # inside the julia folder to find these files. +# 配列は範囲オブジェクトから作ることもできます。 # You can initialize arrays from ranges a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] +# 添字として範囲オブジェクトを渡すことで、 +# 配列の部分列を得ることもできます。 # You can look at ranges with slice syntax. a[1:3] # => [1, 2, 3] a[2:end] # => [2, 3, 4, 5] +# 添字を用いて配列から値の削除をしたい場合は、splice! を使います。 # Remove elements from an array by index with splice! arr = [3,4,5] splice!(arr,2) # => 4 ; arr is now [3,5] +# 配列の結合は append! です。 # Concatenate lists with append! b = [1,2,3] append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] +# 配列内に指定した値があるかどうかを調べるのには in を使います。 # Check for existence in a list with in in(1, a) # => true +# length で配列の長さを取得できます。 # Examine the length with length length(a) # => 8 +# 変更不可能 (immutable) な値の組として、タプルが使えます。 # Tuples are immutable. tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. tup[1] # => 1 @@ -219,51 +296,65 @@ catch e println(e) end +# 配列に関する関数の多くが、タプルでも使えます。 # Many list functions also work on tuples length(tup) # => 3 tup[1:2] # => (1,2) in(2, tup) # => true +# タプルから値をばらして(unpack して) 複数の変数に代入できます。 # You can unpack tuples into variables a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 +# 丸括弧なしでもタプルになります。 # Tuples are created even if you leave out the parentheses d, e, f = 4, 5, 6 # => (4,5,6) +# ひとつの値だけからなるタプルは、その値自体とは区別されます。 # A 1-element tuple is distinct from the value it contains (1,) == 1 # => false (1) == 1 # => true +# 値の交換もタプルを使えば簡単です。 # Look how easy it is to swap two values e, d = d, e # => (5,4) # d is now 5 and e is now 4 +# 辞書 (Dict) は、値から値への変換の集合です。 # Dictionaries store mappings empty_dict = Dict() # => Dict{Any,Any}() +# 辞書型リテラルは次のとおりです。 # You can create a dictionary using a literal filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] # => Dict{ASCIIString,Int64} +# [] を使ったアクセスができます。 # Look up values with [] filled_dict["one"] # => 1 +# すべての鍵(添字)は keys で得られます。 # Get all keys keys(filled_dict) # => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# 必ずしも辞書に追加した順番には並んでいないことに注意してください。 # Note - dictionary keys are not sorted or in the order you inserted them. +# 同様に、values はすべての値を返します。 # Get all values values(filled_dict) # => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# 鍵と同様に、必ずしも辞書に追加した順番には並んでいないことに注意してください。 # Note - Same as above regarding key ordering. +# in や haskey を使うことで、要素や鍵が辞書の中にあるかを調べられます。 # Check for existence of keys in a dictionary with in, haskey in(("one", 1), filled_dict) # => true in(("two", 3), filled_dict) # => false haskey(filled_dict, "one") # => true haskey(filled_dict, 1) # => false +# 存在しない鍵を問い合わせると、エラーが発生します。 # Trying to look up a non-existant key will raise an error try filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 @@ -271,23 +362,30 @@ catch e println(e) end +# get 関数を使い、鍵がなかった場合のデフォルト値を与えておくことで、 +# このエラーを回避できます。 # Use the get method to avoid that error by providing a default value # get(dictionary,key,default_value) get(filled_dict,"one",4) # => 1 get(filled_dict,"four",4) # => 4 +# 集合 (Set) は一意な値の、順序付けられていない集まりです。 # Use Sets to represent collections of unordered, unique values empty_set = Set() # => Set{Any}() +# 集合の初期化 # Initialize a set with values filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) +# 集合への追加 # Add more values to a set push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) +# in で、値が既に存在するかを調べられます。 # Check if the values are in the set in(2, filled_set) # => true in(10, filled_set) # => false +# 積集合や和集合、差集合を得る関数も用意されています。 # There are functions for set intersection, union, and difference. other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) intersect(filled_set, other_set) # => Set{Int64}(3,4,5) @@ -297,26 +395,32 @@ setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) #################################################### ## 3. Control Flow +## 3. 制御構文 #################################################### +# まずは変数を作ります。 # Let's make a variable some_var = 5 +# if 構文です。Julia ではインデントに意味はありません。 # Here is an if statement. Indentation is not meaningful in Julia. if some_var > 10 println("some_var is totally bigger than 10.") -elseif some_var < 10 # This elseif clause is optional. +elseif some_var < 10 # elseif 節は省略可能です。 println("some_var is smaller than 10.") -else # The else clause is optional too. +else # else 節も省略可能です。 println("some_var is indeed 10.") end -# => prints "some var is smaller than 10" - +# => "some var is smaller than 10" と出力されます。 +# for ループによって、反復可能なオブジェクトを走査できます。 +# 反復可能なオブジェクトの型として、 +# Range, Array, Set, Dict, String などがあります。 # For loops iterate over iterables. # Iterable types include Range, Array, Set, Dict, and String. for animal=["dog", "cat", "mouse"] println("$animal is a mammal") + # $ を使うことで文字列に変数の値を埋め込めます。 # You can use $ to interpolate variables or expression into strings end # prints: @@ -324,6 +428,7 @@ end # cat is a mammal # mouse is a mammal +# for = の代わりに for in を使うこともできます # You can use 'in' instead of '='. for animal in ["dog", "cat", "mouse"] println("$animal is a mammal") @@ -349,6 +454,7 @@ end # cat is a mammal # mouse is a mammal +# while ループは、条件式がtrue となる限り実行され続けます。 # While loops loop while a condition is true x = 0 while x < 4 @@ -361,6 +467,7 @@ end # 2 # 3 +# 例外は try/catch で捕捉できます。 # Handle exceptions with a try/catch block try error("help") @@ -372,8 +479,10 @@ end #################################################### ## 4. Functions +## 4. 関数 #################################################### +# function キーワードを次のように使うことで、新しい関数を定義できます。 # The keyword 'function' creates new functions #function name(arglist) # body... @@ -381,34 +490,42 @@ end function add(x, y) println("x is $x and y is $y") + # 最後に評価された式の値が、関数全体の返り値となります。 # Functions return the value of their last statement x + y end add(5, 6) # => 11 after printing out "x is 5 and y is 6" +# 可変長引数関数も定義できます。 # You can define functions that take a variable number of # positional arguments function varargs(args...) return args + # return キーワードを使うことで、好きな位置で関数から抜けられます。 # use the keyword return to return anywhere in the function end # => varargs (generic function with 1 method) varargs(1,2,3) # => (1,2,3) +# ... はsplat と呼ばれます +# (訳注:「ピシャッという音(名詞)」「衝撃で平らにする(動詞)」) +# 今回は関数定義で使いましたが、関数呼び出しに使うこともできます。 +# その場合、配列やタプルの要素を開いて、複数の引数へと割り当てることとなります。 # The ... is called a splat. # We just used it in a function definition. # It can also be used in a fuction call, # where it will splat an Array or Tuple's contents into the argument list. -Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays -Set([1,2,3]...) # => Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) +Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # 「整数の配列」の集合 +Set([1,2,3]...) # => Set{Int64}(1,2,3) # 整数の集合 x = (1,2,3) # => (1,2,3) -Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # タプルの集合 Set(x...) # => Set{Int64}(2,3,1) +# 引数に初期値を与えることで、オプション引数をもった関数を定義できます。 # You can define functions with optional positional arguments function defaults(a,b,x=5,y=6) return "$a $b and $x $y" @@ -424,8 +541,9 @@ catch e println(e) end +# キーワード引数を持った関数も作れます。 # You can define functions that take keyword arguments -function keyword_args(;k1=4,name2="hello") # note the ; +function keyword_args(;k1=4,name2="hello") # ; が必要なことに注意 return ["k1"=>k1,"name2"=>name2] end @@ -433,6 +551,7 @@ keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] keyword_args() # => ["name2"=>"hello","k1"=>4] +# もちろん、これらを組み合わせることもできます。 # You can combine all kinds of arguments in the same function function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") println("normal arg: $normal_arg") @@ -446,6 +565,7 @@ all_the_args(1, 3, keyword_arg=4) # optional arg: 3 # keyword arg: 4 +# Julia では関数は第一級関数として、値として扱われます。 # Julia has first class functions function create_adder(x) adder = function (y) @@ -454,14 +574,17 @@ function create_adder(x) return adder end +# ラムダ式によって無名関数をつくれます。 # This is "stabby lambda syntax" for creating anonymous functions (x -> x > 2)(3) # => true +# 先ほどの create_adder と同じもの # This function is identical to create_adder implementation above. function create_adder(x) y -> x + y end +# 中の関数に名前をつけても構いません。 # You can also name the internal function, if you want function create_adder(x) function adder(y) @@ -474,31 +597,44 @@ add_10 = create_adder(10) add_10(3) # => 13 +# いくつかの高階関数が定義されています。 # There are built-in higher order functions map(add_10, [1,2,3]) # => [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +# map の代わりとしてリスト内包表記も使えます。 # We can use list comprehensions for nicer maps [add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] #################################################### ## 5. Types +## 5. 型 #################################################### +# Julia ではすべての値にひとつの型がついています。 +# 変数に、ではなくて値に、です。 +# typeof 関数を使うことで、値が持つ型を取得できます。 # Julia has a type system. # Every value has a type; variables do not have types themselves. # You can use the `typeof` function to get the type of a value. typeof(5) # => Int64 +# 型自身もまた、第一級の値であり、型を持っています。 # Types are first-class values typeof(Int64) # => DataType typeof(DataType) # => DataType +# DataType は型を表現する型であり、DataType 自身もDataType 型の値です。 # DataType is the type that represents types, including itself. +# 型はドキュメント化や最適化、関数ディスパッチのために使われます。 +# 静的な型チェックは行われません。 # Types are used for documentation, optimizations, and dispatch. # They are not statically checked. +# 自分で新しい型を定義することもできます。 +# 他の言語で言う、構造体やレコードに近いものになっています。 +# 型定義には type キーワードを使います。 # Users can define types # They are like records or structs in other languages. # New types are defined using the `type` keyword. @@ -509,23 +645,33 @@ typeof(DataType) # => DataType # end type Tiger taillength::Float64 + coatcolor # 型注釈を省略した場合、自動的に :: Any として扱われます。 coatcolor # not including a type annotation is the same as `::Any` end +# 型を定義すると、その型のプロパティすべてを、定義した順番に +# 引数として持つデフォルトコンストラクタが自動的に作られます。 # The default constructor's arguments are the properties # of the type, in the order they are listed in the definition tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") +# 型名がそのままコンストラクタ名(関数名)となります。 # The type doubles as the constructor function for values of that type sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") +# このような、構造体スタイルの型は、具体型(concrete type)と呼ばれます。 +# 具体型はインスタンス化可能ですが、派生型(subtype)を持つことができません。 +# 具体型の他には抽象型(abstract type)があります。 # These struct-style types are called concrete types # They can be instantiated, but cannot have subtypes. # The other kind of types is abstract types. # abstract Name +abstract Cat # 型の階層図の途中の一点を指し示す名前となります。 abstract Cat # just a name and point in the type hierarchy +# 抽象型はインスタンス化できませんが、派生型を持つことができます。 +# 例えば、 Number は以下の派生型を持つ抽象型です。 # Abstract types cannot be instantiated, but can have subtypes. # For example, Number is an abstract type subtypes(Number) # => 6-element Array{Any,1}: @@ -537,6 +683,8 @@ subtypes(Number) # => 6-element Array{Any,1}: # Real subtypes(Cat) # => 0-element Array{Any,1} +# すべての型は、直接的にはただひとつの基本型(supertype) を持ちます。 +# super 関数でこれを取得可能です。 # Every type has a super type; use the `super` function to get it. typeof(5) # => Int64 super(Int64) # => Signed @@ -545,41 +693,60 @@ super(Real) # => Number super(Number) # => Any super(super(Signed)) # => Number super(Any) # => Any +# Int64 を除き、これらはすべて抽象型です。 # All of these type, except for Int64, are abstract. +# <: は派生形を表す演算子です。 +# これを使うことで派生型を定義できます。 # <: is the subtyping operator -type Lion <: Cat # Lion is a subtype of Cat +type Lion <: Cat # Lion は 抽象型 Cat の派生型 mane_color roar::String end +# 型名と同じ名前の関数を定義し、既に存在するコンストラクタを呼び出して、 +# 必要とする型の値を返すことによって、 +# デフォルトコンストラクタ以外のコンストラクタを作ることができます。 + # You can define more constructors for your type # Just define a function of the same name as the type # and call an existing constructor to get a value of the correct type Lion(roar::String) = Lion("green",roar) +# 型定義の外側で定義されたコンストラクタなので、外部コンストラクタと呼ばれます。 # This is an outer constructor because it's outside the type definition -type Panther <: Cat # Panther is also a subtype of Cat +type Panther <: Cat # Panther も Cat の派生型 eye_color Panther() = new("green") + # Panther は内部コンストラクタとしてこれのみを持ち、 + # デフォルトコンストラクタを持たない # Panthers will only have this constructor, and no default constructor. end +# 内部コンストラクタを使うことで、どのような値が作られるのかをコントロールすることができます。 +# 出来る限り、外部コンストラクタを使うべきです。 # Using inner constructors, like Panther does, gives you control # over how values of the type can be created. # When possible, you should use outer constructors rather than inner ones. #################################################### ## 6. Multiple-Dispatch +## 6. 多重ディスパッチ #################################################### +# Julia では、すべての名前付きの関数は総称的関数(generic function) です。 +# これは、関数はいくつかの細かいメソッドの集合である、という意味です。 +# 例えば先の Lion 型のコンストラクタ Lion は、Lion という関数の1つのメソッドです。 # In Julia, all named functions are generic functions # This means that they are built up from many small methods # Each constructor for Lion is a method of the generic function Lion. +# コンストラクタ以外の例をみるために、新たに meow 関数を作りましょう。 # For a non-constructor example, let's make a function meow: +# Lion, Panther, Tiger 型それぞれに対する meow 関数のメソッド定義 # Definitions for Lion, Panther, Tiger function meow(animal::Lion) + animal.roar # 型のプロパティには . でアクセスできます。 animal.roar # access type properties using dot notation end @@ -591,16 +758,19 @@ function meow(animal::Tiger) "rawwwr" end +# meow 関数の実行 # Testing the meow function meow(tigger) # => "rawwr" meow(Lion("brown","ROAAR")) # => "ROAAR" meow(Panther()) # => "grrr" +# 型の階層関係を見てみましょう # Review the local type hierarchy issubtype(Tiger,Cat) # => false issubtype(Lion,Cat) # => true issubtype(Panther,Cat) # => true +# 抽象型 Cat の派生型を引数にとる関数 # Defining a function that takes Cats function pet_cat(cat::Cat) println("The cat says $(meow(cat))") @@ -613,10 +783,15 @@ catch e println(e) end +# オブジェクト指向言語では、一般的にシングルディスパッチが用いられます。 +# つまり、関数に複数あるメソッドのうちにどれが呼ばれるかは、 +# その第一引数によってのみ決定されます。 +# 一方でJulia では、すべての引数の型が、このメソッド決定に寄与します。 # In OO languages, single dispatch is common; # this means that the method is picked based on the type of the first argument. # In Julia, all of the argument types contribute to selecting the best method. +# 多変数関数を定義して、この辺りを見て行きましょう。 # Let's define a function with more arguments, so we can see the difference function fight(t::Tiger,c::Cat) println("The $(t.coatcolor) tiger wins!") @@ -626,6 +801,7 @@ end fight(tigger,Panther()) # => prints The orange tiger wins! fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! +# 第二引数の Cat が実際は Lion だった時に、挙動が変わるようにします。 # Let's change the behavior when the Cat is specifically a Lion fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") # => fight (generic function with 2 methods) @@ -633,6 +809,7 @@ fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") fight(tigger,Panther()) # => prints The orange tiger wins! fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! +# 別に Tiger だけが戦う必要もないですね。 # We don't need a Tiger in order to fight fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") # => fight (generic function with 3 methods) @@ -643,6 +820,7 @@ try catch end +# 第一引数にも Cat を許しましょう。 # Also let the cat go first fight(c::Cat,l::Lion) = println("The cat beats the Lion") # => Warning: New definition @@ -654,14 +832,17 @@ fight(c::Cat,l::Lion) = println("The cat beats the Lion") # is defined first. #fight (generic function with 4 methods) +# 警告が出ましたが、これは次の対戦で何が起きるのかが不明瞭だからです。 # This warning is because it's unclear which fight will be called in: fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr +# Julia のバージョンによっては、結果が違うかもしれません。 # The result may be different in other versions of Julia fight(l::Lion,l2::Lion) = println("The lions come to a tie") fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie +# Julia が生成する LLVM 内部表現や、アセンブリを調べることもできます。 # Under the hood # You can take a look at the llvm and the assembly code generated. @@ -669,6 +850,7 @@ square_area(l) = l * l # square_area (generic function with 1 method) square_area(5) #25 +# square_area に整数を渡すと何が起きる? # What happens when we feed square_area an integer? code_native(square_area, (Int32,)) # .section __TEXT,__text,regular,pure_instructions @@ -704,6 +886,10 @@ code_native(square_area, (Float64,)) # pop RBP # ret # + +# Julia では、浮動小数点数と整数との演算では +# 自動的に浮動小数点数用の命令が生成されることに注意してください。 +# 円の面積を計算してみましょう。 # Note that julia will use floating point instructions if any of the # arguements are floats. # Let's calculate the area of a circle @@ -740,8 +926,14 @@ code_native(circle_area, (Float64,)) # ``` +## より勉強するために ## Further Reading +[公式ドキュメント](http://docs.julialang.org/en/latest/manual/) (英語)にはより詳細な解説が記されています。 + You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) +Julia に関して助けが必要ならば、[メーリングリスト](https://groups.google.com/forum/#!forum/julia-users) が役に立ちます。 +みんな非常に親密に教えてくれます。 + The best place to get help with Julia is the (very friendly) [mailing list](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From 6027c90c90a55702d003f17a72fd82ed7f870be0 Mon Sep 17 00:00:00 2001 From: Artur Mkrtchyan Date: Sat, 20 Dec 2014 23:03:25 +0100 Subject: Scala compiler fails to infer the return type when there's an explicit return statement --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5a478f2a..35645922 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -199,7 +199,7 @@ weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most // def that surrounds it. It has no effect on anonymous functions. For example: -def foo(x: Int) = { +def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) return z // This line makes z the return value of foo! -- cgit v1.2.3 From 6dca0e7ae41140765cb3b0c1513cfa897294efe5 Mon Sep 17 00:00:00 2001 From: Artur Mkrtchyan Date: Sun, 21 Dec 2014 13:08:21 +0100 Subject: Fixed Person class' constructor signature --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5a478f2a..544abd5b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -476,7 +476,7 @@ sSquared.reduce (_+_) // The filter function takes a predicate (a function from A -> Boolean) and // selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) -case class Person(name:String, phoneNumber:String) +case class Person(name:String, age:Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) -- cgit v1.2.3 From c4e1109e3aeef641798a59daf56f82aa60dc81ff Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 22 Dec 2014 13:35:46 +1100 Subject: Remove spurious "[" --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index f08c4679..32febcfd 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -49,7 +49,7 @@ public class LearnJava { // Types & Variables /////////////////////////////////////// - // Declare a variable using [ + // Declare a variable using // Byte - 8-bit signed two's complement integer // (-128 <= byte <= 127) byte fooByte = 100; -- cgit v1.2.3 From c9ae9ea396cae5c357511cecb3a308740409302a Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 22 Dec 2014 13:37:03 +1100 Subject: Spelling corrrection --- java.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index f08c4679..d77d1c23 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -268,9 +268,9 @@ public class LearnJava { System.out.println(bar); // Prints A, because the statement is true - /////////////////////////////////////// - // Converting Data Types And Typcasting - /////////////////////////////////////// + //////////////////////////////////////// + // Converting Data Types And Typecasting + //////////////////////////////////////// // Converting data -- cgit v1.2.3 From 7915169dde85bfd7afdfc2398440b6db7ec28682 Mon Sep 17 00:00:00 2001 From: Yuichi Motoyama Date: Mon, 22 Dec 2014 14:45:11 +0900 Subject: finish translating X=Julia into Japanese --- ja-jp/julia-jp.html.markdown | 240 ++++++------------------------------------- 1 file changed, 31 insertions(+), 209 deletions(-) diff --git a/ja-jp/julia-jp.html.markdown b/ja-jp/julia-jp.html.markdown index 0c596c99..0c1d7e49 100644 --- a/ja-jp/julia-jp.html.markdown +++ b/ja-jp/julia-jp.html.markdown @@ -8,88 +8,67 @@ filename: learnjulia-jp.jl --- Julia は科学技術計算向けに作られた、同図像性を持った(homoiconic) プログラミング言語です。 -マクロによる同図像性や第一級関数をもち、なおかつ低階層も扱えるにもかかわらず、 -Julia はPython 並に学習しやすく、使いやすい言語となっています。 +マクロによる同図像性や第一級関数などの抽象化機能の恩恵を受けつつ、低階層をも扱えますが、 +それでいてPython 並に学習しやすく、使いやすい言語となっています。 この文章は、Julia の2013年10月18日現在の開発バージョンを元にしています。 -Julia is a new homoiconic functional language focused on technical computing. -While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. - -This is based on the current development version of Julia, as of October 18th, 2013. - ```ruby # ハッシュ(シャープ)記号から改行までは単一行コメントとなります。 #= 複数行コメントは、 '#=' と '=#' とで囲むことで行えます。 + #= 入れ子構造にすることもできます。 -=# - -# Single line comments start with a hash (pound) symbol. -#= Multiline comments can be written - by putting '#=' before the text and '=#' - after the text. They can also be nested. + =# =# #################################################### -## 1. Primitive Datatypes and Operators ## 1. 基本的な型と演算子 #################################################### # Julia ではすべて式となります。 -# Everything in Julia is a expression. # 基本となる数値型がいくつかあります。 -# There are several basic types of numbers. 3 # => 3 (Int64) 3.2 # => 3.2 (Float64) 2 + 1im # => 2 + 1im (Complex{Int64}) 2//3 # => 2//3 (Rational{Int64}) # 一般的な中置演算子が使用可能です。 -# All of the normal infix operators are available. 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7.0 5 / 2 # => 2.5 # 整数型同士の割り算の結果は、浮動小数点数型になります -5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float div(5, 2) # => 2 # 整数のまま割り算するには、 div を使います -div(5, 2) # => 2 # for a truncated result, use div 5 \ 35 # => 7.0 2 ^ 2 # => 4 # べき乗です。排他的論理和ではありません -2 ^ 2 # => 4 # power, not bitwise xor 12 % 10 # => 2 # 丸括弧で演算の優先順位をコントロールできます -# Enforce precedence with parentheses (1 + 3) * 2 # => 8 # ビット演算 -# Bitwise Operators ~2 # => -3 # ビット反転 3 & 5 # => 1 # ビット積 2 | 4 # => 6 # ビット和 -2 $ 4 # => 6 # 排他的論理和 +2 $ 4 # => 6 # ビット排他的論理和 2 >>> 1 # => 1 # 右論理シフト 2 >> 1 # => 1 # 右算術シフト 2 << 1 # => 4 # 左シフト # bits 関数を使うことで、数の二進表現を得られます。 -# You can use the bits function to see the binary representation of a number. bits(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" bits(12345.0) # => "0100000011001000000111001000000000000000000000000000000000000000" # ブール値が用意されています -# Boolean values are primitives true false # ブール代数 -# Boolean operators !true # => false !false # => true 1 == 1 # => true @@ -101,151 +80,109 @@ false 2 <= 2 # => true 2 >= 2 # => true # 比較演算子をつなげることもできます -# Comparisons can be chained 1 < 2 < 3 # => true 2 < 3 < 2 # => false # 文字列は " で作れます -# Strings are created with " "This is a string." # 文字リテラルは ' で作れます -# Character literals are written with ' 'a' # 文字列は文字の配列のように添字アクセスできます -# A string can be indexed like an array of characters "This is a string"[1] # => 'T' # Julia では添字は 1 から始まります # ただし、UTF8 文字列の場合は添字アクセスではうまくいかないので、 -# その場合はイテレーションを行ってください(map 関数や for ループなど) -# However, this is will not work well for UTF8 strings, -# so iterating over strings is recommended (map, for loops, etc). +# イテレーションを行ってください(map 関数や for ループなど) # $ を使うことで、文字列に変数や、任意の式を埋め込めます。 -# $ can be used for string interpolation: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" -# You can put any Julia expression inside the parenthesis. # 他にも、printf マクロを使うことでも変数を埋め込めます。 -# Another way to format strings is the printf macro. @printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 # 出力も簡単です -# Printing is easy println("I'm Julia. Nice to meet you!") #################################################### -## 2. Variables and Collections -## 2. 変数と配列 +## 2. 変数と配列、タプル、集合、辞書 #################################################### # 変数の宣言は不要で、いきなり変数に値を代入・束縛できます。 -# You don't declare variables before assigning to them. some_var = 5 # => 5 some_var # => 5 -# 値の束縛されていない変数を使おうとするとエラーになります。 -# Accessing a previously unassigned variable is an error +# 値に束縛されていない変数を使おうとするとエラーになります。 try some_other_var # => ERROR: some_other_var not defined catch e println(e) end -# 変数名は文字から始めます。 -# その後は、文字だけでなく数字やアンダースコア(_), 感嘆符(!)が使えます。 -# Variable names start with a letter. -# After that, you can use letters, digits, underscores, and exclamation points. +# 変数名は数字や記号以外の文字から始めます。 +# その後は、数字やアンダースコア(_), 感嘆符(!)も使えます。 SomeOtherVar123! = 6 # => 6 # Unicode 文字も使えます。 -# You can also use unicode characters ☃ = 8 # => 8 # ギリシャ文字などを使うことで数学的な記法が簡単にかけます。 -# These are especially handy for mathematical notation 2 * π # => 6.283185307179586 # Julia における命名習慣について: -# A note on naming conventions in Julia: # # * 変数名における単語の区切りにはアンダースコアを使っても良いですが、 # 使わないと読みにくくなる、というわけではない限り、 # 推奨はされません。 # -# * Word separation can be indicated by underscores ('_'), but use of -# underscores is discouraged unless the name would be hard to read -# otherwise. -# -# * 型名は大文字で始め、単語の区切りはキャメルケースを使います。 -# -# * Names of Types begin with a capital letter and word separation is shown -# with CamelCase instead of underscores. +# * 型名は大文字で始め、単語の区切りにはキャメルケースを使います。 # # * 関数やマクロの名前は小文字で書きます。 -# 分かち書きにアンダースコアをつかわず、直接つなげます。 -# -# * Names of functions and macros are in lower case, without underscores. +# 単語の分かち書きにはアンダースコアをつかわず、直接つなげます。 # # * 内部で引数を変更する関数は、名前の最後に ! をつけます。 # この手の関数は、しばしば「破壊的な関数」とか「in-place な関数」とか呼ばれます。 -# -# * Functions that modify their inputs have names that end in !. These -# functions are sometimes called mutating functions or in-place functions. + # 配列は、1 から始まる整数によって添字付けられる、値の列です。 -# Arrays store a sequence of values indexed by integers 1 through n: a = Int64[] # => 0-element Int64 Array -# 一次元配列は、角括弧 [] のなかにカンマ , 区切りで値を並べることで作ります。 -# 1-dimensional array literals can be written with comma-separated values. +# 一次元配列(列ベクトル)は、角括弧 [] のなかにカンマ , 区切りで値を並べることで作ります。 b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] b[1] # => 4 b[end] # => 6 # 二次元配列は、空白区切りで作った行を、セミコロンで区切ることで作ります。 -# 2-dimentional arrays use space-separated values and semicolon-separated rows. matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] -# 配列の終端に値を追加するには push! を、 -# 他の配列を追加するには append! を使います。 -# Add stuff to the end of a list with push! and append! +# 配列の末尾に値を追加するには push! を、 +# 他の配列を結合するには append! を使います。 push!(a,1) # => [1] push!(a,2) # => [1,2] push!(a,4) # => [1,2,4] push!(a,3) # => [1,2,4,3] append!(a,b) # => [1,2,4,3,4,5,6] -# 配列の終端から値を削除するには pop! を使います。 -# Remove from the end with pop +# 配列の末尾から値を削除するには pop! を使います。 pop!(b) # => 6 and b is now [4,5] -# もう一度戻しましょう。 -# Let's put it back +# 一旦元に戻しておきましょう。 push!(b,6) # b is now [4,5,6] again. a[1] # => 1 # Julia では添字は0 ではなく1 から始まること、お忘れなく! -a[1] # => 1 # remember that Julia indexes from 1, not 0! # end は最後の添字を表す速記法です。 # 添字を書く場所ならどこにでも使えます。 -# end is a shorthand for the last index. It can be used in any -# indexing expression a[end] # => 6 -# 先頭に対する追加・削除は shift!, unshift! です。 -# we also have shift and unshift +# 先頭に対する削除・追加は shift!, unshift! です。 shift!(a) # => 1 and a is now [2,4,3,4,5,6] unshift!(a,7) # => [7,2,4,3,4,5,6] # ! で終わる関数名は、その引数を変更するということを示します。 -# Function names that end in exclamations points indicate that they modify -# their argument. arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] sort(arr) # => [4,5,6]; arr is still [5,4,6] sort!(arr) # => [4,5,6]; arr is now [4,5,6] # 配列の範囲外アクセスをすると BoundsError が発生します。 -# Looking out of bounds is a BoundsError try a[0] # => ERROR: BoundsError() in getindex at array.jl:270 a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 @@ -254,40 +191,33 @@ catch e end # エラーが発生すると、どのファイルのどの行で発生したかが表示されます。 -# Errors list the line and file they came from, even if it's in the standard -# library. If you built Julia from source, you can look in the folder base -# inside the julia folder to find these files. +# 標準ライブラリで発生したものでもファイル名と行数が出ます。 +# ソースからビルドした場合など、標準ライブラリのソースが手元にある場合は +# base/ ディレクトリから探し出して見てください。 # 配列は範囲オブジェクトから作ることもできます。 -# You can initialize arrays from ranges a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] # 添字として範囲オブジェクトを渡すことで、 # 配列の部分列を得ることもできます。 -# You can look at ranges with slice syntax. a[1:3] # => [1, 2, 3] a[2:end] # => [2, 3, 4, 5] # 添字を用いて配列から値の削除をしたい場合は、splice! を使います。 -# Remove elements from an array by index with splice! arr = [3,4,5] splice!(arr,2) # => 4 ; arr is now [3,5] # 配列の結合は append! です。 -# Concatenate lists with append! b = [1,2,3] append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] # 配列内に指定した値があるかどうかを調べるのには in を使います。 -# Check for existence in a list with in in(1, a) # => true # length で配列の長さを取得できます。 -# Examine the length with length length(a) # => 8 # 変更不可能 (immutable) な値の組として、タプルが使えます。 -# Tuples are immutable. tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. tup[1] # => 1 try: @@ -297,65 +227,51 @@ catch e end # 配列に関する関数の多くが、タプルでも使えます。 -# Many list functions also work on tuples length(tup) # => 3 tup[1:2] # => (1,2) in(2, tup) # => true # タプルから値をばらして(unpack して) 複数の変数に代入できます。 -# You can unpack tuples into variables a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 # 丸括弧なしでもタプルになります。 -# Tuples are created even if you leave out the parentheses d, e, f = 4, 5, 6 # => (4,5,6) # ひとつの値だけからなるタプルは、その値自体とは区別されます。 -# A 1-element tuple is distinct from the value it contains (1,) == 1 # => false (1) == 1 # => true # 値の交換もタプルを使えば簡単です。 -# Look how easy it is to swap two values e, d = d, e # => (5,4) # d is now 5 and e is now 4 # 辞書 (Dict) は、値から値への変換の集合です。 -# Dictionaries store mappings empty_dict = Dict() # => Dict{Any,Any}() # 辞書型リテラルは次のとおりです。 -# You can create a dictionary using a literal filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] # => Dict{ASCIIString,Int64} # [] を使ったアクセスができます。 -# Look up values with [] filled_dict["one"] # => 1 # すべての鍵(添字)は keys で得られます。 -# Get all keys keys(filled_dict) # => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # 必ずしも辞書に追加した順番には並んでいないことに注意してください。 -# Note - dictionary keys are not sorted or in the order you inserted them. # 同様に、values はすべての値を返します。 -# Get all values values(filled_dict) # => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # 鍵と同様に、必ずしも辞書に追加した順番には並んでいないことに注意してください。 -# Note - Same as above regarding key ordering. # in や haskey を使うことで、要素や鍵が辞書の中にあるかを調べられます。 -# Check for existence of keys in a dictionary with in, haskey in(("one", 1), filled_dict) # => true in(("two", 3), filled_dict) # => false haskey(filled_dict, "one") # => true haskey(filled_dict, 1) # => false # 存在しない鍵を問い合わせると、エラーが発生します。 -# Trying to look up a non-existant key will raise an error try filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 catch e @@ -364,29 +280,22 @@ end # get 関数を使い、鍵がなかった場合のデフォルト値を与えておくことで、 # このエラーを回避できます。 -# Use the get method to avoid that error by providing a default value -# get(dictionary,key,default_value) get(filled_dict,"one",4) # => 1 get(filled_dict,"four",4) # => 4 # 集合 (Set) は一意な値の、順序付けられていない集まりです。 -# Use Sets to represent collections of unordered, unique values empty_set = Set() # => Set{Any}() # 集合の初期化 -# Initialize a set with values filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) # 集合への追加 -# Add more values to a set push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) # in で、値が既に存在するかを調べられます。 -# Check if the values are in the set in(2, filled_set) # => true in(10, filled_set) # => false # 積集合や和集合、差集合を得る関数も用意されています。 -# There are functions for set intersection, union, and difference. other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) intersect(filled_set, other_set) # => Set{Int64}(3,4,5) union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) @@ -394,16 +303,13 @@ setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) #################################################### -## 3. Control Flow ## 3. 制御構文 #################################################### # まずは変数を作ります。 -# Let's make a variable some_var = 5 # if 構文です。Julia ではインデントに意味はありません。 -# Here is an if statement. Indentation is not meaningful in Julia. if some_var > 10 println("some_var is totally bigger than 10.") elseif some_var < 10 # elseif 節は省略可能です。 @@ -416,8 +322,6 @@ end # for ループによって、反復可能なオブジェクトを走査できます。 # 反復可能なオブジェクトの型として、 # Range, Array, Set, Dict, String などがあります。 -# For loops iterate over iterables. -# Iterable types include Range, Array, Set, Dict, and String. for animal=["dog", "cat", "mouse"] println("$animal is a mammal") # $ を使うことで文字列に変数の値を埋め込めます。 @@ -429,7 +333,6 @@ end # mouse is a mammal # for = の代わりに for in を使うこともできます -# You can use 'in' instead of '='. for animal in ["dog", "cat", "mouse"] println("$animal is a mammal") end @@ -438,6 +341,7 @@ end # cat is a mammal # mouse is a mammal +# 辞書ではタプルが返ってきます。 for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] println("$(a[1]) is a $(a[2])") end @@ -446,6 +350,7 @@ end # cat is a mammal # mouse is a mammal +# タプルのアンパック代入もできます。 for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] println("$k is a $v") end @@ -455,7 +360,6 @@ end # mouse is a mammal # while ループは、条件式がtrue となる限り実行され続けます。 -# While loops loop while a condition is true x = 0 while x < 4 println(x) @@ -468,7 +372,6 @@ end # 3 # 例外は try/catch で捕捉できます。 -# Handle exceptions with a try/catch block try error("help") catch e @@ -478,12 +381,10 @@ end #################################################### -## 4. Functions ## 4. 関数 #################################################### # function キーワードを次のように使うことで、新しい関数を定義できます。 -# The keyword 'function' creates new functions #function name(arglist) # body... #end @@ -491,19 +392,15 @@ function add(x, y) println("x is $x and y is $y") # 最後に評価された式の値が、関数全体の返り値となります。 - # Functions return the value of their last statement x + y end add(5, 6) # => 11 after printing out "x is 5 and y is 6" # 可変長引数関数も定義できます。 -# You can define functions that take a variable number of -# positional arguments function varargs(args...) return args # return キーワードを使うことで、好きな位置で関数から抜けられます。 - # use the keyword return to return anywhere in the function end # => varargs (generic function with 1 method) @@ -513,10 +410,6 @@ varargs(1,2,3) # => (1,2,3) # (訳注:「ピシャッという音(名詞)」「衝撃で平らにする(動詞)」) # 今回は関数定義で使いましたが、関数呼び出しに使うこともできます。 # その場合、配列やタプルの要素を開いて、複数の引数へと割り当てることとなります。 -# The ... is called a splat. -# We just used it in a function definition. -# It can also be used in a fuction call, -# where it will splat an Array or Tuple's contents into the argument list. Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # 「整数の配列」の集合 Set([1,2,3]...) # => Set{Int64}(1,2,3) # 整数の集合 @@ -526,7 +419,6 @@ Set(x...) # => Set{Int64}(2,3,1) # 引数に初期値を与えることで、オプション引数をもった関数を定義できます。 -# You can define functions with optional positional arguments function defaults(a,b,x=5,y=6) return "$a $b and $x $y" end @@ -542,7 +434,6 @@ catch e end # キーワード引数を持った関数も作れます。 -# You can define functions that take keyword arguments function keyword_args(;k1=4,name2="hello") # ; が必要なことに注意 return ["k1"=>k1,"name2"=>name2] end @@ -552,7 +443,6 @@ keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] keyword_args() # => ["name2"=>"hello","k1"=>4] # もちろん、これらを組み合わせることもできます。 -# You can combine all kinds of arguments in the same function function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") println("normal arg: $normal_arg") println("optional arg: $optional_positional_arg") @@ -566,7 +456,6 @@ all_the_args(1, 3, keyword_arg=4) # keyword arg: 4 # Julia では関数は第一級関数として、値として扱われます。 -# Julia has first class functions function create_adder(x) adder = function (y) return x + y @@ -575,17 +464,14 @@ function create_adder(x) end # ラムダ式によって無名関数をつくれます。 -# This is "stabby lambda syntax" for creating anonymous functions (x -> x > 2)(3) # => true # 先ほどの create_adder と同じもの -# This function is identical to create_adder implementation above. function create_adder(x) y -> x + y end # 中の関数に名前をつけても構いません。 -# You can also name the internal function, if you want function create_adder(x) function adder(y) x + y @@ -598,47 +484,33 @@ add_10(3) # => 13 # いくつかの高階関数が定義されています。 -# There are built-in higher order functions map(add_10, [1,2,3]) # => [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # map の代わりとしてリスト内包表記も使えます。 -# We can use list comprehensions for nicer maps [add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] #################################################### -## 5. Types ## 5. 型 #################################################### # Julia ではすべての値にひとつの型がついています。 # 変数に、ではなくて値に、です。 # typeof 関数を使うことで、値が持つ型を取得できます。 -# Julia has a type system. -# Every value has a type; variables do not have types themselves. -# You can use the `typeof` function to get the type of a value. typeof(5) # => Int64 # 型自身もまた、第一級の値であり、型を持っています。 -# Types are first-class values typeof(Int64) # => DataType typeof(DataType) # => DataType # DataType は型を表現する型であり、DataType 自身もDataType 型の値です。 -# DataType is the type that represents types, including itself. # 型はドキュメント化や最適化、関数ディスパッチのために使われます。 # 静的な型チェックは行われません。 -# Types are used for documentation, optimizations, and dispatch. -# They are not statically checked. # 自分で新しい型を定義することもできます。 # 他の言語で言う、構造体やレコードに近いものになっています。 # 型定義には type キーワードを使います。 -# Users can define types -# They are like records or structs in other languages. -# New types are defined using the `type` keyword. - # type Name # field::OptionalType # ... @@ -646,34 +518,24 @@ typeof(DataType) # => DataType type Tiger taillength::Float64 coatcolor # 型注釈を省略した場合、自動的に :: Any として扱われます。 - coatcolor # not including a type annotation is the same as `::Any` end # 型を定義すると、その型のプロパティすべてを、定義した順番に # 引数として持つデフォルトコンストラクタが自動的に作られます。 -# The default constructor's arguments are the properties -# of the type, in the order they are listed in the definition tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") # 型名がそのままコンストラクタ名(関数名)となります。 -# The type doubles as the constructor function for values of that type sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") # このような、構造体スタイルの型は、具体型(concrete type)と呼ばれます。 # 具体型はインスタンス化可能ですが、派生型(subtype)を持つことができません。 # 具体型の他には抽象型(abstract type)があります。 -# These struct-style types are called concrete types -# They can be instantiated, but cannot have subtypes. -# The other kind of types is abstract types. # abstract Name abstract Cat # 型の階層図の途中の一点を指し示す名前となります。 -abstract Cat # just a name and point in the type hierarchy # 抽象型はインスタンス化できませんが、派生型を持つことができます。 # 例えば、 Number は以下の派生型を持つ抽象型です。 -# Abstract types cannot be instantiated, but can have subtypes. -# For example, Number is an abstract type subtypes(Number) # => 6-element Array{Any,1}: # Complex{Float16} # Complex{Float32} @@ -685,7 +547,6 @@ subtypes(Cat) # => 0-element Array{Any,1} # すべての型は、直接的にはただひとつの基本型(supertype) を持ちます。 # super 関数でこれを取得可能です。 -# Every type has a super type; use the `super` function to get it. typeof(5) # => Int64 super(Int64) # => Signed super(Signed) # => Real @@ -694,11 +555,9 @@ super(Number) # => Any super(super(Signed)) # => Number super(Any) # => Any # Int64 を除き、これらはすべて抽象型です。 -# All of these type, except for Int64, are abstract. # <: は派生形を表す演算子です。 # これを使うことで派生型を定義できます。 -# <: is the subtyping operator type Lion <: Cat # Lion は 抽象型 Cat の派生型 mane_color roar::String @@ -708,46 +567,31 @@ end # 必要とする型の値を返すことによって、 # デフォルトコンストラクタ以外のコンストラクタを作ることができます。 -# You can define more constructors for your type -# Just define a function of the same name as the type -# and call an existing constructor to get a value of the correct type Lion(roar::String) = Lion("green",roar) # 型定義の外側で定義されたコンストラクタなので、外部コンストラクタと呼ばれます。 -# This is an outer constructor because it's outside the type definition type Panther <: Cat # Panther も Cat の派生型 eye_color Panther() = new("green") # Panther は内部コンストラクタとしてこれのみを持ち、 # デフォルトコンストラクタを持たない - # Panthers will only have this constructor, and no default constructor. end # 内部コンストラクタを使うことで、どのような値が作られるのかをコントロールすることができます。 # 出来る限り、外部コンストラクタを使うべきです。 -# Using inner constructors, like Panther does, gives you control -# over how values of the type can be created. -# When possible, you should use outer constructors rather than inner ones. #################################################### -## 6. Multiple-Dispatch ## 6. 多重ディスパッチ #################################################### # Julia では、すべての名前付きの関数は総称的関数(generic function) です。 # これは、関数はいくつかの細かいメソッドの集合である、という意味です。 # 例えば先の Lion 型のコンストラクタ Lion は、Lion という関数の1つのメソッドです。 -# In Julia, all named functions are generic functions -# This means that they are built up from many small methods -# Each constructor for Lion is a method of the generic function Lion. # コンストラクタ以外の例をみるために、新たに meow 関数を作りましょう。 -# For a non-constructor example, let's make a function meow: # Lion, Panther, Tiger 型それぞれに対する meow 関数のメソッド定義 -# Definitions for Lion, Panther, Tiger function meow(animal::Lion) animal.roar # 型のプロパティには . でアクセスできます。 - animal.roar # access type properties using dot notation end function meow(animal::Panther) @@ -759,19 +603,16 @@ function meow(animal::Tiger) end # meow 関数の実行 -# Testing the meow function meow(tigger) # => "rawwr" meow(Lion("brown","ROAAR")) # => "ROAAR" meow(Panther()) # => "grrr" # 型の階層関係を見てみましょう -# Review the local type hierarchy issubtype(Tiger,Cat) # => false issubtype(Lion,Cat) # => true issubtype(Panther,Cat) # => true # 抽象型 Cat の派生型を引数にとる関数 -# Defining a function that takes Cats function pet_cat(cat::Cat) println("The cat says $(meow(cat))") end @@ -785,14 +626,10 @@ end # オブジェクト指向言語では、一般的にシングルディスパッチが用いられます。 # つまり、関数に複数あるメソッドのうちにどれが呼ばれるかは、 -# その第一引数によってのみ決定されます。 +# その第一引数(もしくは、 . や -> の前にある値の型)によってのみ決定されます。 # 一方でJulia では、すべての引数の型が、このメソッド決定に寄与します。 -# In OO languages, single dispatch is common; -# this means that the method is picked based on the type of the first argument. -# In Julia, all of the argument types contribute to selecting the best method. # 多変数関数を定義して、この辺りを見て行きましょう。 -# Let's define a function with more arguments, so we can see the difference function fight(t::Tiger,c::Cat) println("The $(t.coatcolor) tiger wins!") end @@ -802,7 +639,6 @@ fight(tigger,Panther()) # => prints The orange tiger wins! fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! # 第二引数の Cat が実際は Lion だった時に、挙動が変わるようにします。 -# Let's change the behavior when the Cat is specifically a Lion fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") # => fight (generic function with 2 methods) @@ -810,7 +646,6 @@ fight(tigger,Panther()) # => prints The orange tiger wins! fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! # 別に Tiger だけが戦う必要もないですね。 -# We don't need a Tiger in order to fight fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") # => fight (generic function with 3 methods) @@ -821,7 +656,6 @@ catch end # 第一引数にも Cat を許しましょう。 -# Also let the cat go first fight(c::Cat,l::Lion) = println("The cat beats the Lion") # => Warning: New definition # fight(Cat,Lion) at none:1 @@ -833,25 +667,20 @@ fight(c::Cat,l::Lion) = println("The cat beats the Lion") #fight (generic function with 4 methods) # 警告が出ましたが、これは次の対戦で何が起きるのかが不明瞭だからです。 -# This warning is because it's unclear which fight will be called in: fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr # Julia のバージョンによっては、結果が違うかもしれません。 -# The result may be different in other versions of Julia fight(l::Lion,l2::Lion) = println("The lions come to a tie") fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie # Julia が生成する LLVM 内部表現や、アセンブリを調べることもできます。 -# Under the hood -# You can take a look at the llvm and the assembly code generated. square_area(l) = l * l # square_area (generic function with 1 method) square_area(5) #25 # square_area に整数を渡すと何が起きる? -# What happens when we feed square_area an integer? code_native(square_area, (Int32,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none @@ -859,10 +688,10 @@ code_native(square_area, (Int32,)) # push RBP # mov RBP, RSP # Source line: 1 - # movsxd RAX, EDI # Fetch l from memory? - # imul RAX, RAX # Square l and store the result in RAX - # pop RBP # Restore old base pointer - # ret # Result will still be in RAX + # movsxd RAX, EDI # l を取得 + # imul RAX, RAX # l*l を計算して RAX に入れる + # pop RBP # Base Pointer を元に戻す + # ret # 終了。RAX の中身が結果 code_native(square_area, (Float32,)) # .section __TEXT,__text,regular,pure_instructions @@ -871,7 +700,7 @@ code_native(square_area, (Float32,)) # push RBP # mov RBP, RSP # Source line: 1 - # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) + # vmulss XMM0, XMM0, XMM0 # 単精度浮動小数点数演算 (AVX) # pop RBP # ret @@ -882,7 +711,7 @@ code_native(square_area, (Float64,)) # push RBP # mov RBP, RSP # Source line: 1 - # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) + # vmulsd XMM0, XMM0, XMM0 # 倍精度浮動小数点数演算 (AVX) # pop RBP # ret # @@ -890,9 +719,6 @@ code_native(square_area, (Float64,)) # Julia では、浮動小数点数と整数との演算では # 自動的に浮動小数点数用の命令が生成されることに注意してください。 # 円の面積を計算してみましょう。 -# Note that julia will use floating point instructions if any of the -# arguements are floats. -# Let's calculate the area of a circle circle_area(r) = pi * r * r # circle_area (generic function with 1 method) circle_area(5) # 78.53981633974483 @@ -927,13 +753,9 @@ code_native(circle_area, (Float64,)) ``` ## より勉強するために -## Further Reading [公式ドキュメント](http://docs.julialang.org/en/latest/manual/) (英語)にはより詳細な解説が記されています。 -You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) - Julia に関して助けが必要ならば、[メーリングリスト](https://groups.google.com/forum/#!forum/julia-users) が役に立ちます。 みんな非常に親密に教えてくれます。 -The best place to get help with Julia is the (very friendly) [mailing list](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From a3ce8e9d6c0810e83852f6e197cf3a55006f5c7e Mon Sep 17 00:00:00 2001 From: Nikolay Kirsh Date: Mon, 22 Dec 2014 13:01:43 +0500 Subject: Russuan spelling corrrection --- ru-ru/go-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 44a22b45..e06ae9bd 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -65,7 +65,7 @@ func beyondHello() { learnTypes() // < y minutes, learn more! } -// Функция имеющая входные параметры и возврат нескольких значений. +// Функция, имеющая входные параметры и возвращающая несколько значений. func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Возврат двух значений. } -- cgit v1.2.3 From 54b8be676862ec85920c952db4f4e791f4d721b0 Mon Sep 17 00:00:00 2001 From: euporie Date: Mon, 22 Dec 2014 13:26:30 +0100 Subject: Fixed typo at the end --- pogo.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pogo.html.markdown b/pogo.html.markdown index 60a83edd..aa5d49f3 100644 --- a/pogo.html.markdown +++ b/pogo.html.markdown @@ -199,4 +199,4 @@ 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! +There is plenty of documentation on [http://pogoscript.org/](http://pogoscript.org/), including 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! -- cgit v1.2.3 From 674284cfcb0fa3194ad854d711288ec9aa5b98e9 Mon Sep 17 00:00:00 2001 From: maniexx Date: Mon, 22 Dec 2014 15:24:09 +0100 Subject: Delete PYMOTW3 due to lack of content --- python3.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index f6babaff..8bcc85d1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -609,7 +609,6 @@ 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/) -* [Python Module of the Week](http://pymotw.com/3/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) ### Dead Tree -- cgit v1.2.3 From ed819ed91774d37ada2e77af941289aeefbf6a86 Mon Sep 17 00:00:00 2001 From: switchhax Date: Tue, 23 Dec 2014 16:27:30 +0100 Subject: [YAML/en] translated to [YAML/de] --- de-de/bash-de.html.markdown | 2 +- de-de/yaml-de.html.markdown | 138 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 de-de/yaml-de.html.markdown diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index ad782e06..fb9cd9d4 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -17,7 +17,7 @@ Beinahe alle der folgenden Beispiele können als Teile eines Shell-Skripts oder ```bash #!/bin/bash -# Die erste Zeile des Scripts nennt sich Shebang in gibt dem System an, wie +# Die erste Zeile des Scripts nennt sich Shebang, dies gibt dem System an, # wie das Script ausgeführt werden soll: http://de.wikipedia.org/wiki/Shebang # Du hast es bestimmt schon mitgekriegt, Kommentare fangen mit # an. Das Shebang ist auch ein Kommentar diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown new file mode 100644 index 00000000..88318014 --- /dev/null +++ b/de-de/yaml-de.html.markdown @@ -0,0 +1,138 @@ +--- +language: yaml +filename: learnyaml.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Ruben M.", https://github.com/switchhax] +--- + +YAML ist eine Sprache zur Datenserialisierung, die sofort von Menschenhand geschrieben und gelesen werden kann. + +YAML ist eine Erweiterung von JSON, mit der Erweiterung von syntaktisch wichtigen Zeilenumbrüche und Einrückung sowie in Python. Anders als in Python erlaubt YAML keine Tabulator-Zeichen. + +```yaml +# Kommentare in YAML schauen so aus. + +################# +# SKALARE TYPEN # +################# + +# Unser Kernobjekt (für das ganze Dokument) wird das Assoziative Datenfeld (Map) sein, +# welches equivalent zu einem Hash oder einem Objekt einer anderen Sprache ist. +Schlüssel: Wert +nochn_Schlüssel: Hier kommt noch ein Wert hin. +eine_Zahl: 100 +wissenschaftliche_Notation: 1e+12 +boolean: true +null_Wert: null +Schlüssel mit Leerzeichen: value +# Strings müssen nicht immer mit Anführungszeichen umgeben sein, können aber: +jedoch: "Ein String in Anführungzeichen" +"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schluessel haben willst." + +# Mehrzeilige Strings schreibst du am besten als 'literal block' (| gefolgt vom Text) +# oder ein 'folded block' (> gefolgt vom text). +literal_block: | + Dieser ganze Block an Text ist der Wert vom Schlüssel literal_block, + mit Erhaltung der Zeilenumbrüche. + + Das Literal fährt solange fort bis dieses unverbeult ist und die vorherschende Einrückung wird + gekürzt. + + Zeilen, die weiter eingerückt sind, behalten den Rest ihrer Einrückung - + diese Zeilen sind mit 4 Leerzeichen eingerückt. +folded_style: > + Dieser ganze Block an Text ist der Wert vom Schlüssel folded_style, aber diesmal + werden alle Zeilenumbrüche durch ein Leerzeichen ersetzt. + + Freie Zeilen, wie obendrüber, werden in einen Zeilenumbruch verwandelt. + + Weiter eingerückte Zeilen behalten ihre Zeilenumbrüche - + diese Textpassage wird auf zwei Zeilen sichtbar sein. + +#################### +# COLLECTION TYPEN # +#################### + +# Verschachtelung wird duch Einrückung erzielt. +eine_verschachtelte_map: + schlüssel: wert + nochn_Schlüssel: Noch ein Wert. + noch_eine_verschachtelte_map: + hallo: hallo + +# Schlüssel müssen nicht immer String sein. +0.25: ein Float-Wert als Schluessel + +# Schlüssel können auch mehrzeilig sein, ? symbolisiert den Anfang des Schlüssels +? | + Dies ist ein Schlüssel, + der mehrzeilig ist. +: und dies ist sein Wert + +# YAML erlaubt auch Collections als Schlüssel, doch viele Programmiersprachen +# werden sich beklagen. + +# Folgen (equivalent zu Listen oder Arrays) schauen so aus: +eine_Folge: + - Artikel 1 + - Artikel 2 + - 0.5 # Folgen können verschiedene Typen enthalten. + - Artikel 4 + - schlüssel: wert + nochn_schlüssel: nochn_wert + - + - Dies ist eine Folge + - innerhalb einer Folge + +# Weil YAML eine Erweiterung von JSON ist, können JSON-ähnliche Maps und Folgen +# geschrieben werden: +json_map: {"schlüssel": "wert"} +json_seq: [3, 2, 1, "Start"] + +############################ +# EXTRA YAML EIGENSCHAFTEN # +############################ + +# YAML stellt zusätzlich Verankerung zu Verfügung, welche es einfach machen +# Inhalte im Dokument zu vervielfältigen. Beide Schlüssel werden den selben Wert haben. +verankerter_inhalt: &anker_name Dieser String wird als Wert beider Schlüssel erscheinen. +anderer_anker: *anker_name + +# YAML hat auch Tags, mit denen man explizit Typangaben angibt. +explicit_string: !!str 0.5 +# Manche Parser implementieren sprachspezifische Tags wie dieser hier für Pythons +# komplexe Zahlen. +python_komplexe_Zahlen: !!python/komplex 1+2j + +#################### +# EXTRA YAML TYPEN # +#################### + +# Strings and Zahlen sind nicht die einzigen Skalare, welche YAML versteht. +# ISO-formatierte Datumsangaben and Zeiangaben können ebenso geparsed werden. +DatumZeit: 2001-12-15T02:59:43.1Z +DatumZeit_mit_Leerzeichen: 2001-12-14 21:59:43.10 -5 +Datum: 2002-12-14 + +# Der !!binary Tag zeigt das ein String base64 verschlüsselt ist. +# Representation des Binären Haufens +gif_datei: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML bietet auch Mengen (Sets), welche so ausschauen +menge: + ? artikel1 + ? artikel2 + ? artikel3 + +# Wie in Python sind Mengen nicht anderes als Maps nur mit null als Wert; das Beispiel oben drüber ist equivalent zu: +menge: + artikel1: null + artikel2: null + artikel3: null +``` -- cgit v1.2.3 From 28fcbc8e1c7d22bbc192418b4f3513f2ca4ead3e Mon Sep 17 00:00:00 2001 From: Louie Dinh Date: Tue, 23 Dec 2014 11:23:22 -0800 Subject: Fix typo --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 53381f32..da04d381 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -264,7 +264,7 @@ 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 -# note that filled_dict.get("four") is still => 4 +# note that filled_dict.get("four") is still => None # (get doesn't set the value in the dictionary) # set the value of a key with a syntax similar to lists -- cgit v1.2.3 From 4ab8d7427d60f48a5b076c0e589477a147659d31 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 24 Dec 2014 10:38:16 +0100 Subject: Update livescript.html.markdown Fix syntax errors on numbery var names --- livescript.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/livescript.html.markdown b/livescript.html.markdown index 429b91cb..e64f7719 100644 --- a/livescript.html.markdown +++ b/livescript.html.markdown @@ -219,8 +219,8 @@ identity 1 # => 1 # Operators are not functions in LiveScript, but you can easily turn # them into one! Enter the operator sectioning: -divide-by-2 = (/ 2) -[2, 4, 8, 16].map(divide-by-2) .reduce (+) +divide-by-two = (/ 2) +[2, 4, 8, 16].map(divide-by-two) .reduce (+) # Not only of function application lives LiveScript, as in any good @@ -248,8 +248,8 @@ reduce = (f, xs, initial) --> xs.reduce f, initial # The underscore is also used in regular partial application, which you # can use for any function: div = (left, right) -> left / right -div-by-2 = div _, 2 -div-by-2 4 # => 2 +div-by-two = div _, 2 +div-by-two 4 # => 2 # Last, but not least, LiveScript has back-calls, which might help -- cgit v1.2.3 From f323083ba49a2e1fa0b5a11b4ce2bf74a21cac86 Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 24 Dec 2014 18:22:48 +0100 Subject: rework of the tutorial --- perl6.html.markdown | 356 ++++++++++++++++++++++++++-------------------------- 1 file changed, 180 insertions(+), 176 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index b178de1e..1536b152 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -35,7 +35,8 @@ my $variable; ## * Scalars. They represent a single value. They start with a `$` my $str = 'String'; -my $str2 = "String"; # double quotes allow for interpolation +# double quotes allow for interpolation (which we'll see later): +my $str2 = "String"; # variable names can contain but not end with simple quotes and dashes, # and can contain (and end with) underscores : @@ -66,23 +67,13 @@ my @keys = 0, 2; @array[@keys] = @letters; # Assign using an array say @array; #=> a 6 b -# There are two more kinds of lists: Parcel and Arrays. -# Parcels are immutable lists (you can't modify a list that's not assigned). -# This is a parcel: -(1, 2, 3); # Not assigned to anything. Changing an element would provoke an error -# This is a list: -my @a = (1, 2, 3); # Assigned to `@a`. Changing elements is okay! - -# Lists flatten (in list context). You'll see below how to apply item context -# or use arrays to have real nested lists. - - -## * Hashes. Key-Value Pairs. -# Hashes are actually arrays of Pairs (`Key => Value`), -# except they get "flattened", removing duplicated keys. +## * Hashes, or key-value Pairs. +# Hashes are actually arrays of Pairs +# (you can construct a Pair object using the syntax `Key => Value`), +# except they get "flattened" (hash context), removing duplicated keys. my %hash = 1 => 2, 3 => 4; -my %hash = autoquoted => "key", # keys *can* get auto-quoted +my %hash = autoquoted => "key", # keys get auto-quoted "some other" => "value", # trailing commas are okay ; my %hash = ; # you can also create a hash @@ -112,30 +103,6 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument say "Hello, $name !"; } -# Since you can omit parenthesis to call a function with no arguments, -# you need "&" in the name to capture `say-hello`. -my &s = &say-hello; -my &other-s = sub { say "Anonymous function !" } - -# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" -sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else". - # Note: you can have parameters *before* (like here) - # a slurpy one, but not *after*. - say @rest.join(' / ') ~ " !"; -} -say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! - # Note that the splat did not consume - # the parameter before. - -## You can call a function with an array using the -# "argument list flattening" operator `|` -# (it's not actually the only role of this operator, but it's one of them) -sub concat3($a, $b, $c) { - say "$a, $b, $c"; -} -concat3(|@array); #=> a, b, c - # `@array` got "flattened" as a part of the argument list - ## It can also have optional arguments: sub with-optional($arg?) { # the "?" marks the argument optional say "I might return `(Any)` if I don't have an argument passed, @@ -154,23 +121,20 @@ hello-to; #=> Hello, World ! hello-to(); #=> Hello, World ! hello-to('You'); #=> Hello, You ! -## You can also, by using a syntax akin to the one of hashes (yay unification !), +## You can also, by using a syntax akin to the one of hashes (yay unified syntax !), ## pass *named* arguments to a `sub`. +# They're optional, and will default to "Any" (Perl's "null"-like value). sub with-named($normal-arg, :$named) { say $normal-arg + $named; } with-named(1, named => 6); #=> 7 # There's one gotcha to be aware of, here: # If you quote your key, Perl 6 won't be able to see it at compile time, -# and you'll have a single Pair object as a positional paramater. +# and you'll have a single Pair object as a positional paramater, +# which means this fails: +with-named(1, 'named' => 6); with-named(2, :named(5)); #=> 7 -with-named(3, :4named); #=> 7 - # (special colon pair syntax for numbers, - # to be used with s// and such, see later) - -with-named(3); # warns, because we tried to use the undefined $named in a `+`: - # by default, named arguments are *optional* # To make a named argument mandatory, you can use `?`'s inverse, `!` sub with-mandatory-named(:$str!) { @@ -187,11 +151,6 @@ sub takes-a-bool($name, :$bool) { # ... you can use the same "short boolean" hash syntax: takes-a-bool('config', :bool); # config takes True takes-a-bool('config', :!bool); # config takes False -# or you can use the "adverb" form: -takes-a-bool('config'):bool; #=> config takes True -takes-a-bool('config'):!bool; #=> config takes False -# You'll learn to love (or maybe hate, eh) that syntax later. - ## You can also provide your named arguments with defaults: sub named-def(:$def = 5) { @@ -201,8 +160,29 @@ named-def; #=> 5 named-def(:10def); #=> 10 named-def(def => 15); #=> 15 -# -- Note: we're going to learn *more* on subs really soon, -# but we need to grasp a few more things to understand their real power. Ready? +# Since you can omit parenthesis to call a function with no arguments, +# you need "&" in the name to capture `say-hello`. +my &s = &say-hello; +my &other-s = sub { say "Anonymous function !" } + +# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" +sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else". + # Note: you can have parameters *before* (like here) + # a slurpy one, but not *after*. + say @rest.join(' / ') ~ " !"; +} +say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! + # Note that the splat did not consume + # the parameter before. + +## You can call a function with an array using the +# "argument list flattening" operator `|` +# (it's not actually the only role of this operator, but it's one of them) +sub concat3($a, $b, $c) { + say "$a, $b, $c"; +} +concat3(|@array); #=> a, b, c + # `@array` got "flattened" as a part of the argument list ### Containers # In Perl 6, values are actually stored in "containers". @@ -220,17 +200,13 @@ sub mutate($n is rw) { # A sub itself returns a container, which means it can be marked as rw: my $x = 42; -sub mod() is rw { $x } -mod() = 52; # in this case, the parentheses are mandatory - # (else Perl 6 thinks `mod` is a "term") +sub x-store() is rw { $x } +x-store() = 52; # in this case, the parentheses are mandatory + # (else Perl 6 thinks `mod` is an identifier) say $x; #=> 52 ### Control Flow Structures - -# You don't need to put parenthesis around the condition, -# but that also means you always have to use brackets (`{ }`) for their body: - ## Conditionals # - `if` @@ -247,30 +223,38 @@ unless False { say "It's not false !"; } +# As you can see, you don't need parentheses around conditions. +# However, you do need the brackets around the "body" block: +# if (true) say; # This doesn't work ! + # You can also use their postfix versions, with the keyword after: say "Quite truthy" if True; -# if (true) say; # This doesn't work ! - # - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages) my $a = $condition ?? $value-if-true !! $value-if-false; # - `given`-`when` looks like other languages `switch`, but much more # powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_. +# # This variable contains the default argument of a block, # a loop's current iteration (unless explicitly named), etc. +# # `given` simply puts its argument into `$_` (like a block would do), # and `when` compares it using the "smart matching" (`~~`) operator. +# # Since other Perl 6 constructs use this variable (as said before, like `for`, # blocks, etc), this means the powerful `when` is not only applicable along with # a `given`, but instead anywhere a `$_` exists. given "foo bar" { - when /foo/ { # Don't worry about smart matching -- just know `when` uses it. + say $_; #=> foo bar + when /foo/ { # Don't worry about smart matching yet – just know `when` uses it. # This is equivalent to `if $_ ~~ /foo/`. say "Yay !"; } 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 {...} say "Quite a long string !"; } default { # same as `when *` (using the Whatever Star) @@ -281,7 +265,7 @@ given "foo bar" { ## Looping constructs # - `loop` is an infinite loop if you don't pass it arguments, -# but can also be a c-style `for`: +# but can also be a C-style `for` loop: loop { say "This is an infinite loop !"; last; # last breaks out of the loop, like the `break` keyword in other languages @@ -296,7 +280,7 @@ loop (my $i = 0; $i < 5; $i++) { # - `for` - Passes through an array for @array -> $variable { - say "I've found $variable !"; + say "I've got $variable !"; } # As we saw with given, for's default "current iteration" variable is `$_`. @@ -316,22 +300,15 @@ for @array { last if $_ == 5; # Or break out of a loop (like `break` in C-like languages). } -# Note - the "lambda" `->` syntax isn't reserved to `for`: +# The "pointy block" syntax isn't specific to for. +# It's just a way to express a block in Perl6. if long-computation() -> $result { say "The result is $result"; } -## Loops can also have a label, and be jumped to through these. -OUTER: while 1 { - say "hey"; - while 1 { - OUTER.last; # All the control keywords must be called on the label itself - } -} - # 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 (except if some sub-list were put in item context ($)). +# shallow list. for 1, 2, (3, (4, ((5)))) { say "Got $_."; } #=> Got 1. Got 2. Got 3. Got 4. Got 5. @@ -348,9 +325,14 @@ for [1, 2, 3, 4] { say "Got $_."; } #=> Got 1 2 3 4. -# The other difference between `$()` and `[]` is that `[]` always returns a mutable Array -# whereas `$()` will return a Parcel when given a Parcel. +# 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 @@ -394,9 +376,6 @@ $arg ~~ &bool-returning-function; # `True` if the function, passed `$arg` 1 ~~ True; # smart-matching against a boolean always returns that boolean # (and will warn). -# - `===` is value identity and uses `.WHICH` on the objects to compare them -# - `=:=` is container identity and uses `VAR()` on the objects to compare them - # You also, of course, have `<`, `<=`, `>`, `>=`. # Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`. 3 > 4; @@ -559,6 +538,21 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) # Note : those are sorted lexicographically. # `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` +## About types... +# Perl6 is gradually typed. This means you can specify the type +# of your variables/arguments/return types, or you can omit them +# and they'll default to "Any". +# You obviously get access to a few base types, like Int and Str. +# The constructs for declaring types are "class", "role", +# which you'll see later. + +# For now, let us examinate "subset": +# a "subset" is a "sub-type" with additional checks. +# For example: "a very big integer is an Int that's greater than 500" +# You can specify the type you're subtyping (by default, Any), +# and add additional checks with the "where" keyword: +subset VeryBigInteger of Int where * > 500; + ## Multiple Dispatch # Perl 6 can decide which variant of a `sub` to call based on the type of the # arguments, or on arbitrary preconditions, like with a type or a `where`: @@ -567,20 +561,19 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) multi sub sayit(Int $n) { # note the `multi` keyword here say "Number: $n"; } -multi sayit(Str $s) } # the `sub` is the default +multi sayit(Str $s) } # a multi is a `sub` by default say "String: $s"; } sayit("foo"); # prints "String: foo" sayit(True); # fails at *compile time* with # "calling 'sayit' will never work with arguments of types ..." -# with arbitrary precondition: +# with arbitrary precondition (remember subsets?): multi is-big(Int $n where * > 50) { "Yes !" } # using a closure multi is-big(Int $ where 10..50) { "Quite." } # Using smart-matching # (could use a regexp, etc) multi is-big(Int $) { "No" } -# You can also name these checks, by creating "subsets": subset Even of Int where * %% 2; multi odd-or-even(Even) { "Even" } # The main case using the type. @@ -724,7 +717,7 @@ role PrintableVal { } } -# you "use" a mixin with "does" : +# you "import" a mixin (a "role") with "does": class Item does PrintableVal { has $.val; @@ -1083,9 +1076,7 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # It's a prefix meta-operator that takes a binary functions and # one or many lists. If it doesn't get passed any argument, # it either return a "default value" for this operator -# (a value that wouldn't change the result if passed as one -# of the element of the list to be passed to the operator), -# or `Any` if there's none (examples below). +# (a meaningless value) or `Any` if there's none (examples below). # # Otherwise, it pops an element from the list(s) one at a time, and applies # the binary function to the last result (or the list's first element) @@ -1107,9 +1098,7 @@ say [//] Nil, Any, False, 1, 5; #=> False # Default value examples: say [*] (); #=> 1 say [+] (); #=> 0 - # In both cases, they're results that, were they in the lists, - # wouldn't have any impact on the final value - # (since N*1=N and N+0=N). + # meaningless values, since N*1=N and N+0=N. say [//]; #=> (Any) # There's no "default value" for `//`. @@ -1163,90 +1152,6 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55 # That's why `@primes[^100]` will take a long time the first time you print # it, then be instant. - -## * Sort comparison -# They return one value of the `Order` enum : `Less`, `Same` and `More` -# (which numerify to -1, 0 or +1). -1 <=> 4; # sort comparison for numerics -'a' leg 'b'; # sort comparison for string -$obj eqv $obj2; # sort comparison using eqv semantics - -## * Generic ordering -3 before 4; # True -'b' after 'a'; # True - -## * Short-circuit default operator -# Like `or` and `||`, but instead returns the first *defined* value : -say Any // Nil // 0 // 5; #=> 0 - -## * Short-circuit exclusive or (XOR) -# Returns `True` if one (and only one) of its arguments is true -say True ^^ False; #=> True - -## * Flip Flop -# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`). -# are operators that take two predicates to test: -# They are `False` until their left side returns `True`, then are `True` until -# their right side returns `True`. -# Like for ranges, you can exclude the iteration when it became `True`/`False` -# by using `^` on either side. -# Let's start with an example : -for { - # by default, `ff`/`fff` smart-match (`~~`) against `$_`: - if 'met' ^ff 'meet' { # Won't enter the if for "met" - # (explained in details below). - .say - } - - if rand == 0 ff rand == 1 { # compare variables other than `$_` - say "This ... probably will never run ..."; - } -} -# This will print "young hero we shall meet" (excluding "met"): -# the flip-flop will start returning `True` when it first encounters "met" -# (but will still return `False` for "met" itself, due to the leading `^` -# on `ff`), until it sees "meet", which is when it'll start returning `False`. - -# The difference between `ff` (awk-style) and `fff` (sed-style) is that -# `ff` will test its right side right when its left side changes to `True`, -# and can get back to `False` right away -# (*except* it'll be `True` for the iteration that matched) - -# While `fff` will wait for the next iteration to -# try its right side, once its left side changed: -.say if 'B' ff 'B' for ; #=> B B - # because the right-hand-side was tested - # directly (and returned `True`). - # "B"s are printed since it matched that time - # (it just went back to `False` right away). -.say if 'B' fff 'B' for ; #=> B C B - # The right-hand-side wasn't tested until - # `$_` became "C" - # (and thus did not match instantly). - -# A flip-flop can change state as many times as needed: -for { - .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", - #=> "print this printing again" -} - -# you might also use a Whatever Star, -# which is equivalent to `True` for the left side or `False` for the right: -for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here - # (sometimes called "superstitious parentheses") - .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, - # it'll never go back to `False` - #=> 60 3 40 60 -} - -# You can also use this property to create an `If` -# that'll not go through the first time : -for { - .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, - # but the `^` makes it *not run* on the first iteration - #=> b c -} - - ### Regular Expressions # I'm sure a lot of you have been waiting for this one. # Well, now that you know a good deal of Perl 6 already, we can get started. @@ -1470,6 +1375,105 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name # As you can see, this is *very* powerful. # It even went as far as to show inline the constants. # (the type is only displayed if the argument is `$`/is named) + +### +### APPENDIX A: +### +### List of things +### + +# It's considered by now you know the Perl6 basics. +# This section is just here to list some common operations, +# but which are not in the "main part" of the tutorial to bloat it up + +## Operators + + +## * Sort comparison +# They return one value of the `Order` enum : `Less`, `Same` and `More` +# (which numerify to -1, 0 or +1). +1 <=> 4; # sort comparison for numerics +'a' leg 'b'; # sort comparison for string +$obj eqv $obj2; # sort comparison using eqv semantics + +## * Generic ordering +3 before 4; # True +'b' after 'a'; # True + +## * Short-circuit default operator +# Like `or` and `||`, but instead returns the first *defined* value : +say Any // Nil // 0 // 5; #=> 0 + +## * Short-circuit exclusive or (XOR) +# Returns `True` if one (and only one) of its arguments is true +say True ^^ False; #=> True +## * Flip Flop +# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`). +# are operators that take two predicates to test: +# They are `False` until their left side returns `True`, then are `True` until +# their right side returns `True`. +# Like for ranges, you can exclude the iteration when it became `True`/`False` +# by using `^` on either side. +# Let's start with an example : +for { + # by default, `ff`/`fff` smart-match (`~~`) against `$_`: + if 'met' ^ff 'meet' { # Won't enter the if for "met" + # (explained in details below). + .say + } + + if rand == 0 ff rand == 1 { # compare variables other than `$_` + say "This ... probably will never run ..."; + } +} +# This will print "young hero we shall meet" (excluding "met"): +# the flip-flop will start returning `True` when it first encounters "met" +# (but will still return `False` for "met" itself, due to the leading `^` +# on `ff`), until it sees "meet", which is when it'll start returning `False`. + +# The difference between `ff` (awk-style) and `fff` (sed-style) is that +# `ff` will test its right side right when its left side changes to `True`, +# and can get back to `False` right away +# (*except* it'll be `True` for the iteration that matched) - +# While `fff` will wait for the next iteration to +# try its right side, once its left side changed: +.say if 'B' ff 'B' for ; #=> B B + # because the right-hand-side was tested + # directly (and returned `True`). + # "B"s are printed since it matched that time + # (it just went back to `False` right away). +.say if 'B' fff 'B' for ; #=> B C B + # The right-hand-side wasn't tested until + # `$_` became "C" + # (and thus did not match instantly). + +# A flip-flop can change state as many times as needed: +for { + .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", + #=> "print this printing again" +} + +# you might also use a Whatever Star, +# which is equivalent to `True` for the left side or `False` for the right: +for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here + # (sometimes called "superstitious parentheses") + .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, + # it'll never go back to `False` + #=> 60 3 40 60 +} + +# You can also use this property to create an `If` +# that'll not go through the first time : +for { + .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, + # but the `^` makes it *not run* on the first iteration + #=> b c +} + + +# - `===` is value identity and uses `.WHICH` on the objects to compare them +# - `=:=` is container identity and uses `VAR()` on the objects to compare them + ``` If you want to go further, you can: -- cgit v1.2.3 From e2606bb26259f702e6359afa4075c8a081fb7600 Mon Sep 17 00:00:00 2001 From: elf Date: Fri, 26 Dec 2014 08:56:36 -0200 Subject: general translation to pt-br for common-lisp completed --- pt-br/common-lisp-pt.html.markdown | 636 +++++++++++++++++++++++++++++++++++++ 1 file changed, 636 insertions(+) create mode 100644 pt-br/common-lisp-pt.html.markdown diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown new file mode 100644 index 00000000..a2506aec --- /dev/null +++ b/pt-br/common-lisp-pt.html.markdown @@ -0,0 +1,636 @@ +--- + +language: "Common Lisp" +filename: commonlisp.lisp +contributors: + - ["Paul Nathan", "https://github.com/pnathan"] +--- + + + + + +ANSI Common Lisp é uma linguagem de uso geral, multi-paradigma, designada +para uma variedade de aplicações na indústria. É frequentemente citada +como uma linguagem de programação programável. + + + + +O ponto inicial clássico é [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/) + + + + +Outro livro recente e popular é o +[Land of Lisp](http://landoflisp.com/). + + +```common_lisp + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 0. Sintaxe +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; "Form" Geral + + + + +;; Lisp tem dois pedaços fundamentais de sintaxe: o ATOM e S-expression. +;; Tipicamente, S-expressions agrupadas são chamadas de `forms`. + + +10 ; um atom; é avaliado para ele mesmo + + + +:THING ;Outro atom; avaliado para o símbolo :thing. + + + +t ; outro atom, denotado true. + + + +(+ 1 2 3 4) ; uma s-expression + +'(4 :foo t) ;outra s-expression + + +;;; Comentários + +;; Comentários de uma única linha começam com ponto e vírgula; usar dois para +;; comentários normais, três para comentários de seção, e quadro para comentários +;; em nível de arquivo. + +#| Bloco de comentário + pode abranger várias linhas e... + #| + eles podem ser aninhados + |# +|# + +;;; Ambiente + +;; Existe uma variedade de implementações; a maioria segue o padrão. +;; CLISP é um bom ponto de partida. + +;; Bibliotecas são gerenciadas através do Quicklisp.org's Quicklisp systemm. + +;; Common Lisp é normalmente desenvolvido com um editor de texto e um REPL +;; (Read Evaluate Print Loop) rodando ao mesmo tempo. O REPL permite exploração +;; interativa do programa como ele é "ao vivo" no sistema. + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 1. Tipos Primitivos e Operadores +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Símbolos + +'foo ; => FOO Perceba que um símbolo é automáticamente convertido para maíusculo. + +;; Intern manualmente cria um símbolo a partir de uma string. + +(intern "AAAA") ; => AAAA + +(intern "aaa") ; => |aaa| + +;;; Números +9999999999999999999999 ; inteiro +#b111 ; binário => 7 +#o111 ; octal => 73 +#x111 ; hexadecimal => 273 +3.14159s0 ; single +3.14159d0 ; double +1/2 ; ratios +#C(1 2) ; números complexos + + +;; Funções são escritas como (f x y z ...) +;; onde f é uma função e x, y, z, ... são operadores +;; Se você quiser criar uma lista literal de dados, use ' para evitar +;; que a lista seja avaliada - literalmente, "quote" os dados. +'(+ 1 2) ; => (+ 1 2) +;; Você também pode chamar uma função manualmente: +(funcall #'+ 1 2 3) ; => 6 +;; O mesmo para operações aritiméticas +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + + ;;; Booleans +t ; para true (qualquer valor não nil é true) +nil ; para false - e para lista vazia +(not nil) ; => t +(and 0 t) ; => t +(or 0 nil) ; => 0 + + ;;; Caracteres +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + +;;; String são arrays de caracteres com tamanho fixo. +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; barra é um escape de caracter + +;; String podem ser concatenadas também! +(concatenate 'string "Hello " "world!") ; => "Hello world!" + +;; Uma String pode ser tratada como uma sequência de caracteres +(elt "Apple" 0) ; => #\A + +;; format pode ser usado para formatar strings +(format nil "~a can be ~a" "strings" "formatted") + +;; Impimir é bastante fácil; ~% indica nova linha +(format t "Common Lisp is groovy. Dude.~%") + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variáveis +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Você pode criar uma global (escopo dinâmico) usando defparameter +;; um nome de variável pode conter qualquer caracter, exceto: ()",'`;#|\ + +;; Variáveis de escopo dinâmico devem ter asteriscos em seus nomes! + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;; Você pode usar caracteres unicode também. +(defparameter *AΛB* nil) + + +;; Acessando uma variável anteriormente não ligada é um +;; comportamento não definido (mas possível). Não faça isso. + +;; Ligação local: `me` é vinculado com "dance with you" somente dentro +;; de (let ... ). Let permite retornar o valor do último `form` no form let. + +(let ((me "dance with you")) + me) +;; => "dance with you" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Estruturas e Coleções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Estruturas +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) + +(dog-p *rover*) ; => t ;; ewww) +(dog-name *rover*) ; => "rover" + +;; Dog-p, make-dog, and dog-name foram todas criadas por defstruct! + +;;; Pares +;; `cons' constroi pares, `car' and `cdr' extrai o primeiro +;; e o segundo elemento +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + +;;; Listas + +;; Listas são estruturas de dados do tipo listas encadeadas, criadas com `cons' +;; pares e terminam `nil' (ou '()) para marcar o final da lista +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) +;; `list' é um construtor conveniente para listas +(list 1 2 3) ; => '(1 2 3) +;; e a quote (') também pode ser usado para um valor de lista literal +'(1 2 3) ; => '(1 2 3) + +;; Ainda pode-se usar `cons' para adicionar um item no começo da lista. +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; Use `append' para - surpreendentemente - juntar duas listas +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; Ou use concatenate - + +(concatenate 'list '(1 2) '(3 4)) + +;; Listas são um tipo muito central, então existe uma grande variedade de +;; funcionalidades para eles, alguns exemplos: +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => nil +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; Vetores + +;; Vector's literais são arrays de tamanho fixo. +#(1 2 3) ; => #(1 2 3) + +;; Use concatenate para juntar dois vectors +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; Arrays + +;; Ambos vetores e strings são um caso especial de arrays. + +;; 2D arrays + +(make-array (list 2 2)) + +;; (make-array '(2 2)) também funciona. + +; => #2A((0 0) (0 0)) + +(make-array (list 2 2 2)) + +; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;; Cuidado - os valores de inicialição padrões são +;; definidos pela implementção. Aqui vai como defini-lós. + +(make-array '(2) :initial-element 'unset) + +; => #(UNSET UNSET) + +;; E, para acessar o element em 1,1,1 - +(aref (make-array (list 2 2 2)) 1 1 1) + +; => 0 + +;;; Vetores Ajustáveis + +;; Vetores ajustáveis tem a mesma representação impressa que os vectores +;; de tamanho fixo +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) + +*adjvec* ; => #(1 2 3) + +;; Adicionando novo elemento +(vector-push-extend 4 *adjvec*) ; => 3 + +*adjvec* ; => #(1 2 3 4) + + + +;;; Ingenuamente, conjuntos são apenas listas: + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;; Mas você irá querer usar uma estrutura de dados melhor que uma lista encadeada. +;; para performance. + +;;; Dicionários são implementados como hash tables + +;; Cria um hash table +(defparameter *m* (make-hash-table)) + +;; seta um valor +(setf (gethash 'a *m*) 1) + +;; Recupera um valor +(gethash 'a *m*) ; => 1, t + +;; Detalhe - Common Lisp tem multiplos valores de retorno possíveis. gethash +;; retorna t no segundo valor se alguma coisa foi encontrada, e nil se não. + +;; Recuperando um valor não presente retorna nil + (gethash 'd *m*) ;=> nil, nil + +;; Você pode fornecer um valor padrão para uma valores não encontrados +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;; Vamos tratas múltiplos valores de rotorno aqui. + +(multiple-value-bind + (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind + (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Funções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `lambda' para criar funções anônimas +;; Uma função sempre retorna um valor da última expressão avaliada. +;; A representação exata impressão de uma função varia de acordo ... + +(lambda () "Hello World") ; => # + +;; Use funcall para chamar uma função lambda. +(funcall (lambda () "Hello World")) ; => "Hello World" + +;; Ou Apply +(apply (lambda () "Hello World") nil) ; => "Hello World" + +;; "De-anonymize" a função +(defun hello-world () + "Hello World") +(hello-world) ; => "Hello World" + +;; O () acima é a lista de argumentos da função. +(defun hello (name) + (format nil "Hello, ~a " name)) + +(hello "Steve") ; => "Hello, Steve" + +;; Funções podem ter argumentos opcionais; eles são nil por padrão + +(defun hello (name &optional from) + (if from + (format t "Hello, ~a, from ~a" name from) + (format t "Hello, ~a" name))) + + (hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas + +;; E os padrões podem ser configurados... +(defun hello (name &optional (from "The world")) + (format t "Hello, ~a, from ~a" name from)) + +(hello "Steve") +; => Hello, Steve, from The world + +(hello "Steve" "the alpacas") +; => Hello, Steve, from the alpacas + + +;; E é claro, palavras-chaves são permitidas também... frequentemente mais +;; flexivel que &optional. + +(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) + (format t "Hello, ~a ~a, from ~a" honorific name from)) + +(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world + +(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") +; => Hello, Mr Jim, from the alpacas you met last summer + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Igualdade +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Common Lisp tem um sistema sofisticado de igualdade. Alguns são cobertos aqui. + +;; Para número use `=' +(= 3 3.0) ; => t +(= 2 1) ; => nil + +;; para identidade de objeto (aproximadamente) use `eql` +(eql 3 3) ; => t +(eql 3 3.0) ; => nil +(eql (list 3) (list 3)) ; => nil + +;; para listas, strings, e para pedaços de vetores use `equal' +(equal (list 'a 'b) (list 'a 'b)) ; => t +(equal (list 'a 'b) (list 'b 'a)) ; => nil + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Fluxo de Controle +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Condicionais + +(if t ; testa a expressão + "this is true" ; então expressão + "this is false") ; senão expressão +; => "this is true" + +;; Em condicionais, todos valores não nulos são tratados como true +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;; `cond' encadeia uma série de testes para selecionar um resultado +(cond ((> 2 2) (error "wrong!")) + ((< 2 2) (error "wrong again!")) + (t 'ok)) ; => 'OK + +;; Typecase é um condicional que escolhe uma de seus cláusulas com base do tipo do valor + +(typecase 1 + (string :string) + (integer :int)) + +; => :int + +;;; Interação + +;; Claro que recursão é suportada: + +(defun walker (n) + (if (zerop n) + :walked + (walker (1- n)))) + +(walker 5) ; => :walked + +;; Na maioria das vezes, nós usamos DOTLISO ou LOOP + +(dolist (i '(1 2 3 4)) + (format t "~a" i)) + +; => 1234 + +(loop for i from 0 below 10 + collect i) + +; => (0 1 2 3 4 5 6 7 8 9) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutação +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `setf' para atribuir um novo valor para uma variável existente. Isso foi +;; demonstrado anteriormente no exemplo da hash table. + +(let ((variable 10)) + (setf variable 2)) + ; => 2 + + +;; Um bom estilo Lisp é para minimizar funções destrutivas e para evitar +;; mutação quando razoável. + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Classes e Objetos +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Sem clases Animal, vamos usar os veículos de transporte de tração +;; humana mecânicos. + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "A human powered conveyance")) + +;; defcalss, seguido do nome, seguido por uma list de superclass, +;; seguido por um uma 'slot list', seguido por qualidades opcionais como +;; :documentation + +;; Quando nenhuma lista de superclasse é setada, uma lista padrão para +;; para o objeto padrão é usada. Isso *pode* ser mudado, mas não até você +;; saber o que está fazendo. Olhe em Art of the Metaobject Protocol +;; para maiores informações. + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + + +;; Chamando DESCRIBE na classe human-powered-conveyance no REPL dá: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;; Note o comportamento reflexivo disponível para você! Common Lisp é +;; projetada para ser um sistema interativo. + +;; Para definir um métpdo, vamos encontrar o que nossa cirunferência da +;; roda da bicicleta usando a equação: C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;; pi já é definido para a gente em Lisp! + +;; Vamos supor que nós descobrimos que o valor da eficiência do número +;; de remadores em uma canoa é aproximadamente logarítmica. Isso provavelmente deve ser definido +;; no construtor / inicializador. + +;; Veja como initializar sua instância após Common Lisp ter construído isso: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + +;; Em seguida, para a construção de uma ocorrência e verificar a eficiência média ... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros permitem que você estenda a sintaxe da lingaugem + +;; Common Lisp nãov vem com um loop WHILE- vamos adicionar um. +;; Se obedecermos nossos instintos 'assembler', acabamos com: + +(defmacro while (condition &body body) + "Enquanto `condition` é verdadeiro, `body` é executado. + +`condition` é testado antes de cada execução do `body`" + (let ((block-name (gensym))) + `(tagbody + (unless ,condition + (go ,block-name)) + (progn + ,@body) + ,block-name))) + +;; Vamos dar uma olhada em uma versão alto nível disto: + + +(defmacro while (condition &body body) + "Enquanto `condition` for verdadeira, `body` é executado. + +`condition` é testado antes de cada execução do `body`" + `(loop while ,condition + do + (progn + ,@body))) + +;; Entretanto, com um compilador moderno, isso não é preciso; o LOOP +;; 'form' compila igual e é bem mais fácil de ler. + +;; Noteq ue ``` é usado , bem como `,` e `@`. ``` é um operador 'quote-type' +;; conhecido como 'quasiquote'; isso permite o uso de `,` . `,` permite "unquoting" +;; e variáveis. @ interpolará listas. + +;; Gensym cria um símbolo único garantido que não existe em outras posições +;; o sistema. Isto é porque macros são expandidas em tempo de compilação e +;; variáveis declaradas na macro podem colidir com as variáveis usadas na +;; código regular. + +;; Veja Practical Common Lisp para maiores informações sobre macros. +``` + + +## Leitura Adicional + +[Continua em frente com Practical Common Lisp book.](http://www.gigamonkeys.com/book/) + + +## Créditos + +Muitos agradecimentos ao pessoal de Schema fornecer um grande ponto de partida +o que facilitou muito a migração para Common Lisp. + +- [Paul Khuong](https://github.com/pkhuong) pelas grandes revisiões. -- cgit v1.2.3 From 0b65be8f0c876a10fb2ac823d5c551f90d7ef51e Mon Sep 17 00:00:00 2001 From: elf Date: Fri, 26 Dec 2014 09:06:38 -0200 Subject: Removing comments... --- pt-br/common-lisp-pt.html.markdown | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index a2506aec..ba45c4ed 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -1,27 +1,19 @@ --- - language: "Common Lisp" -filename: commonlisp.lisp +filename: commonlisp-pt.lisp contributors: - ["Paul Nathan", "https://github.com/pnathan"] +translators: + - ["Édipo Luis Féderle", "https://github.com/edipofederle"] --- - - - - ANSI Common Lisp é uma linguagem de uso geral, multi-paradigma, designada para uma variedade de aplicações na indústria. É frequentemente citada como uma linguagem de programação programável. - - O ponto inicial clássico é [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/) - - - Outro livro recente e popular é o [Land of Lisp](http://landoflisp.com/). @@ -34,25 +26,17 @@ Outro livro recente e popular é o ;;; "Form" Geral - - ;; Lisp tem dois pedaços fundamentais de sintaxe: o ATOM e S-expression. ;; Tipicamente, S-expressions agrupadas são chamadas de `forms`. - -10 ; um atom; é avaliado para ele mesmo - +10 ; um atom; é avaliado para ele mesmo :THING ;Outro atom; avaliado para o símbolo :thing. - - t ; outro atom, denotado true. - - (+ 1 2 3 4) ; uma s-expression '(4 :foo t) ;outra s-expression -- cgit v1.2.3 From a56473fc318aefbe279077c9fa6efc275894ab39 Mon Sep 17 00:00:00 2001 From: elf Date: Fri, 26 Dec 2014 09:15:03 -0200 Subject: clean up and improvements --- pt-br/common-lisp-pt.html.markdown | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index ba45c4ed..b154c544 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -12,7 +12,7 @@ para uma variedade de aplicações na indústria. É frequentemente citada como uma linguagem de programação programável. -O ponto inicial clássico é [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/) +O ponto inicial clássico é [Practical Common Lisp e livremente disponível](http://www.gigamonkeys.com/book/) Outro livro recente e popular é o [Land of Lisp](http://landoflisp.com/). @@ -60,7 +60,7 @@ t ; outro atom, denotado true. ;; Existe uma variedade de implementações; a maioria segue o padrão. ;; CLISP é um bom ponto de partida. -;; Bibliotecas são gerenciadas através do Quicklisp.org's Quicklisp systemm. +;; Bibliotecas são gerenciadas através do Quicklisp.org's Quicklisp sistema. ;; Common Lisp é normalmente desenvolvido com um editor de texto e um REPL ;; (Read Evaluate Print Loop) rodando ao mesmo tempo. O REPL permite exploração @@ -73,7 +73,7 @@ t ; outro atom, denotado true. ;;; Símbolos -'foo ; => FOO Perceba que um símbolo é automáticamente convertido para maíusculo. +'foo ; => FOO Perceba que um símbolo é automáticamente convertido para maiúscula. ;; Intern manualmente cria um símbolo a partir de uma string. @@ -413,7 +413,8 @@ nil ; para false - e para lista vazia ((< 2 2) (error "wrong again!")) (t 'ok)) ; => 'OK -;; Typecase é um condicional que escolhe uma de seus cláusulas com base do tipo do valor +;; Typecase é um condicional que escolhe uma de seus cláusulas com base do tipo +;; do seu valor (typecase 1 (string :string) @@ -542,8 +543,8 @@ nil ; para false - e para lista vazia ;; pi já é definido para a gente em Lisp! ;; Vamos supor que nós descobrimos que o valor da eficiência do número -;; de remadores em uma canoa é aproximadamente logarítmica. Isso provavelmente deve ser definido -;; no construtor / inicializador. +;; de remadores em uma canoa é aproximadamente logarítmica. Isso provavelmente +;; deve ser definido no construtor / inicializador. ;; Veja como initializar sua instância após Common Lisp ter construído isso: @@ -564,7 +565,7 @@ nil ; para false - e para lista vazia ;; Macros permitem que você estenda a sintaxe da lingaugem -;; Common Lisp nãov vem com um loop WHILE- vamos adicionar um. +;; Common Lisp não vem com um loop WHILE - vamos adicionar um. ;; Se obedecermos nossos instintos 'assembler', acabamos com: (defmacro while (condition &body body) -- cgit v1.2.3 From f4c735c05021418bf8e207d49619397bfe37eff7 Mon Sep 17 00:00:00 2001 From: elf Date: Fri, 26 Dec 2014 09:19:21 -0200 Subject: fix. --- pt-br/common-lisp-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index b154c544..5561c23d 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -178,7 +178,7 @@ nil ; para false - e para lista vazia (dog-p *rover*) ; => t ;; ewww) (dog-name *rover*) ; => "rover" -;; Dog-p, make-dog, and dog-name foram todas criadas por defstruct! +;; Dog-p, make-dog, e dog-name foram todas criadas por defstruct! ;;; Pares ;; `cons' constroi pares, `car' and `cdr' extrai o primeiro @@ -615,7 +615,7 @@ nil ; para false - e para lista vazia ## Créditos -Muitos agradecimentos ao pessoal de Schema fornecer um grande ponto de partida +Muitos agradecimentos ao pessoal de Schema por fornecer um grande ponto de partida o que facilitou muito a migração para Common Lisp. - [Paul Khuong](https://github.com/pkhuong) pelas grandes revisiões. -- cgit v1.2.3 From b59262601656a0f803729d37b6c83d414af0457a Mon Sep 17 00:00:00 2001 From: elf Date: Fri, 26 Dec 2014 09:20:30 -0200 Subject: fix word --- pt-br/common-lisp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index 5561c23d..ce654846 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -618,4 +618,4 @@ nil ; para false - e para lista vazia Muitos agradecimentos ao pessoal de Schema por fornecer um grande ponto de partida o que facilitou muito a migração para Common Lisp. -- [Paul Khuong](https://github.com/pkhuong) pelas grandes revisiões. +- [Paul Khuong](https://github.com/pkhuong) pelas grandes revisões. -- cgit v1.2.3 From 1c52c5ea125285eb8a3af5cf4cb510e9c3e7a49b Mon Sep 17 00:00:00 2001 From: ven Date: Mon, 29 Dec 2014 22:48:01 +0100 Subject: @wryk++ --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 1536b152..b10e04bf 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -212,7 +212,7 @@ say $x; #=> 52 # - `if` # Before talking about `if`, we need to know which values are "Truthy" # (represent True), and which are "Falsey" (or "Falsy") -- represent False. -# Only these values are Falsey: (), 0, "0", Nil, A type (like `Str` or `Int`), +# Only these values are Falsey: (), 0, "0", "", Nil, A type (like `Str` or `Int`), # and of course False itself. # Every other value is Truthy. if True { -- cgit v1.2.3 From 228cc6ec5ae0d20a94292c66cf43e44755d3758b Mon Sep 17 00:00:00 2001 From: Cameron Steele Date: Mon, 29 Dec 2014 15:00:12 -0800 Subject: typo in Haxe documentation --- haxe.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 6a868f09..8599de8d 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -484,7 +484,7 @@ class LearnHaxe3{ // we can read this variable trace(foo_instance.public_read + " is the value for foo_instance.public_read"); // but not write it - // foo_instance.public_write = 4; // this will throw an error if uncommented: + // foo_instance.public_read = 4; // this will throw an error if uncommented: // trace(foo_instance.public_write); // as will this. trace(foo_instance + " is the value for foo_instance"); // calls the toString method -- cgit v1.2.3 From 427875663c221ae11ff3b8a8a6e6d66e89b36ac2 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 11:56:23 +0200 Subject: basic --- tr-tr/csharp-tr.html.markdown | 824 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 824 insertions(+) create mode 100644 tr-tr/csharp-tr.html.markdown diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown new file mode 100644 index 00000000..ecbc2b18 --- /dev/null +++ b/tr-tr/csharp-tr.html.markdown @@ -0,0 +1,824 @@ +--- +language: c# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] + - ["Max Yankov", "https://github.com/golergka"] + - ["Melvyn Laïly", "http://x2a.yt"] + - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] + - ["Melih Mucuk", "http://melihmucuk.com"] +filename: LearnCSharp.cs +--- + +C# zarif ve tip güvenli nesne yönelimli bir dil olup geliştiricilerin .NET framework üzerinde çalışan güçlü ve güvenli uygulamalar geliştirmesini sağlar. + +[Daha fazlasını okuyun.](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) + +```c# +// Tek satırlık yorumlar // ile başlar +/* +Birden fazla satırlı yorumlar buna benzer +*/ +/// +/// Bu bir XML dokümantasyon yorumu +/// + +// Uygulamanın kullanacağı ad alanlarını belirtin +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +using System.Net; +using System.Threading.Tasks; +using System.IO; + +// Kodu düzenlemek için paketler içinde alan tanımlayın +namespace Learning +{ + // Her .cs dosyası, dosya ile aynı isimde en az bir sınıf içermeli + // bu kurala uymak zorunda değilsiniz ancak mantıklı olan yol budur. + public class LearnCSharp + { + // TEMEL SÖZ DİZİMİ - daha önce Java ya da C++ kullandıysanız İLGİNÇ ÖZELLİKLER'e geçin + public static void Syntax() + { + // Satırları yazdırmak için Console.WriteLine kullanın + Console.WriteLine("Merhaba Dünya"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Yeni satıra geçmeden yazdırmak için Console.Write kullanın + Console.Write("Merhaba "); + Console.Write("Dünya"); + + /////////////////////////////////////////////////// + // Tipler & Değişkenler + // + // Bir değişken tanımlamak için kullanın + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - 16-bit integer + // Signed - (-32,768 <= short <= 32,767) + // Unsigned - (0 <= ushort <= 65,535) + short fooShort = 10000; + ushort fooUshort = 10000; + + // Integer - 32-bit integer + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) + + // Long - 64-bit integer + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // Numbers default to being int or uint depending on size. + // L is used to denote that this variable value is of type long or ulong + + // Double - Double-precision 64-bit IEEE 754 Floating Point + double fooDouble = 123.4; // Precision: 15-16 digits + + // Float - Single-precision 32-bit IEEE 754 Floating Point + float fooFloat = 234.5f; // Precision: 7 digits + // f is used to denote that this variable value is of type float + + // Decimal - a 128-bits data type, with more precision than other floating-point types, + // suited for financial and monetary calculations + decimal fooDecimal = 150.3m; + + // Boolean - true & false + bool fooBoolean = true; // or false + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // 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 = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; + Console.WriteLine(fooString); + + // You can access each character of the string with an indexer: + char charFromString = fooString[1]; // => 'e' + // Strings are immutable: you can't do fooString[1] = 'X'; + + // Compare strings with current culture, ignoring case + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // Formatting, based on sprintf + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + + // Dates & Formatting + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // You can split a string over two lines with the @ symbol. To escape " use "" + string bazString = @"Here's some stuff +on a new line! ""Wow!"", the masses cried"; + + // Use const or read-only to make a variable immutable + // const values are calculated at compile time + const int HOURS_I_WORK_PER_WEEK = 9001; + + /////////////////////////////////////////////////// + // Data Structures + /////////////////////////////////////////////////// + + // Arrays - zero indexed + // The array size must be decided upon declaration + // The format for declaring an array is follows: + // [] = new []; + int[] intArray = new int[10]; + + // Another way to declare & initialize an array + int[] y = { 9000, 1000, 1337 }; + + // Indexing an array - Accessing an element + Console.WriteLine("intArray @ 0: " + intArray[0]); + // Arrays are mutable. + intArray[1] = 1; + + // Lists + // Lists are used more frequently than arrays as they are more flexible + // The format for declaring a list is follows: + // List = new List(); + List intList = new List(); + List stringList = new List(); + List z = new List { 9000, 1000, 1337 }; // intialize + // The <> are for generics - Check out the cool stuff section + + // Lists don't default to a value; + // A value must be added before accessing the index + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + // Others data structures to check out: + // Stack/Queue + // Dictionary (an implementation of a hash map) + // HashSet + // Read-only Collections + // Tuple (.Net 4+) + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Comparison operators + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Ternary operators + // A simple if/else can be written as follows + // ? : + string isTrue = (true) ? "True" : "False"; + + // While loop + int fooWhile = 0; + while (fooWhile < 100) + { + //Iterated 100 times, fooWhile 0->99 + fooWhile++; + } + + // Do While Loop + int fooDoWhile = 0; + do + { + //Iterated 100 times, fooDoWhile 0->99 + fooDoWhile++; + } while (fooDoWhile < 100); + + //for loop structure => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + //Iterated 10 times, fooFor 0->9 + } + + // For Each Loop + // foreach loop structure => foreach( in ) + // The foreach loop loops over any object implementing IEnumerable or IEnumerable + // 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()) + { + //Iterated over all the characters in the string + } + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), + // the String class, and a few special classes that wrap + // primitive types: Character, Byte, Short, and Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + 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; + } + + /////////////////////////////////////// + // Converting Data Types And Typecasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + // this will throw an Exception on failure + int.Parse("123");//returns an integer version of "123" + + // try parse will default to type default on failure + // in this case: 0 + int tryInt; + if (int.TryParse("123", out tryInt)) // Function is boolean + Console.WriteLine(tryInt); // 123 + + // Convert Integer To String + // Convert class has a number of methods to facilitate conversions + Convert.ToString(123); + // or + tryInt.ToString(); + } + + /////////////////////////////////////// + // CLASSES - see definitions at end of file + /////////////////////////////////////// + public static void Classes() + { + // See Declaration of objects at end of file + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.SpeedUp(3); // You should always use setter and getter methods + trek.Cadence = 100; + + // ToString is a convention to display the value of this Object. + Console.WriteLine("trek info: " + trek.Info()); + + // Instantiate a new Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.Info()); + + Console.Read(); + } // End main method + + // CONSOLE ENTRY A console application must have a main method as an entry point + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // INTERESTING FEATURES + // + + // DEFAULT METHOD SIGNATURES + + public // Visibility + static // Allows for direct call on class without object + int // Return Type, + MethodSignatures( + int maxCount, // First variable, expects an int + int count = 0, // will default the value to 0 if not passed in + int another = 3, + params string[] otherParams // captures all other parameters passed to method + ) + { + return -1; + } + + // Methods can have the same name, as long as the signature is unique + public static void MethodSignatures(string maxCount) + { + } + + // GENERICS + // The classes for TKey and TValue is specified by the user calling this function. + // This method emulates the SetDefault of Python + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // You can narrow down the objects that are passed in + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // We can iterate, since T is a IEnumerable + foreach (var item in toPrint) + // Item is an int + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // OPTIONAL PARAMETERS + MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); + MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + + // EXTENSION METHODS + int i = 3; + i.Print(); // Defined below + + // NULLABLE TYPES - great for database interaction / return values + // any value type (i.e. not a class) can be made nullable by suffixing a ? + // ? = + int? nullable = null; // short hand for Nullable + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // true if not null + + // ?? is syntactic sugar for specifying default value (coalesce) + // in case variable is null + int notNullable = nullable ?? 0; // 0 + + // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: + var magic = "magic is a string, at compile time, so you still get type safety"; + // magic = 9; will not work as magic is a string, not an int + + // GENERICS + // + var phonebook = new Dictionary() { + {"Sarah", "212 555 5555"} // Add some entries to the phone book + }; + + // Calling SETDEFAULT defined as a generic above + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone + // nb, you don't need to specify the TKey and TValue since they can be + // derived implicitly + Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 + + // LAMBDA EXPRESSIONS - allow you to write code in line + Func square = (x) => x * x; // Last T item is the return value + Console.WriteLine(square(3)); // 9 + + // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. + // Most of objects that access unmanaged resources (file handle, device contexts, etc.) + // implement the IDisposable interface. The using statement takes care of + // cleaning those IDisposable objects for you. + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Nothing suspicious here"); + // At the end of scope, resources will be released. + // Even if an exception is thrown. + } + + // PARALLEL FRAMEWORK + // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary(); + + // Will spin up separate threads for each request, and join on them + // before going to the next step! + Parallel.ForEach(websites, + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads + website => + { + // Do something that takes a long time on the file + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // This won't happen till after all requests have been completed + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // DYNAMIC OBJECTS (great for working with other languages) + dynamic student = new ExpandoObject(); + student.FirstName = "First Name"; // No need to define class first! + + // You can even add methods (returns a string, and takes in a string) + student.Introduce = new Func( + (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE - almost all collections implement this, which gives you a lot of + // very useful Map / Filter / Reduce style methods + var bikes = new List(); + bikes.Sort(); // Sorts the array + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels + var result = bikes + .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable + + var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection + + // Create a list of IMPLICIT objects based on some parameters of the bike + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Hard to show here, but you get type ahead completion since the compiler can implicitly work + // out the types above! + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + // ASPARALLEL + // And this is where things get wicked - combines linq and parallel operations + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // this will happen in parallel! Threads will automagically be spun up and the + // results divvied amongst them! Amazing for large datasets when you have lots of + // cores + + // LINQ - maps a store to IQueryable objects, with delayed execution + // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document + var db = new BikeRepository(); + + // execution is delayed, which is great when querying a database + var filter = db.Bikes.Where(b => b.HasTassles); // no query run + if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality + filter = filter.Where(b => b.IsBroken); // no query run + + var query = filter + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // still no query run + + // Now the query runs, but opens a reader, so only populates are you iterate through + foreach (string bike in query) + Console.WriteLine(result); + + + + } + + } // End LearnCSharp class + + // You can include other classes in a .cs file + + public static class Extensions + { + // EXTENSION FUNCTIONS + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } + + // Class Declaration Syntax: + // class { + // //data fields, constructors, functions all inside. + // //functions are called as methods in Java. + // } + + public class Bicycle + { + // Bicycle's Fields/Variables + public int Cadence // Public: Can be accessed from anywhere + { + get // get - define a method to retrieve the property + { + return _cadence; + } + set // set - define a method to set a proprety + { + _cadence = value; // Value is the value passed in to the setter + } + } + private int _cadence; + + protected virtual int Gear // Protected: Accessible from the class and subclasses + { + get; // creates an auto property so you don't need a member field + set; + } + + internal int Wheels // Internal: Accessible from within the assembly + { + get; + private set; // You can set modifiers on the get/set methods + } + + int _speed; // Everything is private by default: Only accessible from within this class. + // can also use keyword private + public string Name { get; set; } + + // 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 BikeBrand + { + AIST, + BMC, + Electra = 42, //you can explicitly set a value to a name + Gitane // 43 + } + // 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 BikeBrand 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. + // You can access them without a reference to any object: + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + static public int BicyclesCreated = 0; + + // readonly values are set at run time + // they can only be assigned upon declaration or in a constructor + readonly bool _hasCardsInSpokes = false; // read-only private + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() + { + this.Gear = 1; // you can access members of the object with the keyword this + Cadence = 50; // but you don't always need it + _speed = 5; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // calls base first + { + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; + } + + // Constructors can be chained + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) + { + } + + // Function Syntax: + // () + + // classes can implement getters and setters for their fields + // or they can implement properties (this is the preferred way in C#) + + // 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; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // properties get/set values + // when only data needs to be accessed, consider using properties. + // properties may have either get or set, or both + private bool _hasTassles; // private variable + public bool HasTassles // public accessor + { + 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 + { + get; + // you are able to specify access modifiers for either get or set + // this means only Bicycle class can call set on Framesize + private set; + } + + // It's also possible to define custom Indexers on objects. + // All though this is not entirely useful in this example, you + // could do bicycle[0] which yields "chris" to get the first passenger or + // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) + private string[] passengers = { "chris", "phil", "darren", "regina" } + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + return passengers[i] = value; + } + } + + //Method to display the attribute values of this Object. + public virtual string Info() + { + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + + // 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 members + return BicyclesCreated > 9000; + } // If your class only needs static members, consider marking the class itself as static. + + + } // end class Bicycle + + // PennyFarthing is a subclass of Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + // calling parent constructor + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) + { + } + + protected override int Gear + { + get + { + return 0; + } + set + { + throw new ArgumentException("You can't change gears on a PennyFarthing"); + } + } + + public override string Info() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Calling the base version of the method + return result; + } + } + + // Interfaces only contain signatures of the members, without the implementation. + interface IJumpable + { + void Jump(int meters); // all interface members are implicitly public + } + + interface IBreakable + { + 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 + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public bool Broken + { + get + { + return damage > 100; + } + } + } + + /// + /// Used to connect to DB for LinqToSql example. + /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// + public class BikeRepository : DbSet + { + public BikeRepository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // End Namespace +``` + +## Topics Not Covered + + * Flags + * Attributes + * Static properties + * Exceptions, Abstraction + * ASP.NET (Web Forms/MVC/WebMatrix) + * Winforms + * Windows Presentation Foundation (WPF) + +## Further Reading + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + + + +[C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) -- cgit v1.2.3 From 32174fe9ce787f9135bda27dd3d3fddc9b0225bd Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 12:01:40 +0200 Subject: types --- tr-tr/csharp-tr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index ecbc2b18..29c29145 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -81,8 +81,8 @@ namespace Learning // Long - 64-bit integer long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) - // Numbers default to being int or uint depending on size. - // L is used to denote that this variable value is of type long or ulong + // Sayılar boyutlarına göre ön tanımlı olarak int ya da uint olabilir. + // L, bir değerin long ya da ulong tipinde olduğunu belirtmek için kullanılır. // Double - Double-precision 64-bit IEEE 754 Floating Point double fooDouble = 123.4; // Precision: 15-16 digits -- cgit v1.2.3 From 20a921fd03a8274e817944f5732b7b69f4267abd Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 16:07:18 +0200 Subject: arrays --- tr-tr/csharp-tr.html.markdown | 52 +++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 29c29145..8c6a7d43 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -82,63 +82,63 @@ namespace Learning long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) // Sayılar boyutlarına göre ön tanımlı olarak int ya da uint olabilir. - // L, bir değerin long ya da ulong tipinde olduğunu belirtmek için kullanılır. + // L, değişken değerinin long ya da ulong tipinde olduğunu belirtmek için kullanılır. - // Double - Double-precision 64-bit IEEE 754 Floating Point - double fooDouble = 123.4; // Precision: 15-16 digits + // Double - Çift hassasiyetli 64-bit IEEE 754 kayan sayı + double fooDouble = 123.4; // Hassasiyet: 15-16 basamak - // Float - Single-precision 32-bit IEEE 754 Floating Point - float fooFloat = 234.5f; // Precision: 7 digits - // f is used to denote that this variable value is of type float + // Float - Tek hassasiyetli 32-bit IEEE 754 kayan sayı + float fooFloat = 234.5f; // Hassasiyet: 7 basamak + // f, değişken değerinin float tipinde olduğunu belirtmek için kullanılır. - // Decimal - a 128-bits data type, with more precision than other floating-point types, - // suited for financial and monetary calculations + // Decimal - 128-bit veri tiğinde ve diğer kayan sayı veri tiplerinden daha hassastır, + // finansal ve mali hesaplamalar için uygundur. decimal fooDecimal = 150.3m; // Boolean - true & false - bool fooBoolean = true; // or false + bool fooBoolean = true; // veya false - // Char - A single 16-bit Unicode character + // Char - 16-bitlik tek bir unicode karakter char fooChar = 'A'; - // 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 + // Strings -- Önceki baz tiplerinin hepsi değer tipiyken, + // string bir referans tipidir. Null değer atayabilirsiniz string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; Console.WriteLine(fooString); - // You can access each character of the string with an indexer: + // İndeks numarası kullanarak bir string'in bütün karakterlerine erişilebilirsiniz: char charFromString = fooString[1]; // => 'e' - // Strings are immutable: you can't do fooString[1] = 'X'; + // String'ler değiştirilemez: fooString[1] = 'X' işlemini yapamazsınız; - // Compare strings with current culture, ignoring case + // String'leri geçerli kültür değeri ve büyük küçük harf duyarlılığı olmadan karşılaştırma string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); - // Formatting, based on sprintf + // sprintf baz alınarak formatlama string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); - // Dates & Formatting + // Tarihler & Formatlama DateTime fooDate = DateTime.Now; Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - // You can split a string over two lines with the @ symbol. To escape " use "" + // Bir string'i iki satıra bölmek için @ sembolü kullanabilirsiniz. " işaretinden kaçmak için "" kullanın string bazString = @"Here's some stuff on a new line! ""Wow!"", the masses cried"; - // Use const or read-only to make a variable immutable - // const values are calculated at compile time + // Bir değişkeni değiştirilemez yapmak için const ya da read-only kullanın. + // const değerleri derleme sırasında hesaplanır const int HOURS_I_WORK_PER_WEEK = 9001; /////////////////////////////////////////////////// - // Data Structures + // Veri Yapıları /////////////////////////////////////////////////// - // Arrays - zero indexed - // The array size must be decided upon declaration - // The format for declaring an array is follows: - // [] = new []; + // Diziler - Sıfır indeksli + // Dizi boyutuna tanımlama sırasında karar verilmelidir. + // Dizi tanımlama formatı şöyledir: + // [] = new []; int[] intArray = new int[10]; - // Another way to declare & initialize an array + // Bir diğer dizi tanımlama formatı şöyledir: int[] y = { 9000, 1000, 1337 }; // Indexing an array - Accessing an element -- cgit v1.2.3 From 4ba98e1b9782ac8dc1a476296fb9cf1095943787 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 16:46:49 +0200 Subject: swithc case --- tr-tr/csharp-tr.html.markdown | 98 +++++++++++++++++++++---------------------- 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 8c6a7d43..1ecf18e8 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -141,46 +141,46 @@ on a new line! ""Wow!"", the masses cried"; // Bir diğer dizi tanımlama formatı şöyledir: int[] y = { 9000, 1000, 1337 }; - // Indexing an array - Accessing an element + // Bir diziyi indeksleme - Bir elemente erişme Console.WriteLine("intArray @ 0: " + intArray[0]); - // Arrays are mutable. + // Diziler değiştirilebilir. intArray[1] = 1; - // Lists - // Lists are used more frequently than arrays as they are more flexible - // The format for declaring a list is follows: - // List = new List(); + // Listeler + // Listeler daha esnek oldukları için dizilerden daha sık kullanılırlar. + // Bir liste tanımlama formatı şöyledir: + // List = new List(); List intList = new List(); List stringList = new List(); - List z = new List { 9000, 1000, 1337 }; // intialize - // The <> are for generics - Check out the cool stuff section + List z = new List { 9000, 1000, 1337 }; // tanımlama + // <> işareti genelleme içindir - Güzel özellikler sekmesini inceleyin - // Lists don't default to a value; - // A value must be added before accessing the index + // Listelerin varsayılan bir değeri yoktur; + // İndekse erişmeden önce değer eklenmiş olmalıdır intList.Add(1); Console.WriteLine("intList @ 0: " + intList[0]); - // Others data structures to check out: - // Stack/Queue - // Dictionary (an implementation of a hash map) - // HashSet - // Read-only Collections - // Tuple (.Net 4+) + // Diğer veri yapıları için şunlara bakın: + // Stack/Queue (Yığın/Kuyruk) + // Dictionary (hash map'in uygulanması) (Sözlük) + // HashSet (karma seti) + // Read-only Collections (Değiştirilemez koleksiyonlar) + // Tuple (.Net 4+) (tüp) /////////////////////////////////////// - // Operators + // Operatörler /////////////////////////////////////// Console.WriteLine("\n->Operators"); - int i1 = 1, i2 = 2; // Shorthand for multiple declarations + int i1 = 1, i2 = 2; // Birden çok tanımlamanın kısa yolu - // Arithmetic is straightforward + // Aritmetik basittir Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 - // Modulo + // Mod Console.WriteLine("11%3 = " + (11 % 3)); // => 2 - // Comparison operators + // Karşılaştırma operatörleri Console.WriteLine("3 == 2? " + (3 == 2)); // => false Console.WriteLine("3 != 2? " + (3 != 2)); // => true Console.WriteLine("3 > 2? " + (3 > 2)); // => true @@ -188,17 +188,17 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true - // Bitwise operators! + // Bit düzeyi operatörleri! /* - ~ Unary bitwise complement - << Signed left shift - >> Signed right shift - & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR + ~ Tekli bit tamamlayıcısı + << Sola kaydırma Signed left shift + >> Sağa kaydırma Signed right shift + & Bit düzeyi AND + ^ Bit düzeyi harici OR + | Bit düzeyi kapsayan OR */ - // Incrementations + // Arttırma int i = 0; Console.WriteLine("\n->Inc/Dec-rementation"); Console.WriteLine(i++); //i = 1. Post-Incrementation @@ -207,11 +207,11 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine(--i); //i = 0. Pre-Decrementation /////////////////////////////////////// - // Control Structures + // Kontrol Yapıları /////////////////////////////////////// Console.WriteLine("\n->Control Structures"); - // If statements are c-like + // If ifadesi c benzeridir int j = 10; if (j == 10) { @@ -226,47 +226,47 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("I also don't"); } - // Ternary operators - // A simple if/else can be written as follows - // ? : + // Üçlü operatörler + // Basit bir if/else ifadesi şöyle yazılabilir + // ? : string isTrue = (true) ? "True" : "False"; - // While loop + // While döngüsü int fooWhile = 0; while (fooWhile < 100) { - //Iterated 100 times, fooWhile 0->99 + //100 kere tekrarlanır, fooWhile 0->99 fooWhile++; } - // Do While Loop + // Do While Döngüsü int fooDoWhile = 0; do { - //Iterated 100 times, fooDoWhile 0->99 + //100 kere tekrarlanır, fooDoWhile 0->99 fooDoWhile++; } while (fooDoWhile < 100); - //for loop structure => for(; ; ) + //for döngüsü yapısı => for(; ; ) for (int fooFor = 0; fooFor < 10; fooFor++) { - //Iterated 10 times, fooFor 0->9 + //10 kere tekrarlanır, fooFor 0->9 } - // For Each Loop - // foreach loop structure => foreach( in ) - // The foreach loop loops over any object implementing IEnumerable or IEnumerable - // 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) + // For Each Döngüsü + // foreach döngüsü yapısı => foreach( in ) + // foreach döngüsü, IEnumerable ya da IEnumerable e dönüştürülmüş herhangi bir obje üzerinde döngü yapabilir + // .Net framework üzerindeki bütün koleksiyon tiplerinden (Dizi, Liste, Sözlük...) + // biri ya da hepsi uygulanarak gerçekleştirilebilir. + // (ToCharArray() silindi, çünkü string'ler aynı zamanda IEnumerable'dır.) foreach (char character in "Hello World".ToCharArray()) { - //Iterated over all the characters in the string + //String içindeki bütün karakterler üzerinde döner } // Switch Case - // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), + // Bir switch byte, short, char ve int veri tipleri ile çalışır. + // Aynı zamanda sıralı tipler ilede çalışabilir.(Enum Tipleri bölümünde tartışıldı), // the String class, and a few special classes that wrap // primitive types: Character, Byte, Short, and Integer. int month = 3; -- cgit v1.2.3 From 9b1b260c6c3510ccbcc213dd37175ae4383cf08f Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 17:13:30 +0200 Subject: classes --- tr-tr/csharp-tr.html.markdown | 50 +++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 1ecf18e8..37a1090a 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -266,9 +266,9 @@ on a new line! ""Wow!"", the masses cried"; // Switch Case // Bir switch byte, short, char ve int veri tipleri ile çalışır. - // Aynı zamanda sıralı tipler ilede çalışabilir.(Enum Tipleri bölümünde tartışıldı), - // the String class, and a few special classes that wrap - // primitive types: Character, Byte, Short, and Integer. + // Aynı zamanda sıralı tipler ile de çalışabilir.(Enum Tipleri bölümünde tartışıldı), + // String sınıfı, ve bir kaç özel sınıf kaydırılır + // basit tipler: Character, Byte, Short, and Integer. int month = 3; string monthString; switch (month) @@ -282,9 +282,9 @@ on a new line! ""Wow!"", the masses cried"; 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 + // Bir aksiyon için birden fazla durum atayabilirsiniz + // Ancak, break olmadan yeni bir durum ekleyemezsiniz + // (Eğer bunu yapmak istiyorsanız, goto komutu eklemek zorundasınız) case 6: case 7: case 8: @@ -296,51 +296,51 @@ on a new line! ""Wow!"", the masses cried"; } /////////////////////////////////////// - // Converting Data Types And Typecasting + // Veri Tipleri Dönüştürme ve Typecasting /////////////////////////////////////// - // Converting data + // Veri Dönüştürme - // Convert String To Integer - // this will throw an Exception on failure - int.Parse("123");//returns an integer version of "123" + // String'i Integer'a Dönüştürme + // bu başarısız olursa hata fırlatacaktır + int.Parse("123");// "123" 'in Integer değerini döndürür - // try parse will default to type default on failure - // in this case: 0 + // try parse hata durumunda değişkene varsayılan bir değer atamak için kullanılır + // bu durumda: 0 int tryInt; - if (int.TryParse("123", out tryInt)) // Function is boolean + if (int.TryParse("123", out tryInt)) // Fonksiyon boolean'dır Console.WriteLine(tryInt); // 123 - // Convert Integer To String - // Convert class has a number of methods to facilitate conversions + // Integer'ı String'e Dönüştürme + // Convert sınıfı dönüştürme işlemini kolaylaştırmak için bir dizi metoda sahiptir Convert.ToString(123); - // or + // veya tryInt.ToString(); } /////////////////////////////////////// - // CLASSES - see definitions at end of file + // SINIFLAR - dosyanın sonunda tanımları görebilirsiniz /////////////////////////////////////// public static void Classes() { - // See Declaration of objects at end of file + // Obje tanımlamalarını dosyanın sonunda görebilirsiniz - // Use new to instantiate a class + // Bir sınıfı türetmek için new kullanın Bicycle trek = new Bicycle(); - // Call object methods - trek.SpeedUp(3); // You should always use setter and getter methods + // Obje metodlarını çağırma + trek.SpeedUp(3); // Her zaman setter ve getter metodları kullanmalısınız trek.Cadence = 100; - // ToString is a convention to display the value of this Object. + // ToString objenin değerini göstermek için kullanılır. Console.WriteLine("trek info: " + trek.Info()); - // Instantiate a new Penny Farthing + // Yeni bir Penny Farthing sınıfı türetmek PennyFarthing funbike = new PennyFarthing(1, 10); Console.WriteLine("funbike info: " + funbike.Info()); Console.Read(); - } // End main method + } // Ana metodun sonu // CONSOLE ENTRY A console application must have a main method as an entry point public static void Main(string[] args) -- cgit v1.2.3 From 765e4d3be987edd441b5f3cdee83543645fca642 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 19:30:07 +0200 Subject: lasssstttt --- tr-tr/csharp-tr.html.markdown | 232 +++++++++++++++++++++--------------------- 1 file changed, 114 insertions(+), 118 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 37a1090a..cfbee5e8 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -153,7 +153,7 @@ on a new line! ""Wow!"", the masses cried"; List intList = new List(); List stringList = new List(); List z = new List { 9000, 1000, 1337 }; // tanımlama - // <> işareti genelleme içindir - Güzel özellikler sekmesini inceleyin + // <> işareti generic ifadeler içindir - Güzel özellikler sekmesini inceleyin // Listelerin varsayılan bir değeri yoktur; // İndekse erişmeden önce değer eklenmiş olmalıdır @@ -342,39 +342,39 @@ on a new line! ""Wow!"", the masses cried"; Console.Read(); } // Ana metodun sonu - // CONSOLE ENTRY A console application must have a main method as an entry point + // KONSOLE BAŞLANGICI Bir konsol uygulaması başlangıç olarak mutlaka ana metod'a sahip olmalı public static void Main(string[] args) { OtherInterestingFeatures(); } // - // INTERESTING FEATURES + // İLGİNÇ ÖZELLİKLER // - // DEFAULT METHOD SIGNATURES + // VARSAYILAN METOD TANIMLAMALARI - public // Visibility - static // Allows for direct call on class without object - int // Return Type, + public // Görünebilir + static // Sınıf üzerinden obje türetmeden çağırılabilir + int // Dönüş Tipi, MethodSignatures( - int maxCount, // First variable, expects an int - int count = 0, // will default the value to 0 if not passed in + int maxCount, // İlk değişken, int değer bekler + int count = 0, // Eğer değer gönderilmezse varsayılan olarak 0 değerini alır int another = 3, - params string[] otherParams // captures all other parameters passed to method + params string[] otherParams // Metoda gönderilen diğer bütün parametreleri alır ) { return -1; } - // Methods can have the same name, as long as the signature is unique + // Metodlar tanımlamalar benzersiz ise aynı isimleri alabilirler public static void MethodSignatures(string maxCount) { } - // GENERICS - // The classes for TKey and TValue is specified by the user calling this function. - // This method emulates the SetDefault of Python + // GENERIC'LER + // TKey ve TValue değerleri kullanıcı tarafından bu fonksiyon çağırılırken belirtilir. + // Bu metod Python'daki SetDefault'a benzer public static TValue SetDefault( IDictionary dictionary, TKey key, @@ -386,68 +386,66 @@ on a new line! ""Wow!"", the masses cried"; return result; } - // You can narrow down the objects that are passed in + // Gönderilen objeleri daraltabilirsiniz public static void IterateAndPrint(T toPrint) where T: IEnumerable { - // We can iterate, since T is a IEnumerable + // Eğer T IEnumerable ise tekrarlayabiliriz foreach (var item in toPrint) - // Item is an int + // Item bir int Console.WriteLine(item.ToString()); } public static void OtherInterestingFeatures() { - // OPTIONAL PARAMETERS + // İSTEĞE BAĞLI PARAMETRELER MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); - MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + MethodSignatures(3, another: 3); // isteğe bağlı olanlar gönderilmedi - // EXTENSION METHODS + // UZANTI METODLARI int i = 3; - i.Print(); // Defined below + i.Print(); // Aşağıda tanımlandı - // NULLABLE TYPES - great for database interaction / return values - // any value type (i.e. not a class) can be made nullable by suffixing a ? - // ? = - int? nullable = null; // short hand for Nullable + // NULLABLE TYPES - veri tabanı işlemleri için uygun / return values + // Herhangi bir değer tipi sonuna ? eklenerek nullable yapılabilir (sınıflar hariç) + // ? = + int? nullable = null; // Nullable için kısa yol Console.WriteLine("Nullable variable: " + nullable); - bool hasValue = nullable.HasValue; // true if not null + bool hasValue = nullable.HasValue; // eğer null değilse true döner - // ?? is syntactic sugar for specifying default value (coalesce) - // in case variable is null + // ?? varsayılan değer belirlemek için söz dizimsel güzel bir özellik + // bu durumda değişken null'dır int notNullable = nullable ?? 0; // 0 - // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: + // TİPİ BELİRTİLMEMİŞ DEĞİŞKENLER - compiler değişkenin tipini bilmeden çalışabilir: var magic = "magic is a string, at compile time, so you still get type safety"; - // magic = 9; will not work as magic is a string, not an int + // magic = 9; string gibi çalışmayacaktır, bu bir int değil - // GENERICS + // GENERIC'LER // var phonebook = new Dictionary() { - {"Sarah", "212 555 5555"} // Add some entries to the phone book + {"Sarah", "212 555 5555"} // Telefon rehberine bir kaç numara ekleyelim. }; - // Calling SETDEFAULT defined as a generic above - Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone - // nb, you don't need to specify the TKey and TValue since they can be - // derived implicitly + // Yukarıda generic olarak tanımlanan SETDEFAULT'u çağırma + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // Telefonu yok + // TKey ve TValue tipini belirtmek zorunda değilsiniz Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 - // LAMBDA EXPRESSIONS - allow you to write code in line - Func square = (x) => x * x; // Last T item is the return value + // LAMBDA IFADELERİ - satır içinde kod yazmanıza olanak sağlar + Func square = (x) => x * x; // Son T nesnesi dönüş değeridir Console.WriteLine(square(3)); // 9 - // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. - // Most of objects that access unmanaged resources (file handle, device contexts, etc.) - // implement the IDisposable interface. The using statement takes care of - // cleaning those IDisposable objects for you. + // TEK KULLANIMLIK KAYNAK YÖNETİMİ - Yönetilemeyen kaynakların üstesinden kolayca gelebilirsiniz. + // Bir çok obje yönetilemeyen kaynaklara (dosya yakalama, cihaz içeriği, vb.) + // IDisposable arabirimi ile erişebilir. Using ifadesi sizin için IDisposable objeleri temizler. using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("Nothing suspicious here"); - // At the end of scope, resources will be released. - // Even if an exception is thrown. + // Bu bölümün sonunda kaynaklar temilenir. + // Hata fırlatılmış olsa bile. } - // PARALLEL FRAMEWORK + // PARALEL FRAMEWORK // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx var websites = new string[] { "http://www.google.com", "http://www.reddit.com", @@ -455,73 +453,71 @@ on a new line! ""Wow!"", the masses cried"; }; var responses = new Dictionary(); - // Will spin up separate threads for each request, and join on them - // before going to the next step! + // Her istek farklı bir thread de işlem görecek + // bir sonraki işleme geçmeden birleştirilecek. Parallel.ForEach(websites, - new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // en fazla 3 thread kullanmak için website => { - // Do something that takes a long time on the file + // Uzun sürecek bir işlem yapın using (var r = WebRequest.Create(new Uri(website)).GetResponse()) { responses[website] = r.ContentType; } }); - // This won't happen till after all requests have been completed + // Bütün istekler tamamlanmadan bu döndü çalışmayacaktır. foreach (var key in responses.Keys) Console.WriteLine("{0}:{1}", key, responses[key]); - // DYNAMIC OBJECTS (great for working with other languages) + // DİNAMİK OBJELER (diğer dillerle çalışırken kullanmak için uygun) dynamic student = new ExpandoObject(); - student.FirstName = "First Name"; // No need to define class first! + student.FirstName = "First Name"; // Önce yeni bir sınıf tanımlamanız gerekmez! - // You can even add methods (returns a string, and takes in a string) + // Hatta metod bile ekleyebilirsiniz (bir string döner, ve bir string alır) student.Introduce = new Func( (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); Console.WriteLine(student.Introduce("Beth")); - // IQUERYABLE - almost all collections implement this, which gives you a lot of - // very useful Map / Filter / Reduce style methods + // IQUERYABLE - neredeyse bütün koleksiyonlar bundan türer, bu size bir çok + // kullanışlı Map / Filter / Reduce stili metod sağlar. var bikes = new List(); - bikes.Sort(); // Sorts the array - bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels + bikes.Sort(); // Dizi sıralama + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Wheels baz alınarak sıralama var result = bikes - .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) + .Where(b => b.Wheels > 3) // Filters- chainable (bir önceki tipin IQueryable'ını döner) .Where(b => b.IsBroken && b.HasTassles) - .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable + .Select(b => b.ToString()); // Map - sadece bunu seçiyoruz, yani sonuç bir IQueryable olacak - var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection + var sum = bikes.Sum(b => b.Wheels); // Reduce - koleksiyonda bulunan bütün wheel değerlerinin toplamı - // Create a list of IMPLICIT objects based on some parameters of the bike + // Bike içindeki bazı parametreleri baz alarak bir liste oluşturmak var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); - // Hard to show here, but you get type ahead completion since the compiler can implicitly work - // out the types above! + // Burada göstermek zor ama, compiler yukaridaki tipleri çözümleyebilirse derlenmeden önce tipi verebilir. foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) Console.WriteLine(bikeSummary.Name); // ASPARALLEL - // And this is where things get wicked - combines linq and parallel operations + // Linq ve paralel işlemlerini birleştirme var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); - // this will happen in parallel! Threads will automagically be spun up and the - // results divvied amongst them! Amazing for large datasets when you have lots of - // cores + // bu paralel bir şekilde gerçekleşecek! Threadler otomatik ve sihirli bir şekilde işleri paylaşacak! + // Birden fazla çekirdeğiniz varsa büyük veri setleri ile kullanmak için oldukça uygun bir yapı. - // LINQ - maps a store to IQueryable objects, with delayed execution - // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document + // LINQ - IQueryable objelerini mapler ve saklar, gecikmeli bir işlemdir + // e.g. LinqToSql - veri tabanını mapler, LinqToXml xml dökümanlarını mapler. var db = new BikeRepository(); - // execution is delayed, which is great when querying a database - var filter = db.Bikes.Where(b => b.HasTassles); // no query run - if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality - filter = filter.Where(b => b.IsBroken); // no query run + // işlem gecikmelidir, bir veri tabanı üzerinde sorgulama yaparken harikadır. + var filter = db.Bikes.Where(b => b.HasTassles); // sorgu henüz çalışmadı + if (42 > 6) // Filtreler eklemeye devam edebilirsiniz - ileri düzey arama fonksiyonları için harikadır + filter = filter.Where(b => b.IsBroken); // sorgu henüz çalışmadı var query = filter .OrderBy(b => b.Wheels) .ThenBy(b => b.Name) - .Select(b => b.Name); // still no query run + .Select(b => b.Name); // hala sorgu çalışmadı - // Now the query runs, but opens a reader, so only populates are you iterate through + // Şimdi sorgu çalışıyor, reader'ı açar ama sadece sizin sorgunuza uyanlar foreach döngüsüne girer. foreach (string bike in query) Console.WriteLine(result); @@ -529,98 +525,98 @@ on a new line! ""Wow!"", the masses cried"; } - } // End LearnCSharp class + } // LearnCSharp sınıfının sonu - // You can include other classes in a .cs file + // Bir .cs dosyasına diğer sınıflarıda dahil edebilirsiniz public static class Extensions { - // EXTENSION FUNCTIONS + // UZANTI FONKSİYONLARI public static void Print(this object obj) { Console.WriteLine(obj.ToString()); } } - // Class Declaration Syntax: - // class { - // //data fields, constructors, functions all inside. - // //functions are called as methods in Java. + // Sınıf Tanımlama Sözdizimi: + // class { + // //veri alanları, kurucular , fonksiyonlar hepsi içindedir. + // //Fonksiyonlar Java'daki gibi metod olarak çağırılır. // } public class Bicycle { - // Bicycle's Fields/Variables - public int Cadence // Public: Can be accessed from anywhere + // Bicycle'ın Alanları/Değişkenleri + public int Cadence // Public: herhangi bir yerden erişilebilir { - get // get - define a method to retrieve the property + get // get - değeri almak için tanımlanan metod { return _cadence; } - set // set - define a method to set a proprety + set // set - değer atamak için tanımlanan metod { - _cadence = value; // Value is the value passed in to the setter + _cadence = value; // Değer setter'a gönderilen value değeridir } } private int _cadence; - protected virtual int Gear // Protected: Accessible from the class and subclasses + protected virtual int Gear // Protected: Sınıf ve alt sınıflar tarafından erişilebilir { - get; // creates an auto property so you don't need a member field + get; // bir üye alanına ihtiyacınız yok, bu otomatik olarak bir değer oluşturacaktır set; } - internal int Wheels // Internal: Accessible from within the assembly + internal int Wheels // Internal: Assembly tarafından erişilebilir { get; - private set; // You can set modifiers on the get/set methods + private set; // Nitelik belirleyicileri get/set metodlarında atayabilirsiniz } - int _speed; // Everything is private by default: Only accessible from within this class. - // can also use keyword private + int _speed; // Her şey varsayılan olarak private'dır : Sadece sınıf içinden erişilebilir. + // İsterseniz yinede private kelimesini kullanabilirsiniz. public string Name { get; set; } - // 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. + // Enum sabitler kümesinden oluşan bir değer tipidir. + // Gerçekten sadece bir isim ile bir değeri tutmak için kullanılır. (aksi belirtilmedikçe bir int'dir). + // İzin verilen enum tipleri şunlardır byte, sbyte, short, ushort, int, uint, long, veya ulong. + // Bir enum aynı değeri birden fazla sayıda barındıramaz. public enum BikeBrand { AIST, BMC, - Electra = 42, //you can explicitly set a value to a name + Electra = 42, // bir isme tam bir değer verebilirsiniz Gitane // 43 } - // 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 + // Bu tipi Bicycle sınıfı içinde tanımladığımız için bu bir bağımlı tipdir. + // Bu sınıf dışında kullanmak için tipi Bicycle.Brand olarak kullanmamız gerekir - public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type + public BikeBrand Brand; // Enum tipini tanımladıktan sonra alan tipini tanımlayabiliriz - // Static members belong to the type itself rather then specific object. - // You can access them without a reference to any object: + // Static üyeler belirli bir obje yerine kendi tipine aittir + // Onlara bir obje referans göstermeden erişebilirsiniz: // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); static public int BicyclesCreated = 0; - // readonly values are set at run time - // they can only be assigned upon declaration or in a constructor + // readonly değerleri çalışma zamanında atanır + // onlara sadece tanımlama yapılarak ya da kurucular içinden atama yapılabilir readonly bool _hasCardsInSpokes = false; // read-only private - // Constructors are a way of creating classes - // This is a default constructor + // Kurucular sınıf oluşturmanın bir yoludur + // Bu bir varsayılan kurucudur. public Bicycle() { - this.Gear = 1; // you can access members of the object with the keyword this - Cadence = 50; // but you don't always need it + this.Gear = 1; // bu objenin üyelerine this anahtar kelimesi ile ulaşılır + Cadence = 50; // ama her zaman buna ihtiyaç duyulmaz _speed = 5; Name = "Bontrager"; Brand = BikeBrand.AIST; BicyclesCreated++; } - // This is a specified constructor (it contains arguments) + // Bu belirlenmiş bir kurucudur. (argümanlar içerir) public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes, BikeBrand brand) - : base() // calls base first + : base() // önce base'i çağırın { Gear = startGear; Cadence = startCadence; @@ -630,20 +626,20 @@ on a new line! ""Wow!"", the masses cried"; Brand = brand; } - // Constructors can be chained + // Kurucular zincirleme olabilir public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : this(startCadence, startSpeed, 0, "big wheels", true, brand) { } - // Function Syntax: - // () + // Fonksiyon Sözdizimi: + // () - // classes can implement getters and setters for their fields - // or they can implement properties (this is the preferred way in C#) + // sınıflar getter ve setter'ları alanları için kendisi uygular + // veya kendisi özellikleri uygulayabilir (C# da tercih edilen yol budur) - // Method parameters can have default values. - // In this case, methods can be called with these parameters omitted + // Metod parametreleri varsayılan değerlere sahip olabilir. + // Bu durumda, metodlar bu parametreler olmadan çağırılabilir. public void SpeedUp(int increment = 1) { _speed += increment; -- cgit v1.2.3 From 3f305ab2831b9e3a1ca9dce35ab42386989e9a61 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 20:07:15 +0200 Subject: completed --- tr-tr/csharp-tr.html.markdown | 71 +++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index cfbee5e8..e5cd3730 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -636,7 +636,7 @@ on a new line! ""Wow!"", the masses cried"; // () // sınıflar getter ve setter'ları alanları için kendisi uygular - // veya kendisi özellikleri uygulayabilir (C# da tercih edilen yol budur) + // veya property'ler eklenebilir (C# da tercih edilen yol budur) // Metod parametreleri varsayılan değerlere sahip olabilir. // Bu durumda, metodlar bu parametreler olmadan çağırılabilir. @@ -650,35 +650,34 @@ on a new line! ""Wow!"", the masses cried"; _speed -= decrement; } - // properties get/set values - // when only data needs to be accessed, consider using properties. - // properties may have either get or set, or both - private bool _hasTassles; // private variable + // property'lerin get/set değerleri + // sadece veri gerektiği zaman erişilebilir, kullanmak için bunu göz önünde bulundurun. + // property'ler sadece get ya da set'e sahip olabilir veya ikisine birden + private bool _hasTassles; // private değişken public bool HasTassles // public accessor { 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: + // Ayrıca tek bir satırda otomatik property tanımlayabilirsiniz. + // bu söz dizimi otomatik olarak alan oluşturacaktır. + // Erişimi kısıtlamak için nitelik belirleyiciler getter veya setter'a ya da ikisine birden atanabilir: public bool IsBroken { get; private set; } - // Properties can be auto-implemented + // Property'ler otomatik eklenmiş olabilir public int FrameSize { get; - // you are able to specify access modifiers for either get or set - // this means only Bicycle class can call set on Framesize + // nitelik beliryecileri get veya set için tanımlayabilirsiniz + // bu sadece Bicycle sınıfı Framesize değerine atama yapabilir demektir private set; } - // It's also possible to define custom Indexers on objects. - // All though this is not entirely useful in this example, you - // could do bicycle[0] which yields "chris" to get the first passenger or - // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) + // Ayrıca obje üzerinde özel indeksleyici belirlemek mümkündür. + // Tüm bunlar bu örnek için çok kullanışlı değil, + // bicycle[0] ile ilk yolcu olan "chris" i almak mümkün veya + // bicycle[1] = "lisa" ile yolcuyu atayabilirsiniz. (bariz quattrocycle) private string[] passengers = { "chris", "phil", "darren", "regina" } public string this[int i] @@ -692,7 +691,7 @@ on a new line! ""Wow!"", the masses cried"; } } - //Method to display the attribute values of this Object. + //Bu objenin nitelik değerlerini göstermek için bir metod. public virtual string Info() { return "Gear: " + Gear + @@ -704,23 +703,23 @@ on a new line! ""Wow!"", the masses cried"; ; } - // Methods can also be static. It can be useful for helper methods + // Metodlar static olabilir. Yardımcı metodlar için kullanışlı olabilir. public static bool DidWeCreateEnoughBycles() { - // Within a static method, we only can reference static class members + // Bir static metod içinde sadece static sınıf üyeleri referans gösterilebilir return BicyclesCreated > 9000; - } // If your class only needs static members, consider marking the class itself as static. + } // Eğer sınıfınızın sadece static üyelere ihtiyacı varsa, sınıfın kendisini static yapmayı düşünebilirsiniz. - } // end class Bicycle + } // Bicycle sınıfı sonu - // PennyFarthing is a subclass of Bicycle + // PennyFarthing , Bicycle sınıfının alt sınıfıdır. class PennyFarthing : Bicycle { - // (Penny Farthings are those bicycles with the big front wheel. - // They have no gears.) + // (Penny Farthing'ler ön jantı büyük bisikletlerdir. + // Vitesleri yoktur.) - // calling parent constructor + // Ana kurucuyu çağırmak public PennyFarthing(int startCadence, int startSpeed) : base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) { @@ -741,23 +740,23 @@ on a new line! ""Wow!"", the masses cried"; public override string Info() { string result = "PennyFarthing bicycle "; - result += base.ToString(); // Calling the base version of the method + result += base.ToString(); // Metodun temel versiyonunu çağırmak return result; } } - // Interfaces only contain signatures of the members, without the implementation. + // Arabirimler sadece üyelerin izlerini içerir, değerlerini değil. interface IJumpable { - void Jump(int meters); // all interface members are implicitly public + void Jump(int meters); // bütün arbirim üyeleri public'tir } interface IBreakable { - bool Broken { get; } // interfaces can contain properties as well as methods & events + bool Broken { get; } // arabirimler property'leri, metodları ve olayları içerebilir } - // Class can inherit only one other class, but can implement any amount of interfaces + // Sınıflar sadece tek bir sınıftan miras alabilir ama sınırsız sayıda arabirime sahip olabilir class MountainBike : Bicycle, IJumpable, IBreakable { int damage = 0; @@ -777,8 +776,8 @@ on a new line! ""Wow!"", the masses cried"; } /// - /// Used to connect to DB for LinqToSql example. - /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// LinqToSql örneği veri tabanına bağlanmak için kullanılır. + /// EntityFramework Code First harika! (Ruby'deki ActiveRecord'a benzer, ama iki yönlü) /// http://msdn.microsoft.com/en-us/data/jj193542.aspx /// public class BikeRepository : DbSet @@ -790,10 +789,10 @@ on a new line! ""Wow!"", the masses cried"; public DbSet Bikes { get; set; } } -} // End Namespace +} // Namespace sonu ``` -## Topics Not Covered +## İşlenmeyen Konular * Flags * Attributes @@ -803,7 +802,7 @@ on a new line! ""Wow!"", the masses cried"; * Winforms * Windows Presentation Foundation (WPF) -## Further Reading +## Daha Fazlasını Okuyun * [DotNetPerls](http://www.dotnetperls.com) * [C# in Depth](http://manning.com/skeet2) @@ -817,4 +816,4 @@ on a new line! ""Wow!"", the masses cried"; -[C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) +[C# Kodlama Adetleri](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) -- cgit v1.2.3 From 634efbb8caaf02feba5f09edd450df1d684e6660 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 20:08:42 +0200 Subject: csharp/tr --- tr-tr/csharp-tr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index e5cd3730..c20f90ad 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -789,7 +789,7 @@ on a new line! ""Wow!"", the masses cried"; public DbSet Bikes { get; set; } } -} // Namespace sonu +} // namespace sonu ``` ## İşlenmeyen Konular -- cgit v1.2.3 From 71eda7df766a2be9777d977b8b3b946e37ee82d9 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 20:11:54 +0200 Subject: csharp/tr --- tr-tr/csharp-tr.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index c20f90ad..3573bbd4 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -11,6 +11,8 @@ filename: LearnCSharp.cs C# zarif ve tip güvenli nesne yönelimli bir dil olup geliştiricilerin .NET framework üzerinde çalışan güçlü ve güvenli uygulamalar geliştirmesini sağlar. +[Yazım yanlışları ve öneriler için bana ulaşabilirsiniz](mailto:melihmucuk@gmail.com) + [Daha fazlasını okuyun.](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) ```c# -- cgit v1.2.3 From 3cb53d9e43143d330cd65c2f29fff93ffa0110f4 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 20:18:46 +0200 Subject: csharp/tr --- tr-tr/csharp-tr.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 3573bbd4..7755ed44 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -5,8 +5,11 @@ contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Melvyn Laïly", "http://x2a.yt"] - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] +translators: - ["Melih Mucuk", "http://melihmucuk.com"] +lang: tr-tr filename: LearnCSharp.cs + --- C# zarif ve tip güvenli nesne yönelimli bir dil olup geliştiricilerin .NET framework üzerinde çalışan güçlü ve güvenli uygulamalar geliştirmesini sağlar. -- cgit v1.2.3 From a7dc8b2f4c349d00754d346c78672844523b42ba Mon Sep 17 00:00:00 2001 From: Poor Yorick Date: Thu, 1 Jan 2015 21:41:21 -0700 Subject: add Tcl document --- tcl.html.markdown | 372 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 372 insertions(+) create mode 100755 tcl.html.markdown diff --git a/tcl.html.markdown b/tcl.html.markdown new file mode 100755 index 00000000..32619b7c --- /dev/null +++ b/tcl.html.markdown @@ -0,0 +1,372 @@ +--- +language: Tcl +contributors: + - ["Poor Yorick", "http://pooryorick.com/"] +filename: learntcl +--- + +Tcl was created by [John Ousterhout](http://wiki.tcl.tk/John Ousterout) as a +reusable scripting language for chip design tools he was creating. In 1997 he +was awarded the [ACM Software System +Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) for Tcl. Tcl +can be used both as an embeddable scripting language and as a general +programming language. It can also be used as a portable C library, even in +cases where no scripting capability is needed, as it provides data structures +such as dynamic strings, lists, and hash tables. The C library also provides +portable functionality for loading dynamic libraries, string formatting and +code conversion, filesystem operations, network operations, and more. + +Tcl is a pleasure to program in. Its discipline of exposing all programmatic +functionality as commands, including things like loops and mathematical +operations that are usually baked into the syntax of other languages, allows it +to fade into the background of whatever domain-specific functionality a project +needs. Its design of exposing all values as strings, while internally caching +a structured representation, bridges the world of scripting and systems +programming in the best way. Even Lisp is more syntactically heavy than Tcl. + + + +```tcl +#! /bin/env tclsh + +################################################################################ +## 1. Guidelines +################################################################################ + +# Tcl is not Bash or C! This needs to be said because standard shell quoting +# habits almost work in Tcl and it is common for people to pick up Tcl and try +# to get by with syntax they know from another language. It works at first, +# but soon leads to frustration with more complex scripts. + +# Braces are just a quoting mechanism, not a code block constructor or a list +# constructor. Tcl doesn't have either of those things. Braces are used, +# though, to escape special characters in procedure bodies and in strings that +# are formatted as lists. + + +################################################################################ +## 2. Syntax +################################################################################ + +# Every line is a command. The first word is the name of the command, and +# subsequent words are arguments to the command. Words are delimited by +# whitespace. Since every word is a string, no escaping is necessary in the +# simple case. + +set greeting1 Sal +set greeting2 ut +set greeting3 ations + + +#semicolon also delimits commands + +set greeting1 Sal; set greeting2 ut; set greeting3 ations + + +# Dollar sign introduces variable substitution + +set greeting $greeting1$greeting2 + + +# Bracket introduces command substitution + +set greeting $greeting[set greeting3] + + +# backslash suppresses the special meaning of characters + +set amount \$16.42 + + +# backslash adds special meaning to certain characters + +puts lots\nof\n\n\n\n\n\nnewlines + + +# A word enclosed in braces is not subject to any special interpretation or +# substitutions, except that a backslash before a brace is not counted when look#ing for the closing brace +set somevar { + This is a literal $ sign, and this \} escaped + brace remains uninterpreted +} + +# In a word enclosed in double quotes, whitespace characters lose their special +# meaning + +set name Neo +set greeting "Hello, $name" + + +#variable names can be any string + +set {first name} New + + +# The brace form of variable substitution handles more complex variable names + +set greeting "Hello, ${first name}" + + +# The "set" command can always be used instead of variable substitution + +set greeting "Hello, [set {first name}]" + + +# To promote the words within a word to individual words of the current +# command, use the expansion operator, "{*}". + +set {*}{name Neo} + +# is equivalent to + +set name Neo + + +# An array is a special variable that is a container for other variables. + +set person(name) Neo +set person(gender) male + +set greeting "Hello, $person(name)" + +# A namespace holds commands and variables + +namespace eval people { + namespace eval person1 { + set name Neo + } +} + +#The full name of a variable includes its enclosing namespace(s), delimited by two colons: + +set greeting "Hello $people::person::name" + + + +################################################################################ +## 3. A Few Notes +################################################################################ + +# From this point on, there is no new syntax. Everything else there is to +# learn about Tcl is about the behaviour of individual commands, and what +# meaning they assign to their arguments. + + +# All other functionality is implemented via commands. To end up with an +# interpreter that can do nothing, delete the global namespace. It's not very +# useful to do such a thing, but it illustrates the nature of Tcl. + +namespace delete :: + + +# Because of name resolution behaviour, its safer to use the "variable" command to declare or to assign a value to a namespace. + +namespace eval people { + namespace eval person1 { + variable name Neo + } +} + + +# The full name of a variable can always be used, if desired. + +set people::person1::name Neo + + + +################################################################################ +## 4. Commands +################################################################################ + +# Math can be done with the "expr" command. + +set a 3 +set b 4 +set c [expr {$a + $b}] + +# Since "expr" performs variable substitution on its own, brace the expression +# to prevent Tcl from performing variable substitution first. See +# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" for details. + + +# The "expr" command understands variable and command substitution + +set c [expr {$a + [set b]}] + + +# The "expr" command provides a set of mathematical functions + +set c [expr {pow($a,$b)}] + + +# Mathematical operators are available as commands in the ::tcl::mathop +# namespace + +::tcl::mathop::+ 5 3 + +# Commands can be imported from other namespaces + +namespace import ::tcl::mathop::+ +set result [+ 5 3] + + +# New commands can be created via the "proc" command. + +proc greet name { + return "Hello, $name!" +} + + +# As noted earlier, braces do not construct a code block. Every value, even +# the third argument of the "proc" command, is a string. The previous command +# could be defined without using braces at all: + +proc greet name return\ \"Hello,\ \$name! + + +# When the last parameter is the literal value, "args", it collects all extra +# arguments when the command is invoked + +proc fold {cmd args} { + set res 0 + foreach arg $args { + set res [cmd $res $arg] + } +} + +fold ::tcl::mathop::* 5 3 3 ;# -> 45 + + + +# Conditional execution is implemented as a command + +if {3 > 4} { + puts {This will never happen} +} elseif {4 > 4} { + puts {This will also never happen} +} else { + puts {This will always happen} +} + + +# Loops are implemented as commands. The first, second, and third +# arguments of the "for" command are treated as mathematical expressions + +for {set i 0} {$i < 10} {incr i} { + set res [expr {$res + $i}] +} + + +# The first argument of the "while" command is also treated as a mathematical +# expression + +set i 0 +while {$i < 10} { + incr i 2 +} + + +# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values + +set amounts 10\ 33\ 18 +set amount [lindex $amounts 1] + + +# Braces and backslash can be used to format more complex values in a list. +# There are three items in the following + +set values { + + one\ two + + {three four} + + five\{six + +} + + +# Since a list is a string, string operations could be performed on it, at the +# risk of corrupting the list. + +set values {one two three four} +set values [string map {two \{} $values] ;# $values is no-longer a \ + properly-formatted listwell-formed list + + +# The sure-fire way to get a properly-formmated list is to use "list" commands +set values [list one \{ three four] + +lappend values { } ;# add a single space as an item in the list + + +# Use "eval" to evaluate a value as a script + +eval { + set name Neo + set greeting "Hello, $name" +} + + +# A list can always be passed to "eval" as a script composed of a single +# command. + +eval {set name Neo} +eval [list set greeting "Hello, $name"] + + +# Therefore, when using "eval", use [list] to build up a desired command + +set command {set name} +lappend command {Archibald Sorbisol} +eval $command + + +# A common mistake is not to use list functions + +set command {set name} +append command { Archibald Sorbisol} +eval $command ;# There is an error here, because there are too many arguments \ + to "set" in {set name Archibald Sorbisol} + + +# This mistake can easily occur with the "subst" command. + +set replacement {Archibald Sorbisol} +set command {set name $replacement} +set command [subst $command] +eval $command ;# The same error as before: to many arguments to "set" in \ + {set name Archibald Sorbisol} + + +# The proper way is to format the substituted value using use the "list" +# command. + +set replacement [list {Archibald Sorbisol}] +set command {set name $replacement} +set command [subst $command] +eval $command + + +# It is extremely common to see the "list" command being used to properly +# format values that are substituted into Tcl script templates. There is an +# example of this in the following replacement "while" implementation. + + +#get rid of the built-in "while" command. + +rename ::while {} + + +# Define a new while command with the "proc" command. More sophisticated error +# handling is left as an exercise. + +proc while {condition script} { + if {[uplevel 1 [list expr $condition]]} { + uplevel 1 $script + tailcall [namespace which while] $condition $script + } +} +``` + + -- cgit v1.2.3 From 335d618b1a7ef1793ba30402101c58438bd44603 Mon Sep 17 00:00:00 2001 From: Poor Yorick Date: Thu, 1 Jan 2015 21:48:42 -0700 Subject: add reference --- tcl.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index 32619b7c..ddf53fe9 100755 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -2,7 +2,6 @@ language: Tcl contributors: - ["Poor Yorick", "http://pooryorick.com/"] -filename: learntcl --- Tcl was created by [John Ousterhout](http://wiki.tcl.tk/John Ousterout) as a @@ -369,4 +368,10 @@ proc while {condition script} { } ``` +## Reference +[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) + +[Tcl Wiki](http://wiki.tcl.tk) + +[Tcl Subreddit](http://www.reddit.com/r/Tcl) -- cgit v1.2.3 From a80663a4ceeadaa813e17918123eff837e91fc51 Mon Sep 17 00:00:00 2001 From: Poor Yorick Date: Fri, 2 Jan 2015 07:56:48 -0700 Subject: better verbiage, add more commands. --- tcl.html.markdown | 159 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 100 insertions(+), 59 deletions(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index ddf53fe9..5402ce04 100755 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -49,8 +49,10 @@ programming in the best way. Even Lisp is more syntactically heavy than Tcl. # Every line is a command. The first word is the name of the command, and # subsequent words are arguments to the command. Words are delimited by -# whitespace. Since every word is a string, no escaping is necessary in the -# simple case. +# whitespace. Since every word is a string, in the simple case no special +# markup such as quotes, braces, or backslash, is necessary. Even when quotes +# are used, they are not a string constructor, but just another escaping +# character. set greeting1 Sal set greeting2 ut @@ -58,27 +60,34 @@ set greeting3 ations #semicolon also delimits commands - set greeting1 Sal; set greeting2 ut; set greeting3 ations # Dollar sign introduces variable substitution +set greeting $greeting1$greeting2$greeting3 -set greeting $greeting1$greeting2 +# Bracket introduces command substitution. The result of the command is +# substituted in place of the bracketed script. When the "set" command is +# given only the name of a variable, it returns the value of that variable. +set greeting $greeting1$greeting2[set greeting3] -# Bracket introduces command substitution -set greeting $greeting[set greeting3] +# Command substitution should really be called script substitution, because an +# entire script, not just a command, can be placed between the brackets. The +# "incr" command increments the value of a variable and returns its value. +set greeting $greeting[ + incr i + incr i + incr i +] # backslash suppresses the special meaning of characters - set amount \$16.42 # backslash adds special meaning to certain characters - puts lots\nof\n\n\n\n\n\nnewlines @@ -89,55 +98,48 @@ set somevar { brace remains uninterpreted } + # In a word enclosed in double quotes, whitespace characters lose their special # meaning - set name Neo set greeting "Hello, $name" #variable names can be any string - set {first name} New # The brace form of variable substitution handles more complex variable names - set greeting "Hello, ${first name}" # The "set" command can always be used instead of variable substitution - set greeting "Hello, [set {first name}]" # To promote the words within a word to individual words of the current # command, use the expansion operator, "{*}". - set {*}{name Neo} # is equivalent to - set name Neo # An array is a special variable that is a container for other variables. - set person(name) Neo set person(gender) male - set greeting "Hello, $person(name)" -# A namespace holds commands and variables +# A namespace holds commands and variables namespace eval people { namespace eval person1 { set name Neo } } -#The full name of a variable includes its enclosing namespace(s), delimited by two colons: +#The full name of a variable includes its enclosing namespace(s), delimited by two colons: set greeting "Hello $people::person::name" @@ -146,20 +148,19 @@ set greeting "Hello $people::person::name" ## 3. A Few Notes ################################################################################ -# From this point on, there is no new syntax. Everything else there is to -# learn about Tcl is about the behaviour of individual commands, and what -# meaning they assign to their arguments. +# All other functionality is implemented via commands. From this point on, +# there is no new syntax. Everything else there is to learn about Tcl is about +# the behaviour of individual commands, and what meaning they assign to their +# arguments. -# All other functionality is implemented via commands. To end up with an -# interpreter that can do nothing, delete the global namespace. It's not very -# useful to do such a thing, but it illustrates the nature of Tcl. - +# To end up with an interpreter that can do nothing, delete the global +# namespace. It's not very useful to do such a thing, but it illustrates the +# nature of Tcl. namespace delete :: # Because of name resolution behaviour, its safer to use the "variable" command to declare or to assign a value to a namespace. - namespace eval people { namespace eval person1 { variable name Neo @@ -168,7 +169,6 @@ namespace eval people { # The full name of a variable can always be used, if desired. - set people::person1::name Neo @@ -178,7 +178,6 @@ set people::person1::name Neo ################################################################################ # Math can be done with the "expr" command. - set a 3 set b 4 set c [expr {$a + $b}] @@ -189,56 +188,52 @@ set c [expr {$a + $b}] # The "expr" command understands variable and command substitution - set c [expr {$a + [set b]}] # The "expr" command provides a set of mathematical functions - set c [expr {pow($a,$b)}] # Mathematical operators are available as commands in the ::tcl::mathop # namespace - ::tcl::mathop::+ 5 3 # Commands can be imported from other namespaces - namespace import ::tcl::mathop::+ set result [+ 5 3] # New commands can be created via the "proc" command. - proc greet name { return "Hello, $name!" } +#multiple parameters can be specified +proc greet {greeting name} { + return "$greeting, $name!" +} + # As noted earlier, braces do not construct a code block. Every value, even # the third argument of the "proc" command, is a string. The previous command -# could be defined without using braces at all: +# rewritten to not use braces at all: +proc greet greeting\ name return\ \"Hello,\ \$name! -proc greet name return\ \"Hello,\ \$name! # When the last parameter is the literal value, "args", it collects all extra # arguments when the command is invoked - proc fold {cmd args} { set res 0 foreach arg $args { set res [cmd $res $arg] } } - fold ::tcl::mathop::* 5 3 3 ;# -> 45 - # Conditional execution is implemented as a command - if {3 > 4} { puts {This will never happen} } elseif {4 > 4} { @@ -250,7 +245,6 @@ if {3 > 4} { # Loops are implemented as commands. The first, second, and third # arguments of the "for" command are treated as mathematical expressions - for {set i 0} {$i < 10} {incr i} { set res [expr {$res + $i}] } @@ -258,7 +252,6 @@ for {set i 0} {$i < 10} {incr i} { # The first argument of the "while" command is also treated as a mathematical # expression - set i 0 while {$i < 10} { incr i 2 @@ -266,14 +259,14 @@ while {$i < 10} { # A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values - set amounts 10\ 33\ 18 set amount [lindex $amounts 1] -# Braces and backslash can be used to format more complex values in a list. -# There are three items in the following - +# Braces and backslash can be used to format more complex values in a list. A +# list looks exactly like a script, except that the newline character and the +# semicolon character lose their special meanings. This feature makes Tcl +# homoiconic. There are three items in the following list. set values { one\ two @@ -286,8 +279,7 @@ set values { # Since a list is a string, string operations could be performed on it, at the -# risk of corrupting the list. - +# risk of corrupting the formatting of the list. set values {one two three four} set values [string map {two \{} $values] ;# $values is no-longer a \ properly-formatted listwell-formed list @@ -295,12 +287,10 @@ set values [string map {two \{} $values] ;# $values is no-longer a \ # The sure-fire way to get a properly-formmated list is to use "list" commands set values [list one \{ three four] - lappend values { } ;# add a single space as an item in the list # Use "eval" to evaluate a value as a script - eval { set name Neo set greeting "Hello, $name" @@ -309,20 +299,17 @@ eval { # A list can always be passed to "eval" as a script composed of a single # command. - eval {set name Neo} eval [list set greeting "Hello, $name"] # Therefore, when using "eval", use [list] to build up a desired command - set command {set name} lappend command {Archibald Sorbisol} eval $command -# A common mistake is not to use list functions - +# A common mistake is not to use list functions when building up a command set command {set name} append command { Archibald Sorbisol} eval $command ;# There is an error here, because there are too many arguments \ @@ -330,7 +317,6 @@ eval $command ;# There is an error here, because there are too many arguments \ # This mistake can easily occur with the "subst" command. - set replacement {Archibald Sorbisol} set command {set name $replacement} set command [subst $command] @@ -340,7 +326,6 @@ eval $command ;# The same error as before: to many arguments to "set" in \ # The proper way is to format the substituted value using use the "list" # command. - set replacement [list {Archibald Sorbisol}] set command {set name $replacement} set command [subst $command] @@ -348,24 +333,80 @@ eval $command # It is extremely common to see the "list" command being used to properly -# format values that are substituted into Tcl script templates. There is an -# example of this in the following replacement "while" implementation. +# format values that are substituted into Tcl script templates. There are +# several examples of this, below. -#get rid of the built-in "while" command. +# The "apply" command evaluates a string as a command. +set cmd {{greeting name} { + return "$greeting, $name!" +}} +apply $cmd Whaddup Neo + + +# The "uplevel" command evaluates a script in some enclosing scope. +proc greet {} { + uplevel {puts "$greeting, $name"} +} + +proc set_double {varname value} { + if {[string is double $value]} { + uplevel [list variable $varname $value] + } else { + error [list {not a double} $value] + } +} + +# The "upvar" command links a variable in the current scope to a variable in +# some enclosing scope +proc set_double {varname value} { + if {[string is double $value]} { + upvar 1 $varname var + set var $value + } else { + error [list {not a double} $value] + } +} + + +#get rid of the built-in "while" command. rename ::while {} # Define a new while command with the "proc" command. More sophisticated error # handling is left as an exercise. - proc while {condition script} { if {[uplevel 1 [list expr $condition]]} { uplevel 1 $script tailcall [namespace which while] $condition $script } } + + +# The "coroutine" command creates a separate call stack, along with a command +# to enter that call stack. The "yield" command suspends execution in that +# stack. +proc countdown {} { + #send something back to the initial "coroutine" command + yield + + set count 3 + while {$count > 1} { + yield [incr count -1] + } + return 0 +} +coroutine countdown1 countdown +coroutine countdown2 countdown +puts [countdown 1] ;# -> 2 +puts [countdown 2] ;# -> 2 +puts [countdown 1] ;# -> 1 +puts [countdown 1] ;# -> 0 +puts [coundown 1] ;# -> invalid command name "countdown1" +puts [countdown 2] ;# -> 1 + + ``` ## Reference -- cgit v1.2.3 From aac20efb70dbd10383c9bfa4dd9108d8a4fda9ce Mon Sep 17 00:00:00 2001 From: Poor Yorick Date: Fri, 2 Jan 2015 08:19:41 -0700 Subject: Reworked summary --- tcl.html.markdown | 46 +++++++++++++++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index 5402ce04..44805b5c 100755 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -13,15 +13,43 @@ programming language. It can also be used as a portable C library, even in cases where no scripting capability is needed, as it provides data structures such as dynamic strings, lists, and hash tables. The C library also provides portable functionality for loading dynamic libraries, string formatting and -code conversion, filesystem operations, network operations, and more. - -Tcl is a pleasure to program in. Its discipline of exposing all programmatic -functionality as commands, including things like loops and mathematical -operations that are usually baked into the syntax of other languages, allows it -to fade into the background of whatever domain-specific functionality a project -needs. Its design of exposing all values as strings, while internally caching -a structured representation, bridges the world of scripting and systems -programming in the best way. Even Lisp is more syntactically heavy than Tcl. +code conversion, filesystem operations, network operations, and more. +Various features of Tcl stand out: + +* Convenient cross-platform networking API + +* Fully virtualized filesystem + +* Stackable I/O channels + +* Asynchronous to the core + +* Full coroutines + +* A threading model recognized as robust and easy to use + + +If Lisp is a list processor, then Tcl is a string processor. All values are +strings. A list is a string format. A procedure definition is a string +format. To achieve performance, Tcl internally caches structured +representations of these values. The list commands, for example, operate on +the internal cached representation, and Tcl takes care of updating the string +representation if it is ever actually needed in the script. The copy-on-write +design of Tcl allows script authors can pass around large data values without +actually incurring additional memory overhead. Procedures are automatically +byte-compiled unless they use the more dynamic commands such as "uplevel", +"upvar", and "trace". + +Tcl is a pleasure to program in. It will appeal to hacker types who find Lisp, +Forth, or Smalltalk interesting, as well as to engineers and scientists who +just want to get down to business with a tool that bends to their will. Its +discipline of exposing all programmatic functionality as commands, including +things like loops and mathematical operations that are usually baked into the +syntax of other languages, allows it to fade into the background of whatever +domain-specific functionality a project needs. It's syntax, which is even +lighter that that of Lisp, just gets out of the way. + + -- cgit v1.2.3 From e059cd98f32fbd7793f2e8622cb6061c1a142146 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 2 Jan 2015 19:53:49 +0000 Subject: Let's see how factor highlighting looks in forth --- forth.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forth.html.markdown b/forth.html.markdown index 570e12ed..4457e607 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -12,7 +12,7 @@ such as Open Firmware. It's also used by NASA. Note: This article focuses predominantly on the Gforth implementation of Forth, but most of what is written here should work elsewhere. -```forth +```factor \ This is a comment ( This is also a comment but it's only used when defining words ) -- cgit v1.2.3 From 732cdbed1ad345f2b826254bc7f0b6283124955e Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 2 Jan 2015 20:33:47 +0000 Subject: Update forth.html.markdown --- forth.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forth.html.markdown b/forth.html.markdown index 4457e607..f7c0bf34 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -12,7 +12,7 @@ such as Open Firmware. It's also used by NASA. Note: This article focuses predominantly on the Gforth implementation of Forth, but most of what is written here should work elsewhere. -```factor +``` \ This is a comment ( This is also a comment but it's only used when defining words ) -- cgit v1.2.3 From 6263dda6de1f9163a80a3ceab2a05666149e6a79 Mon Sep 17 00:00:00 2001 From: sunxb10 Date: Sat, 3 Jan 2015 20:49:39 +0800 Subject: Chinese translation of MATLAB tutorial --- zh-cn/matlab-cn.html.markdown | 491 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 491 insertions(+) create mode 100644 zh-cn/matlab-cn.html.markdown diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown new file mode 100644 index 00000000..77ba765a --- /dev/null +++ b/zh-cn/matlab-cn.html.markdown @@ -0,0 +1,491 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] +translators: + - ["sunxb10", "https://github.com/sunxb10"] +lang: zh-cn +--- + +MATLAB 是 MATrix LABoratory (矩阵实验室)的缩写,它是一种功能强大的数值计算语言,在工程和数学领域中应用广泛。 + +如果您有任何需要反馈或交流的内容,请联系本教程作者[@the_ozzinator](https://twitter.com/the_ozzinator)、[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com)。 + +```matlab +% 以百分号作为注释符 + +%{ +多行注释 +可以 +这样 +表示 +%} + +% 指令可以随意跨行,但需要在跨行处用 '...' 标明: + a = 1 + 2 + ... + + 4 + +% 可以在MATLAB中直接向操作系统发出指令 +!ping google.com + +who % 显示内存中的所有变量 +whos % 显示内存中的所有变量以及它们的类型 +clear % 清除内存中的所有变量 +clear('A') % 清除指定的变量 +openvar('A') % 在变量编辑器中编辑指定变量 + +clc % 清除命令窗口中显示的所有指令 +diary % 将命令窗口中的内容写入本地文件 +ctrl-c % 终止当前计算 + +edit('myfunction.m') % 在编辑器中打开指定函数或脚本 +type('myfunction.m') % 在命令窗口中打印指定函数或脚本的源码 + +profile on % 打开 profile 代码分析工具 +profile of % 关闭 profile 代码分析工具 +profile viewer % 查看 profile 代码分析工具的分析结果 + +help command % 在命令窗口中显示指定命令的帮助文档 +doc command % 在帮助窗口中显示指定命令的帮助文档 +lookfor command % 在所有 MATLAB 内置函数的头部注释块的第一行中搜索指定命令 +lookfor command -all % 在所有 MATLAB 内置函数的整个头部注释块中搜索指定命令 + + +% 输出格式 +format short % 浮点数保留 4 位小数 +format long % 浮点数保留 15 位小数 +format bank % 金融格式,浮点数只保留 2 位小数 +fprintf('text') % 在命令窗口中显示 "text" +disp('text') % 在命令窗口中显示 "text" + + +% 变量与表达式 +myVariable = 4 % 命令窗口中将新创建的变量 +myVariable = 4; % 加上分号可使命令窗口中不显示当前语句执行结果 +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + + +% 调用函数有两种方式: +% 标准函数语法: +load('myFile.mat', 'y') % 参数放在括号内,以英文逗号分隔 +% 指令语法: +load myFile.mat y % 不加括号,以空格分隔参数 +% 注意在指令语法中参数不需要加引号:在这种语法下,所有输入参数都只能是文本文字, +% 不能是变量的具体值,同样也不能是输出变量 +[V,D] = eig(A); % 这条函数调用无法转换成等价的指令语法 +[~,D] = eig(A); % 如果结果中只需要 D 而不需要 V 则可以这样写 + + + +% 逻辑运算 +1 > 5 % 假,ans = 0 +10 >= 10 % 真,ans = 1 +3 ~= 4 % 不等于 -> ans = 1 +3 == 3 % 等于 -> ans = 1 +3 > 1 && 4 > 1 % 与 -> ans = 1 +3 > 1 || 4 > 1 % 或 -> ans = 1 +~1 % 非 -> ans = 0 + +% 逻辑运算可直接应用于矩阵,运算结果也是矩阵 +A > 5 +% 对矩阵中每个元素做逻辑运算,若为真,则在运算结果的矩阵中对应位置的元素就是 1 +A( A > 5 ) +% 如此返回的向量,其元素就是 A 矩阵中所有逻辑运算为真的元素 + +% 字符串 +a = 'MyString' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString +b = '字符串' % MATLAB目前已经可以支持包括中文在内的多种文字 +length(b) % ans = 3 +b(2) % ans = 符 +[b,b] % ans = 字符串字符串 + + +% 元组(cell 数组) +a = {'one', 'two', 'three'} +a(1) % ans = 'one' - 返回一个元组 +char(a(1)) % ans = one - 返回一个字符串 + + +% 结构体 +A.b = {'one','two'}; +A.c = [1 2]; +A.d.e = false; + + +% 向量 +x = [4 32 53 7 1] +x(2) % ans = 32,MATLAB中向量的下标索引从1开始,不是0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % 列向量 + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + + +% 矩阵 +A = [1 2 3; 4 5 6; 7 8 9] +% 以分号分隔不同的行,以空格或逗号分隔同一行中的不同元素 +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6,A(row, column) +A(6) % ans = 8 +% (隐式地将 A 的三列首尾相接组成一个列向量,然后取其下标为 6 的元素) + + +A(2,3) = 42 % 将第 2 行第 3 列的元素设为 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % 取原矩阵中的一块作为新矩阵 +%ans = + +% 5 42 +% 8 9 + +A(:,1) % 第 1 列的所有元素 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % 第 1 行的所有元素 +%ans = + +% 1 2 3 + +[A ; A] % 将两个矩阵上下相接构成新矩阵 +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% 等价于 +vertcat(A, A); + + +[A , A] % 将两个矩阵左右相接构成新矩阵 + +%ans = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% 等价于 +horzcat(A, A); + + +A(:, [3 1 2]) % 重新排布原矩阵的各列 +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % 返回矩阵的行数和列数,ans = 3 3 + +A(1, :) =[] % 删除矩阵的第 1 行 +A(:, 1) =[] % 删除矩阵的第 1 列 + +transpose(A) % 矩阵转置,等价于 A' +ctranspose(A) % 矩阵的共轭转置(对矩阵中的每个元素取共轭复数) + + +% 元素运算 vs. 矩阵运算 +% 单独运算符就是对矩阵整体进行矩阵运算 +% 在运算符加上英文句点就是对矩阵中的元素进行元素计算 +% 示例如下: +A * B % 矩阵乘法,要求 A 的列数等于 B 的行数 +A .* B % 元素乘法,要求 A 和 B 形状一致(A 的行数等于 B 的行数, A 的列数等于 B 的列数) +% 元素乘法的结果是与 A 和 B 形状一致的矩阵,其每个元素等于 A 对应位置的元素乘 B 对应位置的元素 + +% 以下函数中,函数名以 m 结尾的执行矩阵运算,其余执行元素运算: +exp(A) % 对矩阵中每个元素做指数运算 +expm(A) % 对矩阵整体做指数运算 +sqrt(A) % 对矩阵中每个元素做开方运算 +sqrtm(A) % 对矩阵整体做开放运算(即试图求出一个矩阵,该矩阵与自身的乘积等于 A 矩阵) + + +% 绘图 +x = 0:.10:2*pi; % 生成一向量,其元素从 0 开始,以 0.1 的间隔一直递增到 2*pi(pi 就是圆周率) +y = sin(x); +plot(x,y) +xlabel('x axis') +ylabel('y axis') +title('Plot of y = sin(x)') +axis([0 2*pi -1 1]) % x 轴范围是从 0 到 2*pi,y 轴范围是从 -1 到 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % 在同一张图中绘制多条曲线 +legend('Line 1 label', 'Line 2 label') % 为图片加注图例 +% 图例数量应当小于或等于实际绘制的曲线数目,从 plot 绘制的第一条曲线开始对应 + +% 在同一张图上绘制多条曲线的另一种方法: +% 使用 hold on,令系统保留前次绘图结果并在其上直接叠加新的曲线, +% 如果没有 hold on,则每个 plot 都会首先清除之前的绘图结果再进行绘制。 +% 在 hold on 和 hold off 中可以放置任意多的 plot 指令, +% 它们和 hold on 前最后一个 plot 指令的结果都将显示在同一张图中。 +plot(x, y1) +hold on +plot(x, y2) +plot(x, y3) +plot(x, y4) +hold off + +loglog(x, y) % 对数—对数绘图 +semilogx(x, y) % 半对数(x 轴对数)绘图 +semilogy(x, y) % 半对数(y 轴对数)绘图 + +fplot (@(x) x^2, [2,5]) % 绘制函数 x^2 在 [2, 5] 区间的曲线 + +grid on % 在绘制的图中显示网格,使用 grid off 可取消网格显示 +axis square % 将当前坐标系设定为正方形(保证在图形显示上各轴等长) +axis equal % 将当前坐标系设定为相等(保证在实际数值上各轴等长) + +scatter(x, y); % 散点图 +hist(x); % 直方图 + +z = sin(x); +plot3(x,y,z); % 绘制三维曲线 + +pcolor(A) % 伪彩色图(热图) +contour(A) % 等高线图 +mesh(A) % 网格曲面图 + +h = figure % 创建新的图片对象并返回其句柄 h +figure(h) % 将句柄 h 对应的图片作为当前图片 +close(h) % 关闭句柄 h 对应的图片 +close all % 关闭 MATLAB 中所用打开的图片 +close % 关闭当前图片 + +shg % 显示图形窗口 +clf clear % 清除图形窗口中的图像,并重置图像属性 + +% 图像属性可以通过图像句柄进行设定 +% 在创建图像时可以保存图像句柄以便于设置 +% 也可以用 gcf 函数返回当前图像的句柄 +h = plot(x, y); % 在创建图像时显式地保存图像句柄 +set(h, 'Color', 'r') +% 颜色代码:'y' 黄色,'m' 洋红色,'c' 青色,'r' 红色,'g' 绿色,'b' 蓝色,'w' 白色,'k' 黑色 +set(h, 'Color', [0.5, 0.5, 0.4]) +% 也可以使用 RGB 值指定颜色 +set(h, 'LineStyle', '--') +% 线型代码:'--' 实线,'---' 虚线,':' 点线,'-.' 点划线,'none' 不划线 +get(h, 'LineStyle') +% 获取当前句柄的线型 + + +% 用 gca 函数返回当前图像的坐标轴句柄 +set(gca, 'XDir', 'reverse'); % 令 x 轴反向 + +% 用 subplot 指令创建平铺排列的多张子图 +subplot(2,3,1); % 选择 2 x 3 排列的子图中的第 1 张图 +plot(x1); title('First Plot') % 在选中的图中绘图 +subplot(2,3,2); % 选择 2 x 3 排列的子图中的第 2 张图 +plot(x2); title('Second Plot') % 在选中的图中绘图 + + +% 要调用函数或脚本,必须保证它们在你的当前工作目录中 +path % 显示当前工作目录 +addpath /path/to/dir % 将指定路径加入到当前工作目录中 +rmpath /path/to/dir % 将指定路径从当前工作目录中删除 +cd /path/to/move/into % 以制定路径作为当前工作目录 + + +% 变量可保存到 .mat 格式的本地文件 +save('myFileName.mat') % 保存当前工作空间中的所有变量 +load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间 + + +% .m 脚本文件 +% 脚本文件是一个包含多条 MATLAB 指令的外部文件,以 .m 为后缀名 +% 使用脚本文件可以避免在命令窗口中重复输入冗长的指令 + + +% .m 函数文件 +% 与脚本文件类似,同样以 .m 作为后缀名 +% 但函数文件可以接受用户输入的参数并返回运算结果 +% 并且函数拥有自己的工作空间(变量域),不必担心变量名称冲突 +% 函数文件的名称应当与其所定义的函数的名称一致(比如下面例子中函数文件就应命名为 double_input.m) +% 使用 'help double_input.m' 可返回函数定义中第一行注释信息 +function output = double_input(x) + % double_input(x) 返回 x 的 2 倍 + output = 2*x; +end +double_input(6) % ans = 12 + + +% 同样还可以定义子函数和内嵌函数 +% 子函数与主函数放在同一个函数文件中,且只能被这个主函数调用 +% 内嵌函数放在另一个函数体内,可以直接访问被嵌套函数的各个变量 + + +% 使用匿名函数可以不必创建 .m 函数文件 +% 匿名函数适用于快速定义某函数以便传递给另一指令或函数(如绘图、积分、求根、求极值等) +% 下面示例的匿名函数返回输入参数的平方根,可以使用句柄 sqr 进行调用: +sqr = @(x) x.^2; +sqr(10) % ans = 100 +doc function_handle % find out more + + +% 接受用户输入 +a = input('Enter the value: ') + + +% 从文件中读取数据 +fopen(filename) +% 类似函数还有 xlsread(excel 文件)、importdata(CSV 文件)、imread(图像文件) + + +% 输出 +disp(a) % 在命令窗口中打印变量 a 的值 +disp('Hello World') % 在命令窗口中打印字符串 +fprintf % 按照指定格式在命令窗口中打印内容 + +% 条件语句(if 和 elseif 语句中的括号并非必需,但推荐加括号避免混淆) +if (a > 15) + disp('Greater than 15') +elseif (a == 23) + disp('a is 23') +else + disp('neither condition met') +end + +% 循环语句 +% 注意:对向量或矩阵使用循环语句进行元素遍历的效率很低!! +% 注意:只要有可能,就尽量使用向量或矩阵的整体运算取代逐元素循环遍历!! +% MATLAB 在开发时对向量和矩阵运算做了专门优化,做向量和矩阵整体运算的效率高于循环语句 +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + + +% 程序运行计时:'tic' 是计时开始,'toc' 是计时结束并打印结果 +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + + +% 链接 MySQL 数据库 +dbname = 'database_name'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); % 此处 xx 代表具体版本号 +% 这里的 mysql-connector-java-5.1.xx-bin.jar 可从 http://dev.mysql.com/downloads/connector/j/ 下载 +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] % SQL 语句 +a = fetch(conn, sql) % a 即包含所需数据 + + +% 常用数学函数 +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand % 均匀分布的伪随机浮点数 +randi % 均匀分布的伪随机整数 +randn % 正态分布的伪随机浮点数 + +% 常用常数 +pi +NaN +inf + +% 求解矩阵方程(如果方程无解,则返回最小二乘近似解) +% \ 操作符等价于 mldivide 函数,/ 操作符等价于 mrdivide 函数 +x=A\b % 求解 Ax=b,比先求逆再左乘 inv(A)*b 更加高效、准确 +x=b/A % 求解 xA=b + +inv(A) % 逆矩阵 +pinv(A) % 伪逆矩阵 + + +% 常用矩阵函数 +zeros(m, n) % m x n 阶矩阵,元素全为 0 +ones(m, n) % m x n 阶矩阵,元素全为 1 +diag(A) % 返回矩阵 A 的对角线元素 +diag(x) % 构造一个对角阵,对角线元素就是向量 x 的各元素 +eye(m, n) % m x n 阶单位矩阵 +linspace(x1, x2, n) % 返回介于 x1 和 x2 之间的 n 个等距节点 +inv(A) % 矩阵 A 的逆矩阵 +det(A) % 矩阵 A 的行列式 +eig(A) % 矩阵 A 的特征值和特征向量 +trace(A) % 矩阵 A 的迹(即对角线元素之和),等价于 sum(diag(A)) +isempty(A) % 测试 A 是否为空 +all(A) % 测试 A 中所有元素是否都非 0 或都为真(逻辑值) +any(A) % 测试 A 中是否有元素非 0 或为真(逻辑值) +isequal(A, B) % 测试 A 和 B是否相等 +numel(A) % 矩阵 A 的元素个数 +triu(x) % 返回 x 的上三角这部分 +tril(x) % 返回 x 的下三角这部分 +cross(A, B) % 返回 A 和 B 的叉积(矢量积、外积) +dot(A, B) % 返回 A 和 B 的点积(数量积、内积),要求 A 和 B 必须等长 +transpose(A) % A 的转置,等价于 A' +fliplr(A) % 将一个矩阵左右翻转 +flipud(A) % 将一个矩阵上下翻转 + +% 矩阵分解 +[L, U, P] = lu(A) % LU 分解:PA = LU,L 是下三角阵,U 是上三角阵,P 是置换阵 +[P, D] = eig(A) % 特征值分解:AP = PD,D 是由特征值构成的对角阵,P 的各列就是对应的特征向量 +[U, S, V] = svd(X) % 奇异值分解:XV = US,U 和 V 是酉矩阵,S 是由奇异值构成的半正定实数对角阵 + +% 常用向量函数 +max % 最大值 +min % 最小值 +length % 元素个数 +sort % 按升序排列 +sum % 各元素之和 +prod % 各元素之积 +mode % 众数 +median % 中位数 +mean % 平均值 +std % 标准差 +perms(x) % x 元素的全排列 + +``` + +## 相关资料 + +* 官方网页:[http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* 官方论坛:[http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) -- cgit v1.2.3 From d7672a2bc53dd8b81c4da8c620178cc2458c9238 Mon Sep 17 00:00:00 2001 From: Artur Mkrtchyan Date: Sat, 3 Jan 2015 19:48:53 +0100 Subject: Added warning on return usage --- scala.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 35645922..cfc5a1e9 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -198,7 +198,9 @@ weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most -// def that surrounds it. It has no effect on anonymous functions. For example: +// def that surrounds it. +// WARNING: Using return in Scala is error-prone and should be avoided. +// It has no effect on anonymous functions. For example: def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) -- cgit v1.2.3 From 79b730dcaa8994cb6b58af1e25a5aa9e06f48471 Mon Sep 17 00:00:00 2001 From: Poor Yorick Date: Sun, 4 Jan 2015 23:00:23 -0700 Subject: add filename: learntcl.tcl --- tcl.html.markdown | 893 +++++++++++++++++++++++++++--------------------------- 1 file changed, 447 insertions(+), 446 deletions(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index 44805b5c..f2d92fcd 100755 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -1,446 +1,447 @@ ---- -language: Tcl -contributors: - - ["Poor Yorick", "http://pooryorick.com/"] ---- - -Tcl was created by [John Ousterhout](http://wiki.tcl.tk/John Ousterout) as a -reusable scripting language for chip design tools he was creating. In 1997 he -was awarded the [ACM Software System -Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) for Tcl. Tcl -can be used both as an embeddable scripting language and as a general -programming language. It can also be used as a portable C library, even in -cases where no scripting capability is needed, as it provides data structures -such as dynamic strings, lists, and hash tables. The C library also provides -portable functionality for loading dynamic libraries, string formatting and -code conversion, filesystem operations, network operations, and more. -Various features of Tcl stand out: - -* Convenient cross-platform networking API - -* Fully virtualized filesystem - -* Stackable I/O channels - -* Asynchronous to the core - -* Full coroutines - -* A threading model recognized as robust and easy to use - - -If Lisp is a list processor, then Tcl is a string processor. All values are -strings. A list is a string format. A procedure definition is a string -format. To achieve performance, Tcl internally caches structured -representations of these values. The list commands, for example, operate on -the internal cached representation, and Tcl takes care of updating the string -representation if it is ever actually needed in the script. The copy-on-write -design of Tcl allows script authors can pass around large data values without -actually incurring additional memory overhead. Procedures are automatically -byte-compiled unless they use the more dynamic commands such as "uplevel", -"upvar", and "trace". - -Tcl is a pleasure to program in. It will appeal to hacker types who find Lisp, -Forth, or Smalltalk interesting, as well as to engineers and scientists who -just want to get down to business with a tool that bends to their will. Its -discipline of exposing all programmatic functionality as commands, including -things like loops and mathematical operations that are usually baked into the -syntax of other languages, allows it to fade into the background of whatever -domain-specific functionality a project needs. It's syntax, which is even -lighter that that of Lisp, just gets out of the way. - - - - - -```tcl -#! /bin/env tclsh - -################################################################################ -## 1. Guidelines -################################################################################ - -# Tcl is not Bash or C! This needs to be said because standard shell quoting -# habits almost work in Tcl and it is common for people to pick up Tcl and try -# to get by with syntax they know from another language. It works at first, -# but soon leads to frustration with more complex scripts. - -# Braces are just a quoting mechanism, not a code block constructor or a list -# constructor. Tcl doesn't have either of those things. Braces are used, -# though, to escape special characters in procedure bodies and in strings that -# are formatted as lists. - - -################################################################################ -## 2. Syntax -################################################################################ - -# Every line is a command. The first word is the name of the command, and -# subsequent words are arguments to the command. Words are delimited by -# whitespace. Since every word is a string, in the simple case no special -# markup such as quotes, braces, or backslash, is necessary. Even when quotes -# are used, they are not a string constructor, but just another escaping -# character. - -set greeting1 Sal -set greeting2 ut -set greeting3 ations - - -#semicolon also delimits commands -set greeting1 Sal; set greeting2 ut; set greeting3 ations - - -# Dollar sign introduces variable substitution -set greeting $greeting1$greeting2$greeting3 - - -# Bracket introduces command substitution. The result of the command is -# substituted in place of the bracketed script. When the "set" command is -# given only the name of a variable, it returns the value of that variable. -set greeting $greeting1$greeting2[set greeting3] - - -# Command substitution should really be called script substitution, because an -# entire script, not just a command, can be placed between the brackets. The -# "incr" command increments the value of a variable and returns its value. -set greeting $greeting[ - incr i - incr i - incr i -] - - -# backslash suppresses the special meaning of characters -set amount \$16.42 - - -# backslash adds special meaning to certain characters -puts lots\nof\n\n\n\n\n\nnewlines - - -# A word enclosed in braces is not subject to any special interpretation or -# substitutions, except that a backslash before a brace is not counted when look#ing for the closing brace -set somevar { - This is a literal $ sign, and this \} escaped - brace remains uninterpreted -} - - -# In a word enclosed in double quotes, whitespace characters lose their special -# meaning -set name Neo -set greeting "Hello, $name" - - -#variable names can be any string -set {first name} New - - -# The brace form of variable substitution handles more complex variable names -set greeting "Hello, ${first name}" - - -# The "set" command can always be used instead of variable substitution -set greeting "Hello, [set {first name}]" - - -# To promote the words within a word to individual words of the current -# command, use the expansion operator, "{*}". -set {*}{name Neo} - -# is equivalent to -set name Neo - - -# An array is a special variable that is a container for other variables. -set person(name) Neo -set person(gender) male -set greeting "Hello, $person(name)" - - -# A namespace holds commands and variables -namespace eval people { - namespace eval person1 { - set name Neo - } -} - - -#The full name of a variable includes its enclosing namespace(s), delimited by two colons: -set greeting "Hello $people::person::name" - - - -################################################################################ -## 3. A Few Notes -################################################################################ - -# All other functionality is implemented via commands. From this point on, -# there is no new syntax. Everything else there is to learn about Tcl is about -# the behaviour of individual commands, and what meaning they assign to their -# arguments. - - -# To end up with an interpreter that can do nothing, delete the global -# namespace. It's not very useful to do such a thing, but it illustrates the -# nature of Tcl. -namespace delete :: - - -# Because of name resolution behaviour, its safer to use the "variable" command to declare or to assign a value to a namespace. -namespace eval people { - namespace eval person1 { - variable name Neo - } -} - - -# The full name of a variable can always be used, if desired. -set people::person1::name Neo - - - -################################################################################ -## 4. Commands -################################################################################ - -# Math can be done with the "expr" command. -set a 3 -set b 4 -set c [expr {$a + $b}] - -# Since "expr" performs variable substitution on its own, brace the expression -# to prevent Tcl from performing variable substitution first. See -# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" for details. - - -# The "expr" command understands variable and command substitution -set c [expr {$a + [set b]}] - - -# The "expr" command provides a set of mathematical functions -set c [expr {pow($a,$b)}] - - -# Mathematical operators are available as commands in the ::tcl::mathop -# namespace -::tcl::mathop::+ 5 3 - -# Commands can be imported from other namespaces -namespace import ::tcl::mathop::+ -set result [+ 5 3] - - -# New commands can be created via the "proc" command. -proc greet name { - return "Hello, $name!" -} - -#multiple parameters can be specified -proc greet {greeting name} { - return "$greeting, $name!" -} - - -# As noted earlier, braces do not construct a code block. Every value, even -# the third argument of the "proc" command, is a string. The previous command -# rewritten to not use braces at all: -proc greet greeting\ name return\ \"Hello,\ \$name! - - - -# When the last parameter is the literal value, "args", it collects all extra -# arguments when the command is invoked -proc fold {cmd args} { - set res 0 - foreach arg $args { - set res [cmd $res $arg] - } -} -fold ::tcl::mathop::* 5 3 3 ;# -> 45 - - -# Conditional execution is implemented as a command -if {3 > 4} { - puts {This will never happen} -} elseif {4 > 4} { - puts {This will also never happen} -} else { - puts {This will always happen} -} - - -# Loops are implemented as commands. The first, second, and third -# arguments of the "for" command are treated as mathematical expressions -for {set i 0} {$i < 10} {incr i} { - set res [expr {$res + $i}] -} - - -# The first argument of the "while" command is also treated as a mathematical -# expression -set i 0 -while {$i < 10} { - incr i 2 -} - - -# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values -set amounts 10\ 33\ 18 -set amount [lindex $amounts 1] - - -# Braces and backslash can be used to format more complex values in a list. A -# list looks exactly like a script, except that the newline character and the -# semicolon character lose their special meanings. This feature makes Tcl -# homoiconic. There are three items in the following list. -set values { - - one\ two - - {three four} - - five\{six - -} - - -# Since a list is a string, string operations could be performed on it, at the -# risk of corrupting the formatting of the list. -set values {one two three four} -set values [string map {two \{} $values] ;# $values is no-longer a \ - properly-formatted listwell-formed list - - -# The sure-fire way to get a properly-formmated list is to use "list" commands -set values [list one \{ three four] -lappend values { } ;# add a single space as an item in the list - - -# Use "eval" to evaluate a value as a script -eval { - set name Neo - set greeting "Hello, $name" -} - - -# A list can always be passed to "eval" as a script composed of a single -# command. -eval {set name Neo} -eval [list set greeting "Hello, $name"] - - -# Therefore, when using "eval", use [list] to build up a desired command -set command {set name} -lappend command {Archibald Sorbisol} -eval $command - - -# A common mistake is not to use list functions when building up a command -set command {set name} -append command { Archibald Sorbisol} -eval $command ;# There is an error here, because there are too many arguments \ - to "set" in {set name Archibald Sorbisol} - - -# This mistake can easily occur with the "subst" command. -set replacement {Archibald Sorbisol} -set command {set name $replacement} -set command [subst $command] -eval $command ;# The same error as before: to many arguments to "set" in \ - {set name Archibald Sorbisol} - - -# The proper way is to format the substituted value using use the "list" -# command. -set replacement [list {Archibald Sorbisol}] -set command {set name $replacement} -set command [subst $command] -eval $command - - -# It is extremely common to see the "list" command being used to properly -# format values that are substituted into Tcl script templates. There are -# several examples of this, below. - - -# The "apply" command evaluates a string as a command. -set cmd {{greeting name} { - return "$greeting, $name!" -}} -apply $cmd Whaddup Neo - - -# The "uplevel" command evaluates a script in some enclosing scope. -proc greet {} { - uplevel {puts "$greeting, $name"} -} - -proc set_double {varname value} { - if {[string is double $value]} { - uplevel [list variable $varname $value] - } else { - error [list {not a double} $value] - } -} - - -# The "upvar" command links a variable in the current scope to a variable in -# some enclosing scope -proc set_double {varname value} { - if {[string is double $value]} { - upvar 1 $varname var - set var $value - } else { - error [list {not a double} $value] - } -} - - -#get rid of the built-in "while" command. -rename ::while {} - - -# Define a new while command with the "proc" command. More sophisticated error -# handling is left as an exercise. -proc while {condition script} { - if {[uplevel 1 [list expr $condition]]} { - uplevel 1 $script - tailcall [namespace which while] $condition $script - } -} - - -# The "coroutine" command creates a separate call stack, along with a command -# to enter that call stack. The "yield" command suspends execution in that -# stack. -proc countdown {} { - #send something back to the initial "coroutine" command - yield - - set count 3 - while {$count > 1} { - yield [incr count -1] - } - return 0 -} -coroutine countdown1 countdown -coroutine countdown2 countdown -puts [countdown 1] ;# -> 2 -puts [countdown 2] ;# -> 2 -puts [countdown 1] ;# -> 1 -puts [countdown 1] ;# -> 0 -puts [coundown 1] ;# -> invalid command name "countdown1" -puts [countdown 2] ;# -> 1 - - -``` - -## Reference - -[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) - -[Tcl Wiki](http://wiki.tcl.tk) - -[Tcl Subreddit](http://www.reddit.com/r/Tcl) +--- +language: Tcl +contributors: + - ["Poor Yorick", "http://pooryorick.com/"] +filename: learntcl.tcl +--- + +Tcl was created by [John Ousterhout](http://wiki.tcl.tk/John Ousterout) as a +reusable scripting language for chip design tools he was creating. In 1997 he +was awarded the [ACM Software System +Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) for Tcl. Tcl +can be used both as an embeddable scripting language and as a general +programming language. It can also be used as a portable C library, even in +cases where no scripting capability is needed, as it provides data structures +such as dynamic strings, lists, and hash tables. The C library also provides +portable functionality for loading dynamic libraries, string formatting and +code conversion, filesystem operations, network operations, and more. +Various features of Tcl stand out: + +* Convenient cross-platform networking API + +* Fully virtualized filesystem + +* Stackable I/O channels + +* Asynchronous to the core + +* Full coroutines + +* A threading model recognized as robust and easy to use + + +If Lisp is a list processor, then Tcl is a string processor. All values are +strings. A list is a string format. A procedure definition is a string +format. To achieve performance, Tcl internally caches structured +representations of these values. The list commands, for example, operate on +the internal cached representation, and Tcl takes care of updating the string +representation if it is ever actually needed in the script. The copy-on-write +design of Tcl allows script authors can pass around large data values without +actually incurring additional memory overhead. Procedures are automatically +byte-compiled unless they use the more dynamic commands such as "uplevel", +"upvar", and "trace". + +Tcl is a pleasure to program in. It will appeal to hacker types who find Lisp, +Forth, or Smalltalk interesting, as well as to engineers and scientists who +just want to get down to business with a tool that bends to their will. Its +discipline of exposing all programmatic functionality as commands, including +things like loops and mathematical operations that are usually baked into the +syntax of other languages, allows it to fade into the background of whatever +domain-specific functionality a project needs. It's syntax, which is even +lighter that that of Lisp, just gets out of the way. + + + + + +```tcl +#! /bin/env tclsh + +################################################################################ +## 1. Guidelines +################################################################################ + +# Tcl is not Bash or C! This needs to be said because standard shell quoting +# habits almost work in Tcl and it is common for people to pick up Tcl and try +# to get by with syntax they know from another language. It works at first, +# but soon leads to frustration with more complex scripts. + +# Braces are just a quoting mechanism, not a code block constructor or a list +# constructor. Tcl doesn't have either of those things. Braces are used, +# though, to escape special characters in procedure bodies and in strings that +# are formatted as lists. + + +################################################################################ +## 2. Syntax +################################################################################ + +# Every line is a command. The first word is the name of the command, and +# subsequent words are arguments to the command. Words are delimited by +# whitespace. Since every word is a string, in the simple case no special +# markup such as quotes, braces, or backslash, is necessary. Even when quotes +# are used, they are not a string constructor, but just another escaping +# character. + +set greeting1 Sal +set greeting2 ut +set greeting3 ations + + +#semicolon also delimits commands +set greeting1 Sal; set greeting2 ut; set greeting3 ations + + +# Dollar sign introduces variable substitution +set greeting $greeting1$greeting2$greeting3 + + +# Bracket introduces command substitution. The result of the command is +# substituted in place of the bracketed script. When the "set" command is +# given only the name of a variable, it returns the value of that variable. +set greeting $greeting1$greeting2[set greeting3] + + +# Command substitution should really be called script substitution, because an +# entire script, not just a command, can be placed between the brackets. The +# "incr" command increments the value of a variable and returns its value. +set greeting $greeting[ + incr i + incr i + incr i +] + + +# backslash suppresses the special meaning of characters +set amount \$16.42 + + +# backslash adds special meaning to certain characters +puts lots\nof\n\n\n\n\n\nnewlines + + +# A word enclosed in braces is not subject to any special interpretation or +# substitutions, except that a backslash before a brace is not counted when look#ing for the closing brace +set somevar { + This is a literal $ sign, and this \} escaped + brace remains uninterpreted +} + + +# In a word enclosed in double quotes, whitespace characters lose their special +# meaning +set name Neo +set greeting "Hello, $name" + + +#variable names can be any string +set {first name} New + + +# The brace form of variable substitution handles more complex variable names +set greeting "Hello, ${first name}" + + +# The "set" command can always be used instead of variable substitution +set greeting "Hello, [set {first name}]" + + +# To promote the words within a word to individual words of the current +# command, use the expansion operator, "{*}". +set {*}{name Neo} + +# is equivalent to +set name Neo + + +# An array is a special variable that is a container for other variables. +set person(name) Neo +set person(gender) male +set greeting "Hello, $person(name)" + + +# A namespace holds commands and variables +namespace eval people { + namespace eval person1 { + set name Neo + } +} + + +#The full name of a variable includes its enclosing namespace(s), delimited by two colons: +set greeting "Hello $people::person::name" + + + +################################################################################ +## 3. A Few Notes +################################################################################ + +# All other functionality is implemented via commands. From this point on, +# there is no new syntax. Everything else there is to learn about Tcl is about +# the behaviour of individual commands, and what meaning they assign to their +# arguments. + + +# To end up with an interpreter that can do nothing, delete the global +# namespace. It's not very useful to do such a thing, but it illustrates the +# nature of Tcl. +namespace delete :: + + +# Because of name resolution behaviour, its safer to use the "variable" command to declare or to assign a value to a namespace. +namespace eval people { + namespace eval person1 { + variable name Neo + } +} + + +# The full name of a variable can always be used, if desired. +set people::person1::name Neo + + + +################################################################################ +## 4. Commands +################################################################################ + +# Math can be done with the "expr" command. +set a 3 +set b 4 +set c [expr {$a + $b}] + +# Since "expr" performs variable substitution on its own, brace the expression +# to prevent Tcl from performing variable substitution first. See +# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" for details. + + +# The "expr" command understands variable and command substitution +set c [expr {$a + [set b]}] + + +# The "expr" command provides a set of mathematical functions +set c [expr {pow($a,$b)}] + + +# Mathematical operators are available as commands in the ::tcl::mathop +# namespace +::tcl::mathop::+ 5 3 + +# Commands can be imported from other namespaces +namespace import ::tcl::mathop::+ +set result [+ 5 3] + + +# New commands can be created via the "proc" command. +proc greet name { + return "Hello, $name!" +} + +#multiple parameters can be specified +proc greet {greeting name} { + return "$greeting, $name!" +} + + +# As noted earlier, braces do not construct a code block. Every value, even +# the third argument of the "proc" command, is a string. The previous command +# rewritten to not use braces at all: +proc greet greeting\ name return\ \"Hello,\ \$name! + + + +# When the last parameter is the literal value, "args", it collects all extra +# arguments when the command is invoked +proc fold {cmd args} { + set res 0 + foreach arg $args { + set res [cmd $res $arg] + } +} +fold ::tcl::mathop::* 5 3 3 ;# -> 45 + + +# Conditional execution is implemented as a command +if {3 > 4} { + puts {This will never happen} +} elseif {4 > 4} { + puts {This will also never happen} +} else { + puts {This will always happen} +} + + +# Loops are implemented as commands. The first, second, and third +# arguments of the "for" command are treated as mathematical expressions +for {set i 0} {$i < 10} {incr i} { + set res [expr {$res + $i}] +} + + +# The first argument of the "while" command is also treated as a mathematical +# expression +set i 0 +while {$i < 10} { + incr i 2 +} + + +# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values +set amounts 10\ 33\ 18 +set amount [lindex $amounts 1] + + +# Braces and backslash can be used to format more complex values in a list. A +# list looks exactly like a script, except that the newline character and the +# semicolon character lose their special meanings. This feature makes Tcl +# homoiconic. There are three items in the following list. +set values { + + one\ two + + {three four} + + five\{six + +} + + +# Since a list is a string, string operations could be performed on it, at the +# risk of corrupting the formatting of the list. +set values {one two three four} +set values [string map {two \{} $values] ;# $values is no-longer a \ + properly-formatted listwell-formed list + + +# The sure-fire way to get a properly-formmated list is to use "list" commands +set values [list one \{ three four] +lappend values { } ;# add a single space as an item in the list + + +# Use "eval" to evaluate a value as a script +eval { + set name Neo + set greeting "Hello, $name" +} + + +# A list can always be passed to "eval" as a script composed of a single +# command. +eval {set name Neo} +eval [list set greeting "Hello, $name"] + + +# Therefore, when using "eval", use [list] to build up a desired command +set command {set name} +lappend command {Archibald Sorbisol} +eval $command + + +# A common mistake is not to use list functions when building up a command +set command {set name} +append command { Archibald Sorbisol} +eval $command ;# There is an error here, because there are too many arguments \ + to "set" in {set name Archibald Sorbisol} + + +# This mistake can easily occur with the "subst" command. +set replacement {Archibald Sorbisol} +set command {set name $replacement} +set command [subst $command] +eval $command ;# The same error as before: to many arguments to "set" in \ + {set name Archibald Sorbisol} + + +# The proper way is to format the substituted value using use the "list" +# command. +set replacement [list {Archibald Sorbisol}] +set command {set name $replacement} +set command [subst $command] +eval $command + + +# It is extremely common to see the "list" command being used to properly +# format values that are substituted into Tcl script templates. There are +# several examples of this, below. + + +# The "apply" command evaluates a string as a command. +set cmd {{greeting name} { + return "$greeting, $name!" +}} +apply $cmd Whaddup Neo + + +# The "uplevel" command evaluates a script in some enclosing scope. +proc greet {} { + uplevel {puts "$greeting, $name"} +} + +proc set_double {varname value} { + if {[string is double $value]} { + uplevel [list variable $varname $value] + } else { + error [list {not a double} $value] + } +} + + +# The "upvar" command links a variable in the current scope to a variable in +# some enclosing scope +proc set_double {varname value} { + if {[string is double $value]} { + upvar 1 $varname var + set var $value + } else { + error [list {not a double} $value] + } +} + + +#get rid of the built-in "while" command. +rename ::while {} + + +# Define a new while command with the "proc" command. More sophisticated error +# handling is left as an exercise. +proc while {condition script} { + if {[uplevel 1 [list expr $condition]]} { + uplevel 1 $script + tailcall [namespace which while] $condition $script + } +} + + +# The "coroutine" command creates a separate call stack, along with a command +# to enter that call stack. The "yield" command suspends execution in that +# stack. +proc countdown {} { + #send something back to the initial "coroutine" command + yield + + set count 3 + while {$count > 1} { + yield [incr count -1] + } + return 0 +} +coroutine countdown1 countdown +coroutine countdown2 countdown +puts [countdown 1] ;# -> 2 +puts [countdown 2] ;# -> 2 +puts [countdown 1] ;# -> 1 +puts [countdown 1] ;# -> 0 +puts [coundown 1] ;# -> invalid command name "countdown1" +puts [countdown 2] ;# -> 1 + + +``` + +## Reference + +[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) + +[Tcl Wiki](http://wiki.tcl.tk) + +[Tcl Subreddit](http://www.reddit.com/r/Tcl) -- cgit v1.2.3 From 0512b3120acbe9d3a534cbc7685c30a65e067801 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Wed, 7 Jan 2015 23:15:25 +0800 Subject: java: Add `@Override` for interfaces. --- java.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index 4661d4f9..3dd65679 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -4,6 +4,7 @@ language: java contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Madison Dickson", "http://github.com/mix3d"] + - ["Jakukyo Friel", "http://weakish.github.io"] filename: LearnJava.java --- @@ -433,10 +434,12 @@ public interface Digestible { //We can now create a class that implements both of these interfaces public class Fruit implements Edible, Digestible { + @Override public void eat() { //... } + @Override public void digest() { //... } @@ -445,10 +448,12 @@ public class Fruit implements Edible, Digestible { //In java, you can extend only one class, but you can implement many interfaces. //For example: public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { + @Override public void InterfaceOneMethod() { } + @Override public void InterfaceTwoMethod() { } -- cgit v1.2.3 From aa13db251bec274a1227235f0cea376c100f003b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Ara=C3=BAjo?= Date: Wed, 7 Jan 2015 14:35:03 -0300 Subject: [XML/en] translated to [XML/pt-br] --- pt-br/xml-pt.html.markdown | 133 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 pt-br/xml-pt.html.markdown diff --git a/pt-br/xml-pt.html.markdown b/pt-br/xml-pt.html.markdown new file mode 100644 index 00000000..40ddbc3a --- /dev/null +++ b/pt-br/xml-pt.html.markdown @@ -0,0 +1,133 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +XML é uma linguagem de marcação projetada para armazenar e transportar dados. + +Ao contrário de HTML, XML não especifica como exibir ou formatar os dados, +basta carregá-lo. + +* Sintaxe XML + +```xml + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + + + +computer.gif + + +``` + +* Documento bem formatado x Validação + +Um documento XML é bem formatado se estiver sintaticamente correto.No entanto, +é possível injetar mais restrições no documento, utilizando definições de +documentos, tais como DTD e XML Schema. + +Um documento XML que segue uma definição de documento é chamado válido, sobre +esse documento. + +Com esta ferramenta, você pode verificar os dados XML fora da lógica da aplicação. + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` \ No newline at end of file -- cgit v1.2.3 From 7dad0b92cc81b34c98bdcb204ada59c4fd1f627b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Ara=C3=BAjo?= Date: Thu, 8 Jan 2015 11:28:11 -0300 Subject: [Hy/en] translated to [Hy/pt-bt] --- pt-br/hy-pt.html.markdown | 176 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 pt-br/hy-pt.html.markdown diff --git a/pt-br/hy-pt.html.markdown b/pt-br/hy-pt.html.markdown new file mode 100644 index 00000000..4230579d --- /dev/null +++ b/pt-br/hy-pt.html.markdown @@ -0,0 +1,176 @@ +--- +language: hy +filename: learnhy.hy +contributors: + - ["Abhishek L", "http://twitter.com/abhishekl"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +Hy é um dialeto de Lisp escrito sobre Python. Isto é possível convertendo +código Hy em árvore sintática abstrata python (ast). Portanto, isto permite +hy chamar código python nativo e vice-versa. + +Este tutorial funciona para hy ≥ 0.9.12 + +```clojure +;; Isso dá uma introdução básica em hy, como uma preliminar para o link abaixo +;; http://try-hy.appspot.com +;; +; Comentários em ponto-e-vírgula, como em outros LISPS + +;; s-noções básicas de expressão +; programas Lisp são feitos de expressões simbólicas ou sexps que se assemelham +(some-function args) +; agora o essencial "Olá mundo" +(print "hello world") + +;; Tipos de dados simples +; Todos os tipos de dados simples são exatamente semelhantes aos seus homólogos +; em python que +42 ; => 42 +3.14 ; => 3.14 +True ; => True +4+10j ; => (4+10j) um número complexo + +; Vamos começar com um pouco de aritmética muito simples +(+ 4 1) ;=> 5 +; o operador é aplicado a todos os argumentos, como outros lisps +(+ 4 1 2 3) ;=> 10 +(- 2 1) ;=> 1 +(* 4 2) ;=> 8 +(/ 4 1) ;=> 4 +(% 4 2) ;=> 0 o operador módulo +; exponenciação é representado pelo operador ** como python +(** 3 2) ;=> 9 +; formas aninhadas vão fazer a coisa esperada +(+ 2 (* 4 2)) ;=> 10 +; também operadores lógicos e ou não e igual etc. faz como esperado +(= 5 4) ;=> False +(not (= 5 4)) ;=> True + +;; variáveis +; variáveis são definidas usando SETV, nomes de variáveis podem usar utf-8, exceto +; for ()[]{}",'`;#| +(setv a 42) +(setv π 3.14159) +(def *foo* 42) +;; outros tipos de dados de armazenamento +; strings, lists, tuples & dicts +; estes são exatamente os mesmos tipos de armazenamento de python +"hello world" ;=> "hello world" +; operações de string funcionam semelhante em python +(+ "hello " "world") ;=> "hello world" +; Listas são criadas usando [], a indexação começa em 0 +(setv mylist [1 2 3 4]) +; tuplas são estruturas de dados imutáveis +(setv mytuple (, 1 2)) +; dicionários são pares de valores-chave +(setv dict1 {"key1" 42 "key2" 21}) +; :nome pode ser utilizado para definir palavras-chave em hy que podem ser utilizados para as chaves +(setv dict2 {:key1 41 :key2 20}) +; usar 'get' para obter o elemento em um índice/key +(get mylist 1) ;=> 2 +(get dict1 "key1") ;=> 42 +; Alternativamente, se foram utilizadas palavras-chave que podem ser chamadas diretamente +(:key1 dict2) ;=> 41 + +;; funções e outras estruturas de programa +; funções são definidas usando defn, o último sexp é devolvido por padrão +(defn greet [name] + "A simple greeting" ; uma docstring opcional + (print "hello " name)) + +(greet "bilbo") ;=> "hello bilbo" + +; funções podem ter argumentos opcionais, bem como argumentos-chave +(defn foolists [arg1 &optional [arg2 2]] + [arg1 arg2]) + +(foolists 3) ;=> [3 2] +(foolists 10 3) ;=> [10 3] + +; funções anônimas são criados usando construtores 'fn' ou 'lambda' +; que são semelhantes para 'defn' +(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16] + +;; operações de sequência +; hy tem algumas utils embutidas para operações de sequência, etc. +; recuperar o primeiro elemento usando 'first' ou 'car' +(setv mylist [1 2 3 4]) +(setv mydict {"a" 1 "b" 2}) +(first mylist) ;=> 1 + +; corte listas usando 'slice' +(slice mylist 1 3) ;=> [2 3] + +; obter elementos de uma lista ou dict usando 'get' +(get mylist 1) ;=> 2 +(get mydict "b") ;=> 2 +; lista de indexação começa a partir de 0, igual em python +; assoc pode definir elementos em chaves/índices +(assoc mylist 2 10) ; faz mylist [1 2 10 4] +(assoc mydict "c" 3) ; faz mydict {"a" 1 "b" 2 "c" 3} +; há toda uma série de outras funções essenciais que torna o trabalho com +; sequências uma diversão + +;; Python interop +;; importação funciona exatamente como em python +(import datetime) +(import [functools [partial reduce]]) ; importa fun1 e fun2 do module1 +(import [matplotlib.pyplot :as plt]) ; fazendo uma importação em foo como em bar +; todos os métodos de python embutidas etc. são acessíveis a partir hy +; a.foo(arg) is called as (.foo a arg) +(.split (.strip "hello world ")) ;=> ["hello" "world"] + +;; Condicionais +; (if condition (body-if-true) (body-if-false) +(if (= passcode "moria") + (print "welcome") + (print "Speak friend, and Enter!")) + +; aninhe múltiplas cláusulas 'if else if' com cond +(cond + [(= someval 42) + (print "Life, universe and everything else!")] + [(> someval 42) + (print "val too large")] + [(< someval 42) + (print "val too small")]) + +; declarações de grupo com 'do', essas são executadas sequencialmente +; formas como defn tem um 'do' implícito +(do + (setv someval 10) + (print "someval is set to " someval)) ;=> 10 + +; criar ligações lexicais com 'let', todas as variáveis definidas desta forma +; tem escopo local +(let [[nemesis {"superman" "lex luther" + "sherlock" "moriarty" + "seinfeld" "newman"}]] + (for [(, h v) (.items nemesis)] + (print (.format "{0}'s nemesis was {1}" h v)))) + +;; classes +; classes são definidas da seguinte maneira +(defclass Wizard [object] + [[--init-- (fn [self spell] + (setv self.spell spell) ; init a mágica attr + None)] + [get-spell (fn [self] + self.spell)]]) + +;; acesse hylang.org +``` + +### Outras Leituras + +Este tutorial é apenas uma introdução básica para hy/lisp/python. + +Docs Hy: [http://hy.readthedocs.org](http://hy.readthedocs.org) + +Repo Hy no Github: [http://github.com/hylang/hy](http://github.com/hylang/hy) + +Acesso ao freenode irc com #hy, hashtag no twitter: #hylang -- cgit v1.2.3 From d1171443ddc0eda7cbabfc41d110a76a67e494ab Mon Sep 17 00:00:00 2001 From: mordner Date: Thu, 8 Jan 2015 23:21:39 +0100 Subject: Fixed one line being cut off and a comment about the export attribute was referring to the wrong function and variable. --- c.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index b5b804af..7670824a 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -386,7 +386,8 @@ int main() { // or when it's the argument of the `sizeof` or `alignof` operator: int arraythethird[10]; int *ptr = arraythethird; // equivalent with int *ptr = &arr[0]; - printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr); // probably prints "40, 4" or "40, 8" + printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr); + // probably prints "40, 4" or "40, 8" // Pointers are incremented and decremented based on their type @@ -477,7 +478,7 @@ void testFunc() { } //make external variables private to source file with static: -static int j = 0; //other files using testFunc() cannot access variable i +static int j = 0; //other files using testFunc2() cannot access variable j void testFunc2() { extern int j; } -- cgit v1.2.3 From 4ef0e78009896395804c609201c9b70254bddcb2 Mon Sep 17 00:00:00 2001 From: raiph Date: Fri, 9 Jan 2015 18:39:56 -0500 Subject: Fix link to synopses and call them 'design docs' --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index b10e04bf..13f383fe 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1481,5 +1481,5 @@ If you want to go further, you can: - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This is probably the greatest source of Perl 6 information, snippets and such. - Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful. - Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize). - - Read the [Synopses](perlcabal.org/syn). They explain it from an implementor point-of-view, but it's still very interesting. + - Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting. -- cgit v1.2.3 From 8f29b15cda9cbc7ca8fc1f31ed0755245c9fc9c7 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 11 Jan 2015 15:30:12 -0700 Subject: Rewrite the pattern matching section --- scala.html.markdown | 64 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 336251ba..3fa4d4b8 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -198,8 +198,8 @@ weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most -// def that surrounds it. -// WARNING: Using return in Scala is error-prone and should be avoided. +// def that surrounds it. +// WARNING: Using return in Scala is error-prone and should be avoided. // It has no effect on anonymous functions. For example: def foo(x: Int): Int = { val anonFunc: Int => Int = { z => @@ -407,41 +407,55 @@ val otherGeorge = george.copy(phoneNumber = "9876") // 6. Pattern Matching ///////////////////////////////////////////////// -val me = Person("George", "1234") +// Pattern matching is a powerful and commonly used feature in Scala. Here's how +// you pattern match a case class. NB: Unlike other languages, Scala cases do +// not have breaks. -me match { case Person(name, number) => { - "We matched someone : " + name + ", phone : " + number }} - -me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } +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 +} -me match { case Person("George", number) => "Match"; case _ => "Hm..." } +val email = "(.*)@(.*)".r // Define a regex for the next example. -me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } +// Pattern matching might look familiar to the switch statements in the C family +// of languages, but this is much more powerful. In Scala, you can match much +// more: +def matchEverything(obj: Any): String = obj match { + // You can match values: + case "Hello world" => "Got the string Hello world" -me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + // You can match by type: + case x: Double => "Got a Double: " + x -val kate = Person("Kate", "1234") + // You can specify conditions: + case x: Int if x > 10000 => "Got a pretty big number!" -kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + // You can match case classes as before: + case Person(name, number) => s"Got contact info for $name!" + // You can match regular expressions: + case email(name, domain) => s"Got email address $name@$domain" + // You can match tuples: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" -// Regular expressions -val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex -val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using verbatim (multiline) syntax + // You can match data structures: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" -val matcher = (value: String) => { - println(value match { - case email(name, domain) => s"It was an email: $name" - case serialKey(p1, p2, p3, p4) => s"Serial key: $p1, $p2, $p3, $p4" - case _ => s"No match on '$value'" // default if no match found - }) + // You can nest patterns: + case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" } -matcher("mrbean@pyahoo.com") // => "It was an email: mrbean" -matcher("nope..") // => "No match on 'nope..'" -matcher("52917") // => "No match on '52917'" -matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" +// In fact, you can pattern match any object with an "unapply" method. This +// feature is so powerful that Scala lets you define whole functions as +// patterns: +val patternFunc: Person => String = { + case Person("George", number") => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} ///////////////////////////////////////////////// -- cgit v1.2.3 From c053f1559bb357d9e8ced2452096bf3a95cc7ddb Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 11 Jan 2015 18:11:06 -0700 Subject: Better wording about breaks in cases --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 3fa4d4b8..61c735e3 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -409,7 +409,7 @@ val otherGeorge = george.copy(phoneNumber = "9876") // Pattern matching is a powerful and commonly used feature in Scala. Here's how // you pattern match a case class. NB: Unlike other languages, Scala cases do -// not have breaks. +// not need breaks, fall-through does not happen. def matchPerson(person: Person): String = person match { // Then you specify the patterns: -- cgit v1.2.3 From 22d0cb02a8e08532555edde1f5ccf9a34a2b6a77 Mon Sep 17 00:00:00 2001 From: Fla Date: Mon, 12 Jan 2015 14:10:41 +0100 Subject: Typo --- fr-fr/ruby-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown index 75c8d0d3..1564d2b6 100644 --- a/fr-fr/ruby-fr.html.markdown +++ b/fr-fr/ruby-fr.html.markdown @@ -268,7 +268,7 @@ end # implicitement la valeur de la dernière instruction évaluée double(2) #=> 4 -# Les paranthèses sont facultative +# Les parenthèses sont facultatives # lorsqu'il n'y a pas d'ambiguïté sur le résultat double 3 #=> 6 -- cgit v1.2.3 From bb2ef18bcc24549560f56bcf1e3b1d8cdcf68f99 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: Wed, 5 Nov 2014 22:39:28 +0200 Subject: Adding the lang header --- ru-ru/java-ru.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 005495cc..913c0fe2 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -1,5 +1,6 @@ --- language: java +lang: ru-ru contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Madison Dickson", "http://github.com/mix3d"] -- cgit v1.2.3 From d2336d0ce4dc35e0d8627a4b0d089e06c8dffd88 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: Wed, 5 Nov 2014 22:52:46 +0200 Subject: Revert "Adding the lang header" This reverts commit 2b0aa461069d5356f5e6b4c166deac04d6597b4a. --- ru-ru/java-ru.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 913c0fe2..005495cc 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -1,6 +1,5 @@ --- language: java -lang: ru-ru contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Madison Dickson", "http://github.com/mix3d"] -- cgit v1.2.3 From 7b9eb42fb5f2c3b29bef2e08b570a6b6ef0ad8a7 Mon Sep 17 00:00:00 2001 From: "a.gonchar" Date: Wed, 24 Dec 2014 16:15:34 +0300 Subject: translation javascript into Russian --- ru-ru/javascript-ru.html.markdown | 503 ++++++++++++++++++-------------------- 1 file changed, 235 insertions(+), 268 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index ad66b501..dc35d18c 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -3,261 +3,250 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] -translators: - - ["Maxim Koretskiy", "http://github.com/maximkoretskiy"] filename: javascript-ru.js +translators: + - ["Alexey Gonchar", "http://github.com/finico"] lang: ru-ru --- -Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально -предполагалось, что он станет простым вариантом скриптового языка для сайтов, -дополняющий к Java, который бы в свою очередь использовался для более сложных -web-приложений. Но тонкая интегрированность javascript с web-страницей и -встроенная поддержка в браузерах привели к тому, чтобы он стал более -распространен в frontend-разработке, чем Java. - -Использование JavaScript не ограничивается браузерами. Проект Node.js, -предоставляющий независимую среду выполнения на движке Google Chrome V8 -JavaScript, становится все более популярным. +JavaScript был создан в 1995 году Бренданом Айком, работающим в компании Netscape. +Изначально он был задуман как простой язык сценариев для веб-сайтов, дополняющий +Java для более сложных веб-приложений, но его тесная интеграция с веб-страницами +и втроенная поддержка браузерами привели к тому, что он стал более распространынным, +чем Java в веб-интерфейсах. -Обратная связь важна и нужна! Вы можете написаться мне -на [@adambrenecki](https://twitter.com/adambrenecki) или -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). +JavaScript не ограничивается только веб-браузером, например, Node.js, программная +платформа, позволяющая выполнять JavaScript, основанная на движке V8 от браузера +Google Chrome, становится все более популярной. ```js -// Комментарии оформляются как в C. -// Однострочнные коментарии начинаются с двух слешей, -/* а многострочные с слеша и звездочки - и заканчиваются звездочеий и слешом */ +// Си-подобные комментарии. Однострочные комментарии начинаются с двух символов слэш, +/* а многострочные комментарии начинаются с звёздочка-слэш + и заканчиваются символами слэш-звёздочка */ -// Выражения разделяются с помощью ; +// Выражения заканчиваються точкой с запятой ; doStuff(); -// ... но этого можно и не делать, разделители подставляются автоматически -// после перехода на новую строку за исключением особых случаев +// ... но они необязательны, так как точки с запятой автоматически вставляются +// везде, где есть символ новой строки, за некоторыми исключениями. doStuff() -// Это может приводить к непредсказуемому результату и поэтому мы будем -// использовать разделители в этом туре. -// Because those cases can cause unexpected results, we'll keep on using -// semicolons in this guide. +// Так как эти исключения могут привести к неожиданным результатам, мы будем всегда +// использовать точку с запятой в этом руководстве. /////////////////////////////////// // 1. Числа, Строки и Операторы -// 1. Numbers, Strings and Operators -// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой -// стандарта IEEE 754) -// Числа имеют 52-битную мантиссу, чего достаточно для хранения хранения целых -// чисел до 9✕10¹⁵ приблизительно. +// В JavaScript только один тип числа (64-bit IEEE 754 double). +// Он имеет 52-битную мантиссу, которой достаточно для хранения целых чисел +// с точностью вплоть до 9✕10¹⁵. 3; // = 3 1.5; // = 1.5 -// В основном базовая арифметика работает предсказуемо +// Некоторые простые арифметические операции работают так, как вы ожидаете. 1 + 1; // = 2 -.1 + .2; // = 0.30000000000000004 +0.1 + 0.2; // = 0.30000000000000004 (а некоторые - нет) 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 -// Включая нецелочисленное деление +// Включая деление с остатком. 5 / 2; // = 2.5 -// Двоичные операции тоже есть. Если применить двоичную операцию к float-числу, -// оно будет приведено к 32-битному целому со знаком. +// Побитовые операции так же имеются; Они производят операции, используя +// двоичное представление числа, и возвращают новую последовательность из +// 32 бит (число) в качестве результата. 1 << 2; // = 4 -// (todo:перевести) -// Приоритет выполнения операций можно менять с помощью скобок. +// Приоритет в выражениях явно задаётся скобками. (1 + 3) * 2; // = 8 -// Есть три особых не реальных числовых значения: -Infinity; // допустим, результат операции 1/0 --Infinity; // допустим, результат операции -1/0 -NaN; // допустим, результат операции 0/0 +// Есть три специальных значения, которые не являются реальными числами: +Infinity; // "бесконечность", например, результат деления на 0 +-Infinity; // "минус бесконечность", результат деления отрицательного числа на 0 +NaN; // "не число", например, результат деления 0/0 -// Так же есть тип булевых данных. +// Существует также логический тип. true; false; -// Строки создаются с помощью ' или ". +// Строки создаются при помощи двойных или одинарных кавычек. 'abc'; "Hello, world"; -// Оператор ! означает отрицание +// Для логического отрицания используется символ восклицательного знака. !true; // = false !false; // = true -// Равество это === +// Строгое равенство === 1 === 1; // = true 2 === 1; // = false -// Неравенство это !== +// Строгое неравенство !== 1 !== 1; // = false 2 !== 1; // = true -// Еще сравнения +// Другие операторы сравнения 1 < 10; // = true 1 > 10; // = false 2 <= 2; // = true 2 >= 2; // = true -// Строки складываются с помощью + +// Строки конкатенируются при помощи оператора + "Hello " + "world!"; // = "Hello world!" -// и сравниваются с помощью < и > +// и сравниваются при помощи < и > "a" < "b"; // = true -// Приведение типов выполняется при сравнении с ==... +// Проверка равенства с приведением типов осуществляется двойным символом равно "5" == 5; // = true null == undefined; // = true -// ...в отличие от === +// ...а если использовать === "5" === 5; // = false null === undefined; // = false -// Для доступа к конкретному символу строки используйте charAt +// ...приведение типов может привести к странному поведению... +13 + !0; // 14 +"13" + !0; // '13true' + +// Вы можете получить доступ к любому символу строки, используя метод charAt "This is a string".charAt(0); // = 'T' -// ... или используйте substring для получения подстроки +// ...или используйте метод substring чтобы получить более крупные части "Hello world".substring(0, 5); // = "Hello" -// length(длина) - свойство, не используйте () +// length это свойство, для его получения не нужно использовать () "Hello".length; // = 5 -// Есть null и undefined -null; // используется что бы указать явно, что значения нет -undefined; // испрользуется чтобы показать, что значения не было установлено - // собственно, undefined так и переводится +// Так же есть null и undefined +null; // используется для обозначения намеренного значения "ничего" +undefined; // используется для обозначения переменных, не имеющих + // присвоенного значения (хотя переменная объявлена) -// false, null, undefined, NaN, 0 и "" являются falsy-значениями(при приведении -// в булеву типу становятся false) -// Обратите внимание что 0 приводится к false, а "0" к true, -// не смотря на то, что "0"==0 +// false, null, undefined, NaN, 0 и "" это ложь; все остальное - истина. +// Следует отметить, что 0 это ложь, а "0" - истина, несмотря на то, что 0 == "0". /////////////////////////////////// -// 2. Переменные, массивы и объекты +// 2. Переменные, Массивы и Объекты -// Переменные объявляются ключевым словом var. Javascript динамически -// типизируемый, так что указывать тип не нужно. -// Присвоение значения описывается с помощью оператора = +// Переменные объявляются при помощи ключевого слова var. JavaScript - язык с +// динамической типизацией, поэтому не нужно явно указывать тип. Для присваивания +// значения переменной используется символ = var someVar = 5; -// если не указать ключевого слова var, ошибки не будет... +// если вы пропустите слово var, вы не получите сообщение об ошибке... someOtherVar = 10; -// ...но переменная будет создана в глобальном контексте, в не области -// видимости, в которой она была объявлена. +// ...но ваша переменная будет создана в глобальном контексте, а не в текущем +// гед вы ее объявили. -// Переменные объявленные без присвоения значения, содержать undefined +// Переменным объявленным без присвоения устанавливается значение undefined. var someThirdVar; // = undefined -// Для математических операций над переменными есть короткая запись: -someVar += 5; // тоже что someVar = someVar + 5; someVar равно 10 теперь -someVar *= 10; // а теперь -- 100 +// У математических операций есть сокращённые формы: +someVar += 5; // как someVar = someVar + 5; someVar теперь имеет значение 10 +someVar *= 10; // теперь someVar имеет значение 100 -// еще более короткая запись для добавления и вычитания 1 -someVar++; // теперь someVar равно 101 -someVar--; // обратно к 100 +// а так же специальные операторы инкремент и декремент для увеличения и +// уменьшения переменной на единицу соответственно +someVar++; // теперь someVar имеет значение 101 +someVar--; // обратно 100 -// Массивы -- упорядоченные списки значений любых типов. +// Массивы это нумерованные списки из значений любого типа. var myArray = ["Hello", 45, true]; -// Для доступу к элементам массивов используйте квадратные скобки. -// Индексы массивов начинаются с 0 +// Их элементы могут быть доступны при помощи синтаксиса с квадратными скобками. +// Индексы массивов начинаются с нуля. myArray[1]; // = 45 -// Массивы мутабельны(изменяемы) и имеют переменную длину. -myArray.push("World"); // добавить элемент +// Массивы можно изменять, как и их длину. +myArray.push("World"); myArray.length; // = 4 -// Добавить или изменить значение по конкретному индексу +// Добавлять и редактировать определенный элемент myArray[3] = "Hello"; -// Объекты javascript похожи на dictionary или map из других языков -// программирования. Это неупорядочнные коллекции пар ключ-значение. +// Объекты в JavaScript похожи на "словари" или ассоциативные массиы в других +// языках: неупорядоченный набор пар ключ-значение. var myObj = {key1: "Hello", key2: "World"}; -// Ключи -- это строки, но кавычки не требуются если названия явлюятся -// корректными javascript идентификаторами. Значения могут быть любого типа. +// Ключи это строки, но кавычки необязательны, если строка удовлетворяет +// ограничениям для имён переменных. Значения могут быть любых типов. var myObj = {myKey: "myValue", "my other key": 4}; -// Доступ к атрибту объекта можно получить с помощью квадратных скобок +// Атрибуты объектов можно также получить, используя квадратные скобки, myObj["my other key"]; // = 4 -// ... или используя точечную нотацию, при условии что ключ является -// корректным идентификатором. +// или через точку, при условии, что ключ является допустимым идентификатором. myObj.myKey; // = "myValue" -// Объекты мутабельны. В существуюещем объекте можно изменить значние -// или добавить новый атрибут. +// Объекты изменяемы; можно изменять значения и добавлять новые ключи. myObj.myThirdKey = true; -// При попытке доступа к атрибуту, который до этого не был создан, будет -// возвращен undefined +// Если вы попытаетесь получить доступ к несуществующему свойству, +// вы получите undefined. myObj.myFourthKey; // = undefined /////////////////////////////////// -// 3. Логика и Управляющие структуры +// 3. Логика и управляющие конструкции. -// Синтаксис управляющих структур очень похож на его реализацию в Java. +// Синтаксис для этого раздела почти такой же как в Java. -// if работает так как вы ожидаете. +// Эта конструкция работает, как и следовало ожидать. var count = 1; -if (count == 3){ - // выполнится, если значение count равно 3 -} else if (count == 4){ - // выполнится, если значение count равно 4 +if (count == 3) { + // выполняется, если count равен 3 +} else if (count == 4) { + // выполняется, если count равен 4 } else { - // выполнится, если значение count не будет равно ни 3 ни 4 + // выполняется, если не 3 и не 4 } -// Поведение while тоже вполне предсказуемо +// Как это делает while. while (true){ - // Бесконечный цикл + // Бесконечный цикл! } -// Циклы do-while похожи на while, но они всегда выполняются хотябы 1 раз. -// Do-while loops are like while loops, except they always run at least once. +// Циклы do-while такие же как while, но они всегда выполняются хотя бы раз. var input do { input = getInput(); } while (!isValid(input)) -// Цикл for такой же как в C и Java: -// инициализация; условие продолжения; итерация -for (var i = 0; i < 5; i++){ - // выполнится 5 раз +// цикл for является таким же, как C и Java: +// инициализация; условие; шаг. +for (var i = 0; i < 5; i++) { + // будет запущен 5 раз } -// && - логическое и, || - логическое или -if (house.size == "big" && house.color == "blue"){ +// && это логическое И, || это логическое ИЛИ +if (house.size == "big" && house.colour == "blue") { house.contains = "bear"; } -if (color == "red" || color == "blue"){ - // если цвет или красный или синий +if (colour == "red" || colour == "blue") { + // цвет красный или синий } -// && и || удобны для установки значений по умолчанию. -// && and || "short circuit", which is useful for setting default values. +// || используется как "короткий цикл вычисления" для присваивания переменных. var name = otherName || "default"; -// выражение switch проверяет равество с помощью === -// используйте 'break' после каждого case, -// иначе помимо правильного case выполнятся и все последующие. -grade = '4'; // оценка +// Оператор switch выполняет проверку на равенство пр помощи === +// используйте break чтобы прервать выполнение после каждого case +// или выполнение пойдёт далее, игнорируя при этом остальные проверки. +grade = 'B'; switch (grade) { - case '5': - console.log("Великолепно"); + case 'A': + console.log("Great job"); break; - case '4': - console.log("Неплохо"); + case 'B': + console.log("OK job"); break; - case '3': - console.log("Можно и лучше"); + case 'C': + console.log("You can do better"); break; default: - console.log("Да уж."); + console.log("Oy vey"); break; } @@ -265,213 +254,197 @@ switch (grade) { /////////////////////////////////// // 4. Функции, Область видимости и Замыкания -// Функции в JavaScript объявляются с помощью ключевого слова function. -function myFunction(thing){ - return thing.toUpperCase(); // приведение к верхнему регистру +// Функции в JavaScript объявляются при помощи ключевого слова function. +function myFunction(thing) { + return thing.toUpperCase(); } myFunction("foo"); // = "FOO" -// Помните, что значение, которое должно быть возкращено должно начинаться -// на той же строке, где расположено ключевое слово 'return'. В противном случае -// будет возвращено undefined. Такое поведения объясняется автоматической -// вставкой разделителей ';'. Помните этот факт, если используете -// BSD стиль оформления кода. -// Note that the value to be returned must start on the same line as the -// 'return' keyword, otherwise you'll always return 'undefined' due to -// automatic semicolon insertion. Watch out for this when using Allman style. +// Обратите внимание, что значение, которое будет возвращено, должно начинаться +// на той же строке, что и ключевое слово return, в противном случае вы будете +// всегда возвращать undefined по причине автоматической вставки точки с запятой. +// Следите за этим при использовании стиля форматирования Allman. function myFunction() { - return // <- разделитель автоматически будет вставлен здесь + return // <- здесь точка с запятой вставится автоматически { thisIsAn: 'object literal' } } myFunction(); // = undefined -// Функции в JavaScript являются объектами, поэтому их можно назначить в -// переменные с разными названиями и передавать в другие функции, как аргументы, -// на пример, при указании обработчика события. -function myFunction(){ - // этот фрагмент кода будет вызван через 5 секунд +// JavaScript функции - это объекты, поэтому они могут быть переприсвоены на +// различные имена переменных и передаваться другим функциям в качестве аргументов, +// например, когда назначается обработчик события: +function myFunction() { + // этот код будет вызван через 5 секунд } setTimeout(myFunction, 5000); -// Обратите внимание, что setTimeout не является частью языка, однако он -// доступен в API браузеров и Node.js. +// Примечание: setTimeout не является частью языка, но реализован в браузерах и Node.js -// Объект функции на самом деле не обязательно объявлять с именем - можно -// создать анонимную функцию прямо в аргументах другой функции. -setTimeout(function(){ - // этот фрагмент кода будет вызван через 5 секунд +// Функции не обязательно должны иметь имя при объявлении - вы можете написать +// анонимное определение функции непосредственно в агрументе другой функции. +setTimeout(function() { + // этот код будет вызван через 5 секунд }, 5000); -// В JavaScript есть области видимости. У функций есть собственные области -// видимости, у других блоков их нет. -if (true){ +// В JavaScript есть область видимости функции; функции имеют свою область +// видимости, а другие блоки - нет. +if (true) { var i = 5; } -i; // = 5, а не undefined, как это было бы в языке, создающем - // области видисти для блоков кода +i; // = 5 - не undefined как ожидалось бы в языках с блочной областью видимости -// Это привело к появлению паттерна общего назначения "immediately-executing -// anonymous functions" (сразу выполняющиеся анонимные функции), который -// позволяет предотвратить запись временных переменных в общую облать видимости. -(function(){ +// Это привело к общепринятому шаблону "самозапускающихся анонимных функций", +// которые препятствуют проникновению переменных в глобальную область видимости +(function() { var temporary = 5; - // Для доступа к глобальной области видимости можно использовать запись в - // некоторый 'глобальный объект', для браузеров это 'window'. Глобальный - // объект может называться по-разному в небраузерных средах, таких Node.js. + // Мы можем получить доступ к глобальной области для записи в "глобальный объект", + // который в веб-браузере всегда window. Глобальный объект может иметь другое + // имя в таких платформах, как Node.js window.permanent = 10; })(); -temporary; // вызывает исключение ReferenceError +temporary; // вызовет сообщение об ошибке с типом ReferenceError permanent; // = 10 -// Одной из сильных сторон JavaScript являются замыкания. Если функция -// объявлена в внутри другой функции, внутренняя функция имеет доступ ко всем -// переменным внешней функции, даже после того, как внешняя функции завершила -// свое выполнение. -function sayHelloInFiveSeconds(name){ - var prompt = "Привет, " + name + "!"; - // Внутренние функции помещаются в локальную область видимости, как-будто - // они объявлены с ключевым словом 'var'. - function inner(){ +// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция +// определена внутри другой функции, то внутренняя функция имеет доступ к +// переменным внешней функции, даже после того, как контекст выполнения выйдет из +// внешней функции. +function sayHelloInFiveSeconds(name) { + var prompt = "Hello, " + name + "!"; + // Внутренние функции по умолчанию помещаются в локальную область видимости, + // как если бы они были объявлены с var. + function inner() { alert(prompt); } setTimeout(inner, 5000); - // setTimeout является асинхроннной, и поэтому функция sayHelloInFiveSeconds - // завершит свое выполнение сразу и setTimeout вызовет inner позже. - // Однако, так как inner "закрыта внутри" или "замкнута в" - // sayHelloInFiveSeconds, inner все еще будет иметь доступ к переменной - // prompt, когда будет вызвана. + // setTimeout асинхронна, поэтому функция sayHelloInFiveSeconds сразу выйдет + // и тело setTimeout будет вызвано позже. Однако, поскольку внутренняя + // функция "замкнута", она по-прежнему имеет доступ к переменной prompt, + // когда sayHelloInFiveSeconds вызывется. } -sayHelloInFiveSeconds("Вася"); // откроет модальное окно с сообщением - // "Привет, Вася" по истечении 5 секунд. - +sayHelloInFiveSeconds("Adam"); // откроется окно с "Hello, Adam!" через 5 секунд /////////////////////////////////// -// 5. Немного еще об Объектах. Конструкторы и Прототипы +// 5. Подробнее про Объекты, Конструкторы и Прототипы -// Объекты могут содержать функции +// Объекты могут содержать в себе функции. var myObj = { - myFunc: function(){ + myFunc: function() { return "Hello world!"; } }; myObj.myFunc(); // = "Hello world!" -// Когда функции прикрепленные к объекту вызываются, они могут получить доступ -// к данным объекта, ипользуя ключевое слово this. +// Когда функции, прикрепленные к объекту, вызываются, они могут получить доступ +// к этому объекту с помощью ключевого слова this. myObj = { myString: "Hello world!", - myFunc: function(){ + myFunc: function() { return this.myString; } }; myObj.myFunc(); // = "Hello world!" -// Содержание this определяется исходя из того, как была вызвана функция, а -// не места её определения. По этой причине наша функция не будет работать вне -// контекста объекта. +// Какое это значение имеет к тому, как вызвана функция и где она определена. +// Итак, наша функция не работает, если она вызывается не в контексте объекта. var myFunc = myObj.myFunc; myFunc(); // = undefined -// И напротив, функция может быть присвоена объекту и получить доступ к нему -// через this, даже если она не была прикреплена к объекту в момент её создания. -var myOtherFunc = function(){ - return this.myString.toUpperCase(); +// И наоборот, функция может быть присвоена объекту и получать доступ к нему +// через this, даже если она не была присвоена при объявлении. +var myOtherFunc = function() { } myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" -// Также можно указать контекс выполнения фунции с помощью 'call' или 'apply'. -var anotherFunc = function(s){ +// Мы можем также указать контекст для выполнения функции, когда мы вызываем ее +// с помощью call или apply. +var anotherFunc = function(s) { return this.myString + s; } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" -// Функция 'apply' очень похожа, но принимает массив со списком аргументов. - +// Функция apply аналогична, но принимает массив аргументов. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" -// Это может быть удобно, когда работаешь с фунцией принимающей на вход -// последовательность аргументов и нужно передать их в виде массива. - +// Это полезно при работе с функцией, которая принимает последовательность +// аргументов, и вы хотите передать массив. Math.min(42, 6, 27); // = 6 -Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min([42, 6, 27]); // = NaN (не сработает!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// Однако, 'call' и 'apply' не имеют постоянного эффекта. Если вы хотите -// зафиксировать контекст для функции, используйте bind. - +// Но, call и apply - временные. Когда мы хотим связать функцию, мы можем +// использовать bind. var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" -// bind также можно использовать чтобы частично передать аргументы в -// функцию (каррировать). - -var product = function(a, b){ return a * b; } +// Bind также может использоваться, для частичного применения (каррирование) функции +var product = function(a, b) { return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 -// Когда функция вызывается с ключевым словом new, создается новый объект. -// Данный объект становится доступным функции через ключевое слово this. -// Функции спроектированные вызываться таким способом называются конструкторами. - -var MyConstructor = function(){ +// Когда вы вызываете функцию с помощью ключевого слова new создается новый объект, +// и создает доступ к функции при помощи this. Такие функции называют конструкторами. +var MyConstructor = function() { this.myNumber = 5; } myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Любой объект в JavaScript имеет 'прототип'. Когда вы пытаетесь получить -// доступ к свойству не объявленному в данном объекте, интерпретатор будет -// искать его в прототипе. +// Каждый объект в JavaScript имеет свойтво prototype. Когда вы хотите получить +// доступ к свойтву объекта, которое не существует в этом объекте, интерпритатор +// будет искать это свойство в прототипе. -// Некоторые реализации JS позволяют получить доступ к прототипу с помощью -// "волшебного" свойства __proto__. До момента пока оно не являются стандартным, -// __proto__ полезно лишь для изучения прототипов в JavaScript. Мы разберемся -// со стандартными способами работы с прототипом несколько позже. +// Некоторые реализации языка позволяют получить доступ к объекту прототипа +// через свойство __proto__. Несмотря на то, что это может быть полезно для +// понимания прототипов, это не часть стандарта; мы увидим стандартные способы +// использования прототипов позже. var myObj = { myString: "Hello world!" }; var myPrototype = { meaningOfLife: 42, - myFunc: function(){ + myFunc: function() { return this.myString.toLowerCase() } }; myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 + +// Для функций это так же работает. myObj.myFunc(); // = "hello world!" -// Естественно, если в свойства нет в прототипе, поиск будет продолжен в +// Если интерпритатор не найдет свойство в прототипе, то продожит поиск в // прототипе прототипа и так далее. myPrototype.__proto__ = { myBoolean: true }; myObj.myBoolean; // = true -// Ничего не копируется, каждый объект хранит ссылку на свой прототип. Если -// изменить прототип, все изменения отразятся во всех его потомках. +// Здесь не участвует копирование; каждый объект хранит ссылку на свой прототип. +// Это означает, что мы можем изменить прототип и наши изменения будут отражены везде myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 -// Как было сказано выше, __proto__ не является стандартом, и нет стандартного -// способа изменить прототип у созданного объекта. Однако, есть два способа -// создать объект с заданным прототипом. +// Мы упомянули, что свойтсво __proto__ нестандартно, и нет никакого стандартного +// способа, чтобы изменить прототип существующего объекта. Однако, есть два +// способа создать новый объект с заданным прототипом. -// Первый способ - Object.create, был добавлен в JS относительно недавно, и -// потому не доступен в более ранних реализациях языка. +// Первый способ это Object.create, который появился в ECMAScript 5 и есть еще +// не во всех реализациях языка. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 -// Второй вариан доступен везде и связан с конструкторами. Конструкторы имеют -// свойство prototype. Это вовсе не прототип функции конструктора, напротив, -// это прототип, который присваевается новым объектам, созданным с этим -// конструктором с помощью ключевого слова new. +// Второй способ, который работает везде, имеет дело с конструкторами. +// У конструкторов есть свойство с именем prototype. Это не прототип +// функции-конструктора; напротив, это прототип для новых объектов, которые +// будут созданы с помощью этого конструктора и ключевого слова new MyConstructor.prototype = { myNumber: 5, - getMyNumber: function(){ + getMyNumber: function() { return this.myNumber; } }; @@ -480,42 +453,41 @@ myNewObj2.getMyNumber(); // = 5 myNewObj2.myNumber = 6 myNewObj2.getMyNumber(); // = 6 -// У встроенных типов таких, как строки и числа, тоже есть конструкторы, -// создающие эквивалентные объекты-обертки. +// У встроенных типов, таких как строки и числа также есть конструкторы, которые +// создают эквивалентые объекты-обертки. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true -// Правда, они не совсем эквивалентны. +// За исключением того, что они не в точности равны. typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false -if (0){ - // Этот фрагмент кода не будет выпонен, так как 0 приводится к false +if (0) { + // Этот код не выполнятся, потому что 0 - это ложь. } -if (Number(0)){ - // Этот фрагмент кода *будет* выпонен, так как Number(0) приводится к true. +if (Number(0)) { + // Этот код выполнится, потому что Number(0) это истина. } -// Однако, оберточные объекты и обычные встроенные типы имеют общие прототипы, -// следовательно вы можете расширить функциональность строки, например. -String.prototype.firstCharacter = function(){ +// Впрочем, обертки это объекты и их можно расширять, например: +String.prototype.firstCharacter = function() { return this.charAt(0); } "abc".firstCharacter(); // = "a" -// Этот факт часто используется для создания полифилов(polyfill) - реализации -// новых возможностей JS в его более старых версиях для того чтобы их можно было -// использовать в устаревших браузерах. +// Это часто используется в полифиллах, которые реализуют новые возможности +// JavaScript в старой реализации языка, так что они могут быть использованы в +// старых средах, таких как устаревшие браузеры. -// Например, мы упомянули, что Object.create не доступен во всех версиях -// JavaScript, но мы можем создать полифилл. -if (Object.create === undefined){ // не переопределяем, если есть - Object.create = function(proto){ - // создаем временный конструктор с заданным прототипом +// Например, мы упомянули, что Object.create доступен не во всех реализациях, но +// мы сможем использовать его с этим полифиллом: +if (Object.create === undefined) { // не перезаписывать метод, если он существует + Object.create = function(proto) { + // создать временный конструктор с правильным прототипом var Constructor = function(){}; Constructor.prototype = proto; - // создаём новый объект с правильным прототипом + // затем использовать его для создания нового объекта, на основе прототипа return new Constructor(); } } @@ -523,21 +495,16 @@ if (Object.create === undefined){ // не переопределяем, если ## Что еще почитать -[Современный учебник JavaScript](http://learn.javascript.ru/) от Ильи Кантора -является довольно качественным и глубоким учебным материалом, освещающим все -особенности современного языка. Помимо учебника на том же домене можно найти -[перевод спецификации ECMAScript 5.1](http://es5.javascript.ru/) и справочник по -возможностям языка. - -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) позволяет -довольно быстро изучить основные тонкие места в работе с JS, но фокусируется -только на таких моментах +[Современный учебник JavaScript (Илья Кантор)](http://learn.javascript.ru) - +качественный учебник по JavaScript на русском языке. -[Справочник](https://developer.mozilla.org/ru/docs/JavaScript) от MDN -(Mozilla Development Network) содержит информацию о возможностях языка на -английском. +[Mozilla Developer Network](https://developer.mozilla.org/ru/docs/Web/JavaScript) - +предоставляет отличную документацию для JavaScript, как он используется в браузерах. +Кроме того, это вики, поэтому, если вы знаете больше, вы можете помочь другим, +делясь своими знаниями. -Название проекта ["Принципы написания консистентного, идиоматического кода на -JavaScript"](https://github.com/rwaldron/idiomatic.js/tree/master/translations/ru_RU) -говорит само за себя. +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) - это +подробное руководство всех неинтуитивных особенностей языка. +[Stack Overflow](http://stackoverflow.com/questions/tagged/javascript) - можно +найти ответ почти на любой ваш вопрос, а если его нет, то задать вопрос самому. -- cgit v1.2.3 From 1a559fe83493cba67961e5009de068dae1ddcc53 Mon Sep 17 00:00:00 2001 From: "a.gonchar" Date: Wed, 24 Dec 2014 16:40:47 +0300 Subject: fix minor typos in javascript-ru #901 --- ru-ru/javascript-ru.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index dc35d18c..d7599e7e 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -12,7 +12,7 @@ lang: ru-ru JavaScript был создан в 1995 году Бренданом Айком, работающим в компании Netscape. Изначально он был задуман как простой язык сценариев для веб-сайтов, дополняющий Java для более сложных веб-приложений, но его тесная интеграция с веб-страницами -и втроенная поддержка браузерами привели к тому, что он стал более распространынным, +и втроенная поддержка браузерами привели к тому, что он стал более распространённым, чем Java в веб-интерфейсах. JavaScript не ограничивается только веб-браузером, например, Node.js, программная @@ -53,7 +53,7 @@ doStuff() // Включая деление с остатком. 5 / 2; // = 2.5 -// Побитовые операции так же имеются; Они производят операции, используя +// Побитовые операции также имеются; они производят операции, используя // двоичное представление числа, и возвращают новую последовательность из // 32 бит (число) в качестве результата. 1 << 2; // = 4 @@ -394,7 +394,7 @@ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 // Каждый объект в JavaScript имеет свойтво prototype. Когда вы хотите получить -// доступ к свойтву объекта, которое не существует в этом объекте, интерпритатор +// доступ к свойтву объекта, которое не существует в этом объекте, интерпретатор // будет искать это свойство в прототипе. // Некоторые реализации языка позволяют получить доступ к объекту прототипа @@ -417,7 +417,7 @@ myObj.meaningOfLife; // = 42 // Для функций это так же работает. myObj.myFunc(); // = "hello world!" -// Если интерпритатор не найдет свойство в прототипе, то продожит поиск в +// Если интерпретатор не найдет свойство в прототипе, то продожит поиск в // прототипе прототипа и так далее. myPrototype.__proto__ = { myBoolean: true -- cgit v1.2.3 From dd5803183c2c73cc8bd0aae05797c1493c334055 Mon Sep 17 00:00:00 2001 From: finico Date: Wed, 24 Dec 2014 22:32:24 +0300 Subject: [javascript/ru] needs correct typos #902 --- ru-ru/javascript-ru.html.markdown | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index d7599e7e..9efc2835 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,10 +9,10 @@ translators: lang: ru-ru --- -JavaScript был создан в 1995 году Бренданом Айком, работающим в компании Netscape. +JavaScript был создан в 1995 году Бренданом Айком, работавшим в компании Netscape. Изначально он был задуман как простой язык сценариев для веб-сайтов, дополняющий Java для более сложных веб-приложений, но его тесная интеграция с веб-страницами -и втроенная поддержка браузерами привели к тому, что он стал более распространённым, +и встроенная поддержка браузерами привели к тому, что он стал более распространённым, чем Java в веб-интерфейсах. JavaScript не ограничивается только веб-браузером, например, Node.js, программная @@ -27,7 +27,7 @@ Google Chrome, становится все более популярной. // Выражения заканчиваються точкой с запятой ; doStuff(); -// ... но они необязательны, так как точки с запятой автоматически вставляются +// ... но она необязательна, так как точки с запятой автоматически вставляются // везде, где есть символ новой строки, за некоторыми исключениями. doStuff() @@ -113,18 +113,18 @@ null === undefined; // = false // Вы можете получить доступ к любому символу строки, используя метод charAt "This is a string".charAt(0); // = 'T' -// ...или используйте метод substring чтобы получить более крупные части +// ...или используйте метод substring, чтобы получить более крупные части "Hello world".substring(0, 5); // = "Hello" -// length это свойство, для его получения не нужно использовать () +// length - это свойство, для его получения не нужно использовать () "Hello".length; // = 5 -// Так же есть null и undefined +// Также есть null и undefined null; // используется для обозначения намеренного значения "ничего" undefined; // используется для обозначения переменных, не имеющих // присвоенного значения (хотя переменная объявлена) -// false, null, undefined, NaN, 0 и "" это ложь; все остальное - истина. +// false, null, undefined, NaN, 0 и "" - это ложь; все остальное - истина. // Следует отметить, что 0 это ложь, а "0" - истина, несмотря на то, что 0 == "0". /////////////////////////////////// @@ -138,22 +138,22 @@ var someVar = 5; // если вы пропустите слово var, вы не получите сообщение об ошибке... someOtherVar = 10; -// ...но ваша переменная будет создана в глобальном контексте, а не в текущем -// гед вы ее объявили. +// ...но ваша переменная будет создана в глобальном контексте, а не в текущем, +// где вы ее объявили. -// Переменным объявленным без присвоения устанавливается значение undefined. +// Переменным, объявленным без присвоения, устанавливается значение undefined. var someThirdVar; // = undefined // У математических операций есть сокращённые формы: someVar += 5; // как someVar = someVar + 5; someVar теперь имеет значение 10 someVar *= 10; // теперь someVar имеет значение 100 -// а так же специальные операторы инкремент и декремент для увеличения и +// а также специальные операторы инкремент и декремент для увеличения и // уменьшения переменной на единицу соответственно someVar++; // теперь someVar имеет значение 101 someVar--; // обратно 100 -// Массивы это нумерованные списки из значений любого типа. +// Массивы - это нумерованные списки содержащие значения любого типа. var myArray = ["Hello", 45, true]; // Их элементы могут быть доступны при помощи синтаксиса с квадратными скобками. -- cgit v1.2.3 From e8d9163796ea76a028d5e23e7f833863425872f6 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, 12 Jan 2015 02:33:53 +0200 Subject: [javascript/ru] Translating JavaScript guide into Russian --- ru-ru/javascript-ru.html.markdown | 266 +++++++++++++++++++------------------- 1 file changed, 136 insertions(+), 130 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 9efc2835..e7398c88 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -6,6 +6,7 @@ contributors: filename: javascript-ru.js translators: - ["Alexey Gonchar", "http://github.com/finico"] + - ["Andre Polykanine", "https://github.com/Oire"] lang: ru-ru --- @@ -15,7 +16,7 @@ Java для более сложных веб-приложений, но его и встроенная поддержка браузерами привели к тому, что он стал более распространённым, чем Java в веб-интерфейсах. -JavaScript не ограничивается только веб-браузером, например, Node.js, программная +JavaScript не ограничивается только веб-браузером: например, Node.js, программная платформа, позволяющая выполнять JavaScript, основанная на движке V8 от браузера Google Chrome, становится все более популярной. @@ -24,7 +25,7 @@ Google Chrome, становится все более популярной. /* а многострочные комментарии начинаются с звёздочка-слэш и заканчиваются символами слэш-звёздочка */ -// Выражения заканчиваються точкой с запятой ; +// Инструкции могут заканчиваться точкой с запятой ; doStuff(); // ... но она необязательна, так как точки с запятой автоматически вставляются @@ -53,12 +54,12 @@ doStuff() // Включая деление с остатком. 5 / 2; // = 2.5 -// Побитовые операции также имеются; они производят операции, используя -// двоичное представление числа, и возвращают новую последовательность из -// 32 бит (число) в качестве результата. +// Побитовые операции также имеются; когда вы проводите такую операцию, +// ваше число с плавающей запятой переводится в целое со знаком +// длиной *до* 32 разрядов. 1 << 2; // = 4 -// Приоритет в выражениях явно задаётся скобками. +// Приоритет в выражениях можно явно задать скобками. (1 + 3) * 2; // = 8 // Есть три специальных значения, которые не являются реальными числами: @@ -71,10 +72,10 @@ true; false; // Строки создаются при помощи двойных или одинарных кавычек. -'abc'; -"Hello, world"; +'абв'; +"Привет, мир!"; -// Для логического отрицания используется символ восклицательного знака. +// Для логического отрицания используется восклицательный знак. !true; // = false !false; // = true @@ -92,8 +93,8 @@ false; 2 <= 2; // = true 2 >= 2; // = true -// Строки конкатенируются при помощи оператора + -"Hello " + "world!"; // = "Hello world!" +// Строки объединяются при помощи оператора + +"привет, " + "мир!"; // = "Привет, мир!" // и сравниваются при помощи < и > "a" < "b"; // = true @@ -102,7 +103,7 @@ false; "5" == 5; // = true null == undefined; // = true -// ...а если использовать === +// ...если только не использовать === "5" === 5; // = false null === undefined; // = false @@ -111,31 +112,33 @@ null === undefined; // = false "13" + !0; // '13true' // Вы можете получить доступ к любому символу строки, используя метод charAt -"This is a string".charAt(0); // = 'T' +"Это строка".charAt(0); // = 'Э' // ...или используйте метод substring, чтобы получить более крупные части -"Hello world".substring(0, 5); // = "Hello" +"Привет, мир".substring(0, 6); // = "Привет" // length - это свойство, для его получения не нужно использовать () -"Hello".length; // = 5 +"Привет".length; // = 6 // Также есть null и undefined -null; // используется для обозначения намеренного значения "ничего" +null; // Намеренное отсутствие значения undefined; // используется для обозначения переменных, не имеющих - // присвоенного значения (хотя переменная объявлена) + // присвоенного значения (хотя непосредственно undefined + // является значением) -// false, null, undefined, NaN, 0 и "" - это ложь; все остальное - истина. -// Следует отметить, что 0 это ложь, а "0" - истина, несмотря на то, что 0 == "0". +// false, null, undefined, NaN, 0 и "" — это ложь; всё остальное - истина. +// Следует отметить, что 0 — это ложь, а "0" — истина, несмотря на то, что +// 0 == "0". /////////////////////////////////// // 2. Переменные, Массивы и Объекты -// Переменные объявляются при помощи ключевого слова var. JavaScript - язык с +// Переменные объявляются при помощи ключевого слова var. JavaScript — язык с // динамической типизацией, поэтому не нужно явно указывать тип. Для присваивания // значения переменной используется символ = var someVar = 5; -// если вы пропустите слово var, вы не получите сообщение об ошибке... +// если вы пропустите слово var, вы не получите сообщение об ошибке, ... someOtherVar = 10; // ...но ваша переменная будет создана в глобальном контексте, а не в текущем, @@ -148,34 +151,33 @@ var someThirdVar; // = undefined someVar += 5; // как someVar = someVar + 5; someVar теперь имеет значение 10 someVar *= 10; // теперь someVar имеет значение 100 -// а также специальные операторы инкремент и декремент для увеличения и -// уменьшения переменной на единицу соответственно +// Ещё более краткая запись увеличения и уменьшения на единицу: someVar++; // теперь someVar имеет значение 101 -someVar--; // обратно 100 +someVar--; // вернулись к 100 -// Массивы - это нумерованные списки содержащие значения любого типа. -var myArray = ["Hello", 45, true]; +// Массивы — это нумерованные списки, содержащие значения любого типа. +var myArray = ["Привет", 45, true]; // Их элементы могут быть доступны при помощи синтаксиса с квадратными скобками. // Индексы массивов начинаются с нуля. myArray[1]; // = 45 -// Массивы можно изменять, как и их длину. -myArray.push("World"); +// Массивы можно изменять, как и их длину, +myArray.push("Мир"); myArray.length; // = 4 -// Добавлять и редактировать определенный элемент -myArray[3] = "Hello"; +// добавлять и редактировать определённый элемент +myArray[3] = "Привет"; -// Объекты в JavaScript похожи на "словари" или ассоциативные массиы в других +// Объекты в JavaScript похожи на словари или ассоциативные массивы в других // языках: неупорядоченный набор пар ключ-значение. -var myObj = {key1: "Hello", key2: "World"}; +var myObj = {key1: "Привет", key2: "Мир"}; -// Ключи это строки, но кавычки необязательны, если строка удовлетворяет +// Ключи — это строки, но кавычки необязательны, если строка удовлетворяет // ограничениям для имён переменных. Значения могут быть любых типов. var myObj = {myKey: "myValue", "my other key": 4}; -// Атрибуты объектов можно также получить, используя квадратные скобки, +// Атрибуты объектов можно также получить, используя квадратные скобки myObj["my other key"]; // = 4 // или через точку, при условии, что ключ является допустимым идентификатором. @@ -184,16 +186,16 @@ myObj.myKey; // = "myValue" // Объекты изменяемы; можно изменять значения и добавлять новые ключи. myObj.myThirdKey = true; -// Если вы попытаетесь получить доступ к несуществующему свойству, +// Если вы попытаетесь получить доступ к несуществующему значению, // вы получите undefined. myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Логика и управляющие конструкции. -// Синтаксис для этого раздела почти такой же как в Java. +// Синтаксис для этого раздела почти такой же, как в Java. -// Эта конструкция работает, как и следовало ожидать. +// Условная конструкция работает, как и следовало ожидать, var count = 1; if (count == 3) { // выполняется, если count равен 3 @@ -203,50 +205,51 @@ if (count == 3) { // выполняется, если не 3 и не 4 } -// Как это делает while. +// ...как и цикл while. while (true){ // Бесконечный цикл! } -// Циклы do-while такие же как while, но они всегда выполняются хотя бы раз. +// Цикл do-while такой же, как while, но он всегда выполняется хотя бы раз. var input do { input = getInput(); } while (!isValid(input)) -// цикл for является таким же, как C и Java: +// цикл for такой же, как в C и Java: // инициализация; условие; шаг. for (var i = 0; i < 5; i++) { - // будет запущен 5 раз + // выполнится 5 раз } -// && это логическое И, || это логическое ИЛИ -if (house.size == "big" && house.colour == "blue") { +// && — это логическое И, || — это логическое ИЛИ +if (house.size == "big" && house.color == "blue") { house.contains = "bear"; } -if (colour == "red" || colour == "blue") { +if (color == "red" || color == "blue") { // цвет красный или синий } -// || используется как "короткий цикл вычисления" для присваивания переменных. +// && и || используют сокращённое вычисление, что полезно +// для задания значений по умолчанию. var name = otherName || "default"; -// Оператор switch выполняет проверку на равенство пр помощи === -// используйте break чтобы прервать выполнение после каждого case -// или выполнение пойдёт далее, игнорируя при этом остальные проверки. -grade = 'B'; +// Оператор switch выполняет проверку на равенство при помощи === +// используйте break, чтобы прервать выполнение после каждого case, +// или выполнение пойдёт далее даже после правильного варианта. +grade = 4; switch (grade) { - case 'A': - console.log("Great job"); + case 5: + console.log("Отлично"); break; - case 'B': - console.log("OK job"); + case 4: + console.log("Хорошо"); break; - case 'C': - console.log("You can do better"); + case 3: + console.log("Можете и лучше"); break; default: - console.log("Oy vey"); + console.log("Ой-вей!"); break; } @@ -273,33 +276,33 @@ function myFunction() } myFunction(); // = undefined -// JavaScript функции - это объекты, поэтому они могут быть переприсвоены на -// различные имена переменных и передаваться другим функциям в качестве аргументов, -// например, когда назначается обработчик события: +// В JavaScript функции — это объекты первого класса, поэтому они могут быть +// присвоены различным именам переменных и передаваться другим функциям +// в качестве аргументов, например, когда назначается обработчик события: function myFunction() { // этот код будет вызван через 5 секунд } setTimeout(myFunction, 5000); // Примечание: setTimeout не является частью языка, но реализован в браузерах и Node.js -// Функции не обязательно должны иметь имя при объявлении - вы можете написать -// анонимное определение функции непосредственно в агрументе другой функции. +// Функции не обязательно должны иметь имя при объявлении — вы можете написать +// анонимное определение функции непосредственно в аргументе другой функции. setTimeout(function() { // этот код будет вызван через 5 секунд }, 5000); -// В JavaScript есть область видимости функции; функции имеют свою область -// видимости, а другие блоки - нет. +// В JavaScript есть область видимости; функции имеют свою область +// видимости, а другие блоки — нет. if (true) { var i = 5; } -i; // = 5 - не undefined как ожидалось бы в языках с блочной областью видимости +i; // = 5, а не undefined, как ожидалось бы в языках с блочной областью видимости // Это привело к общепринятому шаблону "самозапускающихся анонимных функций", // которые препятствуют проникновению переменных в глобальную область видимости (function() { var temporary = 5; - // Мы можем получить доступ к глобальной области для записи в "глобальный объект", + // Мы можем получить доступ к глобальной области для записи в «глобальный объект», // который в веб-браузере всегда window. Глобальный объект может иметь другое // имя в таких платформах, как Node.js window.permanent = 10; @@ -309,100 +312,101 @@ permanent; // = 10 // Одной из самых мощных возможностей JavaScript являются замыкания. Если функция // определена внутри другой функции, то внутренняя функция имеет доступ к -// переменным внешней функции, даже после того, как контекст выполнения выйдет из +// переменным внешней функции даже после того, как контекст выполнения выйдет из // внешней функции. function sayHelloInFiveSeconds(name) { - var prompt = "Hello, " + name + "!"; + var prompt = "Привет, " + name + "!"; // Внутренние функции по умолчанию помещаются в локальную область видимости, - // как если бы они были объявлены с var. + // как если бы они были объявлены с помощью var. function inner() { alert(prompt); } setTimeout(inner, 5000); - // setTimeout асинхронна, поэтому функция sayHelloInFiveSeconds сразу выйдет - // и тело setTimeout будет вызвано позже. Однако, поскольку внутренняя - // функция "замкнута", она по-прежнему имеет доступ к переменной prompt, - // когда sayHelloInFiveSeconds вызывется. + // setTimeout асинхронна, поэтому функция sayHelloInFiveSeconds сразу выйдет, + // после чего setTimeout вызовет функцию inner. Однако поскольку функция inner + // «замкнута» вокруг sayHelloInFiveSeconds, она по-прежнему имеет доступ к переменной prompt + // на то время, когда она наконец будет вызвана. } -sayHelloInFiveSeconds("Adam"); // откроется окно с "Hello, Adam!" через 5 секунд +sayHelloInFiveSeconds("Адам"); // Через 5 с откроется окно «Привет, Адам!» /////////////////////////////////// -// 5. Подробнее про Объекты, Конструкторы и Прототипы +// 5. Подробнее об объектах; конструкторы и прототипы // Объекты могут содержать в себе функции. var myObj = { myFunc: function() { - return "Hello world!"; + return "Привет, мир!"; } }; -myObj.myFunc(); // = "Hello world!" +myObj.myFunc(); // = "Привет, мир!" -// Когда функции, прикрепленные к объекту, вызываются, они могут получить доступ +// Когда вызываются функции, прикреплённые к объекту, они могут получить доступ // к этому объекту с помощью ключевого слова this. myObj = { - myString: "Hello world!", + myString: "Привет, мир!", myFunc: function() { return this.myString; } }; -myObj.myFunc(); // = "Hello world!" +myObj.myFunc(); // = "Привет, мир!" -// Какое это значение имеет к тому, как вызвана функция и где она определена. -// Итак, наша функция не работает, если она вызывается не в контексте объекта. +// Значение this зависит от того, как функция вызывается, +// а не от того, где она определена. Таким образом, наша функция не работает, +// если она вызывается не в контексте объекта. var myFunc = myObj.myFunc; myFunc(); // = undefined // И наоборот, функция может быть присвоена объекту и получать доступ к нему -// через this, даже если она не была присвоена при объявлении. +// через this, даже если она не была прикреплена к нему при объявлении. var myOtherFunc = function() { } myObj.myOtherFunc = myOtherFunc; -myObj.myOtherFunc(); // = "HELLO WORLD!" +myObj.myOtherFunc(); // = "ПРИВЕТ, МИР!" -// Мы можем также указать контекст для выполнения функции, когда мы вызываем ее -// с помощью call или apply. +// Мы можем также указать контекст для выполнения функции при её вызове, +// используя call или apply. var anotherFunc = function(s) { return this.myString + s; } -anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" +anotherFunc.call(myObj, " И привет, Луна!"); // = "Привет, мир! И привет, Луна!" -// Функция apply аналогична, но принимает массив аргументов. -anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" +// Функция apply почти такая же, но принимает в качестве списка аргументов массив. +anotherFunc.apply(myObj, [" И привет, Солнце!"]); // = "Привет, мир! И привет, Солнце!" // Это полезно при работе с функцией, которая принимает последовательность -// аргументов, и вы хотите передать массив. +// аргументов, а вы хотите передать массив. Math.min(42, 6, 27); // = 6 -Math.min([42, 6, 27]); // = NaN (не сработает!) +Math.min([42, 6, 27]); // = NaN (Ой-ой!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// Но, call и apply - временные. Когда мы хотим связать функцию, мы можем -// использовать bind. +// Но call и apply — только временные. Когда мы хотим связать функцию с объектом, +// мы можем использовать bind. var boundFunc = anotherFunc.bind(myObj); -boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" +boundFunc(" И привет, Сатурн!"); // = "Привет, мир! И привет, Сатурн!" -// Bind также может использоваться, для частичного применения (каррирование) функции +// Bind также может использоваться для частичного применения (каррирования) функции var product = function(a, b) { return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 -// Когда вы вызываете функцию с помощью ключевого слова new создается новый объект, -// и создает доступ к функции при помощи this. Такие функции называют конструкторами. +// Когда вы вызываете функцию с помощью ключевого слова new, создается новый объект, +// доступный функции при помощи this. Такие функции называют конструкторами. var MyConstructor = function() { this.myNumber = 5; } myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Каждый объект в JavaScript имеет свойтво prototype. Когда вы хотите получить -// доступ к свойтву объекта, которое не существует в этом объекте, интерпретатор +// У каждого объекта в JavaScript есть прототип. Когда вы хотите получить +// доступ к свойству объекта, которое не существует в этом объекте, интерпретатор // будет искать это свойство в прототипе. -// Некоторые реализации языка позволяют получить доступ к объекту прототипа -// через свойство __proto__. Несмотря на то, что это может быть полезно для -// понимания прототипов, это не часть стандарта; мы увидим стандартные способы +// Некоторые реализации языка позволяют получить доступ к прототипу объекта +// через «магическое» свойство __proto__. Несмотря на то, что это может быть полезно +// для понимания прототипов, это не часть стандарта; мы увидим стандартные способы // использования прототипов позже. var myObj = { - myString: "Hello world!" + myString: "Привет, мир!" }; var myPrototype = { meaningOfLife: 42, @@ -414,34 +418,34 @@ var myPrototype = { myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 -// Для функций это так же работает. -myObj.myFunc(); // = "hello world!" +// Для функций это тоже работает. +myObj.myFunc(); // = "Привет, мир!" -// Если интерпретатор не найдет свойство в прототипе, то продожит поиск в -// прототипе прототипа и так далее. +// Если интерпретатор не найдёт свойство в прототипе, то продожит поиск +// в прототипе прототипа и так далее. myPrototype.__proto__ = { myBoolean: true }; myObj.myBoolean; // = true // Здесь не участвует копирование; каждый объект хранит ссылку на свой прототип. -// Это означает, что мы можем изменить прототип и наши изменения будут отражены везде +// Это означает, что мы можем изменить прототип, и наши изменения будут отражены везде. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 -// Мы упомянули, что свойтсво __proto__ нестандартно, и нет никакого стандартного -// способа, чтобы изменить прототип существующего объекта. Однако, есть два +// Мы упомянули, что свойство __proto__ нестандартно, и нет никакого стандартного +// способа, чтобы изменить прототип существующего объекта. Однако есть два // способа создать новый объект с заданным прототипом. -// Первый способ это Object.create, который появился в ECMAScript 5 и есть еще -// не во всех реализациях языка. +// Первый способ — это Object.create, который появился в JavaScript недавно, +// а потому доступен ещё не во всех реализациях языка. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 // Второй способ, который работает везде, имеет дело с конструкторами. -// У конструкторов есть свойство с именем prototype. Это не прототип +// У конструкторов есть свойство с именем prototype. Это *не* прототип // функции-конструктора; напротив, это прототип для новых объектов, которые -// будут созданы с помощью этого конструктора и ключевого слова new +// будут созданы с помощью этого конструктора и ключевого слова new. MyConstructor.prototype = { myNumber: 5, getMyNumber: function() { @@ -453,8 +457,8 @@ myNewObj2.getMyNumber(); // = 5 myNewObj2.myNumber = 6 myNewObj2.getMyNumber(); // = 6 -// У встроенных типов, таких как строки и числа также есть конструкторы, которые -// создают эквивалентые объекты-обертки. +// У встроенных типов, таких, как строки и числа, также есть конструкторы, которые +// создают эквивалентные объекты-обёртки. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true @@ -464,47 +468,49 @@ typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0) { - // Этот код не выполнятся, потому что 0 - это ложь. + // Этот код не выполнится, потому что 0 - это ложь. } if (Number(0)) { - // Этот код выполнится, потому что Number(0) это истина. + // Этот код *выполнится*, потому что Number(0) истинно. } -// Впрочем, обертки это объекты и их можно расширять, например: +// Впрочем, объекты-обёртки и встроенные типы имеют общие прототипы, +// поэтому вы можете расширить функционал строк, например: String.prototype.firstCharacter = function() { return this.charAt(0); } "abc".firstCharacter(); // = "a" -// Это часто используется в полифиллах, которые реализуют новые возможности +// Это часто используется в т.н. полифилах, которые реализуют новые возможности // JavaScript в старой реализации языка, так что они могут быть использованы в -// старых средах, таких как устаревшие браузеры. +// старых средах, таких, как устаревшие браузеры. // Например, мы упомянули, что Object.create доступен не во всех реализациях, но -// мы сможем использовать его с этим полифиллом: -if (Object.create === undefined) { // не перезаписывать метод, если он существует +// мы сможем использовать его с помощью такого полифила: +if (Object.create === undefined) { // не перезаписываем метод, если он существует Object.create = function(proto) { - // создать временный конструктор с правильным прототипом + // создаём временный конструктор с правильным прототипом var Constructor = function(){}; Constructor.prototype = proto; - // затем использовать его для создания нового объекта, на основе прототипа + // затем используем его для создания нового, + // правильно прототипированного объекта return new Constructor(); } } ``` -## Что еще почитать +## Что ещё почитать -[Современный учебник JavaScript (Илья Кантор)](http://learn.javascript.ru) - +[Современный учебник JavaScript (Илья Кантор)](http://learn.javascript.ru) — качественный учебник по JavaScript на русском языке. -[Mozilla Developer Network](https://developer.mozilla.org/ru/docs/Web/JavaScript) - +[Mozilla Developer Network](https://developer.mozilla.org/ru/docs/Web/JavaScript) — предоставляет отличную документацию для JavaScript, как он используется в браузерах. Кроме того, это вики, поэтому, если вы знаете больше, вы можете помочь другим, делясь своими знаниями. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) - это -подробное руководство всех неинтуитивных особенностей языка. +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) — это +подробное руководство по всем неинтуитивным особенностей языка. -[Stack Overflow](http://stackoverflow.com/questions/tagged/javascript) - можно +[Stack Overflow](http://stackoverflow.com/questions/tagged/javascript) — можно найти ответ почти на любой ваш вопрос, а если его нет, то задать вопрос самому. -- cgit v1.2.3 From d02448f78946d098ea0c906c2622bb4e16235b79 Mon Sep 17 00:00:00 2001 From: Yuichi Motoyama Date: Tue, 13 Jan 2015 09:29:15 +0900 Subject: [julia/ja] Added missing `lang: ja-jp` Sorry, I missed writing `lang: ja-jp` in #894, and made a new Julia language tree in the top page. --- ja-jp/julia-jp.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ja-jp/julia-jp.html.markdown b/ja-jp/julia-jp.html.markdown index 0c1d7e49..0c3160a2 100644 --- a/ja-jp/julia-jp.html.markdown +++ b/ja-jp/julia-jp.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Yuichi Motoyama", "https://github.com/yomichi"] filename: learnjulia-jp.jl +lang: ja-jp --- Julia は科学技術計算向けに作られた、同図像性を持った(homoiconic) プログラミング言語です。 -- cgit v1.2.3 From a7918fb33c82ae350326064d74a98411e8c79995 Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Tue, 13 Jan 2015 11:46:28 +0300 Subject: [brainfuck/ru] Translating Brainfuck guide into Russian --- ru-ru/brainfuck-ru.html.markdown | 83 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 ru-ru/brainfuck-ru.html.markdown diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/brainfuck-ru.html.markdown new file mode 100644 index 00000000..f6e27ed2 --- /dev/null +++ b/ru-ru/brainfuck-ru.html.markdown @@ -0,0 +1,83 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] +lang: ru-ru +--- + +Brainfuck (пишется маленькими буквами, кроме начала предложения) - это очень +маленький Тьюринг-полный язык программирования лишь с 8 командами. + +``` +Любой символ игнорируется кроме "><+-.,[]" (исключая кавычки). + +Brainfuck представлен массивом из 30000 ячеек, инициализированных нулями, +и указателем, указывающего на текущую ячейку. + +Всего восемь команд: ++ : Увеличивает значение на единицу в текущей ячейке. +- : Уменьшает значение на единицу в текущей ячейке. +> : Смещает указатель данных на следующую ячейку (ячейку справа). +< : Смещает указатель данных на предыдущую ячейку (ячейку слева). +. : Печатает ASCII символ из текущей ячейки (напр. 65 = 'A'). +, : Записывает один входной символ в текущую ячейку. +[ : Если значение в текущей ячейке равно нулю, то пропустить все команды + до соответствующей ] . В противном случае, перейти к следующей инструкции. +] : Если значение в текущей ячейке равно нулю, то перейти к следующей инструкции. + В противном случае, вернуться назад к соответствующей [ . + +[ и ] образуют цикл while. Очевидно, они должны быть сбалансированы. + +Давайте рассмотрим некоторые базовые brainfuck программы. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Эта программа выводит букву 'A'. Сначала, программа увеличивает значение +ячейки №1 до 6. Ячейка #1 будет использоваться циклом. Затем, программа входит +в цикл ([) и переходит к ячейке №2. Ячейка №2 увеличивается до 10, переходим +назад к ячейке №1 и уменьшаем ячейку №1. Этот цикл проходит 6 раз (ячейка №1 +уменьшается до нуля, и с этого места пропускает инструкции до соответствующей ] +и идет дальше). + +В этот момент, мы в ячейке №1, которая имеет значение 0, значение ячейки №2 +пока 60. Мы переходим на ячейку №2, увеличиваем 5 раз, до значения 65, и затем +выводим значение ячейки №2. Код 65 является символом 'A' в кодировке ASCII, +так что 'A' выводится на терминал. + + +, [ > + < - ] > . + +Данная программа считывает символ из пользовательского ввода и копирует символ +в ячейку №1. Затем мы начинаем цикл. Переходим к ячейке №2, увеличиваем значение +ячейки №2, идем назад к ячейке №1 и уменьшаем значение ячейки №1. Это продолжается +до тех пор пока, ячейка №1 не равна 0, а ячейка №2 сохраняет старое значение +ячейки №1. Мы завершаем цикл на ячейке №1, поэтому переходим в ячейку №2, и +затем выводим символ ASCII. + +Также, имейте в виду, что пробелы здесь исключительно для читабельности. Вы можете +легко написать и так: + +,[>+<-]>. + +Попытайтесь разгадать, что следующая программа делает: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Программа принимает два числа на вход и умножает их. + +Суть в том, что программа сначала читает два ввода. Затем начинается внешний цикл, +сохраняя ячейку №1. Затем программа перемещается в ячейку №2, и начинается +внутренний цикл с сохранением ячейки №2, увеличивая ячейку №3. Однако появляется +проблема: В конце внутреннего цикла, ячейка №2 равна нулю. В этом случае, +внутренний цикл не будет работать уже в следующий раз. Чтобы решить эту проблему, +мы также увеличим ячейку №4, а затем копируем ячейку №4 в ячейку №2. +Итак, ячейка №3 - результат. +``` + +Это и есть brainfuck. Не так уж сложно, правда? Забавы ради, вы можете написать +свою собственную brainfuck программу или интерпретатор на другом языке. +Интерпретатор достаточно легко реализовать, но если вы мазохист, попробуйте +написать brainfuck интерпретатор... на языке brainfuck. -- cgit v1.2.3 From dd5588a2194b4e1f98fc4cee8a2fc277f6eae2f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Ara=C3=BAjo?= Date: Tue, 13 Jan 2015 10:26:08 -0300 Subject: [C++/en] translated to [C++/pt-br] --- pt-br/c++-pt.html.markdown | 591 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 591 insertions(+) create mode 100644 pt-br/c++-pt.html.markdown diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown new file mode 100644 index 00000000..243627cb --- /dev/null +++ b/pt-br/c++-pt.html.markdown @@ -0,0 +1,591 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +C++ é uma linguagem de programação de sistemas que, +C++ is a systems programming language that, +[de acordo com seu inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +foi concebida para + +- ser um "C melhor" +- suportar abstração de dados +- suportar programação orientada a objetos +- suportar programação genérica + +Embora sua sintaxe pode ser mais difícil ou complexa do que as linguagens mais +recentes, C++ é amplamente utilizado porque compila para instruções nativas que +podem ser executadas diretamente pelo processador e oferece um controlo rígido sobre hardware (como C), enquanto oferece recursos de alto nível, como os +genéricos, exceções e classes. Esta combinação de velocidade e funcionalidade +faz C++ uma das linguagens de programação mais utilizadas. + +```c++ +////////////////// +// Comparação com C +////////////////// + +// C ++ é quase um super conjunto de C e compartilha sua sintaxe básica para +// declarações de variáveis, tipos primitivos, e funções. No entanto, C++ varia +// em algumas das seguintes maneiras: + +// A função main() em C++ deve retornar um int, embora void main() é aceita +// pela maioria dos compiladores (gcc, bumbum, etc.) +// Este valor serve como o status de saída do programa. +// Veja http://en.wikipedia.org/wiki/Exit_status para mais informações. + +int main(int argc, char** argv) +{ + // Argumentos de linha de comando são passados em pelo argc e argv da mesma + // forma que eles estão em C. + // argc indica o número de argumentos, + // e argv é um array de strings, feito C (char*) representado os argumentos + // O primeiro argumento é o nome pelo qual o programa foi chamado. + // argc e argv pode ser omitido se você não se importa com argumentos, + // dando a assinatura da função de int main() + + // Uma saída de status de 0 indica sucesso. + return 0; +} + +// Em C++, caracteres literais são um byte. +sizeof('c') == 1 + +// Em C, caracteres literais são do mesmo tamanho que ints. +sizeof('c') == sizeof(10) + +// C++ tem prototipagem estrita +void func(); // função que não aceita argumentos + +// Em C +void func(); // função que pode aceitar qualquer número de argumentos + +// Use nullptr em vez de NULL em C++ +int* ip = nullptr; + +// Cabeçalhos padrão C estão disponíveis em C++, +// mas são prefixados com "c" e não têm sufixo .h + +#include + +int main() +{ + printf("Hello, world!\n"); + return 0; +} + +/////////////////////// +// Sobrecarga de função +/////////////////////// + +// C++ suporta sobrecarga de função +// desde que cada função tenha parâmetros diferentes. + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("My int is %d", myInt); +} + +int main() +{ + print("Hello"); // Funciona para void print(const char*) + print(15); // Funciona para void print(int) +} + +///////////////////////////// +// Parâmetros padrão de função +///////////////////////////// + +// Você pode fornecer argumentos padrões para uma função se eles não são +// fornecidos pelo chamador. + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // Faça alguma coisa com os ints aqui +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// Argumentos padrões devem estar no final da lista de argumentos. + +void invalidDeclaration(int a = 1, int b) // Erro! +{ +} + + +///////////// +// Namespaces (nome de espaços) +///////////// + +// Namespaces fornecem escopos distintos para variável, função e outras +// declarações. Namespaces podem estar aninhados. + +namespace First { + namespace Nested { + void foo() + { + printf("This is First::Nested::foo\n"); + } + } // Fim do namespace aninhado +} // Fim do namespace First + +namespace Second { + void foo() + { + printf("This is Second::foo\n") + } +} + +void foo() +{ + printf("This is global foo\n"); +} + +int main() +{ + // Assuma que tudo é do namespace "Second" a menos que especificado de + // outra forma. + using namespace Second; + + foo(); // imprime "This is Second::foo" + First::Nested::foo(); // imprime "This is First::Nested::foo" + ::foo(); // imprime "This is global foo" +} + +/////////////// +// Entrada/Saída +/////////////// + +// C ++ usa a entrada e saída de fluxos (streams) +// cin, cout, and cerr representa stdin, stdout, and stderr. +// << É o operador de inserção e >> é o operador de extração. + +#include // Inclusão para o I/O streams + +using namespace std; // Streams estão no namespace std (biblioteca padrão) + +int main() +{ + int myInt; + + // Imprime na saída padrão (ou terminal/tela) + cout << "Enter your favorite number:\n"; + // Pega a entrada + cin >> myInt; + + // cout também pode ser formatado + cout << "Your favorite number is " << myInt << "\n"; + // imprime "Your favorite number is " + + cerr << "Usado para mensagens de erro"; +} + +////////// +// Strings +////////// + +// Strings em C++ são objetos e têm muitas funções de membro +#include + +using namespace std; // Strings também estão no namespace std (bib. padrão) + +string myString = "Hello"; +string myOtherString = " World"; + +// + é usado para concatenação. +cout << myString + myOtherString; // "Hello World" + +cout << myString + " You"; // "Hello You" + +// Em C++, strings são mutáveis e têm valores semânticos. +myString.append(" Dog"); +cout << myString; // "Hello Dog" + + +///////////// +// Referência +///////////// + +// Além de indicadores como os de C, C++ têm _referências_. Esses são tipos de +// ponteiro que não pode ser reatribuída uma vez definidos e não pode ser nulo. +// Eles também têm a mesma sintaxe que a própria variável: Não * é necessário +// para _dereferencing_ e & (endereço de) não é usado para atribuição. + +using namespace std; + +string foo = "I am foo"; +string bar = "I am bar"; + + +string& fooRef = foo; // Isso cria uma referência para foo. +fooRef += ". Hi!"; // Modifica foo através da referência +cout << fooRef; // Imprime "I am foo. Hi!" + +// Não realocar "fooRef". Este é o mesmo que "foo = bar", e foo == "I am bar" +// depois desta linha. + +fooRef = bar; + +const string& barRef = bar; // Cria uma referência const para bar. +// Como C, valores const (e ponteiros e referências) não podem ser modificado. +barRef += ". Hi!"; // Erro, referência const não pode ser modificada. + +////////////////////////////////////////// +// Classes e programação orientada a objeto +////////////////////////////////////////// + +// Primeiro exemplo de classes +#include + +// Declara a classe. +// As classes são geralmente declarado no cabeçalho arquivos (.h ou .hpp). +class Dog { + // Variáveis de membro e funções são privadas por padrão. + std::string name; + int weight; + +// Todos os membros a seguir este são públicos até que "private:" ou +// "protected:" é encontrado. +public: + + // Construtor padrão + Dog(); + + // Declarações de função Membro (implementações a seguir) + // Note que usamos std :: string aqui em vez de colocar + // using namespace std; + // acima. + // Nunca coloque uma declaração "using namespace" em um cabeçalho. + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + + // Funções que não modificam o estado do objecto devem ser marcadas como + // const. Isso permite que você chamá-los se for dada uma referência const + // para o objeto. Além disso, observe as funções devem ser explicitamente + // declarados como _virtual_, a fim de ser substituídas em classes + // derivadas. As funções não são virtuais por padrão por razões de + // performance. + + virtual void print() const; + + // As funções também podem ser definidas no interior do corpo da classe. + // Funções definidas como tal são automaticamente embutidas. + void bark() const { std::cout << name << " barks!\n" } + + // Junto com os construtores, C++ fornece destruidores. + // Estes são chamados quando um objeto é excluído ou fica fora do escopo. + // Isto permite paradigmas poderosos, como RAII + // (veja abaixo) + // Destruidores devem ser virtual para permitir que as classes de ser + // derivada desta. + virtual ~Dog(); + +}; // Um ponto e vírgula deve seguir a definição de classe. + +// Funções membro da classe geralmente são implementados em arquivos .cpp. +void Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} + +// Objetos (como strings) devem ser passados por referência +// se você está modificando-os ou referência const se você não é. +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// Observe que "virtual" só é necessária na declaração, não a definição. +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; // imprime "A dog has been constructed" + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.printDog(); // imprime "Dog is Barkley and weighs 10 kg" + return 0; +} // imprime "Goodbye Barkley" + +// herança: + +// Essa classe herda tudo público e protegido da classe Dog +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner) + + // Substituir o comportamento da função de impressão de todas OwnedDogs. + // Ver http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // Para uma introdução mais geral, se você não estiver familiarizado com o + // polimorfismo subtipo. A palavra-chave override é opcional, mas torna-se + // na verdade você está substituindo o método em uma classe base. + void print() const override; + +private: + std::string owner; +}; + +// Enquanto isso, no arquivo .cpp correspondente: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // Chame a função de impressão na classe Dog base de + std::cout << "Dog is owned by " << owner << "\n"; + // Prints "Dog is and weights " + // "Dog is owned by " +} + +////////////////////////////////////////// +// Inicialização e Sobrecarga de Operadores +////////////////////////////////////////// + +// Em C ++, você pode sobrecarregar o comportamento dos operadores, tais como +// +, -, *, /, etc. Isto é feito através da definição de uma função que é +// chamado sempre que o operador é usado. + +#include +using namespace std; + +class Point { +public: + // Variáveis membro pode ser dado valores padrão desta maneira. + double x = 0; + double y = 0; + + // Define um construtor padrão que não faz nada + // mas inicializar o Point para o valor padrão (0, 0) + Point() { }; + + // A sintaxe a seguir é conhecido como uma lista de inicialização + // e é a maneira correta de inicializar os valores de membro de classe + Point (double a, double b) : + x(a), + y(b) + { /* Não fazer nada, exceto inicializar os valores */ } + + // Sobrecarrega o operador +. + Point operator+(const Point& rhs) const; + + // Sobrecarregar o operador +=. + Point& operator+=(const Point& rhs); + + // Ele também faria sentido para adicionar os operadores - e -=, + // mas vamos pular para sermos breves. +}; + +Point Point::operator+(const Point& rhs) const +{ + // Criar um novo ponto que é a soma de um e 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); + // Isto chama que o operador ponto + + // Ressalte-se a chamadas (função)+ com direito como seu parâmetro... + Point result = up + right; + // Imprime "Result is upright (1,1)" + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +///////////////////////// +// Tratamento de Exceções +///////////////////////// + +// A biblioteca padrão fornece alguns tipos de exceção +// (see http://en.cppreference.com/w/cpp/error/exception) +// mas qualquer tipo pode ser jogado como uma exceção +#include + +// Todas as exceções lançadas dentro do bloco try pode ser capturado por +// manipuladores de captura subseqüentes +try { + // Não aloca exceções no heap usando _new_. + throw std::exception("A problem occurred"); +} +// Capturar exceções por referência const se eles são objetos +catch (const std::exception& ex) +{ + std::cout << ex.what(); +// Captura qualquer exceção não capturada pelos blocos _catch_ anteriores +} catch (...) +{ + std::cout << "Exceção desconhecida encontrada"; + throw; // Re-lança a exceção +} + +/////// +// RAII +/////// + +// RAII significa alocação de recursos é de inicialização. +// Muitas vezes, é considerado o paradigma mais poderoso em C++, e é o +// conceito simples que um construtor para um objeto adquire recursos daquele +// objeto e o destruidor liberá-los. + +// Para entender como isso é útil, +// Considere uma função que usa um identificador de arquivo C: +void doSomethingWithAFile(const char* filename) +{ + // Para começar, assuma que nada pode falhar. + + FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura. + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // Feche o arquivo. +} + +// Infelizmente, as coisas são levemente complicadas para tratamento de erros. +// Suponha que fopen pode falhar, e que doSomethingWithTheFile e +// doSomethingElseWithIt retornam códigos de erro se eles falharem. (As +// exceções são a forma preferida de lidar com o fracasso, mas alguns +// programadores, especialmente aqueles com um conhecimento em C, discordam +// sobre a utilidade de exceções). Agora temos que verificar cada chamada para +// o fracasso e fechar o identificador de arquivo se ocorreu um problema. + +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura + if (fh == nullptr) // O ponteiro retornado é nulo em caso de falha. + reuturn false; // Relate o fracasso para o chamador. + + // Suponha cada função retorne false, se falhar + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Feche o identificador de arquivo para que ele não vaze. + return false; // Propague o erro. + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Feche o identificador de arquivo para que ele não vaze. + return false; // Propague o erro. + } + + fclose(fh); // Feche o identificador de arquivo para que ele não vaze. + return true; // Indica sucesso +} + +// Programadores C frequentemente limpam isso um pouco usando Goto: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + reuturn false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Close the file + return true; // Indica sucesso + +failure: + fclose(fh); + return false; // Propague o erro. +} + +// Se as funções indicam erros usando exceções, +// as coisas são um pouco mais limpo, mas ainda abaixo do ideal. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura. + if (fh == nullptr) + throw std::exception("Não pode abrir o arquivo."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Certifique-se de fechar o arquivo se ocorrer um erro. + throw; // Em seguida, re-lance a exceção. + } + + fclose(fh); // Feche o arquivo + // Tudo ocorreu com sucesso! +} + +// Compare isso com o uso de C++ classe fluxo de arquivo (fstream) fstream usa +// seu destruidor para fechar o arquivo. Lembre-se de cima que destruidores são +// automaticamente chamado sempre que um objeto cai fora do âmbito. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream é curto para o fluxo de arquivo de entrada + std::ifstream fh(filename); // Abra o arquivo + + // faça alguma coisa com o arquivo + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // O arquivo é automaticamente fechado aqui pelo destructor + +// Isto tem _grandes_ vantagens: +// 1. Não importa o que aconteça, +// o recurso (neste caso, o identificador de ficheiro) irá ser limpo. +// Depois de escrever o destruidor corretamente, +// É _impossível_ esquecer de fechar e vazar o recurso +// 2. Nota-se que o código é muito mais limpo. +// As alças destructor fecham o arquivo por trás das cenas +// sem que você precise se preocupar com isso. +// 3. O código é seguro de exceção. +// Uma exceção pode ser jogado em qualquer lugar na função e a limpeza +// irá ainda ocorrer. + +// Todos códigos C++ usam RAII extensivamente para todos os recursos. +// Outros exemplos incluem +// - Memória usa unique_ptr e shared_ptr +// - Contentores - a lista da biblioteca ligada padrão, +// vetor (i.e. array de autodimensionamento), mapas hash, e assim por diante +// tudo é automaticamente destruído quando eles saem de escopo +// - Mutex usa lock_guard e unique_lock +``` +Leitura Adicional: + +Uma referência atualizada da linguagem pode ser encontrada em + + +Uma fonte adicional pode ser encontrada em \ No newline at end of file -- cgit v1.2.3 From 4fc9c89f64e64c3dce19eec7adecd4efb009c162 Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Tue, 13 Jan 2015 19:19:24 +0300 Subject: Fix small mistackes. --- ru-ru/brainfuck-ru.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/brainfuck-ru.html.markdown index f6e27ed2..500ac010 100644 --- a/ru-ru/brainfuck-ru.html.markdown +++ b/ru-ru/brainfuck-ru.html.markdown @@ -12,10 +12,10 @@ Brainfuck (пишется маленькими буквами, кроме нач маленький Тьюринг-полный язык программирования лишь с 8 командами. ``` -Любой символ игнорируется кроме "><+-.,[]" (исключая кавычки). +Любой символ, кроме "><+-.,[]", игнорируется, за исключением кавычек. Brainfuck представлен массивом из 30000 ячеек, инициализированных нулями, -и указателем, указывающего на текущую ячейку. +и указателем с позицией в текущей ячейке. Всего восемь команд: + : Увеличивает значение на единицу в текущей ячейке. @@ -29,22 +29,22 @@ Brainfuck представлен массивом из 30000 ячеек, ини ] : Если значение в текущей ячейке равно нулю, то перейти к следующей инструкции. В противном случае, вернуться назад к соответствующей [ . -[ и ] образуют цикл while. Очевидно, они должны быть сбалансированы. +[ и ] образуют цикл while. Естественно, они должны быть сбалансированы. -Давайте рассмотрим некоторые базовые brainfuck программы. +Давайте рассмотрим некоторые базовые brainfuck-программы. ++++++ [ > ++++++++++ < - ] > +++++ . -Эта программа выводит букву 'A'. Сначала, программа увеличивает значение -ячейки №1 до 6. Ячейка #1 будет использоваться циклом. Затем, программа входит +Эта программа выводит букву 'A'. Сначала программа увеличивает значение +ячейки №1 до 6. Ячейка №1 будет использоваться циклом. Затем программа входит в цикл ([) и переходит к ячейке №2. Ячейка №2 увеличивается до 10, переходим назад к ячейке №1 и уменьшаем ячейку №1. Этот цикл проходит 6 раз (ячейка №1 уменьшается до нуля, и с этого места пропускает инструкции до соответствующей ] и идет дальше). -В этот момент, мы в ячейке №1, которая имеет значение 0, значение ячейки №2 -пока 60. Мы переходим на ячейку №2, увеличиваем 5 раз, до значения 65, и затем -выводим значение ячейки №2. Код 65 является символом 'A' в кодировке ASCII, +В этот момент мы находимся в ячейке №1, которая имеет значение 0, значение +ячейки №2 пока 60. Мы переходим на ячейку №2, увеличиваем 5 раз, до значения 65, +и затем выводим значение ячейки №2. Код 65 является символом 'A' в кодировке ASCII, так что 'A' выводится на терминал. @@ -53,11 +53,11 @@ Brainfuck представлен массивом из 30000 ячеек, ини Данная программа считывает символ из пользовательского ввода и копирует символ в ячейку №1. Затем мы начинаем цикл. Переходим к ячейке №2, увеличиваем значение ячейки №2, идем назад к ячейке №1 и уменьшаем значение ячейки №1. Это продолжается -до тех пор пока, ячейка №1 не равна 0, а ячейка №2 сохраняет старое значение -ячейки №1. Мы завершаем цикл на ячейке №1, поэтому переходим в ячейку №2, и +до тех пор, пока ячейка №1 не равна 0, а ячейка №2 сохраняет старое значение +ячейки №1. Мы завершаем цикл на ячейке №1, поэтому переходим в ячейку №2 и затем выводим символ ASCII. -Также, имейте в виду, что пробелы здесь исключительно для читабельности. Вы можете +Также имейте в виду, что пробелы здесь исключительно для читабельности. Вы можете легко написать и так: ,[>+<-]>. @@ -71,13 +71,13 @@ Brainfuck представлен массивом из 30000 ячеек, ини Суть в том, что программа сначала читает два ввода. Затем начинается внешний цикл, сохраняя ячейку №1. Затем программа перемещается в ячейку №2, и начинается внутренний цикл с сохранением ячейки №2, увеличивая ячейку №3. Однако появляется -проблема: В конце внутреннего цикла, ячейка №2 равна нулю. В этом случае, +проблема: В конце внутреннего цикла ячейка №2 равна нулю. В этом случае, внутренний цикл не будет работать уже в следующий раз. Чтобы решить эту проблему, мы также увеличим ячейку №4, а затем копируем ячейку №4 в ячейку №2. Итак, ячейка №3 - результат. ``` Это и есть brainfuck. Не так уж сложно, правда? Забавы ради, вы можете написать -свою собственную brainfuck программу или интерпретатор на другом языке. +свою собственную brainfuck-программу или интерпретатор на другом языке. Интерпретатор достаточно легко реализовать, но если вы мазохист, попробуйте -написать brainfuck интерпретатор... на языке brainfuck. +написать brainfuck-интерпретатор... на языке brainfuck. -- cgit v1.2.3 From dff86ae3cb5618609f8238cca20c2493b5ffc240 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 13 Jan 2015 20:09:14 +0000 Subject: Update common-lisp-pt.html.markdown --- pt-br/common-lisp-pt.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index ce654846..03a7c15c 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Paul Nathan", "https://github.com/pnathan"] translators: - ["Édipo Luis Féderle", "https://github.com/edipofederle"] +lang: pt-br --- ANSI Common Lisp é uma linguagem de uso geral, multi-paradigma, designada -- cgit v1.2.3 From ecc5d89841ec2417c8d68f0c84347760cf69c140 Mon Sep 17 00:00:00 2001 From: P1start Date: Thu, 15 Jan 2015 15:14:19 +1300 Subject: [rust/en] Update the Rust tutorial This adjusts the English Rust tutorial for changes to the language and generally tweaks a few other things. Fixes #860. --- rust.html.markdown | 169 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 102 insertions(+), 67 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 3717a7d9..dcb54733 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -7,9 +7,13 @@ filename: learnrust.rs Rust is an in-development programming language developed by Mozilla Research. It is relatively unique among systems languages in that it can assert memory -safety *at compile time*. Rust’s first alpha release occurred in January -2012, and development moves so quickly that at the moment the use of stable -releases is discouraged, and instead one should use nightly builds. +safety *at compile time* without resorting to garbage collection. Rust’s first +release, 0.1, occurred in January 2012, and development moves so quickly that at +the moment the use of stable releases is discouraged, and instead one should use +nightly builds. On January 9 2015, Rust 1.0 Alpha was released, and the rate of +changes to the Rust compiler that break existing code has dropped significantly +since. However, a complete guarantee of backward compatibility will not exist +until the final 1.0 release. Although Rust is a relatively low-level language, Rust has some functional concepts that are generally found in higher-level languages. This makes @@ -24,7 +28,8 @@ Rust not only fast, but also easy and efficient to code in. /////////////// // Functions -fn add2(x: int, y: int) -> int { +// `i32` is the type for 32-bit signed integers +fn add2(x: i32, y: i32) -> i32 { // Implicit return (no semicolon) x + y } @@ -34,71 +39,90 @@ fn main() { // Numbers // // Immutable bindings - let x: int = 1; + let x: i32 = 1; // Integer/float suffixes - let y: int = 13i; + let y: i32 = 13i32; let f: f64 = 1.3f64; // Type inference - let implicit_x = 1i; - let implicit_f = 1.3f64; + // Most of the time, the Rust compiler can infer what type a variable is, so + // you don’t have to write an explicit type annotation. + // Throughout this tutorial, types are explicitly annotated in many places, + // but only for demonstrative purposes. Type inference can handle this for + // you most of the time. + let implicit_x = 1; + let implicit_f = 1.3; - // Maths - let sum = x + y + 13i; + // Arithmetic + let sum = x + y + 13; // Mutable variable let mut mutable = 1; + mutable = 4; mutable += 2; // Strings // - + // String literals - let x: &'static str = "hello world!"; + let x: &str = "hello world!"; // Printing println!("{} {}", f, x); // 1.3 hello world - // A `String` - a heap-allocated string + // A `String` – a heap-allocated string let s: String = "hello world".to_string(); - // A string slice - an immutable view into another string - // This is basically an immutable pointer to a string - it doesn’t - // actually contain the characters of a string, just a pointer to + // A string slice – an immutable view into another string + // This is basically an immutable pointer to a string – it doesn’t + // actually contain the contents of a string, just a pointer to // something that does (in this case, `s`) - let s_slice: &str = s.as_slice(); + let s_slice: &str = &*s; println!("{} {}", s, s_slice); // hello world hello world // Vectors/arrays // // A fixed-size array - let four_ints: [int, ..4] = [1, 2, 3, 4]; + let four_ints: [i32; 4] = [1, 2, 3, 4]; - // A dynamically-sized vector - let mut vector: Vec = vec![1, 2, 3, 4]; + // A dynamic array (vector) + let mut vector: Vec = vec![1, 2, 3, 4]; vector.push(5); - // A slice - an immutable view into a vector or array + // A slice – an immutable view into a vector or array // This is much like a string slice, but for vectors - let slice: &[int] = vector.as_slice(); + let slice: &[i32] = &*vector; + + // Use `{:?}` to print something debug-style + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Tuples // - println!("{} {}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + // A tuple is a fixed-size set of values of possibly different types + let x: (i32, &str, f64) = (1, "hello", 3.4); + + // Destructuring `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hello 3.4 + + // Indexing + println!("{}", x.1); // hello ////////////// // 2. Types // ////////////// - + // Struct struct Point { - x: int, - y: int, + x: i32, + y: i32, } let origin: Point = Point { x: 0, y: 0 }; - // Tuple struct - struct Point2(int, int); + // A struct with unnamed fields, called a ‘tuple struct’ + struct Point2(i32, i32); let origin2 = Point2(0, 0); @@ -110,16 +134,16 @@ fn main() { Down, } - let up = Up; + let up = Direction::Up; // Enum with fields - enum OptionalInt { - AnInt(int), + enum OptionalI32 { + AnI32(i32), Nothing, } - let two: OptionalInt = AnInt(2); - let nothing: OptionalInt = Nothing; + let two: OptionalI32 = OptionalI32::AnI32(2); + let nothing = OptionalI32::Nothing; // Generics // @@ -140,10 +164,10 @@ fn main() { } } - let a_foo = Foo { bar: 1i }; + let a_foo = Foo { bar: 1 }; println!("{}", a_foo.get_bar()); // 1 - // Traits (interfaces) // + // Traits (known as interfaces or typeclasses in other languages) // trait Frobnicate { fn frobnicate(self) -> Option; @@ -155,30 +179,31 @@ fn main() { } } - println!("{}", a_foo.frobnicate()); // Some(1) + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) ///////////////////////// // 3. Pattern matching // ///////////////////////// - - let foo = AnInt(1); + + let foo = OptionalI32::AnI32(1); match foo { - AnInt(n) => println!("it’s an int: {}", n), - Nothing => println!("it’s nothing!"), + OptionalI32::AnI32(n) => println!("it’s an i32: {}", n), + OptionalI32::Nothing => println!("it’s nothing!"), } // Advanced pattern matching - struct FooBar { x: int, y: OptionalInt } - let bar = FooBar { x: 15, y: AnInt(32) }; + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; match bar { - FooBar { x: 0, y: AnInt(0) } => + FooBar { x: 0, y: OptionalI32::AnI32(0) } => println!("The numbers are zero!"), - FooBar { x: n, y: AnInt(m) } if n == m => + FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => println!("The numbers are the same"), - FooBar { x: n, y: AnInt(m) } => + FooBar { x: n, y: OptionalI32::AnI32(m) } => println!("Different numbers: {} {}", n, m), - FooBar { x: _, y: Nothing } => + FooBar { x: _, y: OptionalI32::Nothing } => println!("The second number is Nothing!"), } @@ -187,19 +212,20 @@ fn main() { ///////////////////// // `for` loops/iteration - let array = [1i, 2, 3]; + let array = [1, 2, 3]; for i in array.iter() { println!("{}", i); } - for i in range(0u, 10) { + // Ranges + for i in 0u32..10 { print!("{} ", i); } println!(""); // prints `0 1 2 3 4 5 6 7 8 9 ` // `if` - if 1i == 1 { + if 1 == 1 { println!("Maths is working!"); } else { println!("Oh no..."); @@ -213,7 +239,7 @@ fn main() { }; // `while` loop - while 1i == 1 { + while 1 == 1 { println!("The universe is operating normally."); } @@ -225,40 +251,49 @@ fn main() { ///////////////////////////////// // 5. Memory safety & pointers // ///////////////////////////////// - - // Owned pointer - only one thing can ‘own’ this pointer at a time - let mut mine: Box = box 3; + + // Owned pointer – only one thing can ‘own’ this pointer at a time + // This means that when the `Box` leaves its scope, it can be automatically deallocated safely. + let mut mine: Box = Box::new(3); *mine = 5; // dereference + // Here, `now_its_mine` takes ownership of `mine`. In other words, `mine` is moved. let mut now_its_mine = mine; *now_its_mine += 2; + println!("{}", now_its_mine); // 7 - // println!("{}", mine); // this would error + // println!("{}", mine); // this would not compile because `now_its_mine` now owns the pointer - // Reference - an immutable pointer that refers to other data - let mut var = 4i; + // Reference – an immutable pointer that refers to other data + // When a reference is taken to a value, we say that the value has been ‘borrowed’. + // While a value is borrowed immutably, it cannot be mutated or moved. + // A borrow lasts until the end of the scope it was created in. + let mut var = 4; var = 3; - let ref_var: &int = &var; + let ref_var: &i32 = &var; + println!("{}", var); // Unlike `box`, `var` can still be used println!("{}", *ref_var); - // var = 5; // this would error - // *ref_var = 6; // this would too + // var = 5; // this would not compile because `var` is borrowed + // *ref_var = 6; // this would too, because `ref_var` is an immutable reference // Mutable reference - let mut var2 = 4i; - let ref_var2: &mut int = &mut var2; + // While a value is mutably borrowed, it cannot be accessed at all. + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; *ref_var2 += 2; + println!("{}", *ref_var2); // 6 - // var2 = 2; // this would error + // var2 = 2; // this would not compile because `var2` is borrowed } ``` ## Further reading -There’s a lot more to Rust—this is just the basics of Rust so you can -understand the most important things. To learn more about Rust, read [The Rust -Guide](http://doc.rust-lang.org/guide.html) and check out the -[/r/rust](http://reddit.com/r/rust) subreddit. The folks on the #rust channel -on irc.mozilla.org are also always keen to help newcomers. +There’s a lot more to Rust—this is just the basics of Rust so you can understand +the most important things. To learn more about Rust, read [The Rust Programming +Language](http://doc.rust-lang.org/book/index.html) and check out the +[/r/rust](http://reddit.com/r/rust) subreddit. The folks on the #rust channel on +irc.mozilla.org are also always keen to help newcomers. You can also try out features of Rust with an online compiler at the official [Rust playpen](http://play.rust-lang.org) or on the main -- cgit v1.2.3 From 9f765b9c7b0b207b51b914161313fdb7ecadaa5c Mon Sep 17 00:00:00 2001 From: Suzane Sant Ana Date: Sat, 17 Jan 2015 09:17:39 -0200 Subject: removing a piece in english in pt-br translation --- pt-br/c++-pt.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 243627cb..61625ebe 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -9,8 +9,7 @@ translators: lang: pt-br --- -C++ é uma linguagem de programação de sistemas que, -C++ is a systems programming language that, +C++ é uma linguagem de programação de sistemas que, [de acordo com seu inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), foi concebida para @@ -588,4 +587,4 @@ Leitura Adicional: Uma referência atualizada da linguagem pode ser encontrada em -Uma fonte adicional pode ser encontrada em \ No newline at end of file +Uma fonte adicional pode ser encontrada em -- cgit v1.2.3 From 3fa59915d0e30b5b0f08bea5e1a62b73f4250ebb Mon Sep 17 00:00:00 2001 From: yelite Date: Sun, 18 Jan 2015 16:06:48 +0800 Subject: Update swift.html.markdown --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index 0d1d2df4..2fbbe544 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -481,7 +481,7 @@ extension Int { } println(7.customProperty) // "This is 7" -println(14.multiplyBy(2)) // 42 +println(14.multiplyBy(3)) // 42 // Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. -- cgit v1.2.3 From 40c38c125b94430b518d7e402d595694149b7c53 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 18 Jan 2015 13:07:31 -0700 Subject: [Java/cn] Fix inc/dec operator explanation --- zh-cn/java-cn.html.markdown | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index f7d319e6..f08d3507 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -124,7 +124,7 @@ public class LearnJava { // HashMaps /////////////////////////////////////// - // 操作符 + // 操作符 /////////////////////////////////////// System.out.println("\n->Operators"); @@ -161,10 +161,13 @@ public class LearnJava { // 自增 int i = 0; System.out.println("\n->Inc/Dec-rementation"); - System.out.println(i++); //i = 1 后自增 - System.out.println(++i); //i = 2 前自增 - System.out.println(i--); //i = 1 后自减 - System.out.println(--i); //i = 0 前自减 + // ++ 和 -- 操作符使变量加或减1。放在变量前面或者后面的区别是整个表达 + // 式的返回值。操作符在前面时,先加减,后取值。操作符在后面时,先取值 + // 后加减。 + System.out.println(i++); // 后自增 i = 1, 输出0 + System.out.println(++i); // 前自增 i = 2, 输出2 + System.out.println(i--); // 后自减 i = 1, 输出2 + System.out.println(--i); // 前自减 i = 0, 输出0 /////////////////////////////////////// // 控制结构 @@ -192,7 +195,7 @@ public class LearnJava { } System.out.println("fooWhile Value: " + fooWhile); - // Do While循环 + // Do While循环 int fooDoWhile = 0; do { -- cgit v1.2.3 From 8d43943b678846f1fb81c925e8232f92f46baa02 Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Mon, 19 Jan 2015 17:40:07 +0300 Subject: [swift/ru] Translating Swift guide into Russian --- ru-ru/swift-ru.html.markdown | 535 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 535 insertions(+) create mode 100644 ru-ru/swift-ru.html.markdown diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown new file mode 100644 index 00000000..d78365a5 --- /dev/null +++ b/ru-ru/swift-ru.html.markdown @@ -0,0 +1,535 @@ +--- +language: swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] +filename: learnswift.swift +translators: + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] +lang: ru-ru +--- + +Swift - это язык программирования, созданный компанией Apple, для разработки +приложений iOS и OS X. Разработанный, чтобы сосуществовать с Objective-C и +быть более устойчивым к ошибочному коду, Swift был представлен в 2014 году на +конференции разработчиков Apple, WWDC. Приложения на Swift собираются +с помощью LLVM компилятора, включенного в Xcode 6+. + +Официальная книга по [языку программирования Swift](https://itunes.apple.com/us/book/swift-programming-language/id881256329) от Apple доступна в iBooks. + +Смотрите еще [начальное руководство](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) Apple, которое содержит полное учебное пособие по Swift. + +```swift +// импорт модуля +import UIKit + +// +// MARK: Основы +// + +// Xcode поддерживает заметные маркеры, чтобы давать примечания свою коду +// и вносить их в список обозревателя (Jump Bar) +// MARK: Метка раздела +// TODO: Сделайте что-нибудь вскоре +// FIXME: Исправьте этот код + +println("Привет, мир") + +// переменные (var), значение которых можно изменить после инициализации +// константы (let), значение которых нельзя изменить после инициализации + +var myVariable = 42 +let øπΩ = "значение" // именование переменной символами unicode +let π = 3.1415926 +let convenience = "Ключевое слово" // контекстное имя переменной +let weak = "Ключевое слово"; let override = "еще ключевое слово" // операторы + // могут быть отделены точкой с запятой +let `class` = "Ключевое слово" // одинарные кавычки позволяют использовать + // ключевые слова в именовании переменных +let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "некоторый текст " + String(myVariable) // Приведение типа +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Вставка переменных в строку + +// Сборка особых значений +// используя ключ -D сборки конфигурации +#if false + println("Не печатается") + let buildValue = 3 +#else + let buildValue = 7 +#endif +println("Значение сборки: \(buildValue)") // Значение сборки: 7 + +/* + Optional - это особенность языка Swift, которая допускает вам сохранять + `некоторое` или `никакое` значения. + + Язык Swift требует, чтобы каждое свойство имело значение, поэтому даже nil + должен явно сохранен как Optional значение. + + Optional является перечислением. +*/ +var someOptionalString: String? = "optional" // Может быть nil +// как и выше, только ? это постфиксный оператор (синтаксический сахар) +var someOptionalString2: Optional = "optional" + +if someOptionalString != nil { + // я не nil + if someOptionalString!.hasPrefix("opt") { + println("содержит префикс") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +// неявная развертка переменной Optional +var unwrappedString: String! = "Ожидаемое значение." +// как и выше, только ! постфиксный оператор (с еще одним синтаксическим сахаром) +var unwrappedString2: ImplicitlyUnwrappedOptional = "Ожидаемое значение." + +if let someOptionalStringConstant = someOptionalString { + // имеется некоторое значение, не nil + if !someOptionalStringConstant.hasPrefix("ok") { + // нет такого префикса + } +} + +// Swift поддерживает сохранение значение любого типа +// AnyObject == id +// В отличие от `id` в Objective-C, AnyObject работает с любым значением (Class, +// Int, struct и т.д.) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Изменять значение на строку не является хорошей практикой, но возможно." + +/* + Комментируйте здесь + + /* + Вложенные комментарии тоже поддерживаются + */ +*/ + +// +// MARK: Коллекции +// + +/* + Массив (Array) и словарь (Dictionary) являются структурами (struct). Так + `let` и `var` также означают, что они изменяются (var) или не изменяются (let) + при объявлении типов. +*/ + +// Массив +var shoppingList = ["сом", "вода", "лимоны"] +shoppingList[1] = "бутылка воды" +let emptyArray = [String]() // let == неизменный +let emptyArray2 = Array() // как и выше +var emptyMutableArray = [String]() // var == изменяемый + + +// Словарь +var occupations = [ + "Malcolm": "Капитан", + "kaylee": "Техник" +] +occupations["Jayne"] = "Связи с общественностью" +let emptyDictionary = [String: Float]() // let == неизменный +let emptyDictionary2 = Dictionary() // как и выше +var emptyMutableDictionary = [String: Float]() // var == изменяемый + + +// +// MARK: Поток управления +// + +// цикл for для массива +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + println("Один!") + } else { + println("Не один!") + } +} + +// цикл for для словаря +var dict = ["один": 1, "два": 2] +for (key, value) in dict { + println("\(key): \(value)") +} + +// цикл for для диапазона чисел +for i in -1...shoppingList.count { + println(i) +} +shoppingList[1...2] = ["бифштекс", "орехи пекан"] +// используйте ..< для исключения последнего числа + +// цикл while +var i = 1 +while i < 1000 { + i *= 2 +} + +// цикл do-while +do { + println("привет") +} while 1 == 2 + +// Переключатель +// Очень мощный оператор, представляйте себе операторы `if` с синтаксическим +// сахаром +// Они поддерживают строки, объекты и примитивы (Int, Double, etc) +let vegetable = "красный перец" +switch vegetable { +case "сельдерей": + let vegetableComment = "Добавьте немного изюма и make ants on a log." +case "огурец", "жеруха": + let vegetableComment = "Было бы неплохо сделать бутерброд с чаем." +case let localScopeValue where localScopeValue.hasSuffix("перец"): + let vegetableComment = "Это острый \(localScopeValue)?" +default: // обязательный (чтобы преодолеть все возможные вхождения) + let vegetableComment = "Все вкусы хороши для супа." +} + + +// +// MARK: Функции +// + +// Функции являются типом первого класса, т.е. они могут быть вложены в функциях +// и могут передаваться между собой + +// Функция с документированным заголовком Swift (формат reStructedText) + +/** + Операция приветствия + + - Жирная метка в документировании + - Еще одна жирная метка в документации + + :param: name - это имя + :param: day - это день + :returns: Строка, содержащая значения name и day. +*/ +func greet(name: String, day: String) -> String { + return "Привет \(name), сегодня \(day)." +} +greet("Боб", "вторник") + +// как и выше, кроме обращения параметров функции +func greet2(#requiredName: String, externalParamName localParamName: String) -> String { + return "Привет \(requiredName), сегодня \(localParamName)" +} +greet2(requiredName:"Иван", externalParamName: "воскресенье") + +// Функция, которая возвращает множество элементов в кортеже +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// Пропускайте значения кортежей с помощью подчеркивания _ +let (_, price1, _) = pricesTuple // price1 == 3.69 +println(price1 == pricesTuple.1) // вывод: true +println("Цена газа: \(price)") + +// Переменное число аргументов +func setup(numbers: Int...) { + // это массив + let number = numbers[0] + let argCount = numbers.count +} + +// Передача и возврат функций +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + +// передача по ссылке +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +println(someIntB) // 7 + + +// +// MARK: Замыкания +// +var numbers = [1, 2, 6] + +// Функции - это частный случай замыканий ({}) + +// Пример замыкания. +// `->` отделяет аргументы и возвращаемый тип +// `in` отделяет заголовок замыкания от тела замыкания +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result +}) + +// Когда тип известен, как и выше, мы можем сделать так +numbers = numbers.map({ number in 3 * number }) +// Или даже так +//numbers = numbers.map({ $0 * 3 }) + +print(numbers) // [3, 6, 18] + +// Упрощение замыкания +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Суперсокращение, поскольку оператор < выполняет логический вывод типов + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] + +// +// MARK: Структуры +// + +// Структуры и классы имеют очень похожие характеристики +struct NamesTable { + let names = [String]() + + // Пользовательский индекс + subscript(index: Int) -> String { + return names[index] + } +} + +// У структур автогенерируемый (неявно) инициализатор +let namesTable = NamesTable(names: ["Me", "Them"]) +let name = namesTable[1] +println("Name is \(name)") // Name is Them + +// +// MARK: Классы +// + +// Классы, структуры и их члены имеют трехуровневый контроль доступа +// Уровни: internal (по умолчанию), public, private + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + +// Все методы и свойства класса являются открытыми (public). +// Если вам необходимо содержать только данные +// в структурированном объекте, вы должны использовать `struct` + +internal class Rect: Shape { + var sideLength: Int = 1 + + // Пользовательский сеттер и геттер + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` - неявная переменная, доступная в сеттере + sideLength = newValue / 4 + } + } + + // Ленивая загрузка свойства + // свойство subShape остается равным nil (неинициализированным), + // пока не вызовется геттер + lazy var subShape = Rect(sideLength: 4) + + // Если вам не нужны пользовательские геттеры и сеттеры, + // но все же хотите запустить код перед и после вызовов геттера или сеттера + // свойств, вы можете использовать `willSet` и `didSet` + var identifier: String = "defaultID" { + // аргумент у `willSet` будет именем переменной для нового значения + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(sideLength: Int) { + self.sideLength = sideLength + // всегда вызывается super.init последним, когда init с параметрами + super.init() + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} + +// Простой класс `Square` наследует `Rect` +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } +} + +var mySquare = Square() +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// преобразование объектов +let aShape = mySquare as Shape + +// сравнение объектов, но не как операция ==, которая проверяет эквивалентность +if mySquare === mySquare { + println("Ага, это mySquare") +} + + +// +// MARK: Перечисления +// + +// Перечисления могут быть определенного или своего типа. +// Они могут содержать методы подобно классам. + +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + +// Значения перечислений допускают жесткий синтаксис, нет необходимости +// указывать тип перечисления, когда переменная объявляется явно +var suitValue: Suit = .Hearts + +// Нецелочисленные перечисления требуют прямого указания значений +enum BookName: String { + case John = "John" + case Luke = "Luke" +} +println("Имя: \(BookName.John.rawValue)") + + +// +// MARK: Протоколы +// + +// `protocol` может потребовать, чтобы у соответствующих типов +// были определенные свойства экземпляра, методы экземпляра, тип методов, +// операторы и индексы. + +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +// Протоколы, объявленные с @objc, допускают необязательные функции, +// которые позволяют вам проверять на соответствие +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + if let allow = self.delegate?.canReshape?() { + // проверка делегата на выполнение метода + self.delegate?.reshaped?() + } + } +} + + +// +// MARK: Прочее +// + +// `extension`s: Добавляет расширенный функционал к существующему типу + +// Класс Square теперь "соответствует" протоколу `Printable` +extension Square: Printable { + var description: String { + return "Площадь: \(self.getArea()) - ID: \(self.identifier)" + } +} + +println("Объект Square: \(mySquare)") + +// Вы также можете расширить встроенные типы +extension Int { + var customProperty: String { + return "Это \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +println(7.customProperty) // "Это 7" +println(14.multiplyBy(3)) // 42 + +// Обобщения: Подобно языкам Java и C#. Используйте ключевое слово `where`, +// чтобы определить условия обобщений. + +func findIndex(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +println(foundAtIndex == 2) // вывод: true + +// Операторы: +// Пользовательские операторы могут начинаться с символов: +// / = - + * % < > ! & | ^ . ~ +// или +// Unicode- знаков математики, символов, стрелок, декорации и линий/кубов, +// нарисованных символов. +prefix operator !!! {} + +// Префиксный оператор, который утраивает длину стороны, когда используется +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// текущее значение +println(mySquare.sideLength) // 4 + +// Используя пользовательский оператор !!!, изменится длина стороны +// путем увеличения размера в 3 раза +!!!mySquare +println(mySquare.sideLength) // 12 +``` -- cgit v1.2.3 From 4e130fce1c202c31cd0c7b94706da2cab7747aa1 Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Mon, 19 Jan 2015 17:54:12 +0300 Subject: Update filename in the doc header. --- ru-ru/swift-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown index d78365a5..f788ad4c 100644 --- a/ru-ru/swift-ru.html.markdown +++ b/ru-ru/swift-ru.html.markdown @@ -3,7 +3,7 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] -filename: learnswift.swift +filename: learnswift-ru.swift translators: - ["Dmitry Bessonov", "https://github.com/TheDmitry"] lang: ru-ru -- cgit v1.2.3 From ea9acc1b346fffcc820a79b585a5251cc74e857f Mon Sep 17 00:00:00 2001 From: Johnathan Maudlin Date: Mon, 19 Jan 2015 22:10:37 -0500 Subject: Update contributors --- tmux.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 9eb96303..2ccb067a 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -2,7 +2,7 @@ category: tool tool: tmux contributors: - - ["wzsk", "https://github.com/wzsk"] + - ["mdln", "https://github.com/mdln"] filename: LearnTmux.txt --- -- cgit v1.2.3 From 209dc039ecc5ee280e5239afe5e2a77a851f795f Mon Sep 17 00:00:00 2001 From: searoso Date: Tue, 20 Jan 2015 21:34:18 +0300 Subject: Update r.html.markdown Added logical operators that were missing. --- r.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/r.html.markdown b/r.html.markdown index c555d748..13fa2654 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -229,6 +229,13 @@ FALSE != FALSE # FALSE FALSE != TRUE # TRUE # Missing data (NA) is logical, too class(NA) # "logical" +# Use for | and & for logic operations. +# OR +TRUE | FALSE # TRUE +# AND +TRUE & FALSE # FALSE +# You can test if x is TRUE +isTRUE(TRUE) # TRUE # Here we get a logical vector with many elements: c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE -- cgit v1.2.3 From 7a55b4a9b1badebd4b9342304c902fde049dd172 Mon Sep 17 00:00:00 2001 From: Keito Uchiyama Date: Tue, 20 Jan 2015 14:52:31 -0800 Subject: Explain Optional Chaining Without going into too much detail, mention optional chaining so it's not confusing that there is a question mark suffix (it's not currently mentioned anywhere on the page). --- swift.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index 2fbbe544..c6d2a8af 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -445,7 +445,10 @@ class MyShape: Rect { func grow() { sideLength += 2 - + + // Place a question mark after an optional property, method, or + // subscript to gracefully ignore a nil value and return nil + // instead of throwing a runtime error ("optional chaining"). if let allow = self.delegate?.canReshape?() { // test for delegate then for method self.delegate?.reshaped?() -- cgit v1.2.3 From 0d01004725423b29e196acf74a626bd3585934cc Mon Sep 17 00:00:00 2001 From: hirohope Date: Tue, 20 Jan 2015 23:16:35 -0300 Subject: haml-es --- es-es/haml-es.html.markdown | 159 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 es-es/haml-es.html.markdown diff --git a/es-es/haml-es.html.markdown b/es-es/haml-es.html.markdown new file mode 100644 index 00000000..be90b8f3 --- /dev/null +++ b/es-es/haml-es.html.markdown @@ -0,0 +1,159 @@ +--- +language: haml +filename: learnhaml-es.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] +translators: + - ["Camilo Garrido", "http://www.twitter.com/hirohope"] +lang: es-es +--- + +Haml es un lenguage de marcas principalmente usado con Ruby, que de forma simple y limpia describe el HTML de cualquier documento web sin el uso de código en linea. Es una alternativa popular respecto a usar el lenguage de plantilla de Rails (.erb) y te permite embeber código Ruby en tus anotaciones. + +Apunta a reducir la repetición en tus anotaciones cerrando los tags por ti, basándose en la estructura de identación de tu código. El resultado es una anotación bien estructurada, que no se repite, lógica y fácil de leer. + +También puedes usar Haml en un proyecto independiente de Ruby, instalando la gema Haml en tu máquina y usando la línea de comandos para convertirlo en html. + +$ haml archivo_entrada.haml archivo_salida.html + + +```haml +/ ------------------------------------------- +/ Identación +/ ------------------------------------------- + +/ + Por la importancia que la identación tiene en cómo tu código es traducido, + la identación debe ser consistente a través de todo el documento. Cualquier + diferencia en la identación lanzará un error. Es una práctica común usar dos + espacios, pero realmente depende de tí, mientras sea consistente. + + +/ ------------------------------------------- +/ Comentarios +/ ------------------------------------------- + +/ Así es como un comentario se ve en Haml. + +/ + Para escribir un comentario multilínea, identa tu código a comentar de tal forma + que sea envuelto por por una barra. + + +-# Este es un comentario silencioso, significa que no será traducido al código en absoluto + + +/ ------------------------------------------- +/ Elementos Html +/ ------------------------------------------- + +/ Para escribir tus tags, usa el signo de porcentaje seguido por el nombre del tag +%body + %header + %nav + +/ Nota que no hay tags de cierre. El código anterior se traduciría como + +
+ +
+ + +/ El tag div es un elemento por defecto, por lo que pueden ser escritos simplemente así +.foo + +/ Para añadir contenido a un tag, añade el texto directamente después de la declaración +%h1 Headline copy + +/ Para escribir contenido multilínea, anídalo. +%p + Esto es mucho contenido que podríamos dividirlo en dos + líneas separadas. + +/ + Puedes escapar html usando el signo ampersand y el signo igual ( &= ). + Esto convierte carácteres sensibles en html a su equivalente codificado en html. + Por ejemplo + +%p + &= "Sí & si" + +/ se traduciría en 'Sí & si' + +/ Puedes desescapar html usando un signo de exclamación e igual ( != ) +%p + != "Así es como se escribe un tag párrafo

" + +/ se traduciría como 'Así es como se escribe un tag párrafo

' + +/ Clases CSS puedes ser añadidas a tus tags, ya sea encadenando .nombres-de-clases al tag +%div.foo.bar + +/ o como parte de un hash Ruby +%div{:class => 'foo bar'} + +/ Atributos para cualquier tag pueden ser añadidos en el hash +%a{:href => '#', :class => 'bar', :title => 'Bar'} + +/ Para atributos booleanos asigna el valor verdadero 'true' +%input{:selected => true} + +/ Para escribir atributos de datos, usa la llave :dato con su valor como otro hash +%div{:data => {:attribute => 'foo'}} + + +/ ------------------------------------------- +/ Insertando Ruby +/ ------------------------------------------- + +/ + Para producir un valor Ruby como contenido de un tag, usa un signo igual + seguido por código Ruby + +%h1= libro.nombre + +%p + = libro.autor + = libro.editor + + +/ Para correr un poco de código Ruby sin traducirlo en html, usa un guión +- libros = ['libro 1', 'libro 2', 'libro 3'] + +/ Esto te permite hacer todo tipo de cosas asombrosas, como bloques de Ruby +- libros.shuffle.each_with_index do |libro, indice| + %h1= libro + + if libro do + %p Esto es un libro + +/ + Nuevamente, no hay necesidad de añadir los tags de cerrado en el código, ni siquiera para Ruby + La identación se encargará de ello por tí. + + +/ ------------------------------------------- +/ Ruby en linea / Interpolación de Ruby +/ ------------------------------------------- + +/ Incluye una variable Ruby en una línea de texto plano usando #{} +%p Tu juego con puntaje más alto es #{mejor_juego} + + +/ ------------------------------------------- +/ Filtros +/ ------------------------------------------- + +/ + Usa un signo dos puntos para definir filtros Haml, un ejemplo de filtro que + puedes usar es :javascript, el cual puede ser usado para escribir javascript en línea. + +:javascript + console.log('Este es un