diff options
-rw-r--r-- | c.html.markdown | 34 | ||||
-rw-r--r-- | clojure.html.markdown | 97 | ||||
-rw-r--r-- | dart.html.markdown | 4 | ||||
-rw-r--r-- | elixir.html.markdown | 398 | ||||
-rw-r--r-- | erlang.html.markdown | 251 | ||||
-rw-r--r-- | fsharp.html.markdown | 4 | ||||
-rw-r--r-- | git.html.markdown | 388 | ||||
-rw-r--r-- | haskell.html.markdown | 184 | ||||
-rw-r--r-- | java.html.markdown | 592 | ||||
-rw-r--r-- | javascript.html.markdown | 433 | ||||
-rw-r--r-- | julia.html.markdown | 525 | ||||
-rw-r--r-- | livescript.html.markdown | 345 | ||||
-rw-r--r-- | lua.html.markdown | 4 | ||||
-rw-r--r-- | php.html.markdown | 28 | ||||
-rw-r--r-- | python.html.markdown | 131 | ||||
-rw-r--r-- | r.html.markdown | 84 | ||||
-rw-r--r-- | racket.html.markdown | 602 | ||||
-rw-r--r-- | ruby.html.markdown | 315 | ||||
-rw-r--r-- | scala.html.markdown | 419 |
19 files changed, 4333 insertions, 505 deletions
diff --git a/c.html.markdown b/c.html.markdown index 69bf099e..132f75dc 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -1,8 +1,8 @@ --- language: c -author: Adam Bard -author_url: http://adambard.com/ filename: learnc.c +contributors: + - ["Adam Bard", "http://adambard.com/"] --- Ah, C. Still the language of modern high-performance computing. @@ -363,6 +363,36 @@ int area(rect r){ return r.width * r.height; } +/////////////////////////////////////// +// Function pointers +/////////////////////////////////////// +/* +At runtime, functions are located at known memory addresses. Function pointers are +much likely any other pointer (they just store a memory address), but can be used +to invoke functions directly, and to pass handlers (or callback functions) around. +However, definition syntax may be initially confusing. + +Example: use str_reverse from a pointer +*/ +void str_reverse_through_pointer(char * str_in) { + // Define a function pointer variable, named f. + void (*f)(char *); // Signature should exactly match the target function. + f = &str_reverse; // Assign the address for the actual function (determined at runtime) + (*f)(str_in); // Just calling the function through the pointer + // f(str_in); // That's an alternative but equally valid syntax for calling it. +} + +/* +As long as function signatures match, you can assign any function to the same pointer. +Function pointers are usually typedef'd for simplicity and readability, as follows: +*/ + +typedef void (*my_fnp_type)(char *); + +// The used when declaring the actual pointer variable: +// ... +// my_fnp_type f; + ``` ## Further Reading diff --git a/clojure.html.markdown b/clojure.html.markdown index 12611fd3..6baae0ce 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -1,11 +1,11 @@ --- language: clojure -author: Adam Bard -author_url: http://adambard.com/ -filename: test.clj +filename: learnclojure.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] --- -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. @@ -24,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: @@ -71,6 +71,7 @@ and often automatically. ; 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 @@ -79,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) @@ -97,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) @@ -168,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. @@ -200,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} @@ -271,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 @@ -314,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/) diff --git a/dart.html.markdown b/dart.html.markdown index 27365746..34d1c6a8 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -1,8 +1,8 @@ --- language: dart -author: Joao Pedrosa -author_url: https://github.com/jpedrosa/ filename: learndart.dart +contributors: + - ["Joao Pedrosa", "https://github.com/jpedrosa/"] --- Dart is a newcomer into the realm of programming languages. diff --git a/elixir.html.markdown b/elixir.html.markdown new file mode 100644 index 00000000..8ea499ff --- /dev/null +++ b/elixir.html.markdown @@ -0,0 +1,398 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] +filename: learnelixir.ex +--- + +Elixir is a modern functional language built on top of the Erlang VM. +It's fully compatible with Erlang, but features a more standard syntax +and many more features. + +```ruby + +# 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 contiguously 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 practice 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 +Math.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 new file mode 100644 index 00000000..951fdedd --- /dev/null +++ b/erlang.html.markdown @@ -0,0 +1,251 @@ +--- +language: erlang +contributors: + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] +filename: learnerlang.erl +--- + +```erlang +% Percent sign starts an 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: +% 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. +Num = 43. % ** exception error: no match of right hand side value 43 + +% 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. +OtherNode = example@node. + +% Atoms with non alphanumeric values can be written by enclosing the atoms +% with apostrophes. +AtomWithSpace = 'some atom with space'. + +% 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 is 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 a 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". +[72, 101, 108, 108, 111] = "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 list of functions exported from the module. + +% 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 (number of arguments) +% in the same module represent entirely different functions. +-module(lib_misc). +-export([sum/1]). % export function `sum` of arity 1 accepting one argument: list of integers. +sum(L) -> sum(L, 0). +sum([], N) -> N; +sum([H|T], N) -> sum(T, H+N). + +% Funs are "anonymous" functions. They are called this way because they have no +% name. However they can be assigned to variables. +Double = fun(X) -> 2*X end. % `Double` points to an anonymous function with handle: #Fun<erl_eval.6.17052888> +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] +% A list comprehension can have generators and filters which select subset of the generated values. +EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] + +% 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 elements `X` in a list `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, []) -> []. +filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4] + +% `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 + +* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/) +* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang) +* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/) +* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index b1860372..49951c78 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -1,7 +1,7 @@ --- language: F# -author: Scott Wlaschin -author_url: http://fsharpforfunandprofit.com/ +contributors: + - ["Scott Wlaschin", "http://fsharpforfunandprofit.com/"] filename: learnfsharp.fs --- diff --git a/git.html.markdown b/git.html.markdown new file mode 100644 index 00000000..00f38d60 --- /dev/null +++ b/git.html.markdown @@ -0,0 +1,388 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http:#github.com/JakeHP"] +filename: LearnGit.txt + +--- + +Git is a distributed version control and source code management system. + +It does this through a series of snapshots of your project, and it works +with those snapshots to provide you with functionality to version and +manage your source code. + +## Versioning Concepts + +### What is version control? + +Version control is a system that records changes to a file, or set of files, over time. + +### Centralized Versioning VS Distributed Versioning + +* Centralized version control focuses on synchronizing, tracking, and backing up files. +* Distributed version control focuses on sharing changes. Every change has a unique id. +* Distributed systems have no defined structure. You could easily have a SVN style, centralized system, with git. + +[Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### Why Use Git? + +* Can work offline. +* Collaborating with others is easy! +* Branching is easy! +* Merging is easy! +* Git is fast. +* Git is flexible. + +## Git Architecture + + +### Repository + +A set of files, directories, historical records, commits, and heads. Imagine it as a source code datastructure, +with the attribute that each source code "element" gives you access to its revision history, among other things. + +A git repository is comprised of the .git directory & working tree. + +### .git Directory (component of repository) + +The .git directory contains all the configurations, logs, branches, HEAD, and more. +[Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Working Tree (component of repository) + +This is basically the directories and files in your repository. It is often referred to +as your working directory. + +### Index (component of .git dir) + +The Index is the staging area in git. It's basically a layer that separates your working tree +from the Git repository. This gives developers more power over what gets sent to the Git +repository. + +### Commit + +A git commit is a snapshot of a set of changes, or manipulations to your Working Tree. +For example, if you added 5 files, and removed 2 others, these changes will be contained +in a commit (or snapshot). This commit can then be pushed to other repositories, or not! + +### Branch + +A branch is essentially a pointer that points to the last commit you made. As you commit, +this pointer will automatically update and point to the latest commit. + +### HEAD and head (component of .git dir) + +HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD. +head is a pointer that points to any commit. A repository can have any number of heads. + +### Conceptual Resources + +* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) +* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) + + +## Commands + + +### init + +Create an empty Git repository. The Git repository's settings, stored information, +and more is stored in a directory (a folder) named ".git". + +```bash +$ git init +``` + +### config + +To configure settings. Whether it be for the repository, the system itself, or global +configurations. + + +```bash +# Print & Set Some Basic Config Variables (Global) +$ git config --global user.email +$ git config --global user.name + +$ git config --global user.email "MyEmail@Zoho.com" +$ git config --global user.name "My Name" +``` + +[Learn More About git config.](http://git-scm.com/docs/git-config) + +### help + +To give you quick access to an extremely detailed guide of each command. Or to +just give you a quick reminder of some semantics. + +```bash +# Quickly check available commands +$ git help + +# Check all available commands +$ git help -a + +# Command specific help - user manual +# git help <command_here> +$ git help add +$ git help commit +$ git help init +``` + +### status + +To show differences between the index file (basically your working copy/repo) and the current +HEAD commit. + + +```bash +# Will display the branch, untracked files, changes and other differences +$ git status + +# To learn other "tid bits" about git status +$ git help status +``` + +### add + +To add files to the current working tree/directory/repo. If you do not `git add` new files to the +working tree/directory, they will not be included in commits! + +```bash +# add a file in your current working directory +$ git add HelloWorld.java + +# add a file in a nested dir +$ git add /path/to/file/HelloWorld.c + +# Regular Expression support! +$ git add ./*.java +``` + +### branch + +Manage your branches. You can view, edit, create, delete branches using this command. + +```bash +# list existing branches & remotes +$ git branch -a + +# create a new branch +$ git branch myNewBranch + +# delete a branch +$ git branch -d myBranch + +# rename a branch +# git branch -m <oldname> <newname> +$ git branch -m myBranchName myNewBranchName + +# edit a branch's description +$ git branch myBranchName --edit-description +``` + +### checkout + +Updates all files in the working tree to match the version in the index, or specified tree. + +```bash +# Checkout a repo - defaults to master branch +$ git checkout +# Checkout a specified branch +$ git checkout branchName +# Create a new branch & switch to it, like: "git branch <name>; git checkout <name>" +$ git checkout -b newBranch +``` + +### clone + +Clones, or copies, an existing repository into a new directory. It also adds +remote-tracking branches for each branch in the cloned repo, which allows you to push +to a remote branch. + +```bash +# Clone learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +``` + +### commit + +Stores the current contents of the index in a new "commit." This commit contains +the changes made and a message created by the user. + +```bash +# commit with a message +$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" +``` + +### diff + +Shows differences between a file in the working directory, index and commits. + +```bash +# Show difference between your working dir and the index +$ git diff + +# Show differences between the index and the most recent commit. +$ git diff --cached + +# Show differences between your working dir and the most recent commit +$ git diff HEAD +``` + +### grep + +Allows you to quickly search a repository. + +Optional Configurations: + +```bash +# Thanks to Travis Jeffery for these +# Set line numbers to be shown in grep search results +$ git config --global grep.lineNumber true + +# Make search results more readable, including grouping +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Search for "variableName" in all java files +$ git grep 'variableName' -- '*.java' + +# Search for a line that contains "arrayListName" and, "add" or "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Google is your friend; for more examples +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Display commits to the repository. + +```bash +# Show all commits +$ git log + +# Show X number of commits +$ git log -n 10 + +# Show merge commits only +$ git log --merges +``` + +### merge + +"Merge" in changes from external commits into the current branch. + +```bash +# Merge the specified branch into the current. +$ git merge branchName + +# Always generate a merge commit when merging +$ git merge --no-ff branchName +``` + +### mv + +Rename or move a file + +```bash +# Renaming a file +$ git mv HelloWorld.c HelloNewWorld.c + +# Moving a file +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Force rename or move +# "existingFile" already exists in the directory, will be overwritten +$ git mv -f myFile existingFile +``` + +### pull + +Pulls from a repository and merges it with another branch. + +```bash +# Update your local repo, by merging in new changes +# from the remote "origin" and "master" branch. +# git pull <remote> <branch> +$ git pull origin master +``` + +### push + +Push and merge changes from a branch to a remote & branch. + +```bash +# Push and merge changes from a local repo to a +# remote named "origin" and "master" branch. +# git push <remote> <branch> +# git push => implicitly defaults to => git push origin master +$ git push origin master +``` + +### rebase (caution) + +Take all changes that were committed on one branch, and replay them onto another branch. +*Do not rebase commits that you have pushed to a public repo*. + +```bash +# Rebase experimentBranch onto master +# git rebase <basebranch> <topicbranch> +$ git rebase master experimentBranch +``` + +[Additional Reading.](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (caution) + +Reset the current HEAD to the specified state. This allows you to undo merges, +pulls, commits, adds, and more. It's a great command but also dangerous if you don't +know what you are doing. + +```bash +# Reset the staging area, to match the latest commit (leaves dir unchanged) +$ git reset + +# Reset the staging area, to match the latest commit, and overwrite working dir +$ git reset --hard + +# Moves the current branch tip to the specified commit (leaves dir unchanged) +# all changes still exist in the directory. +$ git reset 31f2bb1 + +# Moves the current branch tip backward to the specified commit +# and makes the working dir match (deletes uncommited changes and all commits +# after the specified commit). +$ git reset --hard 31f2bb1 +``` + +### rm + +The opposite of git add, git rm removes files from the current working tree. + +```bash +# remove HelloWorld.c +$ git rm HelloWorld.c + +# Remove a file from a nested dir +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## Further Information + +* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) + +* [git-scm - Video Tutorials](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) diff --git a/haskell.html.markdown b/haskell.html.markdown index a696cb5f..be7d8669 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -1,18 +1,17 @@ --- language: haskell -author: Adit Bhargava -author_url: http://adit.io -filename: learnhaskell.hs +contributors: + - ["Adit Bhargava", "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 -- Single line comments start with two dashes. {- Multiline comments can be enclosed -in a block like this. +en a block like this. -} ---------------------------------------------------- @@ -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 @@ -133,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 ---------------------------------------------------- @@ -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 its type above it: +double :: Integer -> Integer +double x = x * 2 ---------------------------------------------------- --- 6. Control Flow +-- 6. Control Flow and If Statements ---------------------------------------------------- -- if statements @@ -222,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] @@ -235,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 ---------------------------------------------------- @@ -245,43 +281,100 @@ data Color = Red | Blue | Green -- Now you can use it in a function: -say :: Color -> IO String -say Red = putStrLn "You are Red!" -say Blue = putStrLn "You are Blue!" -say Green = putStrLn "You are Green!" + +say :: Color -> String +say Red = "You are Red!" +say Blue = "You are Blue!" +say Green = "You are Green!" -- Your data types can have parameters too: data Maybe a = Nothing | Just a -- These are all of type Maybe -Nothing -Just "hello" -Just 1 +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` ---------------------------------------------------- -- 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. + +-- When a Haskell program is executed, the function `main` is +-- called. It must return a value of type `IO ()`. For example: + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- putStrLn has type String -> IO () --- An IO a value is an IO action: you can chain them with do blocks +-- It is easiest to do IO if you can implement your program as +-- a function from String to String. The function +-- interact :: (String -> String) -> IO () +-- inputs some text, runs a function on it, and prints out the +-- output. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- You can think of a value of type `IO ()` as representing a +-- sequence of actions for the computer to do, much like a +-- computer program written in an imperative language. We can use +-- the `do` notation to chain actions together. For example: + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + name <- getLine -- this gets a line and gives it the name "input" + putStrLn $ "Hello, " ++ name + +-- Exercise: write your own version of `interact` that only reads +-- one line of input. + +-- The code in `sayHello` will never be executed, however. The only +-- action that ever gets executed is the value of `main`. +-- To run `sayHello` comment out the above definition of `main` +-- and replace it with: +-- main = sayHello + +-- Let's understand better how the function `getLine` we just +-- used works. Its type is: +-- getLine :: IO String +-- You can think of a value of type `IO a` as representing a +-- computer program that will generate a value of type `a` +-- when executed (in addition to anything else it does). We can +-- store and reuse this value using `<-`. We can also +-- make our own action of type `IO String`: + +action :: IO String action = do putStrLn "This is a line. Duh" - input <- getLine -- this gets a line and gives it the name "input" + input1 <- getLine input2 <- getLine - return (input1++"\n"++input2) -- This is the result of the whole action + -- The type of the `do` statement is that of its last line. + -- `return` is not a keyword, but merely a function + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String --- This didn't actually do anything. When a haskell program is executed --- an IO action called "main" is read and interprete +-- We can use this just like we used `getLine`: -main = do - putStrLn "Our first program. How exciting!" - result <- action -- our defined action is just like the default ones +main'' = do + putStrLn "I will echo two lines!" + result <- action putStrLn result putStrLn "This was all, folks!" - + +-- The type `IO` is an example of a "monad". The way Haskell uses a monad to +-- do IO allows it to be a purely functional language. 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. ---------------------------------------------------- @@ -298,6 +391,14 @@ let foo = 5 >:t foo foo :: Integer + +-- You can also run any action of type `IO ()` + +> sayHello +What is your name? +Friend! +Hello, Friend! + ``` There's a lot more to Haskell, including typeclasses and monads. These are the big ideas that make Haskell such fun to code in. I'll leave you with one final Haskell example: an implementation of quicksort in Haskell: @@ -311,5 +412,6 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater Haskell is easy to install. Get it [here](http://www.haskell.org/platform/). -You can find a much gentler introduction from the excellent [Learn you a Haskell](http://learnyouahaskell.com/) - +You can find a much gentler introduction from the excellent +[Learn you a Haskell](http://learnyouahaskell.com/) or +[Real World Haskell](http://book.realworldhaskell.org/). diff --git a/java.html.markdown b/java.html.markdown index 8d882234..b4531635 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -1,280 +1,332 @@ --- language: java - -author: Jake Prather - -author_url: http://github.com/JakeHP +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +filename: LearnJava.java --- Java is a general-purpose, concurrent, class-based, object-oriented computer programming language. -Read more here: https://en.wikipedia.org/wiki/Java_(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. */ +/** +JavaDoc comments look like this. Used to describe the Class or various +attributes of a Class. +*/ -// Import Packages +// Import ArrayList class inside of the java.util package import java.util.ArrayList; -import package.path.here; -// Import all "sub-packages" -import java.lang.Math.*; - -// Your program's entry point is a function called main -public class Main -{ - public static void main (String[] args) throws java.lang.Exception - { - //stuff here - } -} +// Import all classes inside of java.security package +import java.security.*; + +// Each .java file contains one public class, with the same name as the file. +public class LearnJava { + + // A program must have a main method as an entry point + public static void main (String[] args) { + + // Use System.out.println to print lines + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // To print without a newline, use System.out.print + System.out.print("Hello "); + System.out.print("World"); + + + /////////////////////////////////////// + // 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; + // L is used to denote that this variable value is of type Long; + // anything without is treated as integer by default. + + // Note: Java has no unsigned types + + // Float - Single-precision 32-bit IEEE 754 Floating Point + float fooFloat = 234.5f; + // f is used to denote that this variable value is of type float; + // otherwise it is treated as double. + + // 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!"; + // \t is an escaped character that adds a tab character + String bazString = "Do you want to add a tab?\tNo Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // 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)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // 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 + int j = 10; + if (j == 10){ + System.out.println("I get printed"); + } else if (j > 10) { + System.out.println("I don't"); + } else { + System.out.println("I also don't"); + } -// Printing, and forcing a new line on next print = 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 = print() -System.out.print("Hello World"); -System.out.print("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); - -/////////////////////////////////////// -// Types -/////////////////////////////////////// - -// Byte - 8-bit signed two's complement integer -// (-128 <= byte <= 127) -byte foo = 100; - -// Short - 16-bit signed two's complement integer -// (-32,768 <= short <= 32,767) -short bar = 10000; - -//Integer - 32-bit signed two's complement integer -// (-2,147,483,648 <= int <= 2,147,483,647) -int foo = 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 bar = 100000L; - -// (Java has no unsigned types) - -//Float - Single-precision 32-bit IEEE 754 Floating Point -float foo = 234.5f; - -//Double - Double-precision 64-bit IEEE 754 Floating Point -double bar = 123.4; - -//Boolean - True & False -boolean foo = true; -boolean bar = false; - -//Char - A single 16-bit Unicode character -char foo = 'A'; - -//Make a variable a constant -final int HOURS_I_WORK_PER_WEEK = 9001; - -//Strings -String foo = "Hello World!"; -// \n is an escaped character that starts a new line -String foo = "Hello World!\nLine2!"; -System.out.println(foo); -//Hello World! -//Line2! - -//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 [] array = new int[10]; -String [] array = new String[1]; -boolean [] array = new boolean[100]; - -// Indexing an array - Accessing an element -array[0]; - -// Arrays are mutable; it's just memory! -array[1] = 1; -System.out.println(array[1]); // => 1 -array[1] = 2; -System.out.println(array[1]); // => 2 - -//Others to check out -//ArrayLists - Like arrays except more functionality is offered, -// and the size is mutable -//LinkedLists -//Maps -//HashMaps - -/////////////////////////////////////// -// Operators -/////////////////////////////////////// - -int i1 = 1, i2 = 2; // Shorthand for multiple declarations - -// Arithmetic is straightforward -i1 + i2; // => 3 -i2 - i1; // => 1 -i2 * i1; // => 2 -i1 / i2; // => 0 (0.5, but truncated towards 0) - -// Modulo -11 % 3; // => 2 - -// Comparison operators -3 == 2; // => 0 (false) -3 != 2; // => 1 (true) -3 > 2; // => 1 -3 < 2; // => 0 -2 <= 2; // => 1 -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; -i++; //i = 1. Post-Incrementation -++i; //i = 2. Pre-Incrementation -i--; //i = 1. Post-Decrementation ---i; //i = 0. Pre-Decrementation - -/////////////////////////////////////// -// 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<10; fooFor++){ + //System.out.println(fooFor); + //Iterated 10 times, fooFor 0->9 + } + System.out.println("fooFor Value: " + fooFor); + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), + // the String class, and a few special classes that wrap + // primitive types: Character, Byte, Short, and Integer. + 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; + } + System.out.println("Switch Case Result: " + monthString); -// While loop -int i = 0; -while(i < 100){ - System.out.println(i); - //Increment the counter - i++; -} -// Do While Loop -int i = 0; -do{ - System.out.println(i); - //Increment the counter - i++; -}while(i < 100); - -// For Loop -int i; -//for loop structure => for(<start_statement>;<conditional>;<step>) -for(i=0;i<100;i++){ - System.out.println(i); -} + /////////////////////////////////////// + // Converting Data Types And Typcasting + /////////////////////////////////////// -// 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(monthString); + // 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 -/////////////////////////////////////// -// Typecasting -/////////////////////////////////////// + // For other conversions check out the following classes: + // Double + // Long + // String -// Converting data + // 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 -//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 + /////////////////////////////////////// + // 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); // You should always use setter and getter methods + trek.setCadence(100); -//For other conversions check out the following classes: -//Double -//Long -//String + // toString is a convention to display the value of this Object. + System.out.println("trek info: " + trek.toString()); -// 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 + } // End main method +} // End LearnJava class -/////////////////////////////////////// -// Classes And Functions -/////////////////////////////////////// +// You can include other, non-public classes in a .java file -// Classes Syntax shown below. -// Function declaration 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 +// Class Declaration Syntax: +// <public/private/protected> class <class name>{ +// //data fields, constructors, functions all inside. +// //functions are called as methods in Java. +// } -public class Bicycle { +class Bicycle { // Bicycle's Fields/Variables - public int cadence; - public int gear; - public int speed; + public int cadence; // Public: Can be accessed from anywhere + private int speed; // Private: Only accessible from within the class + protected int gear; // Protected: Accessible from the class and subclasses + String name; // default: Only accessible from within this package // Constructors are a way of creating classes // This is a default constructor - public Bicycle(){ + public Bicycle() { gear = 1; cadence = 50; - startGear = 1; + speed = 5; + name = "Bontrager"; } // This is a specified constructor (it contains arguments) - public Bicycle(int startCadence, int startSpeed, int startGear) { - gear = startGear; - cadence = startCadence; - speed = startSpeed; + public Bicycle(int startCadence, int startSpeed, int startGear, String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // 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; } - // the Bicycle class has - // four methods + // void methods require no return statement public void setCadence(int newValue) { cadence = newValue; } @@ -283,43 +335,73 @@ public class Bicycle { gear = newValue; } - public void applyBrake(int decrement) { + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { speed -= decrement; } - public void speedUp(int increment) { - speed += increment; + public void setName(String newName) { + name = newName; } -} + public String getName() { + return name; + } -//Now..Later in the main / driver of your java program -public class Main -{ - public static void main (String[] args) throws java.lang.Exception - { - //Call bicycle's constructor - Bicycle trek = new Bicycle(); - //Manipulate your object - trek.speedUp(3); - trek.setCadence(100); + //Method to display the attribute values of this Object. + @Override + public String toString() { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + speed + + " name: " + name; + } +} // 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, "PennyFarthing"); } + + // You should mark a method you're overriding with an @annotation + // To learn more about what annotations are and their purpose + // check this out: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + gear = 0; + } + } ``` ## Further Reading +The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. + Other Topics To Research: -* Inheritance (http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)) +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) -* Abstraction (http://en.wikipedia.org/wiki/Abstraction_(computer_science)) +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [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://en.wikipedia.org/wiki/Exception_handling) +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) -* Interfaces (http://en.wikipedia.org/wiki/Interfaces_(computer_science)) +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) -* Generics (http://en.wikipedia.org/wiki/Generics_in_Java) +* [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 +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) diff --git a/javascript.html.markdown b/javascript.html.markdown new file mode 100644 index 00000000..cbe82054 --- /dev/null +++ b/javascript.html.markdown @@ -0,0 +1,433 @@ +--- +language: javascript +author: Adam Brenecki +author_url: http://adam.brenecki.id.au +--- + +Javascript was created by Netscape's Brendan Eich in 1995. It was originally +intended as a simpler scripting language for websites, complimenting the use of +Java for more complex web applications, but its tight integration with Web pages +and built-in support in browsers has caused it to become far more common than +Java in web frontends. + +JavaScript isn't just limited to web browsers, though: Node.js, a project that +provides a standalone runtime for Google Chrome's V8 JavaScript engine, is +becoming more and more popular. + +Feedback would be highly appreciated! You can reach me at +[@adambrenecki](https://twitter.com/adambrenecki), or +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// Comments are like C. Single-line comments start with two slashes, +/* and multiline comments start with slash-star + and end with star-slash */ + +// Statements can be terminated by ; +doStuff(); + +// ... but they don't have to be, as semicolons are automatically inserted +// wherever there's a newline, except in certain cases. +doStuff() + +// We'll leave semicolons off here; whether you do or not will depend on your +// personal preference or your project's style guide. + +/////////////////////////////////// +// 1. Numbers, Strings and Operators + +// Javascript has one number type (which is a 64-bit IEEE 754 double). +3 // = 3 +1.5 // = 1.5 + +// All the basic arithmetic works as you'd expect. +1 + 1 // = 2 +8 - 1 // = 7 +10 * 2 // = 20 +35 / 5 // = 7 + +// Including uneven division. +5 / 2 // = 2.5 + +// Bitwise operations also work; when you perform a bitwise operation your float +// is converted to a signed int *up to* 32 bits. +1 << 2 // = 4 + +// Precedence is enforced with parentheses. +(1 + 3) * 2 // = 8 + +// There are three special not-a-real-number values: +Infinity // result of e.g. 1/0 +-Infinity // result of e.g. -1/0 +NaN // result of e.g. 0/0 + +// There's also a boolean type. +true +false + +// Strings are created with ' or ". +'abc' +"Hello, world" + +// Negation uses the ! symbol +!true // = false +!false // = true + +// Equality is == +1 == 1 // = true +2 == 1 // = false + +// Inequality is != +1 != 1 // = false +2 != 1 // = true + +// More comparisons +1 < 10 // = true +1 > 10 // = false +2 <= 2 // = true +2 >= 2 // = true + +// Strings are concatenated with + +"Hello " + "world!" // = "Hello world!" + +// and are compared with < and > +"a" < "b" // = true + +// Type coercion is performed for comparisons... +"5" == 5 // = true + +// ...unless you use === +"5" === 5 // = false + +// You can access characters in a string with charAt +"This is a string".charAt(0) + +// There's also null and undefined +null // used to indicate a deliberate non-value +undefined // used to indicate a value that hasn't been set yet + +// null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. +// Note that 0 is falsy and "0" is truthy, even though 0 == "0". + +/////////////////////////////////// +// 2. Variables, Arrays and Objects + +// Variables are declared with the var keyword. Javascript is dynamically typed, +// so you don't need to specify type. Assignment uses a single = character. +var someVar = 5 + +// if you leave the var keyword off, you won't get an error... +someOtherVar = 10 + +// ...but your variable will be created in the global scope, not in the scope +// you defined it in. + +// Variables declared without being assigned to are set to undefined. +var someThirdVar // = undefined + +// There's shorthand for performing math operations on variables: +someVar += 5 // equivalent to someVar = someVar + 5; someVar is 10 now +someVar *= 10 // now someVar is 100 + +// and an even-shorter-hand for adding or subtracting 1 +someVar++ // now someVar is 101 +someVar-- // back to 100 + +// Arrays are ordered lists of values, of any type. +var myArray = ["Hello", 45, true] + +// Their members can be accessed using the square-brackets subscript syntax. +// Array indices start at zero. +myArray[1] // = 45 + +// JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other +// languages: an unordered collection of key-value pairs. +{key1: "Hello", key2: "World"} + +// Keys are strings, but quotes aren't required if they're a valid +// JavaScript identifier. Values can be any type. +var myObj = {myKey: "myValue", "my other key": 4} + +// Object attributes can also be accessed using the subscript syntax, +myObj["my other key"] // = 4 + +// ... or using the dot syntax, provided the key is a valid identifier. +myObj.myKey // = "myValue" + +// Objects are mutable; values can be changed and new keys added. +myObj.myThirdKey = true + +// If you try to access a value that's not yet set, you'll get undefined. +myObj.myFourthKey // = undefined + +/////////////////////////////////// +// 3. Logic and Control Structures + +// The if structure works as you'd expect. +var count = 1 +if (count == 3){ + // evaluated if count is 3 +} else if (count == 4) { + // evaluated if count is 4 +} else { + // evaluated if it's not either 3 or 4 +} + +// As does while. +while (true) { + // An infinite loop! +} + +// Do-while loops are like while loops, except they always run at least once. +var input +do { + input = getInput() +} while (!isValid(input)) + +// the for loop is the same as C and Java: +// initialisation; continue condition; iteration. +for (var i = 0; i < 5; i++){ + // will run 5 times +} + +// && is logical and, || is logical or +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear" +} +if (colour == "red" || colour == "blue"){ + // colour is either red or blue +} + +// && and || "short circuit", which is useful for setting default values. +var name = otherName || "default" + +/////////////////////////////////// +// 4. Functions, Scope and Closures + +// JavaScript functions are declared with the function keyword. +function myFunction(thing){ + return thing.toUpperCase() +} +myFunction("foo") // = "FOO" + +// Functions can also be defined "anonymously" - without a name: +function(thing){ + return thing.toLowerCase() +} +// (we can't call our function, since we don't have a name to refer to it with) + +// JavaScript functions are first class objects, so they can be reassigned to +// different variable names and passed to other functions as arguments - for +// example, when supplying an event handler: +function myFunction(){ + // this code will be called in 5 seconds' time +} +setTimeout(myFunction, 5000) + +// You can even write the function statement directly in the call to the other +// function. + +setTimeout(function myFunction(){ + // this code will be called in 5 seconds' time +}, 5000) + +// JavaScript has function scope; functions get their own scope but other blocks +// do not. +if (true){ + var i = 5 +} +i // = 5 - not undefined as you'd expect in a block-scoped language + +// This has led to a common pattern of "immediately-executing anonymous +// functions", which prevent temporary variables from leaking into the global +// scope. +function(){ + var temporary = 5 + // We can access the global scope by assiging to the 'global object', which + // in a web browser is always 'window'. The global object may have a + // different name in non-browser environments such as Node.js. + window.permanent = 10 + // Or, as previously mentioned, we can just leave the var keyword off. + permanent2 = 15 +}() +temporary // raises ReferenceError +permanent // = 10 +permanent2 // = 15 + +// One of JavaScript's most powerful features is closures. If a function is +// defined inside another function, the inner function has access to all the +// outer function's variables. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!" + function inner(){ + alert(prompt) + } + setTimeout(inner, 5000) + // setTimeout is asynchronous, so this function will finish without waiting + // 5 seconds. However, once the 5 seconds is up, inner will still have + // access to the value of prompt. +} +sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s + +/////////////////////////////////// +// 5. More about Objects; Constructors and Prototypes + +// Objects can contain functions. +var myObj = { + myFunc: function(){ + return "Hello world!" + } +} +myObj.myFunc() // = "Hello world!" + +// When functions attached to an object are called, they can access the object +// they're attached to using the this keyword. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString + } +} +myObj.myFunc() // = "Hello world!" + +// What this is set to has to do with how the function is called, not where +// it's defined. So, our function doesn't work if it isn't called in the +// context of the object. +var myFunc = myObj.myFunc +myFunc() // = undefined + +// Inversely, a function can be assigned to the object and gain access to it +// through this, even if it wasn't attached when it was defined. +var myOtherFunc = function(){ + return this.myString.toUpperCase() +} +myObj.myOtherFunc = myOtherFunc +myObj.myOtherFunc() // = "HELLO WORLD!" + +// When you call a function with the new keyword, a new object is created, and +// made available to the function via this. Functions designed to be called +// like this are called constructors. + +var MyConstructor = function(){ + this.myNumber = 5 +} +myNewObj = new MyConstructor() // = {myNumber: 5} +myNewObj.myNumber // = 5 + +// Every JavaScript object has a 'prototype'. When you go to access a property +// on an object that doesn't exist on the actual object, the interpreter will +// look at its prototype. + +// Some JS implementations let you access an object's prototype on the magic +// property __proto__. While this is useful for explaining prototypes it's not +// part of the standard; we'll get to standard ways of using prototypes later. +var myObj = { + myString: "Hello world!", +} +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +} +myObj.__proto__ = myPrototype +myObj.meaningOfLife // = 42 + +// This works for functions, too. +myObj.myFunc() // = "hello world!" + +// Of course, if your property isn't on your prototype, the prototype's +// prototype is searched, and so on. +myPrototype.__proto__ = { + myBoolean: true +} +myObj.myBoolean // = true + +// There's no copying involved here; each object stores a reference to its +// prototype. This means we can alter the prototype and our changes will be +// reflected everywhere. +myPrototype.meaningOfLife = 43 +myObj.meaningOfLife // = 43 + +// We mentioned that __proto__ was non-standard, and there's no standard way to +// change the prototype of an existing object. However, there's two ways to +// create a new object with a given prototype. + +// The first is Object.create, which is a recent addition to JS, and therefore +// not available in all implementations yet. +var myObj = Object.create(myPrototype) +myObj.meaningOfLife // = 43 + +// The second way, which works anywhere, has to do with constructors. +// Constructors have a property called prototype. This is *not* the prototype of +// the constructor function itself; instead, it's the prototype that new objects +// are given when they're created with that constructor and the new keyword. +myConstructor.prototype = { + getMyNumber: function(){ + return this.myNumber + } +} +var myNewObj2 = new myConstructor() +myNewObj2.getMyNumber() // = 5 + +// Built-in types like strings and numbers also have constructors that create +// equivalent wrapper objects. +var myNumber = 12 +var myNumberObj = new Number(12) +myNumber == myNumberObj // = true + +// Except, they aren't exactly equivalent. +typeof(myNumber) // = 'number' +typeof(myNumberObj) // = 'object' +myNumber === myNumberObj // = false +if (0){ + // This code won't execute, because 0 is falsy. +} +if (Number(0)){ + // This code *will* execute, because Number(0) is truthy. +} + +// However, the wrapper objects and the regular builtins share a prototype, so +// you can actually add functionality to a string, for instance. +String.prototype.firstCharacter = function(){ + return this.charAt(0) +} +"abc".firstCharacter() // = "a" + +// This fact is often used in "polyfilling", which is implementing newer +// features of JavaScript in an older subset of JavaScript, so that they can be +// used in older environments such as outdated browsers. + +// For instance, we mentioned that Object.create isn't yet available in all +// implementations, but we can still use it with this polyfill: +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){} + Constructor.prototype = proto + // then use it to create a new, appropriately-prototyped object + return new Constructor() + } +} +``` + +## Further Reading + +The [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides +excellent documentation for JavaScript as it's used in browsers. Plus, it's a +wiki, so as you learn more you can help others out by sharing your own +knowledge. + +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +covers much of the concepts covered here in more detail. This guide has quite +deliberately only covered the JavaScript language itself; if you want to learn +more about how to use JavaScript in web pages, start by learning about the +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +In addition to direct contributors to this article, some content is adapted +from Louie Dinh's Python tutorial on this site, and the [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +on the Mozilla Developer Network. diff --git a/julia.html.markdown b/julia.html.markdown new file mode 100644 index 00000000..1023e303 --- /dev/null +++ b/julia.html.markdown @@ -0,0 +1,525 @@ +--- +language: julia +contributors: + - ["Leah Hanson", "http://leahhanson.us"] +filename: learnjulia.jl +--- + +Julia is a new homoiconic functional language focused on technical computing. +While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. + +This is based on the current development version of Julia, as of June 29th, 2013. + +```ruby + +# Single line comments start with a hash. + +#################################################### +## 1. Primitive Datatypes and Operators +#################################################### + +# Everything in Julia is a expression. + +# You have numbers +3 #=> 3 (Int64) +3.2 #=> 3.2 (Float64) +2 + 1im #=> 2 + 1im (Complex{Int64}) +2//3 #=> 2//3 (Rational{Int64}) + +# Math is what you would expect +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7.0 +5 \ 35 #=> 7.0 +5 / 2 #=> 2.5 +div(5, 2) #=> 2 +2 ^ 2 #=> 4 # power, not bitwise xor +12 % 10 #=> 2 + +# Enforce precedence with parentheses +(1 + 3) * 2 #=> 8 + +# Bitwise Operators +~2 #=> -3 # bitwise not +3 & 5 #=> 1 # bitwise and +2 | 4 #=> 6 # bitwise or +2 $ 4 #=> 6 # bitwise xor +2 >>> 1 #=> 1 # logical shift right +2 >> 1 #=> 1 # arithmetic shift right +2 << 1 #=> 4 # logical/arithmetic shift left + +# You can use the bits function to see the binary representation of a number. +bits(12345) +#=> "0000000000000000000000000000000000000000000000000011000000111001" +bits(12345.0) +#=> "0100000011001000000111001000000000000000000000000000000000000000" + +# Boolean values are primitives +true +false + +# Boolean operators +!true #=> false +!false #=> true +1 == 1 #=> true +2 == 1 #=> false +1 != 1 #=> false +2 != 1 #=> true +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true +# Comparisons can be chained +1 < 2 < 3 #=> true +2 < 3 < 2 #=> false + +# Strings are created with " +"This is a string." + +# Character literals written with ' +'a' + +# A string can be treated like a list of characters +"This is a string"[1] #=> 'T' # Julia indexes from 1 + +# $ can be used for string interpolation: +"2 + 2 = $(2 + 2)" #=> "2 + 2 = 4" +# You can put any Julia expression inside the parenthesis. + +# Another way to format strings is the printf macro. +@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 + +#################################################### +## 2. Variables and Collections +#################################################### + +# Printing is pretty easy +println("I'm Julia. Nice to meet you!") + +# No need to declare variables before assigning to them. +some_var = 5 #=> 5 +some_var #=> 5 + +# Accessing a previously unassigned variable is an error +try + some_other_var #=> ERROR: some_other_var not defined +catch e + println(e) +end + +# Variable name start with a letter. You can use uppercase letters, digits, +# and exclamation points as well after the initial alphabetic character. +SomeOtherVar123! = 6 #=> 6 + +# You can also use unicode characters +☃ = 8 #=> 8 + +# A note on naming conventions in Julia: +# +# * Names of variables are in lower case, with word separation indicated by +# underscores ('\_'). +# +# * Names of Types begin with a capital letter and word separation is shown +# with CamelCase instead of underscores. +# +# * Names of functions and macros are in lower case, without underscores. +# +# * Functions that modify their inputs have names that end in !. These +# functions are sometimes called mutating functions or in-place functions. + +# Arrays store a sequence of values indexed by integers 1 through n: +a = Int64[] #=> 0-element Int64 Array + +# 1-dimensional array literals can be written with comma-separated values. +b = [4, 5, 6] #=> 3-element Int64 Array: [4, 5, 6] +b[1] #=> 4 +b[end] #=> 6 + +# 2-dimentional arrays use space-separated values and semicolon-separated rows. +matrix = [1 2; 3 4] #=> 2x2 Int64 Array: [1 2; 3 4] + +# Add stuff to the end of a list with push! and append! +push!(a,1) #=> [1] +push!(a,2) #=> [1,2] +push!(a,4) #=> [1,2,4] +push!(a,3) #=> [1,2,4,3] +append!(a,b) #=> [1,2,4,3,4,5,6] + +# Remove from the end with pop +pop!(a) #=> 6 and b is now [4,5] + +# Let's put it back +push!(b,6) # b is now [4,5,6] again. + +a[1] #=> 1 # remember that Julia indexes from 1, not 0! + +# end is a shorthand for the last index. It can be used in any +# indexing expression +a[end] #=> 6 + +# Function names that end in exclamations points indicate that they modify +# their argument. +arr = [5,4,6] #=> 3-element Int64 Array: [5,4,6] +sort(arr) #=> [4,5,6]; arr is still [5,4,6] +sort!(arr) #=> [4,5,6]; arr is now [4,5,6] + +# Looking out of bounds is a BoundsError +try + a[0] #=> ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] #=> ERROR: BoundsError() in getindex at array.jl:270 +catch e + println(e) +end + +# Errors list the line and file they came from, even if it's in the standard +# library. If you built Julia from source, you can look in the folder base +# inside the julia folder to find these files. + +# You can initialize arrays from ranges +a = [1:5] #=> 5-element Int64 Array: [1,2,3,4,5] + +# You can look at ranges with slice syntax. +a[1:3] #=> [1, 2, 3] +a[2:] #=> [2, 3, 4, 5] + +# Remove arbitrary elements from a list with splice! +arr = [3,4,5] +splice!(arr,2) #=> 4 ; arr is now [3,5] + +# Concatenate lists with append! +b = [1,2,3] +append!(a,b) # Now a is [1, 3, 4, 5, 1, 2, 3] + +# Check for existence in a list with contains +contains(a,1) #=> true + +# Examine the length with length +length(a) #=> 7 + +# Tuples are immutable. +tup = (1, 2, 3) #=>(1,2,3) # an (Int64,Int64,Int64) tuple. +tup[1] #=> 1 +try: + tup[0] = 3 #=> ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +catch e + println(e) +end + +# Many list functions also work on tuples +length(tup) #=> 3 +tup[1:2] #=> (1,2) +contains(tup,2) #=> true + +# You can unpack tuples into variables +a, b, c = (1, 2, 3) #=> (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 #=> (4,5,6) + +# Now look how easy it is to swap two values +e, d = d, e #=> (5,4) # d is now 5 and e is now 4 + + +# Dictionaries store mappings +empty_dict = Dict() #=> Dict{Any,Any}() + +# Here is a prefilled dictionary +filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +# => Dict{ASCIIString,Int64} + +# Look up values with [] +filled_dict["one"] #=> 1 + +# Get all keys +keys(filled_dict) +#=> KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# Note - dictionary keys are not sorted or in the order you inserted them. + +# Get all values +values(filled_dict) +#=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# Note - Same as above regarding key ordering. + +# Check for existence of keys in a dictionary with contains, haskey +contains(filled_dict, ("one", 1)) #=> true +contains(filled_dict, ("two", 3)) #=> false +haskey(filled_dict, "one") #=> true +haskey(filled_dict, 1) #=> false + +# Trying to look up a non-existing key will raise an error +try + filled_dict["four"] #=> ERROR: key not found: four in getindex at dict.jl:489 +catch e + println(e) +end + +# Use get method to avoid the error +# get(dictionary,key,default_value) +get(filled_dict,"one",4) #=> 1 +get(filled_dict,"four",4) #=> 4 + +# Sets store sets +empty_set = Set() #=> Set{Any}() +# Initialize a set with a bunch of values +filled_set = Set(1,2,2,3,4) #=> Set{Int64}(1,2,3,4) + +# Add more items to a set +add!(filled_set,5) #=> Set{Int64}(5,4,2,3,1) + +# There are functions for set intersection, union, and difference. +other_set = Set(3, 4, 5, 6) #=> Set{Int64}(6,4,5,3) +intersect(filled_set, other_set) #=> Set{Int64}(3,4,5) +union(filled_set, other_set) #=> Set{Int64}(1,2,3,4,5,6) +setdiff(Set(1,2,3,4),Set(2,3,5)) #=> Set{Int64}(1,4) + +# Check for existence in a set with contains +contains(filled_set,2) #=> true +contains(filled_set,10) #=> false + + +#################################################### +## 3. Control Flow +#################################################### + +# Let's make a variable +some_var = 5 + +# Here is an if statement. Indentation is NOT meaningful in Julia. +# prints "some var is smaller than 10" +if some_var > 10 + println("some_var is totally bigger than 10.") +elseif some_var < 10 # This elseif clause is optional. + println("some_var is smaller than 10.") +else # The else clause is optional too. + println("some_var is indeed 10.") +end + + +# For loops iterate over iterables, such as ranges, lists, sets, dicts, strings. + +for animal=["dog", "cat", "mouse"] + # You can use $ to interpolate into strings + println("$animal is a mammal") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# You can use in instead of =, if you want. +for animal in ["dog", "cat", "mouse"] + println("$animal is a mammal") +end + +for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$(a[1]) is $(a[2])") +end + +for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$k is $v") +end + + +# While loops go until a condition is no longer met. +# prints: +# 0 +# 1 +# 2 +# 3 +x = 0 +while x < 4 + println(x) + x += 1 # Shorthand for x = x + 1 +end + +# Handle exceptions with a try/except block +try + error("help") +catch e + println("caught it $e") +end +#=> caught it ErrorException("help") + + +#################################################### +## 4. Functions +#################################################### + +# Use the keyword function to create new functions +function add(x, y) + println("x is $x and y is $y") + + # Functions implicitly return the value of their last statement + x + y +end + +add(5, 6) #=> 11 after printing out "x is 5 and y is 6" + +# You can define functions that take a variable number of +# positional arguments +function varargs(args...) + return args +end + +varargs(1,2,3) #=> (1,2,3) + +# The ... is called a splat. +# It can also be used in a fuction call +# to splat a list or tuple out to be the arguments +Set([1,2,3]) #=> Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays +Set([1,2,3]...) #=> Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) + +x = (1,2,3) #=> (1,2,3) +Set(x) #=> Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples +Set(x...) #=> Set{Int64}(2,3,1) + + +# You can define functions with optional positional arguments +function defaults(a,b,x=5,y=6) + return "$a $b and $x $y" +end + +defaults('h','g') #=> "h g and 5 6" +defaults('h','g','j') #=> "h g and j 6" +defaults('h','g','j','k') #=> "h g and j k" +try + defaults('h') #=> ERROR: no method defaults(Char,) + defaults() #=> ERROR: no methods defaults() +catch e +println(e) +end + +# You can define functions that take keyword arguments +function keyword_args(;k1=4,name2="hello") # note the ; + return ["k1"=>k1,"name2"=>name2] +end + +keyword_args(name2="ness") #=> ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") #=> ["k1"=>"mine","name2"=>"hello"] +keyword_args() #=> ["name2"=>"hello","k2"=>4] + +# You can also do both at once +function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") + println("normal arg: $normal_arg") + println("optional arg: $optional_positional_arg") + println("keyword arg: $keyword_arg") +end + +all_the_args(1, 3, keyword_arg=4) +# prints: +# normal arg: 1 +# optional arg: 3 +# keyword arg: 4 + +# Julia has first class functions +function create_adder(x) + adder = function (y) + return x + y + end + return adder +end + +# or equivalently +function create_adder(x) + y -> x + y +end + +# you can also name the internal function, if you want +function create_adder(x) + function adder(y) + x + y + end + adder +end + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# The first two inner functions above are anonymous functions +(x -> x > 2)(3) #=> true + +# There are built-in higher order functions +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# We can use list comprehensions for nice maps and filters +[add_10(i) for i=[1, 2, 3]] #=> [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] + +#################################################### +## 5. Types and Multiple-Dispatch +#################################################### + +# Type definition +type Tiger + taillength::Float64 + coatcolor # no type annotation is implicitly Any +end +# default constructor is the properties in order +# so, Tiger(taillength,coatcolor) + +# Type instantiation +tigger = Tiger(3.5,"orange") # the type doubles as the constructor function + +# Abtract Types +abstract Cat # just a name and point in the type hierarchy + +# * types defined with the type keyword are concrete types; they can be +# instantiated +# +# * types defined with the abstract keyword are abstract types; they can +# have subtypes. +# +# * each type has one supertype; a supertype can have zero or more subtypes. + +type Lion <: Cat # Lion is a subtype of Cat + mane_color + roar::String +end + +type Panther <: Cat # Panther is also a subtype of Cat + eye_color + Panther() = new("green") + # Panthers will only have this constructor, and no default constructor. +end + +# Multiple Dispatch + +# In Julia, all named functions are generic functions +# This means that they are built up from many small methods +# For example, let's make a function meow: +function meow(cat::Lion) + cat.roar # access properties using dot notation +end + +function meow(cat::Panther) + "grrr" +end + +function meow(cat::Tiger) + "rawwwr" +end + +meow(tigger) #=> "rawwr" +meow(Lion("brown","ROAAR")) #=> "ROAAR" +meow(Panther()) #=> "grrr" + +function pet_cat(cat::Cat) + println("The cat says $(meow(cat))") +end + +try + pet_cat(tigger) #=> ERROR: no method pet_cat(Tiger,) +catch e + println(e) +end + +pet_cat(Lion(Panther(),"42")) #=> prints "The cat says 42" + +``` + +## Further Reading + +You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) + diff --git a/livescript.html.markdown b/livescript.html.markdown new file mode 100644 index 00000000..8e11439b --- /dev/null +++ b/livescript.html.markdown @@ -0,0 +1,345 @@ +--- +language: LiveScript +filename: learnLivescript.ls +contributors: + - ["Christina Whyte", "http://github.com/kurisuwhyte/"] +--- + +LiveScript is a functional compile-to-JavaScript language which shares +most of the underlying semantics with its host language. Nice additions +comes with currying, function composition, pattern matching and lots of +other goodies heavily borrowed from languages like Haskell, F# and +Scala. + +LiveScript is a fork of [Coco][], which is itself a fork of +[CoffeeScript][]. The language is stable, and a new version is in active +development to bring a plethora of new niceties! + +[Coco]: http://satyr.github.io/coco/ +[CoffeeScript]: http://coffeescript.org/ + +Feedback is always welcome, so feel free to reach me over at +[@kurisuwhyte](https://twitter.com/kurisuwhyte) :) + + +```coffeescript +# Just like its CoffeeScript cousin, LiveScript uses hash symbols for +# single-line comments. + +/* + Multi-line comments are written C-style. Use them if you want comments + to be preserved in the JavaScript output. + */ +``` +```coffeescript +# As far as syntax goes, LiveScript uses indentation to delimit blocks, +# rather than curly braces, and whitespace to apply functions, rather +# than parenthesis. + + +######################################################################## +## 1. Basic values +######################################################################## + +# Lack of value is defined by the keyword `void` instead of `undefined` +void # same as `undefined` but safer (can't be overridden) + +# No valid value is represented by Null. +null + + +# The most basic actual value is the logical type: +true +false + +# And it has a plethora of aliases that mean the same thing: +on; off +yes; no + + +# Then you get numbers. These are double-precision floats like in JS. +10 +0.4 # Note that the leading `0` is required + +# For readability, you may use underscores and letter suffixes in a +# number, and these will be ignored by the compiler. +12_344km + + +# Strings are immutable sequences of characters, like in JS: +"Christina" # apostrophes are okay too! +"""Multi-line + strings + are + okay + too.""" + +# Sometimes you want to encode a keyword, the backslash notation makes +# this easy: +\keyword # => 'keyword' + + +# Arrays are ordered collections of values. +fruits = + * \apple + * \orange + * \pear + +# They can be expressed more concisely with square brackets: +fruits = [ \apple, \orange, \pear ] + +# You also get a convenient way to create a list of strings, using +# white space to delimit the items. +fruits = <[ apple orange pear ]> + +# You can retrieve an item by their 0-based index: +fruits[0] # => "apple" + +# Objects are a collection of unordered key/value pairs, and a few other +# things (more on that later). +person = + name: "Christina" + likes: + * "kittens" + * "and other cute stuff" + +# Again, you can express them concisely with curly brackets: +person = {name: "Christina", likes: ["kittens", "and other cute stuff"]} + +# You can retrieve an item by their key: +person.name # => "Christina" +person["name"] # => "Christina" + + +# Regular expressions use the same syntax as JavaScript: +trailing-space = /\s$/ # dashed-words become dashedWords + +# Except you can do multi-line expressions too! +# (comments and whitespace just gets ignored) +funRE = // + function\s+(.+) # name + \s* \((.*)\) \s* # arguments + { (.*) } # body + // + + +######################################################################## +## 2. Basic operations +######################################################################## + +# Arithmetic operators are the same as JavaScript's: +1 + 2 # => 3 +2 - 1 # => 1 +2 * 3 # => 6 +4 / 2 # => 2 +3 % 2 # => 1 + + +# Comparisons are mostly the same too, except that `==` and `===` are +# inverted. +2 == 2 # => true +2 == "2" # => false +2 === "2" # => true + +# Other relational operators include <, <=, > and >= + +# Logical values can be combined through the logical operators `or`, +# `and` and `not` +true and false # => false +false or true # => true +not false # => true + + +# Collections also get some nice additional operators +[1, 2] ++ [3, 4] # => [1, 2, 3, 4] +'a' in <[ a b c ]> # => true +'name' of { name: 'Chris' } # => true + + +######################################################################## +## 3. Functions +######################################################################## + +# Since LiveScript is functional, you'd expect functions to get a nice +# treatment. In LiveScript it's even more apparent that functions are +# first class: +add = (left, right) -> left + right +add 1, 2 # => 3 + +# Functions which take no arguments are called with a bang! +two = -> 2 +two! + +# LiveScript uses function scope, just like JavaScript, and has proper +# closures too. Unlike JavaScript, the `=` works as a declaration +# operator, and will always declare the variable on the left hand side. + +# The `:=` operator is available to *reuse* a name from the parent +# scope. + + +# You can destructure arguments of a function to quickly get to +# interesting values inside a complex data structure: +tail = ([head, ...rest]) -> rest +tail [1, 2, 3] # => [2, 3] + +# You can also transform the arguments using binary or unary +# operators. Default arguments are also possible. +foo = (a = 1, b = 2) -> a + b +foo! # => 3 + +# You could use it to clone a particular argument to avoid side-effects, +# for example: +copy = (^^target, source) -> + for k,v of source => target[k] = v + target +a = { a: 1 } +copy a, { b: 2 } # => { a: 1, b: 2 } +a # => { a: 1 } + + +# A function may be curried by using a long arrow rather than a short +# one: +add = (left, right) --> left + right +add1 = add 1 +add1 2 # => 3 + +# Functions get an implicit `it` argument, even if you don't declare +# any. +identity = -> it +identity 1 # => 1 + +# Operators are not functions in LiveScript, but you can easily turn +# them into one! Enter the operator sectioning: +divide-by-2 = (/ 2) +[2, 4, 8, 16].map(divide-by-2) .reduce (+) + + +# Not only of function application lives LiveScript, as in any good +# functional language you get facilities for composing them: +double-minus-one = (- 1) . (* 2) + +# Other than the usual `f . g` mathematical formulae, you get the `>>` +# and `<<` operators, that describe how the flow of values through the +# functions. +double-minus-one = (* 2) >> (- 1) +double-minus-one = (- 1) << (* 2) + + +# And talking about flow of value, LiveScript gets the `|>` and `<|` +# operators that apply a value to a function: +map = (f, xs) --> xs.map f +[1 2 3] |> map (* 2) # => [2 4 6] + +# You can also choose where you want the value to be placed, just mark +# the place with an underscore (_): +reduce = (f, xs, initial) --> xs.reduce f, initial +[1 2 3] |> reduce (+), _, 0 # => 6 + + +# The underscore is also used in regular partial application, which you +# can use for any function: +div = (left, right) -> left / right +div-by-2 = div _, 2 +div-by-2 4 # => 2 + + +# Last, but not least, LiveScript has back-calls, which might help +# with some callback-based code (though you should try more functional +# approaches, like Promises): +readFile = (name, f) -> f name +a <- readFile 'foo' +b <- readFile 'bar' +console.log a + b + +# Same as: +readFile 'foo', (a) -> readFile 'bar', (b) -> console.log a + b + + +######################################################################## +## 4. Patterns, guards and control-flow +######################################################################## + +# You can branch computations with the `if...else` expression: +x = if n > 0 then \positive else \negative + +# Instead of `then`, you can use `=>` +x = if n > 0 => \positive + else \negative + +# Complex conditions are better-off expressed with the `switch` +# expression, though: +y = {} +x = switch + | (typeof y) is \number => \number + | (typeof y) is \string => \string + | 'length' of y => \array + | otherwise => \object # `otherwise` and `_` always matches. + +# Function bodies, declarations and assignments get a free `switch`, so +# you don't need to type it again: +take = (n, [x, ...xs]) --> + | n == 0 => [] + | _ => [x] ++ take (n - 1), xs + + +######################################################################## +## 5. Comprehensions +######################################################################## + +# While the functional helpers for dealing with lists and objects are +# right there in the JavaScript's standard library (and complemented on +# the prelude-ls, which is a "standard library" for LiveScript), +# comprehensions will usually allow you to do this stuff faster and with +# a nice syntax: +oneToTwenty = [1 to 20] +evens = [x for x in oneToTwenty when x % 2 == 0] + +# `when` and `unless` can be used as filters in the comprehension. + +# Object comprehension works in the same way, except that it gives you +# back an object rather than an Array: +copy = { [k, v] for k, v of source } + + +######################################################################## +## 4. OOP +######################################################################## + +# While LiveScript is a functional language in most aspects, it also has +# some niceties for imperative and object oriented programming. One of +# them is class syntax and some class sugar inherited from CoffeeScript: +class Animal + (@name, kind) -> + @kind = kind + action: (what) -> "*#{@name} (a #{@kind}) #{what}*" + +class Cat extends Animal + (@name) -> super @name, 'cat' + purr: -> @action 'purrs' + +kitten = new Cat 'Mei' +kitten.purr! # => "*Mei (a cat) purrs*" + +# Besides the classical single-inheritance pattern, you can also provide +# as many mixins as you would like for a class. Mixins are just plain +# objects: +Huggable = + hug: -> @action 'is hugged' + +class SnugglyCat extends Cat implements Huggable + +kitten = new SnugglyCat 'Purr' +kitten.hug! # => "*Mei (a cat) is hugged*" +``` + +## Further reading + +There's just so much more to LiveScript, but this should be enough to +get you started writing little functional things in it. The +[official website](http://livescript.net/) has a lot of information on the +language, and a nice online compiler for you to try stuff out! + +You may also want to grab yourself some +[prelude.ls](http://gkz.github.io/prelude-ls/), and check out the `#livescript` +channel on the Freenode network. diff --git a/lua.html.markdown b/lua.html.markdown index 4df57a92..0ece399f 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -1,7 +1,7 @@ --- language: lua -author: Tyler Neylon -author_url: http://tylerneylon.com/ +contributors: + - ["Tyler Neylon", "http://tylerneylon.com/"] filename: learnlua.lua --- diff --git a/php.html.markdown b/php.html.markdown index 75bbd214..e81b88fd 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -1,7 +1,8 @@ --- language: php -author: Malcolm Fell -author_url: http://emarref.net/ +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] filename: learnphp.php --- @@ -47,9 +48,9 @@ $boolean = true; // or TRUE or True $boolean = false; // or FALSE or False // Integers -$int1 = 19; // => 19 -$int2 = -19; // => -19 -$int3 = 019; // => 15 (a leading 0 denotes an octal number) +$int1 = 12; // => 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (a leading 0 denotes an octal number) $int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) // Floats (aka doubles) @@ -231,6 +232,9 @@ if (false) { print 'Does'; } +// ternary operator +print (false ? 'Does not get printed' : 'Does'); + $x = 0; if ($x === '0') { print 'Does not print'; @@ -240,6 +244,8 @@ if ($x === '0') { print 'Does print'; } + + // This alternative syntax is useful for templates: ?> @@ -375,9 +381,6 @@ echo $function_name(1, 2); // => 3 * Includes */ -/* -``` -```php <?php // PHP within included files must also begin with a PHP open tag. @@ -521,6 +524,12 @@ interface InterfaceTwo public function doSomethingElse(); } +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + abstract class MyAbstractClass implements InterfaceOne { public $x = 'doSomething'; @@ -585,9 +594,6 @@ $cls->myTraitMethod(); // Prints "I have MyTrait" // This section is separate, because a namespace declaration // must be the first statement in a file. Let's pretend that is not the case -/* -``` -```php <?php // By default, classes exist in the global namespace, and can diff --git a/python.html.markdown b/python.html.markdown index 467a179e..e7ee6fbd 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -1,12 +1,12 @@ --- language: python -author: Louie Dinh -author_url: http://ldinh.ca +contributors: + - ["Louie Dinh", "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 -languages in existence. I fell in love with Python for it's syntactic clarity. It's basically +languages in existence. I fell in love with Python for its syntactic clarity. Its basically executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] @@ -87,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 @@ -104,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 = 1 if 1 > 2 else 2 # => 2 -# 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 = [] @@ -136,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.) @@ -164,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 @@ -178,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 @@ -207,16 +214,12 @@ filled_dict.values() #=> [3, 2, 1] "one" in filled_dict #=> True 1 in filled_dict #=> False -try: - # Trying to look up a non-existing key will raise a KeyError - filled_dict["four"] #=> KeyError -except KeyError: - pass + # 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 @@ -259,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." @@ -279,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. @@ -302,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 @@ -319,7 +328,8 @@ def add(x, y): return x + y # Return values with a return statement # Calling functions with parameters -add(5, 6) #=> 11 and prints out "x is 5 and y is 6" +add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11 + # Another way to call functions is with keyword arguments add(y=6, x=5) # Keyword arguments can arrive in any order. @@ -340,21 +350,22 @@ def keyword_args(**kwargs): keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} # You can do both at once, if you like -def foo(*args, **kwargs): +def all_the_args(*args, **kwargs): print args 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): @@ -424,9 +435,47 @@ 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. + +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + + ``` ## 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/) diff --git a/r.html.markdown b/r.html.markdown index f68ede0e..0240e8fb 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -1,11 +1,11 @@ --- language: R -author: e99n09 -author_url: http://github.com/e99n09 +contributors: + - ["e99n09", "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,24 +131,36 @@ 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 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" # 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) @@ -192,7 +209,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 +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,7 +291,8 @@ 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. @@ -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 diff --git a/racket.html.markdown b/racket.html.markdown new file mode 100644 index 00000000..b6c1f86b --- /dev/null +++ b/racket.html.markdown @@ -0,0 +1,602 @@ +--- + +language: racket +filename: learnracket.rkt +contributors: + - ["th3rac25", "https://github.com/voila"] + - ["Eli Barzilay", "https://github.com/elibarzilay"] +--- + +Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family. + +Feedback is appreciated! You can reach me at [@th3rac25](http://twitter.com/th3rac25) or th3rac25 [at] [google's email service] + + +```racket +#lang racket ; defines the language we are using + +;;; Comments + +;; Single line comments start with a semicolon + +#| Block comments + can span multiple lines and... + #| + they can be nested! + |# +|# + +;; S-expression comments discard the following expression, +;; useful to comment expressions when debugging +#; (this expression is discarded) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Primitive Datatypes and Operators +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Numbers +9999999999999999999999 ; integers +#b111 ; binary => 7 +#o111 ; octal => 73 +#x111 ; hexadecimal => 273 +3.14 ; reals +6.02e+23 +1/2 ; rationals +1+2i ; complex numbers + +;; Function application is written (f x y z ...) +;; where f is a function and x, y, z, ... are operands +;; If you want to create a literal list of data, use ' to stop it from +;; being evaluated +'(+ 1 2) ; => (+ 1 2) +;; Now, some arithmetic operations +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(quotient 5 2) ; => 2 +(remainder 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(exact->inexact 1/3) ; => 0.3333333333333333 +(+ 1+2i 2-3i) ; => 3-1i + +;;; Booleans +#t ; for true +#f ; for false -- any value other than #f is true +(not #t) ; => #f +(and 0 #f (error "doesn't get here")) ; => #f +(or #f 0 (error "doesn't get here")) ; => 0 + +;;; Characters +#\A ; => #\A +#\λ ; => #\λ +#\u03BB ; => #\λ + +;;; Strings are fixed-length array of characters. +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; backslash is an escaping character +"Foo\tbar\41\x21\u0021\a\r\n" ; includes C escapes, Unicode +"λx:(μα.α→α).xx" ; can include Unicode characters + +;; Strings can be added too! +(string-append "Hello " "world!") ; => "Hello world!" + +;; A string can be treated like a list of characters +(string-ref "Apple" 0) ; => #\A + +;; format can be used to format strings: +(format "~a can be ~a" "strings" "formatted") + +;; Printing is pretty easy +(printf "I'm Racket. Nice to meet you!\n") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variables +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; You can create a variable using define +;; a variable name can use any character except: ()[]{}",'`;#|\ +(define some-var 5) +some-var ; => 5 + +;; You can also use unicode characters +(define ⊆ subset?) +(⊆ (set 3 2) (set 1 2 3)) ; => #t + +;; Accessing a previously unassigned variable is an exception +; x ; => x: undefined ... + +;; Local binding: `me' is bound to "Bob" only within the (let ...) +(let ([me "Bob"]) + "Alice" + me) ; => "Bob" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Structs and Collections +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Structs +(struct dog (name breed age)) +(define my-pet + (dog "lassie" "collie" 5)) +my-pet ; => #<dog> +(dog? my-pet) ; => #t +(dog-name my-pet) ; => "lassie" + +;;; Pairs (immutable) +;; `cons' constructs pairs, `car' and `cdr' extract the first +;; and second elements +(cons 1 2) ; => '(1 . 2) +(car (cons 1 2)) ; => 1 +(cdr (cons 1 2)) ; => 2 + +;;; Lists + +;; Lists are linked-list data structures, made of `cons' pairs and end +;; with a `null' (or '()) to mark the end of the list +(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) +;; `list' is a convenience variadic constructor for lists +(list 1 2 3) ; => '(1 2 3) +;; and a quote can also be used for a literal list value +'(1 2 3) ; => '(1 2 3) + +;; Can still use `cons' to add an item to the beginning of a list +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; Use `append' to add lists together +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; Lists are a very basic type, so there is a *lot* of functionality for +;; them, a few examples: +(map add1 '(1 2 3)) ; => '(2 3 4) +(map + '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(filter even? '(1 2 3 4)) ; => '(2 4) +(count even? '(1 2 3 4)) ; => 2 +(take '(1 2 3 4) 2) ; => '(1 2) +(drop '(1 2 3 4) 2) ; => '(3 4) + +;;; Vectors + +;; Vectors are fixed-length arrays +#(1 2 3) ; => '#(1 2 3) + +;; Use `vector-append' to add vectors together +(vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; Sets + +;; Create a set from a list +(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) + +;; Add a member with `set-add' +;; (Functional: returns the extended set rather than mutate the input) +(set-add (set 1 2 3) 4) ; => (set 1 2 3 4) + +;; Remove one with `set-remove' +(set-remove (set 1 2 3) 1) ; => (set 2 3) + +;; Test for existence with `set-member?' +(set-member? (set 1 2 3) 1) ; => #t +(set-member? (set 1 2 3) 4) ; => #f + +;;; Hashes + +;; Create an immutable hash table (mutable example below) +(define m (hash 'a 1 'b 2 'c 3)) + +;; Retrieve a value +(hash-ref m 'a) ; => 1 + +;; Retrieving a non-present value is an exception +; (hash-ref m 'd) => no value found + +;; You can provide a default value for missing keys +(hash-ref m 'd 0) ; => 0 + +;; Use `hash-set' to extend an immutable hash table +;; (Returns the extended hash instdead of mutating it) +(define m2 (hash-set m 'd 4)) +m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) + +;; Remember, these hashes are immutable! +m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' + +;; Use `hash-remove' to remove keys (functional too) +(hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Functions +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `lambda' to create functions. +;; A function always returns the value of its last expression +(lambda () "Hello World") ; => #<procedure> +;; Can also use a unicode `λ' +(λ () "Hello World") ; => same function + +;; Use parens to call all functions, including a lambda expression +((lambda () "Hello World")) ; => "Hello World" +((λ () "Hello World")) ; => "Hello World" + +;; Assign a function to a var +(define hello-world (lambda () "Hello World")) +(hello-world) ; => "Hello World" + +;; You can shorten this using the function definition syntatcic sugae: +(define (hello-world2) "Hello World") + +;; The () in the above is the list of arguments for the function +(define hello + (lambda (name) + (string-append "Hello " name))) +(hello "Steve") ; => "Hello Steve" +;; ... or equivalently, using a sugared definition: +(define (hello2 name) + (string-append "Hello " name)) + +;; You can have multi-variadic functions too, using `case-lambda' +(define hello3 + (case-lambda + [() "Hello World"] + [(name) (string-append "Hello " name)])) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" +;; ... or specify optional arguments with a default value expression +(define (hello4 [name "World"]) + (string-append "Hello " name)) + +;; Functions can pack extra arguments up in a list +(define (count-args . args) + (format "You passed ~a args: ~a" (length args) args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" +;; ... or with the unsugared `lambda' form: +(define count-args2 + (lambda args + (format "You passed ~a args: ~a" (length args) args))) + +;; You can mix regular and packed arguments +(define (hello-count name . args) + (format "Hello ~a, you passed ~a extra args" name (length args))) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" +;; ... unsugared: +(define hello-count2 + (lambda (name . args) + (format "Hello ~a, you passed ~a extra args" name (length args)))) + +;; And with keywords +(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) + (format "~a ~a, ~a extra args" g name (length args))) +(hello-k) ; => "Hello World, 0 extra args" +(hello-k 1 2 3) ; => "Hello World, 3 extra args" +(hello-k #:greeting "Hi") ; => "Hi World, 0 extra args" +(hello-k #:name "Finn" #:greeting "Hey") ; => "Hey Finn, 0 extra args" +(hello-k 1 2 3 #:greeting "Hi" #:name "Finn" 4 5 6) + ; => "Hi Finn, 6 extra args" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Equality +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; for numbers use `=' +(= 3 3.0) ; => #t +(= 2 1) ; => #f + +;; for object identity use `eq?' +(eq? 3 3) ; => #t +(eq? 3 3.0) ; => #f +(eq? (list 3) (list 3)) ; => #f + +;; for collections use `equal?' +(equal? (list 'a 'b) (list 'a 'b)) ; => #t +(equal? (list 'a 'b) (list 'b 'a)) ; => #f + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Control Flow +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Conditionals + +(if #t ; test expression + "this is true" ; then expression + "this is false") ; else expression +; => "this is true" + +;; In conditionals, all non-#f values are treated as true +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(Groucho Zeppo) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'yep + +;; `cond' chains a series of tests to select a result +(cond [(> 2 2) (error "wrong!")] + [(< 2 2) (error "wrong again!")] + [else 'ok]) ; => 'ok + +;;; Pattern Matching + +(define (fizzbuzz? n) + (match (list (remainder n 3) (remainder n 5)) + [(list 0 0) 'fizzbuzz] + [(list 0 _) 'fizz] + [(list _ 0) 'buzz] + [_ #f])) + +(fizzbuzz? 15) ; => 'fizzbuzz +(fizzbuzz? 37) ; => #f + +;;; Loops + +;; Looping can be done through (tail-) recursion +(define (loop i) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) +(loop 5) ; => i=5, i=6, ... + +;; Similarly, with a named let +(let loop ((i 0)) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) ; => i=0, i=1, ... + +;; See below how to add a new `loop' form, but Racket already has a very +;; flexible `for' form for loops: +(for ([i 10]) + (printf "i=~a\n" i)) ; => i=0, i=1, ... +(for ([i (in-range 5 10)]) + (printf "i=~a\n" i)) ; => i=5, i=6, ... + +;;; Iteration Over Other Sequences +;; `for' allows iteration over many other kinds of sequences: +;; lists, vectors, strings, sets, hash tables, etc... + +(for ([i (in-list '(l i s t))]) + (displayln i)) + +(for ([i (in-vector #(v e c t o r))]) + (displayln i)) + +(for ([i (in-string "string")]) + (displayln i)) + +(for ([i (in-set (set 'x 'y 'z))]) + (displayln i)) + +(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))]) + (printf "key:~a value:~a\n" k v)) + +;;; More Complex Iterations + +;; Parallel scan of multiple sequences (stops on shortest) +(for ([i 10] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x 1:y 2:z + +;; Nested loops +(for* ([i 2] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x, 0:y, 0:z, 1:x, 1:y, 1:z + +;; Conditions +(for ([i 1000] + #:when (> i 5) + #:unless (odd? i) + #:break (> i 10)) + (printf "i=~a\n" i)) +; => i=6, i=8, i=10 + +;;; Comprehensions +;; Very similar to `for' loops -- just collect the results + +(for/list ([i '(1 2 3)]) + (add1 i)) ; => '(2 3 4) + +(for/list ([i '(1 2 3)] #:when (even? i)) + i) ; => '(2) + +(for/list ([i 10] [j '(x y z)]) + (list i j)) ; => '((0 x) (1 y) (2 z)) + +(for/list ([i 1000] #:when (> i 5) #:unless (odd? i) #:break (> i 10)) + i) ; => '(6 8 10) + +(for/hash ([i '(1 2 3)]) + (values i (number->string i))) +; => '#hash((1 . "1") (2 . "2") (3 . "3")) + +;; There are many kinds of other built-in ways to collect loop values: +(for/sum ([i 10]) (* i i)) ; => 285 +(for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000 +(for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t +(for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t +;; And to use any arbitrary combination, use `for/fold' +(for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 +;; (This can often replace common imperative loops) + +;;; Exceptions + +;; To catch exceptions, use the `with-handlers' form +(with-handlers ([exn:fail? (lambda (exn) 999)]) + (+ 1 "2")) ; => 999 +(with-handlers ([exn:break? (lambda (exn) "no time")]) + (sleep 3) + "phew") ; => "phew", but if you break it => "no time" + +;; Use `raise' to throw exceptions or any other value +(with-handlers ([number? ; catch numeric values raised + identity]) ; return them as plain values + (+ 1 (raise 2))) ; => 2 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutation +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `set!' to assign a new value to an existing variable +(define n 5) +(set! n (add1 n)) +n ; => 6 + +;; Use boxes for explicitly mutable values (similar to pointers or +;; references in other languages) +(define n* (box 5)) +(set-box! n* (add1 (unbox n*))) +(unbox n*) ; => 6 + +;; Many Racket datatypes are immutable (pairs, lists, etc), some come in +;; both mutable and immutable flavors (strings, vectors, hash tables, +;; etc...) + +;; Use `vector' or `make-vector' to create mutable vectors +(define vec (vector 2 2 3 4)) +(define wall (make-vector 100 'bottle-of-beer)) +;; Use vector-set! to update a slot +(vector-set! vec 0 1) +(vector-set! wall 99 'down) +vec ; => #(1 2 3 4) + +;; Create an empty mutable hash table and manipulate it +(define m3 (make-hash)) +(hash-set! m3 'a 1) +(hash-set! m3 'b 2) +(hash-set! m3 'c 3) +(hash-ref m3 'a) ; => 1 +(hash-ref m3 'd 0) ; => 0 +(hash-remove! m3 'a) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Modules +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Modules let you organize code into multiple files and reusable +;; libraries; here we use sub-modules, nested in the whole module that +;; this text makes (starting from the "#lang" line) + +(module cake racket/base ; define a `cake' module based on racket/base + + (provide print-cake) ; function exported by the module + + (define (print-cake n) + (show " ~a " n #\.) + (show " .-~a-. " n #\|) + (show " | ~a | " n #\space) + (show "---~a---" n #\-)) + + (define (show fmt n ch) ; internal function + (printf fmt (make-string n ch)) + (newline))) + +;; Use `require' to get all `provide'd names from a module +(require 'cake) ; the ' is for a local submodule +(print-cake 3) +; (show "~a" 1 #\A) ; => error, `show' was not exported + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. Classes and Objects +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Create a class fish% (-% is idomatic for class bindings) +(define fish% + (class object% + (init size) ; initialization argument + (super-new) ; superclass initialization + ;; Field + (define current-size size) + ;; Public methods + (define/public (get-size) + current-size) + (define/public (grow amt) + (set! current-size (+ amt current-size))) + (define/public (eat other-fish) + (grow (send other-fish get-size))))) + +;; Create an instance of fish% +(define charlie + (new fish% [size 10])) + +;; Use `send' to call an object's methods +(send charlie get-size) ; => 10 +(send charlie grow 6) +(send charlie get-size) ; => 16 + +;; `fish%' is a plain "first class" value, which can get us mixins +(define (add-color c%) + (class c% + (init color) + (super-new) + (define my-color color) + (define/public (get-color) my-color))) +(define colored-fish% (add-color fish%)) +(define charlie2 (new colored-fish% [size 10] [color 'red])) +(send charlie2 get-color) +;; or, with no names: +(send (new (add-color fish%) [size 10] [color 'red]) get-color) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 9. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros let you extend the syntax of the language + +;; Let's add a while loop +(define-syntax-rule (while condition body ...) + (let loop () + (when condition + body ... + (loop)))) + +(let ([i 0]) + (while (< i 10) + (displayln i) + (set! i (add1 i)))) + +;; Macros are hygienic, you cannot clobber existing variables! +(define-syntax-rule (swap! x y) ; -! is idomatic for mutation + (let ([tmp x]) + (set! x y) + (set! y tmp))) + +(define tmp 1) +(define a 2) +(define b 3) +(swap! a b) +(printf "tmp = ~a; a = ~a; b = ~a\n" tmp a b) ; tmp is unaffected + +;; But they are still code transformations, for example: +(define-syntax-rule (bad-while condition body ...) + (when condition + body ... + (bad-while condition body ...))) +;; this macro is broken: it generates infinite code, if you try to use +;; it, the compiler will get in an infinite loop + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 10. Contracts +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Contracts impose constraints on values exported from modules + +(module bank-account racket + (provide (contract-out + [deposit (-> positive? any)] ; amounts are always positive + [balance (-> positive?)])) + + (define amount 0) + (define (deposit a) (set! amount (+ amount a))) + (define (balance) amount) + ) + +(require 'bank-account) +(deposit 5) + +(balance) ; => 5 + +;; Clients that attempt to deposit a non-positive amount are blamed +;; (deposit -5) ; => deposit: contract violation +;; expected: positive? +;; given: -5 +;; more details.... +``` + +## Further Reading + +Still up for more? Try [Getting Started with Racket](http://docs.racket-lang.org/getting-started/) diff --git a/ruby.html.markdown b/ruby.html.markdown new file mode 100644 index 00000000..38d060a3 --- /dev/null +++ b/ruby.html.markdown @@ -0,0 +1,315 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] +--- + +```ruby +# This is a comment + +=begin +This is a multiline comment +No-one uses them +You shouldn't either +=end + +# First and foremost: Everything is an object. + +# Numbers are objects + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Some basic arithmetic +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Special values are objects +nil # Nothing to see here +true # truth +false # falsehood + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Equality +1 == 1 #=> true +2 == 1 #=> false + +# Inequality +1 != 1 #=> false +2 != 1 #=> true +!true #=> false +!false #=> true + +# apart from false itself, nil is the only other 'falsey' value + +!nil #=> true +!false #=> true +!0 #=> false + +# More comparisons +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Strings are objects + +'I am a string'.class #=> String +"I am a string too".class #=> String + +placeholder = "use string interpolation" +"I can #{placeholder} when using double quoted strings" +#=> "I can use string interpolation when using double quoted strings" + + +# print to the output +puts "I'm printing!" + +# Variables +x = 25 #=> 25 +x #=> 25 + +# Note that assignment returns the value assigned +# This means you can do multiple assignment: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# By convention, use snake_case for variable names +snake_case = true + +# Use descriptive variable names +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Symbols (are objects) +# Symbols are immutable, reusable constants represented internally by an +# integer value. They're often used instead of strings to efficiently convey +# specific, meaningful values + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# Arrays + +# This is an array +[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Arrays can contain different types of items + +array = [1, "hello", false] #=> => [1, "hello", false] + +# Arrays can be indexed +# From the front +array[0] #=> 1 +array[12] #=> nil + +# From the end +array[-1] #=> 5 + +# With a start and end index +array[2, 4] #=> [3, 4, 5] + +# Or with a range +array[1..3] #=> [2, 3, 4] + +# Add to an array like this +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# Hashes are Ruby's primary dictionary with keys/value pairs. +# Hashes are denoted with curly braces: +hash = {'color' => 'green', 'number' => 5} + +hash.keys #=> ['color', 'number'] + +# Hashes can be quickly looked up by key: +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# Asking a hash for a key that doesn't exist returns nil: +hash['nothing here'] #=> nil + +# Iterate over hashes with the #each method: +hash.each do |k, v| + puts "#{k} is #{v}" +end + +# Since Ruby 1.9, there's a special syntax when using symbols as keys: + +new_hash = { defcon: 3, action: true} + +new_hash.keys #=> [:defcon, :action] + +# Tip: Both Arrays and Hashes are Enumerable +# They share a lot of useful methods such as each, map, count, and more + +# Control structures + +if true + "if statement" +elsif false + "else if, optional" +else + "else, also optional" +end + +for counter in 1..5 + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# HOWEVER +# No-one uses for loops +# Use `each` instead, like this: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +grade = 'B' + +case grade +when 'A' + puts "Way to go kiddo" +when 'B' + puts "Better luck next time" +when 'C' + puts "You can do better" +when 'D' + puts "Scraping through" +when 'F' + puts "You failed!" +else + puts "Alternative grading system, eh?" +end + +# Functions + +def double(x) + x * 2 +end + +# Functions (and all blocks) implcitly return the value of the last statement +double(2) #=> 4 + +# Parentheses are optional where the result is unambiguous +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x,y) + x + y +end + +# Method arguments are separated by a comma +sum 3, 4 #=> 7 + +sum sum(3,4), 5 #=> 12 + +# yield +# All methods have an implicit, optional block parameter +# it can be called with the 'yield' keyword + +def surround + puts "{" + yield + puts "}" +end + +surround { puts 'hello world' } + +# { +# hello world +# } + + +# Define a class with the class keyword +class Human + + # A class variable. It is shared by all instances of this class. + @@species = "H. sapiens" + + # Basic initializer + def initialize(name, age=0) + # Assign the argument to the "name" instance variable for the instance + @name = name + # If no age given, we will fall back to the default in the arguments list. + @age = age + end + + # Basic setter method + def name=(name) + @name = name + end + + # Basic getter method + def name + @name + end + + # A class method uses self to distinguish from instance methods. + # It can only be called on the class, not an instance. + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end + +end + + +# Instantiate a class +jim = Human.new("Jim Halpert") + +dwight = Human.new("Dwight K. Schrute") + +# Let's call a couple of methods +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# Call the class method +Human.say("Hi") #=> "Hi" +``` diff --git a/scala.html.markdown b/scala.html.markdown index e8cde611..8e00f135 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,40 +1,35 @@ --- -language: scala -author: Dominic Bou-Samra -author_url: http://dbousamra.github.com -filename: learnscala.scala +language: Scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra, "http://dbousamra.github.com"] +filename: learn.scala --- -Scala is a <insert something nice here> +Scala - the scalable language -```scala +```c -/////////////////////////////////////// -// Basic syntax -/////////////////////////////////////// -// Single line comments start with two forward slashes -/* -Multi line comments look like this. + +/* + Set yourself up: + + 1) Download Scala - http://www.scala-lang.org/downloads + 2) unzip/untar in your favourite location and put the bin subdir on the path + 3) Start a scala REPL by typing scala. You should see the prompt: + + scala> + + This is the so called REPL. You can run commands in the REPL. Let's do just that: */ -// Import packages -import scala.collection.immutable.List -// Import all "sub packages" -import scala.collection.immutable._ -// Import multiple classes in one statement -import scala.collection.immutable.{List, Map} -// Rename an import using '=>' -import scala.collection.immutable{ List => ImmutableList } -// Import all classes, except some. The following excludes Map and Set: -import scala.collection.immutable.{Map => _, Set => _, _} +println(10) // prints the integer 10 -// Your programs entry point is defined in an scala file using an object, with a single method, main: -object Application { - def main(args: Array[String]): Unit = { - // stuff goes here. - } -} +println("Boo!") // printlns the string Boo! + + +// Some basics // Printing, and forcing a new line on the next print println("Hello world!") @@ -48,20 +43,10 @@ x = 20 // error: reassignment to val var x = 10 x = 20 // x is now 20 -/////////////////////////////////////// -// Types -/////////////////////////////////////// - -// Almost all types are objects. - -// You have numbers -3 //3 - -// Math is as per usual -1 + 1 // 2 -2 - 1 // 1 -5 * 3 // 15 -6 / 2 // 3 +// Single line comments start with two forward slashes +/* +Multi line comments look like this. +*/ // Boolean values true @@ -73,75 +58,48 @@ false true == false // false 10 > 5 // true -// Strings and characters -"Scala strings are surrounded by double quotes" // -'a' // A Scala Char -'Single quote strings don't exist' // Error -"Strings have the usual Java methods defined on them".length -"They also have some extra Scala methods.".reverse // See scala.collection.immutable.StringOps +// Math is as per usual +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 -/////////////////////////////////////// -// Basic control constructs -/////////////////////////////////////// -// if statements (else statements are optional) -if (10 > 5) println("10 is greater than 5") -// an else -if (x > 5) println("x is greater than 5") -else println("No it's not.") +// Evaluating a command in the REPL gives you the type and value of the result -// Iteration +1 + 7 -// A while loop -while (x < 10) { - println("x is still less then 10") - x += 1 -} +/* The above line results in: -// A do while loop -do { - println("x is still less then 10"); - x += 1 -} while (x < 10) + scala> 1 + 7 + res29: Int = 8 -// A for loop -for (x <- 0 until 10) { - println(x) -} + This means the result of evaluating 1 + 7 is an object of type Int with a value of 8 -// Any object implementing the map/filter/flatMap methods allows the use of a for loop: -val aListOfNumbers: List[Int] = List(1, 2, 3) -for (x <- aListOfNumbers) { - println(x) -} + 1+7 will give you the same result +*/ -// Pattern matching (see respective section) -x match { - case 5 => println("x is 5") - case 10 => println("x is 10") - case _ => println("default case") -} -/////////////////////////////////////// -// Functions, methods and classes -/////////////////////////////////////// +// Everything is an object, including a function. Type these in the REPL: -// Scala has classes +7 // results in res30: Int = 7 (res30 is just a generated var name for the result) -// classname is Dog -class Dog { - //A method called bark, returning a String - def bark: String = { - // the body of the method - "Woof, woof!" - } -} +// The next line gives you a function that takes an Int and returns it squared +(x:Int) => x * x + +// You can assign this function to an identifier, like this: +val sq = (x:Int) => x * x + +/* The above says this + + sq: Int => Int = <function1> -// They can contain nearly any other construct, including other classes, functions, methods, objects, case classes, traits etc. + Which means that this time we gave an explicit name to the value - sq is a function that take an Int and returns Int. -/////////////////////////////////////// -// Higher-order functions -/////////////////////////////////////// + sq can be executed as follows: +*/ + +sq(10) // Gives you this: res33: Int = 100. The result is the Int with a value 100 // Scala allows methods and functions to return, or take as parameters, other functions or methods. @@ -158,10 +116,64 @@ TODO // If the anonymous block AND the function you are applying both take one a List("Dom", "Bob", "Natalia") foreach println -// Scala collections have rich higher-order functions defined on them. Some examples: -// The map function takes a function/method, and applies it to each element in the structure -List(1, 2, 3) map (number => number.toString) +// Data structures + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Throws an exception + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Throws an exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Look up the documentation of map here - http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * and make sure you can read it + */ + + +// Tuples + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(a, 2, "three") + +// Why have this? +val divideInts = (x:Int, y:Int) => (x / y, x % y) + +divideInts(10,3) // The function divideInts gives you the result and the remainder + +// To access the elements of a tuple, use _._n where n is the 1-based index of the element +val d = divideInts(10,3) + +d._1 + +d._2 + + + +// Combinators + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) // The filter function takes a predicate (a function from A -> Boolean) and selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) @@ -176,3 +188,208 @@ aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println + + +// For comprehensions + +for { n <- s } yield sq(n) + +val nSquared2 = for { n <- s } yield sq(n) + +for { n <- nSquared2 if n < 10 } yield n + +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + +/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas a for-comprehension + defines a relationship between two sets of data. Research this further */ + + + +// Loops and iteration + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// NB: Scala is quite lenien when it comes to dots and brackets - study the rules separately. This +// helps write DSLs and APIs that read like English + +(5 to 1 by -1) foreach ( println ) + +// A while loops +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why? + +i // Show the value of i. Note that while is a loop in the classical sense - it executes + // sequentially while changing the loop variable. while is very fast, faster that Java + // loops, but using the combinators and comprehensions above is easier to understand + // and parallelize + +// A do while loop +do { + println("x is still less then 10"); + x += 1 +} while (x < 10) + +// Tail recursion is an idiomatic way of doing recurring things in Scala. Recursive functions need an +// explicit return type, the compiler can't infer it. Here it's Unit. +def showNumbersInRange(a:Int, b:Int):Unit = { print(a); if (a < b) showNumbersInRange(a+1, b) } + + + +// Conditionals + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nay") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + + + +// Object oriented features + +// Classname is Dog +class Dog { + //A method called bark, returning a String + def bark: String = { + // the body of the method + "Woof, woof!" + } +} + +// Classes can contain nearly any other construct, including other classes, functions, methods, objects, case classes, traits etc. + + + +// Case classes + +case class Person(name:String, phoneNumber:String) + +Person("George", "1234") == Person("Kate", "1236") + + + + +// Pattern matching + +val me = Person("George", "1234") + +me match { case Person(name, number) => "We matched someone : " + name + ", phone : " + number } + +me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } + +me match { case Person("George", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + +val kate = Person("Kate", "1234") + +kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + + + +// Regular expressions + +val email = "(.*)@(.*)".r // The suffix .r invokes method r on String, which makes it a Regex + +val email(user, domain) = "henry@zkpr.com" + +"mrbean@pyahoo.com" match { + case email(name, domain) => "I know your name, " + name +} + + + +// Strings + +"Scala strings are surrounded by double quotes" // +'a' // A Scala Char +'Single quote strings don't exist' // Error +"Strings have the usual Java methods defined on them".length +"They also have some extra Scala methods.".reverse // See scala.collection.immutable.StringOps + +println("ABCDEF".length) +println("ABCDEF".substring(2, 6)) +println("ABCDEF".replace("C", "3")) + +val n = 45 +println(s"We have $n apples") + +val a = Array(11, 9, 6) +println(s"My second daughter is ${a(2-1)} years old") + +// Some characters need to be 'escaped', e.g. a double quote inside a string: +val a = "They stood outside the \"Rose and Crown\"" + +// Triple double-quotes allow for strings to span multiple rows and contain funny characters +val html = """<form id="daform"> + <p>Press belo', Joe</p> + | <input type="submit"> + </form>""" + + + +// Application structure and organization + +// Importing things +import scala.collection.immutable.List + +// Import all "sub packages" +import scala.collection.immutable._ + +// Import multiple classes in one statement +import scala.collection.immutable.{List, Map} + +// Rename an import using '=>' +import scala.collection.immutable{ List => ImmutableList } + +// Import all classes, except some. The following excludes Map and Set: +import scala.collection.immutable.{Map => _, Set => _, _} + +// Your programs entry point is defined in an scala file using an object, with a single method, main: +object Application { + def main(args: Array[String]): Unit = { + // stuff goes here. + } +} + +// Files can contain multiple classes and objects. Compile with scalac + + + + +// Input and output + +// To read a file line by line +import scala.io.Source +for(line <- Source.fromPath("myfile.txt").getLines()) + println(line) + +// To write a file use Java's PrintWriter + + +``` + +## Further resources + +[Scala for the impatient](http://horstmann.com/scala/) + +[Twitter Scala school(http://twitter.github.io/scala_school/) + +[The scala documentation] + +Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) + |