summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--haskell.html.markdown71
-rw-r--r--java.html.markdown349
-rw-r--r--php.html.markdown2
-rw-r--r--python.html.markdown64
4 files changed, 432 insertions, 54 deletions
diff --git a/haskell.html.markdown b/haskell.html.markdown
index a696cb5f..f3baa9a5 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -2,7 +2,6 @@
language: haskell
author: Adit Bhargava
author_url: http://adit.io
-filename: learnhaskell.hs
---
Haskell was designed as a practical, purely functional programming language. It's famous for
@@ -45,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'
@@ -69,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
@@ -105,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
@@ -136,12 +155,12 @@ 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
-- our own map function:
-map func [x] = [func x]
-map func (x:xs) = func x:(map func xs)
+myMap func [x] = [func x]
+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
@@ -180,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
@@ -198,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 it's type above it:
+double :: Integer -> Integer
+double x = x * 2
----------------------------------------------------
--- 6. Control Flow
+-- 6. Control Flow and If Statements
----------------------------------------------------
-- if statements
@@ -263,25 +286,35 @@ Just 1
-- 8. Haskell IO
----------------------------------------------------
--- While IO can't be explained fully without explaining monads
--- it is not hard to explain enough to get going
+-- 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
+-- 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
+ 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 interprete
+-- 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 it's 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.
----------------------------------------------------
diff --git a/java.html.markdown b/java.html.markdown
new file mode 100644
index 00000000..3208971d
--- /dev/null
+++ b/java.html.markdown
@@ -0,0 +1,349 @@
+---
+
+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 Packages
+import java.util.ArrayList;
+// Import all "sub-packages"
+import java.lang.Math.*;
+
+// 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];
+
+// 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("1+2 = "+(i2 - i1)); // => 1
+System.out.println("1+2 = "+(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
+
+// Typecsating
+// 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)
+
+* The links provided are just to get an understanding of the topic, feel free to google and find specific examples
diff --git a/php.html.markdown b/php.html.markdown
index 20923548..75bbd214 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -379,7 +379,7 @@ echo $function_name(1, 2); // => 3
```
```php
<?php
-// Included files must also begin with a PHP open tags.
+// PHP within included files must also begin with a PHP open tag.
include 'my-file.php';
// The code in my-file.php is now available in the current scope.
diff --git a/python.html.markdown b/python.html.markdown
index 9c59a8d7..e3f04e19 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -87,6 +87,8 @@ 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
@@ -96,6 +98,10 @@ None #=> None
"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
@@ -114,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 1 > 2 else 2 #=> "yahoo!"
# Lists store sequences
li = []
@@ -146,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.)
@@ -180,10 +179,7 @@ li2 = [1, "Hello", [[], "Hi", 5,]]
# 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
@@ -220,13 +216,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
@@ -248,7 +243,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 |
@@ -269,7 +264,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."
@@ -324,12 +319,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
@@ -367,16 +356,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):
@@ -476,14 +466,20 @@ 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.
+# 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 has a huge amount of modules within the standard library. See the
[official documentation](http://docs.python.org/2/library/index.html) or