diff options
-rw-r--r-- | clojure.html.markdown | 2 | ||||
-rw-r--r-- | erlang.html.markdown | 239 | ||||
-rw-r--r-- | haskell.html.markdown | 8 | ||||
-rw-r--r-- | java.html.markdown | 19 | ||||
-rw-r--r-- | python.html.markdown | 71 |
5 files changed, 325 insertions, 14 deletions
diff --git a/clojure.html.markdown b/clojure.html.markdown index 12611fd3..cb202a92 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -5,7 +5,7 @@ author_url: http://adambard.com/ filename: test.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. diff --git a/erlang.html.markdown b/erlang.html.markdown new file mode 100644 index 00000000..6ceb3172 --- /dev/null +++ b/erlang.html.markdown @@ -0,0 +1,239 @@ +--- +language: erlang +author: Giovanni Cappellotto +author_url: http://www.focustheweb.com/ +filename: learnerlang.erl +--- + +```erlang +% 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`, you’ll 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 we’re not interested in. +% The symbol `_` is called an anonymous variable. Unlike regular variables, +% several occurrences of _ in the same pattern don’t 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, what’s 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/)
\ No newline at end of file diff --git a/haskell.html.markdown b/haskell.html.markdown index f3baa9a5..1a4cdc67 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -152,10 +152,10 @@ 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: -myMap func [x] = [func x] +myMap func [] = [] myMap func (x:xs) = func x:(myMap func xs) -- Anonymous functions are created with a backslash followed by @@ -164,7 +164,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 ---------------------------------------------------- diff --git a/java.html.markdown b/java.html.markdown index 3208971d..3339b6d1 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -19,10 +19,10 @@ Java is a general-purpose, concurrent, class-based, object-oriented computer pro Multi-line comments look like this. */ -// Import Packages +// Import ArrayList class inside of the java.util package import java.util.ArrayList; -// Import all "sub-packages" -import java.lang.Math.*; +// Import all classes inside of java.lang package +import java.lang.*; // Inside of the learnjava class, is your program's // starting point. The main method. @@ -93,6 +93,9 @@ 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]); @@ -118,9 +121,9 @@ 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) +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 @@ -245,7 +248,7 @@ Integer.toString(123);//returns a string version of 123 // Long // String -// Typecsating +// 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 @@ -346,4 +349,6 @@ Other Topics To Research: * [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + * The links provided are just to get an understanding of the topic, feel free to google and find specific examples diff --git a/python.html.markdown b/python.html.markdown index 19e2aebe..e3f04e19 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -93,6 +93,20 @@ not False #=> True # 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 @@ -159,6 +173,9 @@ li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # Examine the length with len len(li) #=> 6 +# Note: lists can contain arbitrary values +li2 = [1, "Hello", [[], "Hi", 5,]] + # Tuples are like lists but are immutable. tup = (1, 2, 3) tup[0] #=> 1 @@ -170,7 +187,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 @@ -267,6 +284,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. @@ -350,6 +379,8 @@ add_10(3) #=> 13 # There are also anonymous functions (lambda x: x > 2)(3) #=> True +rectangle_area = lambda a, b: a * b +print rectangle_area(3, 4) #=> 12 # There are built-in higher order functions map(add_10, [1,2,3]) #=> [11, 12, 13] @@ -359,6 +390,9 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] +# You can also use dictionary comprehensions +{i: add_10(i) for i in [1, 2, 3]} #=> {1: 11, 2: 12, 3: 13} + #################################################### ## 5. Classes #################################################### @@ -374,7 +408,8 @@ class Human(object): # Assign the argument to the instance's name attribute self.name = name - # An instance method. All methods take self as the first argument + # An instance method. All methods take self as the first argument, + # which refers to the instance of this class def say(self, msg): return "%s: %s" % (self.name, msg) @@ -407,6 +442,34 @@ 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 floor3.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 @@ -417,3 +480,7 @@ Still up for more? Try: * [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 +[Python Module of the Week](http://pymotw.com/2/) for more. |