diff options
-rw-r--r-- | c.html.markdown | 30 | ||||
-rw-r--r-- | go.html.markdown | 53 | ||||
-rw-r--r-- | json.html.markdown | 10 | ||||
-rw-r--r-- | python3.html.markdown | 5 | ||||
-rw-r--r-- | rust.html.markdown | 265 | ||||
-rw-r--r-- | whip.html.markdown | 4 |
6 files changed, 347 insertions, 20 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 <keyword> #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 <limits.h> // 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. diff --git a/go.html.markdown b/go.html.markdown index bb6b04eb..03227676 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 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 +// 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) { @@ -182,10 +192,35 @@ 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 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 +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.") @@ -304,17 +339,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 diff --git a/json.html.markdown b/json.html.markdown index 0e1a7d24..9041eaa2 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 (either double or single)", "numbers": 0, "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", "has bools?": true, @@ -42,6 +46,12 @@ 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" + , "another comment": "how nice" + }, "that was short": "And, you're done. You now know everything JSON has to offer." } 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 & diff --git a/rust.html.markdown b/rust.html.markdown new file mode 100644 index 00000000..0b9a5e58 --- /dev/null +++ b/rust.html.markdown @@ -0,0 +1,265 @@ +--- +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` - 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 + // 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<int> = 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 // + ////////////// + + // 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<T> { bar: T } + + // This is defined in the standard library as `Option` + enum Optional<T> { + SomeVal(T), + NoVal, + } + + // Methods // + + impl<T> Foo<T> { + // 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<T> { + fn frobnicate(self) -> Option<T>; + } + + impl<T> Frobnicate<T> for Foo<T> { + fn frobnicate(self) -> Option<T> { + 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<int> = 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). 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 |