summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--elixir.html.markdown392
-rw-r--r--erlang.html.markdown2
-rw-r--r--haskell.html.markdown15
-rw-r--r--java.html.markdown606
-rw-r--r--python.html.markdown5
-rw-r--r--r.html.markdown74
6 files changed, 771 insertions, 323 deletions
diff --git a/elixir.html.markdown b/elixir.html.markdown
new file mode 100644
index 00000000..c0544982
--- /dev/null
+++ b/elixir.html.markdown
@@ -0,0 +1,392 @@
+---
+language: elixir
+author: Joao Marques
+author_url: http://github.com/mrshankly
+filename: learnelixir.ex
+---
+
+```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.
+
+# 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 contigously 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.
+<<?a, ?b, ?c>> #=> "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 practive 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
+Match.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<erl_eval.20.80484245>
+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
diff --git a/erlang.html.markdown b/erlang.html.markdown
index 66370a7d..42d0b809 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -5,7 +5,7 @@ author_url: http://www.focustheweb.com/
filename: learnerlang.erl
---
-```latex
+```erlang
% Percent sign start a one-line comment.
%% Two percent characters shall be used to comment functions.
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 84b8f263..840569fb 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -245,7 +245,7 @@ case args of
_ -> putStrLn "bad args"
-- Haskell doesn't have loops because it uses recursion instead.
--- map a function over every element in an array
+-- map applies a function over every element in an array
map (*2) [1..5] -- [2, 4, 6, 8, 10]
@@ -258,6 +258,19 @@ 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 <fn> <initial value> <list>
+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
----------------------------------------------------
diff --git a/java.html.markdown b/java.html.markdown
index 712233ba..8ba48d73 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -21,314 +21,330 @@ 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 all classes inside of java.security 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
-*/
+// Each .java file contains one public class, with the same name as the file.
+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
-
-///////////////////////////////////////
-// 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");
-}
+ // A program must have a main method as an entry point
+ public static void main (String[] args) {
-// 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;
- }
+ // Use System.out.println to print lines
+ System.out.println("Hello World!");
+ System.out.println(
+ "Integer: " + 10 +
+ " Double: " + 3.14 +
+ " Boolean: " + true);
- // This is a specified constructor (it contains arguments)
- public Bicycle(int startCadence, int startSpeed, int startGear) {
- gear = startGear;
- cadence = startCadence;
- speed = startSpeed;
- }
+ // To print without a newline, use System.out.print
+ System.out.print("Hello ");
+ System.out.print("World");
- // the Bicycle class has
- // four functions/methods
- public void setCadence(int newValue) {
- cadence = newValue;
- }
- public void setGear(int newValue) {
- gear = newValue;
+ ///////////////////////////////////////
+ // Types & Variables
+ ///////////////////////////////////////
+
+ // Declare a variable using <type> <name> [
+ // 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';
+
+ // Use final to make a variable immutable
+ 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 zero-indexed and mutable.
+ intArray[1] = 1;
+ System.out.println("intArray @ 1: " + intArray[1]); // => 1
+
+ // 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 truncated down)
+
+ // 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 statements are c-like
+ 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");
}
- public void applyBrake(int decrement) {
- speed -= decrement;
+ // While loop
+ int fooWhile = 0;
+ while(fooWhile < 100)
+ {
+ //System.out.println(fooWhile);
+ //Increment the counter
+ //Iterated 99 times, fooWhile 0->99
+ fooWhile++;
}
-
- public void speedUp(int increment) {
- speed += increment;
+ 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<10; fooFor++){
+ //System.out.println(fooFor);
+ //Iterated 10 times, fooFor 0->9
}
-
- public String toString(){
- return "gear: "+Integer.toString(gear)+
- " cadence: "+Integer.toString(cadence)+
- " speed: "+Integer.toString(speed);
+ System.out.println("fooFor Value: " + fooFor);
+
+ // Switch Case
+ 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;
}
- // bracket to close nested Bicycle class
+ 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
+ ///////////////////////////////////////
+
+ System.out.println("\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);
+ trek.setCadence(100);
+
+ // toString is a convention
+ System.out.println("trek info: " + trek.toString());
+
+ } // End main method
+} // End LearnJava class
+
+
+// You can include other, non-public classes in a .java file
+
+
+// Class Declaration Syntax:
+// <public/private/protected> class <class name>{
+// //data fields, constructors, functions all inside
+// }
+
+class Bicycle {
+
+ // Bicycle's Fields/Variables
+ public int cadence; // Public: Can be accessed from anywhere
+ private int speed; // Private: Only accessable from within the class
+ protected int gear; // Protected: Accessible from the class and subclasses
+
+ // 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;
}
-// bracket to close learnjava.java
+
+ // Function Syntax:
+ // <public/private/protected> <return type> <function name>(<args>)
+
+ // Java classes often implement getters and setters for their fields
+
+ // Method declaration syntax:
+ // <scope> <return type> <method name>(<args>)
+ public int getCadence() {
+ return cadence;
+ }
+
+ // void methods require no return statement
+ 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 String toString() {
+ return "gear: "+Integer.toString(gear)+
+ " cadence: "+Integer.toString(cadence)+
+ " speed: "+Integer.toString(speed);
+ }
+} // end class Bicycle
+
+// PennyFarthing is a subclass of Bicycle
+class PennyFarthing extends Bicycle {
+ // (Penny Farthings are those bicycles with the big front wheel.
+ // They have no gears.)
+
+ public PennyFarthing(int startCadence, int startSpeed){
+ // Call the parent constructor with super
+ super(startCadence, startSpeed, 0);
+ }
+
+ // You should mark a method you're overriding with an @annotation
+ @Override
+ public void setGear(int gear) {
+ gear = 0;
+ }
+
}
```
diff --git a/python.html.markdown b/python.html.markdown
index 59a0b85c..ff77fac6 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -461,6 +461,11 @@ math.sqrt(16) == m.sqrt(16) #=> True
# 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)
+
```
diff --git a/r.html.markdown b/r.html.markdown
index 38317776..535b9065 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -5,7 +5,7 @@ author_url: http://github.com/e99n09
filename: learnr.r
---
-R is a statistical computing language.
+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.
```python
@@ -14,36 +14,30 @@ R is a statistical computing language.
# You can't make a multi-line comment per se,
# but you can stack multiple comments like so.
-# Protip: hit COMMAND-ENTER to execute a line
+# Hit COMMAND-ENTER to execute a line
#########################
# The absolute basics
#########################
-# NUMERICS
+# NUMBERS
-# We've got numbers! Behold the "numeric" class
+# 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"
# Try ?class for more information on the class() function
# In fact, you can look up the documentation on just about anything with ?
-# Numerics are like doubles. There's no such thing as integers
-5 == 5.0 # => [1] TRUE
-# Because R doesn't distinguish between integers and doubles,
-# R shows the "integer" form instead of the equivalent "double" form
-# whenever it's convenient:
-5.0 # => [1] 5
-
# All the normal operations!
10 + 66 # => [1] 76
53.2 - 4 # => [1] 49.2
-3.37 * 5.4 # => [1] 18.198
2 * 2.0 # => [1] 4
-3 / 4 # => [1] 0.75
-2.0 / 2 # => [1] 1
+3L / 4 # => [1] 0.75
3 %% 2 # => [1] 1
-4 %% 2 # => [1] 0
# Finally, we've got not-a-numbers! They're numerics too
class(NaN) # => [1] "numeric"
@@ -107,6 +101,17 @@ while (a > 4) {
# 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:
@@ -126,8 +131,8 @@ myFunc(5) # => [1] 19
# ONE-DIMENSIONAL
# You can vectorize anything, so long as all components have the same type
-vec <- c(4, 5, 6, 7)
-vec # => [1] 4 5 6 7
+vec <- c(8, 9, 10, 11)
+vec # => [1] 8 9 10 11
# The class of a vector is the class of its components
class(vec) # => [1] "numeric"
# If you vectorize items of different classes, weird coercions happen
@@ -135,15 +140,27 @@ c(TRUE, 4) # => [1] 1 4
c("dog", TRUE, 4) # => [1] "dog" "TRUE" "4"
# We ask for specific components like so (R starts counting from 1)
-vec[1] # => [1] 4
-# We can also search for the indices of specific components
-which(vec %% 2 == 0)
+vec[1] # => [1] 8
+# We can also search for the indices of specific components,
+which(vec %% 2 == 0) # => [1] 1 3
+# or grab just the first or last entry in the vector
+head(vec, 1) # => [1] 8
+tail(vec, 1) # => [1] 11
# If an index "goes over" you'll get NA:
vec[6] # => [1] NA
+# You can find the length of your vector with length()
+length(vec) # => [1] 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
+# 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
# TWO-DIMENSIONAL (ALL ONE CLASS)
@@ -243,7 +260,8 @@ 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))) # random
+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
@@ -273,6 +291,7 @@ apply(mat, MAR = 2, myFunc)
# [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.
@@ -303,13 +322,13 @@ write.csv(pets, "pets2.csv") # to make a new .csv file
# Scatterplots!
plot(list1$time, list1$price, main = "fake data")
-# Fit a linear model
-myLm <- lm(price ~ time, data = list1)
-myLm # outputs result of regression
+# Regressions!
+linearModel <- lm(price ~ time, data = list1)
+linearModel # outputs result of regression
# Plot regression line on existing plot
-abline(myLm, col = "red")
+abline(linearModel, col = "red")
# Get a variety of nice diagnostics
-plot(myLm)
+plot(linearModel)
# Histograms!
hist(rpois(n = 10000, lambda = 5), col = "thistle")
@@ -325,4 +344,7 @@ require(ggplot2)
```
+## 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