Merge branch 'master' of github.com:adambard/learnxinyminutes-docs

This commit is contained in:
Leah Hanson 2013-07-01 18:10:18 -04:00
commit 759753cb5b
13 changed files with 1215 additions and 382 deletions

View File

@ -17,7 +17,6 @@ properly!
The most requested languages are:
* Scala
* Python
* Javascript
... but there are many more requests to do "every language", so don't let that stop you.

View File

@ -2,6 +2,7 @@
language: c
author: Adam Bard
author_url: http://adambard.com/
filename: learnc.c
---
Ah, C. Still the language of modern high-performance computing.
@ -12,6 +13,7 @@ memory management and C will take you as far as you need to go.
```c
// Single-line comments start with //
/*
Multi-line comments look like this.
*/
@ -19,6 +21,7 @@ Multi-line comments look like this.
// Import headers with #include
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// Declare function signatures in advance in a .h file, or at the top of
// your .c file.
@ -75,7 +78,7 @@ unsigned long long ux_long_long;
// 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("%d\n", sizeof(int)); // => 4 (on machines with 4-byte words)
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
@ -107,7 +110,7 @@ Char #17 is the NUL byte.
Chars #18, 19 and 20 have undefined values.
*/
printf("%d\n", a_string[16]); => 0
printf("%d\n", a_string[16]); // => 0
///////////////////////////////////////
// Operators

View File

@ -2,9 +2,10 @@
language: clojure
author: Adam Bard
author_url: http://adambard.com/
filename: learnclojure.clj
---
Clojure is a variant of LISP developed for the Java Virtual Machine. It has
Clojure is a Lisp family language developed for the Java Virtual Machine. It has
a much stronger emphasis on pure [functional programming](https://en.wikipedia.org/wiki/Functional_programming) than
Common Lisp, but includes several [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) utilities to handle
state as it comes up.
@ -23,9 +24,9 @@ and often automatically.
;
; The clojure reader assumes that the first thing is a
; function or macro to call, and the rest are arguments.
;
; Here's a function that sets the current namespace:
(ns test)
; The first call in a file should be ns, to set the namespace
(ns learnclojure)
; More basic examples:
@ -59,15 +60,18 @@ and often automatically.
(class false) ; Booleans are java.lang.Boolean
(class nil); The "null" value is called nil
; If you want to create a literal list of data, use ' to make a "symbol"
; 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))
; You can eval symbols.
; You can eval a quoted list
(eval '(+ 1 2)) ; => 3
; Collections & Sequences
;;;;;;;;;;;;;;;;;;;
; Lists are linked-list data structures, while Vectors are array-backed.
; Vectors and Lists are java classes too!
(class [1 2 3]); => clojure.lang.PersistentVector
(class '(1 2 3)); => clojure.lang.PersistentList
@ -76,16 +80,18 @@ and often automatically.
; it to stop the reader thinking it's a function.
; Also, (list 1 2 3) is the same as '(1 2 3)
; "Collections" are just groups of data
; Both lists and vectors are collections:
(coll? '(1 2 3)) ; => true
(coll? [1 2 3]) ; => true
; "Sequences" (seqs) are abstract descriptions of lists of data.
; Only lists are seqs.
(seq? '(1 2 3)) ; => true
(seq? [1 2 3]) ; => false
; Seqs are an interface for logical lists, which can be lazy.
; "Lazy" means that a seq can define an infinite series, like so:
; A seq need only provide an entry when it is accessed.
; So, seqs which can be lazy -- they can define infinite series:
(range 4) ; => (0 1 2 3)
(range) ; => (0 1 2 3 4 ...) (an infinite series)
(take 4 (range)) ; (0 1 2 3)
@ -94,8 +100,8 @@ and often automatically.
(cons 4 [1 2 3]) ; => (4 1 2 3)
(cons 4 '(1 2 3)) ; => (4 1 2 3)
; Use conj to add an item to the beginning of a list,
; or the end of a vector
; Conj will add an item to a collection in the most efficient way.
; For lists, they insert at the beginning. For vectors, they insert at the end.
(conj [1 2 3] 4) ; => [1 2 3 4]
(conj '(1 2 3) 4) ; => (4 1 2 3)
@ -165,20 +171,26 @@ x ; => 1
; => "Hello Finn, you passed 3 extra args"
; Hashmaps
; Maps
;;;;;;;;;;
; Hash maps and array maps share an interface. Hash maps have faster lookups
; but don't retain key order.
(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap
(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap
; Arraymaps will automatically become hashmaps through most operations
; if they get big enough, so you don't need to worry.
; Maps can use any hashable type as a key, but usually keywords are best
; Keywords are like strings with some efficiency bonuses
(class :a) ; => clojure.lang.Keyword
; Maps can use any type as a key, but usually keywords are best
(def stringmap (hash-map "a" 1, "b" 2, "c" 3))
(def stringmap {"a" 1, "b" 2, "c" 3})
stringmap ; => {"a" 1, "b" 2, "c" 3}
(def keymap (hash-map :a 1 :b 2 :c 3))
keymap ; => {:a 1, :c 3, :b 2} (order is not guaranteed)
(def keymap {:a 1, :b 2, :c 3})
keymap ; => {:a 1, :c 3, :b 2}
; By the way, commas are always treated as whitespace and do nothing.
@ -197,7 +209,8 @@ keymap ; => {:a 1, :c 3, :b 2} (order is not guaranteed)
(stringmap "d") ; => nil
; Use assoc to add new keys to hash-maps
(assoc keymap :d 4) ; => {:a 1, :b 2, :c 3, :d 4}
(def newkeymap (assoc keymap :d 4))
newkeymap ; => {:a 1, :b 2, :c 3, :d 4}
; But remember, clojure types are immutable!
keymap ; => {:a 1, :b 2, :c 3}
@ -268,6 +281,7 @@ keymap ; => {:a 1, :b 2, :c 3}
(require 'clojure.string)
; Use / to call functions from a module
; Here, the module is clojure.string and the function is blank?
(clojure.string/blank? "") ; => true
; You can give a module a shorter name on import
@ -311,4 +325,56 @@ keymap ; => {:a 1, :b 2, :c 3}
(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 is the mechanism clojure uses to handle
; persistent state. There are a few constructs in clojure that use this.
; An atom is the simplest. Pass it an initial value
(def my-atom (atom {}))
; Update an atom with swap!.
; swap! takes a function and calls it with the current value of the atom
; as the first argument, and any trailing arguments as the second
(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
my-atom ;=> Atom<#...> (Returns the Atom object)
@my-atom ; => {:a 1 :b 2}
; Here's a simple counter using an atom
(def counter (atom 0))
(defn inc-counter []
(swap! counter inc))
(inc-counter)
(inc-counter)
(inc-counter)
(inc-counter)
(inc-counter)
@counter ; => 5
; Other STM constructs are refs and agents.
; Refs: http://clojure.org/refs
; Agents: http://clojure.org/agents
```
### Further Reading
This is far from exhaustive, but hopefully it's enought o get you on your feet.
Clojure.org has lots of articles:
[http://clojure.org/](http://clojure.org/)
Clojuredocs.org has documentation with examples for most core functions:
[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core)
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:
[http://clojure-doc.org/](http://clojure-doc.org/)

View File

@ -1,7 +1,8 @@
---
language: Dart
language: dart
author: Joao Pedrosa
author_url: https://github.com/jpedrosa/
filename: learndart.dart
---
Dart is a newcomer into the realm of programming languages.

239
erlang.html.markdown Normal file
View File

@ -0,0 +1,239 @@
---
language: erlang
author: Giovanni Cappellotto
author_url: http://www.focustheweb.com/
filename: learnerlang.erl
---
```latex
% Percent sign start a one-line comment.
%% Two percent characters shall be used to comment functions.
%%% Three percent characters shall be used to comment modules.
% We use three types of punctuation in Erlang.
% Commas (`,`) separate arguments in function calls, data constructors, and
% patterns.
% Periods (`.`) (followed by whitespace) separate entire functions and
% expressions in the shell.
% Semicolons (`;`) separate clauses. We find clauses in several contexts: in kn
% function definitions and in `case`, `if`, `try..catch` and `receive`
% expressions.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 1. Variables and pattern matching.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Num = 42. % All variable names must start with an uppercase letter.
% Erlang has single assignment variables, if you try to assign a different value
% to the variable `Num`, youll get an error.
% In most languages, `=` denotes an assignment statement. In Erlang, however,
% `=` denotes a pattern matching operation. `Lhs = Rhs` really means this:
% evaluate the right side (Rhs), and then match the result against the pattern
% on the left side (Lhs).
Num = 7 * 6.
% Floating point number.
Pi = 3.14159.
% Atoms, are used to represent different non-numerical constant values. Atoms
% start with lowercase letters, followed by a sequence of alphanumeric
% characters or the underscore (`_`) or at (`@`) sign.
Hello = hello.
% Tuples are similar to structs in C.
Point = {point, 10, 45}.
% If we want to extract some values from a tuple, we use the pattern matching
% operator `=`.
{point, X, Y} = Point. % X = 10, Y = 45
% We can use `_` as a placeholder for variables that were not interested in.
% The symbol `_` is called an anonymous variable. Unlike regular variables,
% several occurrences of _ in the same pattern dont have to bind to the same
% value.
Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}.
{_, {_, {_, Who}, _}, _} = Person. % Who = joe
% We create a list by enclosing the list elements in square brackets and
% separating them with commas.
% The individual elements of a list can be of any type.
% The first element of a list the head of the list. If you imagine removing the
% head from the list, whats left is called the tail of the list.
ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}].
% If `T` is a list, then `[H|T]` is also a list, with head H and tail T.
% The vertical bar (`|`) separates the head of a list from its tail.
% `[]` is the empty list.
% We can extract elements from a list with a pattern matching operation. If we
% have the nonempty list `L`, then the expression `[X|Y] = L`, where `X` and `Y`
% are unbound variables, will extract the head of the list into `X` and the tail
% of the list into `Y`.
[FirstThing|OtherThingsToBuy] = ThingsToBuy.
% FirstThing = {apples, 10}
% OtherThingsToBuy = {pears, 6}, {milk, 3}
% There are no strings in Erlang. Strings are really just lists of integers.
% Strings are enclosed in double quotation marks (`"`).
Name = "Hello".
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 2. Sequential programming.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Modules are the basic unit of code in Erlang. All the functions we write are
% stored in modules. Modules are stored in files with `.erl` extensions.
% Modules must be compiled before the code can be run. A compiled module has the
% extension `.beam`.
-module(geometry).
-export([area/1]).
% The function area consists of two clauses. The clauses are separated by a
% semicolon, and the final clause is terminated by dot-whitespace.
% Each clause has a head and a body; the head consists of a function name
% followed by a pattern (in parentheses), and the body consists of a sequence of
% expressions, which are evaluated if the pattern in the head is successfully
% matched against the calling arguments. The patterns are matched in the order
% they appear in the function definition.
area({rectangle, Width, Ht}) -> Width * Ht;
area({circle, R}) -> 3.14159 * R * R.
% Compile the code in the file geometry.erl.
c(geometry). % {ok,geometry}
% We need to include the module name together with the function name in order to
% identify exactly which function we want to call.
geometry:area({rectangle, 10, 5}). % 50
geometry:area({circle, 1.4}). % 6.15752
% In Erlang, two functions with the same name and different arity in the same
% module represent entirely different functions.
-module(lib_misc).
-export([sum/1]).
sum(L) -> sum(L, 0).
sum([], N) -> N;
sum([H|T], N) -> sum(T, H+N).
% Funs are "anonymous" functions. They are called this because they have no
% name.
Double = fun(X) -> 2*X end.
Double(2). % 4
% Functions accept funs as their arguments and can return funs.
Mult = fun(Times) -> ( fun(X) -> X * Times end ) end.
Triple = Mult(3).
Triple(5). % 15
% List comprehensions are expressions that create lists without having to use
% funs, maps, or filters.
% The notation `[F(X) || X <- L]` means "the list of `F(X)` where `X` is taken
% from the list `L`."
L = [1,2,3,4,5].
[2*X || X <- L]. % [2,4,6,8,10]
% Guards are constructs that we can use to increase the power of pattern
% matching. Using guards, we can perform simple tests and comparisons on the
% variables in a pattern.
% You can use guards in the heads of function definitions where they are
% introduced by the `when` keyword, or you can use them at any place in the
% language where an expression is allowed.
max(X, Y) when X > Y -> X;
max(X, Y) -> Y.
% A guard is a series of guard expressions, separated by commas (`,`).
% The guard `GuardExpr1, GuardExpr2, ..., GuardExprN` is true if all the guard
% expressions `GuardExpr1, GuardExpr2, ...` evaluate to true.
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.
% A `guard sequence` is either a single guard or a series of guards, separated
%by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at least
% one of the guards `G1, G2, ...` evaluates to true.
is_pet(A) when is_dog(A); is_cat(A) -> true;
is_pet(A) -> false.
% Records provide a method for associating a name with a particular element in a
% tuple.
% Record definitions can be included in Erlang source code files or put in files
% with the extension `.hrl`, which are then included by Erlang source code
% files.
-record(todo, {
status = reminder, % Default value
who = joe,
text
}).
% We have to read the record definitions into the shell before we can define a
% record. We use the shell function `rr` (short for read records) to do this.
rr("records.hrl"). % [todo]
% Creating and updating records:
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` expressions.
% `filter` returns a list of all those elements `X` in `L` for which `P(X)` is
% true.
filter(P, [H|T]) ->
case P(H) of
true -> [H|filter(P, T)];
false -> filter(P, T)
end;
filter(P, []) -> [].
% `if` expressions.
max(X, Y) ->
if
X > Y -> X;
X < Y -> Y;
true -> nil;
end.
% Warning: at least one of the guards in the if expression must evaluate to true;
% otherwise, an exception will be raised.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 3. Exceptions.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Exceptions are raised by the system when internal errors are encountered or
% explicitly in code by calling `throw(Exception)`, `exit(Exception)` or
% `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 has two methods of catching an exception. One is to enclose the call to
% the function, which raised the exception within a `try...catch` expression.
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.
% The other is to enclose the call in a `catch` expression. When you catch an
% exception, it is converted into a tuple that describes the error.
catcher(N) -> catch generate_exception(N).
```
## References
* "Programming Erlang: Software for a Concurrent World" by Joe Armstrong
* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml)
* [Erlang/OTP Documentation](http://www.erlang.org/doc/)

1
file.erb Normal file
View File

@ -0,0 +1 @@
<%= rawcode %>

View File

@ -2,6 +2,7 @@
language: F#
author: Scott Wlaschin
author_url: http://fsharpforfunandprofit.com/
filename: learnfsharp.fs
---
F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more.

View File

@ -5,7 +5,7 @@ author_url: http://adit.io
---
Haskell was designed as a practical, purely functional programming language. It's famous for
it's monads and it's type system, but I keep coming back to it because of it's elegance. Haskell
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
@ -44,15 +44,21 @@ not False -- True
1 /= 1 -- False
1 < 10 -- True
-- In the above examples, `not` is a function that takes one value.
-- Haskell doesn't need parentheses for function calls...all the arguments
-- are just listed after the function. So the general pattern is:
-- func arg1 arg2 arg3...
-- See the section on functions for information on how to write your own.
-- Strings and characters
"This is a string."
'a' -- character
'You cant use single quotes for strings.' -- error!
-- Strings can be added too!
-- Strings can be concatenated
"Hello " ++ "world!" -- "Hello world!"
-- A string can be treated like a list of characters
-- A string is a list of characters
"This is a string" !! 0 -- 'T'
@ -68,14 +74,24 @@ not False -- True
-- You can also have infinite lists in Haskell!
[1..] -- a list of all the natural numbers
-- joining two lists
-- Infinite lists work because Haskell has "lazy evaluation". This means
-- that Haskell only evaluates things when it needs to. So you can ask for
-- the 1000th element of your list and Haskell will give it to you:
[1..] !! 999 -- 1000
-- And now Haskell has evaluated elements 1 - 1000 of this list...but the
-- 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
[1..5] ++ [6..10]
-- adding to the head of a list
0:[1..5] -- [0, 1, 2, 3, 4, 5]
-- indexing into a list
[0..] !! 5 -- 4
[0..] !! 5 -- 5
-- more list operations
head [1..5] -- 1
@ -104,6 +120,10 @@ snd ("haskell", 1) -- 1
-- 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
@ -132,19 +152,19 @@ fib x = fib (x - 1) + fib (x - 2)
-- Pattern matching on tuples:
foo (x, y) = (x + 1, y + 2)
-- Pattern matching on arrays. Here `x` is the first element
-- in the array, and `xs` is the rest of the array. We can write
-- 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:
map func [x] = [func x]
map func (x:xs) = func x:(map func xs)
myMap func [] = []
myMap func (x:xs) = func x:(myMap func xs)
-- Anonymous functions are created with a backslash followed by
-- all the arguments.
map (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7]
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
-- array as the initial value for the accumulator.
-- list as the initial value for the accumulator.
foldl1 (\acc x -> acc + x) [1..5] -- 15
----------------------------------------------------
@ -179,10 +199,10 @@ foo 5 -- 75
-- of parentheses:
-- before
(even (double 7)) -- true
(even (fib 7)) -- true
-- after
even . double $ 7 -- true
even . fib $ 7 -- true
----------------------------------------------------
-- 5. Type signatures
@ -197,13 +217,17 @@ True :: Bool
-- Functions have types too.
-- `not` takes a boolean and returns a boolean:
not :: Bool -> Bool
-- not :: Bool -> Bool
-- Here's a function that takes two arguments:
add :: Integer -> Integer -> Integer
-- 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
-- 6. Control Flow and If Statements
----------------------------------------------------
-- if statements
@ -259,7 +283,42 @@ Just "hello"
Just 1
----------------------------------------------------
-- 8. The Haskell REPL
-- 8. Haskell IO
----------------------------------------------------
-- While IO can't be explained fully without explaining monads,
-- it is not hard to explain enough to get going.
-- An `IO a` value is an IO action: you can chain them with do blocks
action :: IO String
action = do
putStrLn "This is a line. Duh"
input <- getLine -- this gets a line and gives it the name "input"
input2 <- getLine
return (input1 ++ "\n" ++ input2) -- This is the result of the whole action
-- This didn't actually do anything. When a haskell program is executed
-- an IO action called "main" is read and interpreted.
main = do
putStrLn "Our first program. How exciting!"
result <- action -- our defined action is just like the default ones
putStrLn result
putStrLn "This was all, folks!"
-- Haskell does IO through a monad because this allows it to be a purely
-- functional language. Our `action` function had a type signature of `IO String`.
-- In general 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`.

354
java.html.markdown Normal file
View File

@ -0,0 +1,354 @@
---
language: java
author: Jake Prather
author_url: http://github.com/JakeHP
filename: LearnJava.java
---
Java is a general-purpose, concurrent, class-based, object-oriented computer programming language.
[Read more here.](http://docs.oracle.com/javase/tutorial/java/index.html)
```java
// Single-line comments start with //
/*
Multi-line comments look like this.
*/
// Import ArrayList class inside of the java.util package
import java.util.ArrayList;
// Import all classes inside of java.lang package
import java.security.*;
// Inside of the LearnJava class, is your program's
// starting point. The main method.
public class LearnJava
{
//main method
public static void main (String[] args)
{
System.out.println("->Printing");
// Printing, and forcing a new line on next print, use println()
System.out.println("Hello World!");
System.out.println("Integer: "+10+" Double: "+3.14+ " Boolean: "+true);
// Printing, without forcing a new line on next print, use print()
System.out.print("Hello World - ");
System.out.print("Integer: "+10+" Double: "+3.14+ " Boolean: "+true);
///////////////////////////////////////
// Types
///////////////////////////////////////
System.out.println("\n\n->Types");
// 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;
// (Java has no unsigned types)
// Float - Single-precision 32-bit IEEE 754 Floating Point
float fooFloat = 234.5f;
// 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';
// Make a variable a constant
final int HOURS_I_WORK_PER_WEEK = 9001;
// Strings
String fooString = "My String Is Here!";
// \n is an escaped character that starts a new line
String barString = "Printing on a new line?\nNo Problem!";
System.out.println(fooString);
System.out.println(barString);
// Arrays
//The array size must be decided upon declaration
//The format for declaring an array is follows:
//<datatype> [] <var name> = new <datatype>[<array size>];
int [] intArray = new int[10];
String [] stringArray = new String[1];
boolean [] booleanArray = new boolean[100];
// Another way to declare & initialize an array
int [] y = {9000, 1000, 1337};
// Indexing an array - Accessing an element
System.out.println("intArray @ 0: "+intArray[0]);
// Arrays are mutable; it's just memory!
intArray[1] = 1;
System.out.println("intArray @ 1: "+intArray[1]); // => 1
intArray[1] = 2;
System.out.println("intArray @ 1: "+intArray[1]); // => 2
// Others to check out
// ArrayLists - Like arrays except more functionality is offered,
// and the size is mutable
// LinkedLists
// Maps
// HashMaps
///////////////////////////////////////
// Operators
///////////////////////////////////////
System.out.println("\n->Operators");
int i1 = 1, i2 = 2; // Shorthand for multiple declarations
// Arithmetic is straightforward
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, but truncated towards 0)
// Modulo
System.out.println("11%3 = "+(11 % 3)); // => 2
// Comparison operators
System.out.println("3 == 2? "+(3 == 2)); // => 0 (false)
System.out.println("3 != 2? "+(3 != 2)); // => 1 (true)
System.out.println("3 > 2? "+(3 > 2)); // => 1
System.out.println("3 < 2? "+(3 < 2)); // => 0
System.out.println("2 <= 2? "+(2 <= 2)); // => 1
System.out.println("2 >= 2? "+(2 >= 2)); // => 1
// 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;
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
///////////////////////////////////////
// Control Structures
///////////////////////////////////////
System.out.println("\n->Control Structures");
if (false){
System.out.println("I never run");
}else if (false) {
System.out.println("I am also never run");
} else {
System.out.println("I print");
}
// While loop
int fooWhile = 0;
while(fooWhile < 100)
{
//System.out.println(fooWhile);
//Increment the counter
//Iterated 99 times, fooWhile 0->99
fooWhile++;
}
System.out.println("fooWhile Value: "+fooWhile);
// Do While Loop
int fooDoWhile = 0;
do
{
//System.out.println(fooDoWhile);
//Increment the counter
//Iterated 99 times, fooDoWhile 0->99
fooDoWhile++;
}while(fooDoWhile < 100);
System.out.println("fooDoWhile Value: "+fooDoWhile);
// For Loop
int fooFor;
//for loop structure => for(<start_statement>;<conditional>;<step>)
for(fooFor=0;fooFor<100;fooFor++){
//System.out.println(fooFor);
//Iterated 99 times, fooFor 0->99
}
System.out.println("fooFor Value: "+fooFor);
// Switch Case
int month = 8;
String monthString;
switch (month){
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println("Switch Case Result: "+monthString);
///////////////////////////////////////
// Converting Data Types And Typcasting
///////////////////////////////////////
// Converting data
// Convert String To Integer
Integer.parseInt("123");//returns an integer version of "123"
// Convert Integer To String
Integer.toString(123);//returns a string version of 123
// For other conversions check out the following classes:
// Double
// Long
// String
// Typecasting
// You can also cast java objects, there's a lot of details and
// deals with some more intermediate concepts.
// Feel free to check it out here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
///////////////////////////////////////
// Classes And Functions
///////////////////////////////////////
// Read about the class, and function syntax before
// reading this.
System.out.println("\n->Classes & Functions");
// Call bicycle's constructor
Bicycle trek = new Bicycle();
// Manipulate your object
trek.speedUp(3);
trek.setCadence(100);
System.out.println("trek info: "+trek.toString());
// Classes Syntax:
// <public/private/protected> class <class name>{
// //data fields, constructors, functions all inside
// }
// Function Syntax:
// <public/private/protected> <return type> <function name>(<args>)
// Here is a quick rundown on access level modifiers (public, private, etc.)
// http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
// This bracket ends the main method
}
// The static field is only required because this class
// is nested inside of the learnjava.java class.
public static class Bicycle {
// Bicycle's Fields/Variables
public int cadence;
public int gear;
public int speed;
// Constructors are a way of creating classes
// This is a default constructor
public Bicycle(){
gear = 1;
cadence = 50;
speed = 5;
}
// This is a specified constructor (it contains arguments)
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has
// four functions/methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
public String toString(){
return "gear: "+Integer.toString(gear)+
" cadence: "+Integer.toString(cadence)+
" speed: "+Integer.toString(speed);
}
// bracket to close nested Bicycle class
}
// bracket to close learnjava.java
}
```
## Further Reading
Other Topics To Research:
* [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)
* The links provided are just to get an understanding of the topic, feel free to google and find specific examples

View File

@ -2,6 +2,7 @@
language: lua
author: Tyler Neylon
author_url: http://tylerneylon.com/
filename: learnlua.lua
---
```lua

View File

@ -2,19 +2,16 @@
language: php
author: Malcolm Fell
author_url: http://emarref.net/
filename: learnphp.php
---
This document describes PHP 5+.
## [Basic Syntax](http://www.php.net/manual/en/language.basic-syntax.php)
All statements must end with a semi-colon; All PHP code must be between <?php and ?> tags. PHP can also be
configured to respect the [short open tags](http://www.php.net/manual/en/ini.core.php#ini.short-open-tag) <? and ?>.
## [Comments](http://www.php.net/manual/en/language.basic-syntax.comments.php)
```php
<?php
<?php // PHP code must be enclosed with <?php ? > tags
// If your php file only contains PHP code, it is best practise
// to omit the php closing tag.
// Two forward slashes start a one-line comment.
@ -24,27 +21,36 @@ configured to respect the [short open tags](http://www.php.net/manual/en/ini.cor
Surrounding text in slash-asterisk and asterisk-slash
makes it a multi-line comment.
*/
```
## [Types](http://www.php.net/manual/en/language.types.php)
// Use "echo" or "print" to print output
print('Hello '); // Prints "Hello " with no line break
Types are [weakly typed](http://en.wikipedia.org/wiki/Strong_and_weak_typing) and begin with the $ symbol.
A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
// () are optional for print and echo
echo "World\n"; // Prints "World" with a line break
// (all statements must end with a semicolon)
### Scalars
```php
// Anything outside <?php tags is echoed automatically
?>Hello World Again!
<?php
/************************************
* Types & Variables
*/
// Variables begin with the $ symbol.
// A valid variable name starts with a letter or underscore,
// followed by any number of letters, numbers, or underscores.
// Boolean values are case-insensitive
$boolean = true; // or TRUE or True
$boolean = true; // or TRUE or True
$boolean = false; // or FALSE or False
// Integers
$integer = 1234; // decimal number
$integer = -123; // a negative number
$integer = 0123; // octal number (equivalent to 83 decimal)
$integer = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$int1 = 19; // => 19
$int2 = -19; // => -19
$int3 = 019; // => 15 (a leading 0 denotes an octal number)
$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal)
// Floats (aka doubles)
$float = 1.234;
@ -52,28 +58,30 @@ $float = 1.2e3;
$float = 7E-10;
// Arithmetic
$sum = $number + $float;
$difference = $number - $float;
$product = $number * $float;
$quotient = $number / $float;
$sum = 1 + 1; // 2
$difference = 2 - 1; // 1
$product = 2 * 2; // 4
$quotient = 2 / 1; // 2
// Shorthand arithmetic
$number += 1; // Add 1 to $number
$number++; // Add 1 to $number after it is used
++$number; // Add 1 to $number before it is used.
$number /= $float // Divide and assign the quotient to $number
$number = 0;
$number += 1; // Increment $number by 1
echo $number++; // Prints 1 (increments after evaluation)
echo ++$number; // Prints 3 (increments before evalutation)
$number /= $float; // Divide and assign the quotient to $number
// Strings should be enclosed in single quotes;
$sgl_quotes = '$String'; // => '$String'
// Avoid using double quotes except to embed other variables
$dbl_quotes = "This is a $sgl_quotes." // => 'This is a $String'
$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
// Escape special characters with backslash
$escaped = "This contains a \t tab character.";
// Special characters are only escaped in double quotes
$escaped = "This contains a \t tab character.";
$unescaped = 'This just contains a slash and a t: \t';
// Enclose a variable in curly braces if needed
$money = "I have $${integer} in the bank."
$money = "I have $${number} in the bank.";
// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners
$nowdoc = <<<'END'
@ -81,35 +89,40 @@ Multi line
string
END;
// Heredocs will do string interpolation
$heredoc = <<<END
Multi line
$sgl_quotes
END; // Nowdoc syntax is available in PHP 5.3.0
END;
// Manipulation
$concatenated = $sgl_quotes . $dbl_quotes;
```
// String concatenation is done with .
echo 'This string ' . 'is concatenated';
### Compound
```php
<?php
/********************************
* Arrays
*/
// Arrays
$array = array(1, 2, 3);
$array = [1, 2, 3]; // As of PHP 5.4
$string = ["One", "Two", "Three"];
$string[0]; // Holds the value "One";
// All arrays in PHP are associative arrays (hashmaps),
// Associative arrays, known as hashmaps in some languages.
$associative = ["One" => 1, "Two" => 2, "Three" => 3];
$associative["One"]; // Holds the value 1
```
## Output
// Works with all PHP versions
$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
```php
<?php
// PHP 5.4 introduced a new syntax
$associative = ['One' => 1, 'Two' => 2, 'Three' => 3];
echo $associative['One']; // prints 1
// List literals implicitly assign integer keys
$array = ['One', 'Two', 'Three'];
echo $array[0]; // => "One"
/********************************
* Output
*/
echo('Hello World!');
// Prints Hello World! to stdout.
@ -121,133 +134,129 @@ print('Hello World!'); // The same as echo
echo 'Hello World!';
print 'Hello World!'; // So is print
echo 100;
echo $variable;
echo function_result();
$paragraph = 'paragraph';
echo 100; // Echo scalar variables directly
echo $paragraph; // or variables
// If short open tags are configured, or your PHP version is
// 5.4.0 or greater, you can use the short echo syntax
<?= $variable ?>
```
## [Operators](http://www.php.net/manual/en/language.operators.php)
### Assignment
```php
?>
<p><?= $paragraph ?></p>
<?php
$x = 1;
$y = 2;
$x = $y; // A now contains the same value sa $y
$x = &$y;
// $x now contains a reference to $y. Changing the value of
// $x will change the value of $y also, and vice-versa.
```
$x = $y; // $x now contains the same value as $y
$z = &$y;
// $z now contains a reference to $y. Changing the value of
// $z will change the value of $y also, and vice-versa.
// $x will remain unchanged as the original value of $y
### Comparison
echo $x; // => 2
echo $z; // => 2
$y = 0;
echo $x; // => 2
echo $z; // => 0
```php
<?php
/********************************
* Logic
*/
$a = 0;
$b = '0';
$c = '1';
$d = '1';
// assert throws a warning if its argument is not true
// These comparisons will always be true, even if the types aren't the same.
$a == $b // TRUE if $a is equal to $b after type juggling.
$a != $b // TRUE if $a is not equal to $b after type juggling.
$a <> $b // TRUE if $a is not equal to $b after type juggling.
$a < $b // TRUE if $a is strictly less than $b.
$a > $b // TRUE if $a is strictly greater than $b.
$a <= $b // TRUE if $a is less than or equal to $b.
$a >= $b // TRUE if $a is greater than or equal to $b.
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);
// The following will only be true if the values match and are the same type.
$a === $b // TRUE if $a is equal to $b, and they are of the same type.
$a !== $b // TRUE if $a is not equal to $b, or they are not of the same type.
1 == '1' // TRUE
1 === '1' // FALSE
```
assert($c === $d);
assert($a !== $d);
assert(1 == '1');
assert(1 !== '1');
## [Type Juggling](http://www.php.net/manual/en/language.types.type-juggling.php)
Variables can be converted between types, depending on their usage.
```php
<?php
// Variables can be converted between types, depending on their usage.
$integer = 1;
echo $integer + $integer; // Outputs 2;
echo $integer + $integer; // => 2
$string = '1';
echo $string + $string;
// Also outputs 2 because the + operator converts the strings to integers
echo $string + $string; // => 2 (strings are coerced to integers)
$string = 'one';
echo $string + $string;
echo $string + $string; // => 0
// Outputs 0 because the + operator cannot cast the string 'one' to a number
```
Type casting can be used to treat a variable as another type temporarily by using cast operators in parentheses.
// Type casting can be used to treat a variable as another type
```php
$boolean = (boolean) $integer; // $boolean is true
$boolean = (boolean) 1; // => true
$zero = 0;
$boolean = (boolean) $zero; // $boolean is false
$boolean = (boolean) $zero; // => false
// There are also dedicated functions for casting most types
$integer = 5;
$string = strval($integer);
// There are also dedicated functions for casting most types
$var = null; // Null value
```
## [Control Structures](http://www.php.net/manual/en/language.control-structures.php)
### If Statements
/********************************
* Control Structures
*/
```php
<?php
if (/* test */) {
// Do something
if (true) {
print 'I get printed';
}
if (/* test */) {
// Do something
if (false) {
print 'I don\'t';
} else {
// Do something else
print 'I get printed';
}
if (/* test */) {
// Do something
} elseif(/* test2 */) {
// Do something else, only if test2
if (false) {
print 'Does not get printed';
} elseif(true) {
print 'Does';
}
if (/* test */) {
// Do something
} elseif(/* test2 */) {
// Do something else, only if test2
$x = 0;
if ($x === '0') {
print 'Does not print';
} elseif($x == '1') {
print 'Does not print';
} else {
// Do something default
print 'Does print';
}
// This alternative syntax is useful for templates:
?>
<?php if (/* test */): ?>
<?php if ($x): ?>
This is displayed if the test is truthy.
<?php else: ?>
This is displayed otherwise.
<?php endif; ?>
```
### Switch statements
```php
<?php
switch ($variable) {
case 'one':
// Do something if $variable == 'one'
break;
// Use switch to save some logic.
switch ($x) {
case '0':
print 'Switch does type coercion';
break; // You must include a break, or you will fall through
// to cases 'two' and 'three'
case 'two':
case 'three':
// Do something if $variable is either 'two' or 'three'
@ -256,199 +265,231 @@ switch ($variable) {
// Do something by default
}
```
### Loops
```php
<?php
// While, do...while and for loops are probably familiar
$i = 0;
while ($i < 5) {
echo $i++;
}
}; // Prints "01234"
echo "\n";
$i = 0;
do {
echo $i++;
} while ($i < 5);
} while ($i < 5); // Prints "01234"
echo "\n";
for ($x = 0; $x < 10; $x++) {
echo $x; // Will echo 0 - 9
}
echo $x;
} // Prints "0123456789"
$wheels = ["bicycle" => 2, "car" => 4];
echo "\n";
$wheels = ['bicycle' => 2, 'car' => 4];
// Foreach loops can iterate over arrays
foreach ($wheels as $wheel_count) {
echo $wheel_count;
} // Prints "24"
echo "\n";
// You can iterate over the keys as well as the values
foreach ($wheels as $vehicle => $wheel_count) {
echo "A $vehicle has $wheel_count wheels";
}
// This loop will stop after outputting 2
echo "\n";
$i = 0;
while ($i < 5) {
if ($i == 3) {
break; // Exit out of the while loop and continue.
if ($i === 3) {
break; // Exit out of the while loop
}
echo $i++;
}
} // Prints "012"
// This loop will output everything except 3
$i = 0;
while ($i < 5) {
if ($i == 3) {
for ($i = 0; $i < 5; $i++) {
if ($i === 3) {
continue; // Skip this iteration of the loop
}
echo $i++;
}
```
echo $i;
} // Prints "0124"
## Functions
Functions are created with the ```function``` keyword.
/********************************
* Functions
*/
```php
<?php
function my_function($my_arg) {
$my_variable = 1;
// Define a function with "function":
function my_function () {
return 'Hello';
}
// $my_variable and $my_arg cannot be accessed outside of the function
```
echo my_function(); // => "Hello"
Functions may be invoked by name.
// A valid function name starts with a letter or underscore, followed by any
// number of letters, numbers, or underscores.
```php
<?php
my_function_name();
$variable = get_something(); // A function may return a value
```
A valid function name starts with a letter or underscore, followed by any
number of letters, numbers, or underscores. There are three ways to declare functions.
### [User-defined](http://www.php.net/manual/en/functions.user-defined.php)
```php
<?php
function my_function_name ($arg_1, $arg_2) {
// $arg_1 and $arg_2 are required
function add ($x, $y = 1) { // $y is optional and defaults to 1
$result = $x + $y;
return $result;
}
// Functions may be nested to limit scope
function outer_function ($arg_1 = null) { // $arg_1 is optional
function inner_function($arg_2 = 'two') { // $arg_2 will default to 'two'
}
}
echo add(4); // => 5
echo add(4, 2); // => 6
// inner_function() does not exist and cannot be called until
// outer_function() is called
```
// $result is not accessible outside the function
// print $result; // Gives a warning.
This enables [currying](http://en.wikipedia.org/wiki/Currying) in PHP.
// Since PHP 5.3 you can declare anonymous functions;
$inc = function ($x) {
return $x + 1;
};
echo $inc(2); // => 3
```php
function foo ($x, $y, $z) {
echo "$x - $y - $z";
}
// Functions can return functions
function bar ($x, $y) {
// Use 'use' to bring in outside variables
return function ($z) use ($x, $y) {
foo($x, $y, $z);
};
}
$bar = bar('A', 'B');
$bar('C');
$bar('C'); // Prints "A - B - C"
// You can call named functions using strings
$function_name = 'add';
echo $function_name(1, 2); // => 3
// Useful for programatically determining which function to run.
// Or, use call_user_func(callable $callback [, $parameter [, ... ]]);
/********************************
* Includes
*/
/*
```
### [Variable](http://www.php.net/manual/en/functions.variable-functions.php)
```php
<?php
// PHP within included files must also begin with a PHP open tag.
$function_name = 'my_function_name';
include 'my-file.php';
// The code in my-file.php is now available in the current scope.
// If the file cannot be included (e.g. file not found), a warning is emitted.
$function_name(); // will execute the my_function_name() function
```
include_once 'my-file.php';
// If the code in my-file.php has been included elsewhere, it will
// not be included again. This prevents multiple class declaration errors
### [Anonymous](http://www.php.net/manual/en/functions.anonymous.php)
require 'my-file.php';
require_once 'my-file.php';
// Same as include(), except require() will cause a fatal error if the
// file cannot be included.
Similar to variable functions, functions may be anonymous.
```php
// Contents of my-include.php:
<?php
function my_function($callback) {
$callback('My argument');
}
return 'Anything you like.';
// End file
my_function(function ($my_argument) {
// do something
});
// Includes and requires may also return a value.
$value = include 'my-include.php';
// Closure style
$my_function = function() {
// Do something
};
// Files are included based on the file path given or, if none is given,
// the include_path configuration directive. If the file isn't found in
// the include_path, include will finally check in the calling script's
// own directory and the current working directory before failing.
/* */
$my_function();
```
/********************************
* Classes
*/
## [Classes](http://www.php.net/manual/en/language.oop5.php)
// Classes are defined with the class keyword
Classes are defined with the ```class``` keyword.
class MyClass
{
const MY_CONST = 'value'; // A constant
```php
<?php
static $staticVar = 'static';
class MyClass {
const MY_CONST = 'value';
static $staticVar = 'something';
public $property = 'value'; // Properties must declare their visibility
}
// Properties must declare their visibility
public $property = 'public';
public $instanceProp;
protected $prot = 'protected'; // Accessible from the class and subclasses
private $priv = 'private'; // Accessible within the class only
echo MyClass::MY_CONST; // Outputs "value";
final class YouCannotExtendMe {
}
```
Classes are instantiated with the ```new``` keyword. Functions are referred to as
methods if they belong to a class.
```php
<?php
class MyClass {
function myFunction() {
// Create a constructor with __construct
public function __construct($instanceProp) {
// Access instance variables with $this
$this->instanceProp = $instanceProp;
}
final function youCannotOverrideMe() {
// Methods are declared as functions inside a class
public function myMethod()
{
print 'MyClass';
}
public static function myStaticMethod() {
final function youCannotOverrideMe()
{
}
public static function myStaticMethod()
{
print 'I am static';
}
}
$cls = new MyClass(); // The parentheses are optional.
echo MyClass::MY_CONST; // Outputs 'value';
echo MyClass::$staticVar; // Outputs 'static';
MyClass::myStaticMethod(); // Outputs 'I am static';
echo MyClass::$staticVar; // Access to static vars
// Instantiate classes using new
$my_class = new MyClass('An instance property');
// The parentheses are optional if not passing in an argument.
echo $cls->property; // Access to properties
// Access class members using ->
echo $my_class->property; // => "public"
echo $my_class->instanceProp; // => "An instance property"
$my_class->myMethod(); // => "MyClass"
MyClass::myStaticMethod(); // myStaticMethod cannot be run on $cls
```
PHP offers some [magic methods](http://www.php.net/manual/en/language.oop5.magic.php) for classes.
// Extend classes using "extends"
class MyOtherClass extends MyClass
{
function printProtectedProperty()
{
echo $this->prot;
}
```php
<?php
// Override a method
function myMethod()
{
parent::myMethod();
print ' > MyOtherClass';
}
}
class MyClass {
$my_other_class = new MyOtherClass('Instance prop');
$my_other_class->printProtectedProperty(); // => Prints "protected"
$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass"
final class YouCannotExtendMe
{
}
// You can use "magic methods" to create getters and setters
class MyMapClass
{
private $property;
public function __get($key)
@ -462,16 +503,13 @@ class MyClass {
}
}
$x = new MyClass();
$x = new MyMapClass();
echo $x->property; // Will use the __get() method
$x->property = 'Something'; // Will use the __set() method
```
Classes can be abstract (using the ```abstract``` keyword), extend other classes (using the ```extends``` keyword) and
implement interfaces (using the ```implements``` keyword). An interface is declared with the ```interface``` keyword.
```php
<?php
// Classes can be abstract (using the abstract keyword) or
// implement interfaces (using the implements keyword).
// An interface is declared with the interface keyword.
interface InterfaceOne
{
@ -480,90 +518,112 @@ interface InterfaceOne
interface InterfaceTwo
{
public function doSomething();
public function doSomethingElse();
}
abstract class MyAbstractClass implements InterfaceOne
{
public $x = 'doSomething';
}
class MyClass extends MyAbstractClass implements InterfaceTwo
class MyConcreteClass extends MyAbstractClass implements InterfaceTwo
{
public function doSomething()
{
echo $x;
}
public function doSomethingElse()
{
echo 'doSomethingElse';
}
}
// Classes can implement more than one interface
class SomeOtherClass implements InterfaceOne, InterfaceTwo
{
public function doSomething()
{
echo 'doSomething';
}
public function doSomethingElse()
{
echo 'doSomethingElse';
}
}
/********************************
* Traits
*/
// Traits are available from PHP 5.4.0 and are declared using "trait"
trait MyTrait
{
public function myTraitMethod()
{
print 'I have MyTrait';
}
}
class MyTraitfulClass
{
use MyTrait;
}
$cls = new MyTraitfulClass();
$cls->myTraitMethod(); // Prints "I have MyTrait"
/********************************
* Namespaces
*/
// This section is separate, because a namespace declaration
// must be the first statement in a file. Let's pretend that is not the case
/*
```
### [Namespaces](http://www.php.net/manual/en/language.namespaces.rationale.php)
By default, classes exist in the global namespace, and can be explicitly called with a backslash.
```php
<?php
// By default, classes exist in the global namespace, and can
// be explicitly called with a backslash.
$cls = new \MyClass();
```
```php
<?php
// Set the namespace for a file
namespace My\Namespace;
class MyClass
{
}
// (from another file)
$cls = new My\Namespace\MyClass;
```
Or from within another namespace.
```php
<?php
//Or from within another namespace.
namespace My\Other\Namespace;
use My\Namespace\MyClass;
$cls = new MyClass();
```
Or you can alias the namespace;
```php
<?php
// Or you can alias the namespace;
namespace My\Other\Namespace;
use My\Namespace as SomeOtherNamespace;
$cls = new SomeOtherNamespace\MyClass();
```
### [Traits](http://www.php.net/manual/en/language.oop5.traits.php)
*/
Traits are available since PHP 5.4.0 and are declared using the ```trait``` keyword.
```php
<?php
trait MyTrait {
public function myTraitMethod()
{
// Do something
}
}
class MyClass
{
use MyTrait;
}
$cls = new MyClass();
$cls->myTraitMethod();
```
## More Information
@ -573,3 +633,5 @@ Visit the [official PHP documentation](http://www.php.net/manual/) for reference
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/).
For common standards, visit the PHP Framework Interoperability Group's [PSR standards](https://github.com/php-fig/fig-standards).

View File

@ -2,6 +2,7 @@
language: python
author: Louie Dinh
author_url: http://ldinh.ca
filename: learnpython.py
---
Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular
@ -15,7 +16,7 @@ to Python 2.x. Look for another tour of Python 3 soon!
```python
# Single line comments start with a hash.
""" Multiline strings can we written
""" Multiline strings can be written
using three "'s, and are often used
as comments
"""
@ -86,10 +87,26 @@ not False #=> True
# A newer way to format strings is the format method.
# This method is the preferred way
"{0} can be {1}".format("strings", "formatted")
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
# None is an object
None #=> None
# Don't use the equality `==` symbol to compare objects to None
# Use `is` instead
"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
# very useful when dealing with objects.
# None, 0, and empty strings/lists all evaluate to False.
# All other values are True
0 == False #=> True
"" == False #=> True
####################################################
## 2. Variables and Collections
@ -103,16 +120,12 @@ print "I'm Python. Nice to meet you!"
some_var = 5 # Convention is to use lower_case_with_underscores
some_var #=> 5
# Accessing a previously unassigned variable is an exception
try:
some_other_var
except NameError:
print "Raises a name error"
# 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
some_var = a if a > b else b
# If a is greater than b, then a is assigned to some_var.
# Otherwise b is assigned to some_var.
"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
# Lists store sequences
li = []
@ -135,10 +148,7 @@ li[0] #=> 1
li[-1] #=> 3
# Looking out of bounds is an IndexError
try:
li[4] # Raises an IndexError
except IndexError:
print "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.)
@ -163,13 +173,11 @@ li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
# Examine the length with len
len(li) #=> 6
# Tuples are like lists but are immutable.
tup = (1, 2, 3)
tup[0] #=> 1
try:
tup[0] = 3 # Raises a TypeError
except TypeError:
print "Tuples cannot be mutated."
tup[0] = 3 # Raises a TypeError
# You can do all those list thingies on tuples too
len(tup) #=> 3
@ -177,7 +185,7 @@ tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
tup[:2] #=> (1, 2)
2 in tup #=> True
# You can unpack tuples into variables
# 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
@ -206,13 +214,12 @@ filled_dict.values() #=> [3, 2, 1]
"one" in filled_dict #=> True
1 in filled_dict #=> False
# Trying to look up a non-existing key will raise a KeyError
filled_dict["four"] #=> KeyError
# 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
@ -234,7 +241,7 @@ filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
# Do set intersection with &
other_set = set{3, 4, 5, 6}
other_set = {3, 4, 5, 6}
filled_set & other_set #=> {3, 4, 5}
# Do set union with |
@ -255,7 +262,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
# Let's just make a variable
some_var = 5
# Here is an if statement. INDENTATION IS SIGNIFICANT IN PYTHON!
# 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."
@ -275,6 +282,18 @@ 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
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.
@ -298,12 +317,6 @@ try:
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery here.
# Works for Python 2.7 and down:
try:
raise IndexError("This is an index error")
except IndexError, e: # No "as", comma instead
pass
####################################################
## 4. Functions
@ -341,16 +354,17 @@ def all_the_args(*args, **kwargs):
print kwargs
"""
all_the_args(1, 2, a=3, b=4) prints:
[1, 2]
(1, 2)
{"a": 3, "b": 4}
"""
# You can also use * and ** when calling a function
# When calling functions, you can do the opposite of varargs/kwargs!
# Use * to expand tuples and use ** to expand kwargs.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
foo(*args) # equivalent to foo(1, 2, 3, 4)
foo(**kwargs) # equivalent to foo(a=3, b=4)
foo(*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):
@ -420,9 +434,42 @@ 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.
```
## Further Reading
Still up for more? Try [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
Still up for more? Try:
* [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/)

View File

@ -2,12 +2,12 @@
language: R
author: e99n09
author_url: http://github.com/e99n09
filename: learnr.r
---
R is a statistical computing language.
```r
```python
# Comments start with hashtags.
@ -16,9 +16,9 @@ R is a statistical computing language.
# Protip: hit COMMAND-ENTER to execute a line
###################################################################################
#########################
# The absolute basics
###################################################################################
#########################
# NUMERICS
@ -119,9 +119,9 @@ myFunc <- function(x) {
# Called like any other R function:
myFunc(5) # => [1] 19
###################################################################################
#########################
# Fun with data: vectors, matrices, data frames, and arrays
###################################################################################
#########################
# ONE-DIMENSIONAL
@ -130,7 +130,7 @@ vec <- c(4, 5, 6, 7)
vec # => [1] 4 5 6 7
# The class of a vector is the class of its components
class(vec) # => [1] "numeric"
# If you vectorize items of different classes, weird coersions happen
# If you vectorize items of different classes, weird coercions happen
c(TRUE, 4) # => [1] 1 4
c("dog", TRUE, 4) # => [1] "dog" "TRUE" "4"
@ -192,7 +192,7 @@ mat3
# [,1] [,2] [,3] [,4]
# [1,] 1 2 4 5
# [2,] 6 7 0 4
# Aah, everything of the same class. No coersions. Much better.
# Aah, everything of the same class. No coercions. Much better.
# TWO-DIMENSIONAL (DIFFERENT CLASSES)
@ -243,7 +243,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))
# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES)
# Finally, R has lists (of vectors)
list1 <- list(time = 1:40, price = c(rnorm(40,.5*list1$time,4))) # generate random
list1 <- list(time = 1:40, price = c(rnorm(40,.5*list1$time,4))) # random
list1
# You can get items in the list like so
@ -251,9 +251,9 @@ list1$time
# You can subset list items like vectors
list1$price[4]
###################################################################################
#########################
# The apply() family of functions
###################################################################################
#########################
# Remember mat?
mat
@ -273,7 +273,7 @@ apply(mat, MAR = 2, myFunc)
# [2,] 7 19
# [3,] 11 23
# Other functions: ?lapply, ?sapply
# Don't feel too intimiated; everyone agrees they are rather confusing
# Don't feel too intimidated; everyone agrees they are rather confusing
# The plyr package aims to replace (and improve upon!) the *apply() family.
@ -281,9 +281,9 @@ install.packages("plyr")
require(plyr)
?plyr
###################################################################################
#########################
# Loading data
###################################################################################
#########################
# "pets.csv" is a file on the internet
pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv")
@ -292,14 +292,14 @@ 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 in the working directory
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
###################################################################################
#########################
# Scatterplots!
plot(list1$time, list1$price, main = "fake data")