diff options
| -rw-r--r-- | angularjs.html.markdown | 8 | ||||
| -rw-r--r-- | csharp.html.markdown | 6 | ||||
| -rw-r--r-- | elixir.html.markdown | 4 | ||||
| -rw-r--r-- | es-es/go-es.html.markdown | 12 | ||||
| -rw-r--r-- | go.html.markdown | 2 | ||||
| -rw-r--r-- | json.html.markdown | 1 | ||||
| -rw-r--r-- | lfe.html.markdown | 459 | ||||
| -rw-r--r-- | php.html.markdown | 4 | ||||
| -rw-r--r-- | standard-ml.html.markdown | 2 | 
9 files changed, 479 insertions, 19 deletions
| diff --git a/angularjs.html.markdown b/angularjs.html.markdown index 737b99c7..9156490e 100644 --- a/angularjs.html.markdown +++ b/angularjs.html.markdown @@ -699,10 +699,10 @@ app.controller('myCtrl', function($scope) {  **Examples** -- http://www.w3schools.com/angular/angular_examples.asp +- [http://www.w3schools.com/angular/angular_examples.asp](http://www.w3schools.com/angular/angular_examples.asp)  **References** -- http://www.w3schools.com/angular/angular_ref_directives.asp -- http://www.w3schools.com/angular/default.asp -- https://teamtreehouse.com/library/angular-basics/ +- [http://www.w3schools.com/angular/angular_ref_directives.asp](http://www.w3schools.com/angular/angular_ref_directives.asp) +- [http://www.w3schools.com/angular/default.asp](http://www.w3schools.com/angular/default.asp) +- [https://teamtreehouse.com/library/angular-basics/](https://teamtreehouse.com/library/angular-basics/) diff --git a/csharp.html.markdown b/csharp.html.markdown index cca99fb0..78f9db34 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -593,7 +593,7 @@ on a new line! ""Wow!"", the masses cried";                  Console.WriteLine(bikeSummary.Name);              // ASPARALLEL -            // And this is where things get wicked - combines linq and parallel operations +            // And this is where things get wicked - combine linq and parallel operations              var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);              // this will happen in parallel! Threads will automagically be spun up and the              // results divvied amongst them! Amazing for large datasets when you have lots of @@ -613,7 +613,7 @@ on a new line! ""Wow!"", the masses cried";                  .ThenBy(b => b.Name)                  .Select(b => b.Name); // still no query run -            // Now the query runs, but opens a reader, so only populates are you iterate through +            // Now the query runs, but opens a reader, so only populates as you iterate through              foreach (string bike in query)                  Console.WriteLine(result); @@ -711,7 +711,7 @@ on a new line! ""Wow!"", the masses cried";          // Before .NET 4: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell          public BikeAccessories Accessories { get; set; } -        // Static members belong to the type itself rather then specific object. +        // Static members belong to the type itself rather than specific object.          // You can access them without a reference to any object:          // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated);          public static int BicyclesCreated { get; set; } diff --git a/elixir.html.markdown b/elixir.html.markdown index 9dfffc41..a74baa38 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -4,6 +4,7 @@ contributors:      - ["Joao Marques", "http://github.com/mrshankly"]      - ["Dzianis Dashkevich", "https://github.com/dskecse"]      - ["Ryan Plant", "https://github.com/ryanplant-au"] +    - ["Ev Bogdanov", "https://github.com/evbogdanov"]  filename: learnelixir.ex  --- @@ -127,7 +128,8 @@ rem(10, 3) #=> 1  # These operators expect a boolean as their first argument.  true and true #=> true  false or true #=> true -# 1 and true    #=> ** (ArgumentError) argument error +# 1 and true +#=> ** (BadBooleanError) expected a boolean on left-side of "and", got: 1  # Elixir also provides `||`, `&&` and `!` which accept arguments of any type.  # All values except `false` and `nil` will evaluate to true. diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index c41d693d..78267695 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -26,7 +26,7 @@ Es rápido compilando y rápido al ejecutar, añade una concurrencia fácil de  entender para las CPUs de varios núcleos de hoy día, y tiene  características que ayudan con la programación a gran escala. -Go viene con una biblioteca estándar muy buena y una entusiasta comunidad. +Go viene con una biblioteca estándar muy buena y una comunidad entusiasta.  ```go  // Comentario de una sola línea @@ -52,7 +52,7 @@ import (  // para el ejecutable. Te guste o no, Go utiliza llaves.  func main() {  	// Println imprime una línea a stdout. -	// Cualificalo con el nombre del paquete, fmt. +	// Llámalo con el nombre del paquete, fmt.  	fmt.Println("¡Hola mundo!")  	// Llama a otra función de este paquete. @@ -90,12 +90,12 @@ saltos de línea.` // mismo tipo cadena  	g := 'Σ' // Tipo rune, un alias de int32, alberga un carácter unicode.  	f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit.  	c := 3 + 4i  // complex128, representado internamente por dos float64. -	// Sintaxis Var con iniciadores. +	// Sintaxis var con iniciadores.  	var u uint = 7 // Sin signo, pero la implementación depende del tamaño  	               // como en int.  	var pi float32 = 22. / 7 -	// Sintáxis de conversión con una declaración corta. +	// Sintaxis de conversión con una declaración corta.  	n := byte('\n') // byte es un alias para uint8.  	// Los Arreglos tienen un tamaño fijo a la hora de compilar. @@ -377,8 +377,8 @@ func aprendeConcurrencia() {  	go func() { c <- 84 }()       // Inicia una nueva rutinago solo para  											// enviar un valor.  	go func() { cs <- "verboso" }() // Otra vez, para cs en esta ocasión. -	// Select tiene una sintáxis parecida a la instrucción switch pero cada -	// caso involucra una operacion con un canal. Selecciona un caso de +	// Select tiene una sintaxis parecida a la instrucción switch pero cada +	// caso involucra una operación con un canal. Selecciona un caso de  	// forma aleatoria de los casos que están listos para comunicarse.  	select {  	case i := <-c: // El valor recibido se puede asignar a una variable, diff --git a/go.html.markdown b/go.html.markdown index 50692f9c..e5263cf6 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -99,7 +99,7 @@ can include line breaks.` // Same string type.  	// Arrays have size fixed at compile time.  	var a4 [4]int           // An array of 4 ints, initialized to all 0. -	a5 := [...]int{3, 1, 5, 10, 100} // An array initialized with a fixed size of fize +	a5 := [...]int{3, 1, 5, 10, 100} // An array initialized with a fixed size of five  	// elements, with values 3, 1, 5, 10, and 100.  	// Slices have dynamic size. Arrays and slices each have advantages diff --git a/json.html.markdown b/json.html.markdown index a612cffe..cd42d42d 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -11,6 +11,7 @@ contributors:  JSON is an extremely simple data-interchange format. As [json.org](http://json.org) says, it is easy for humans to read and write and for machines to parse and generate.  A piece of JSON must represent either: +  * A collection of name/value pairs (`{ }`). In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.  * An ordered list of values (`[ ]`). In various languages, this is realized as an array, vector, list, or sequence.   an array/list/sequence (`[ ]`) or a dictionary/object/associated array (`{ }`). diff --git a/lfe.html.markdown b/lfe.html.markdown new file mode 100644 index 00000000..413de36e --- /dev/null +++ b/lfe.html.markdown @@ -0,0 +1,459 @@ +--- + +language: "Lisp Flavoured Erlang(LFE)" +filename: lispflavourederlang.lfe +contributors: +  - ["Pratik Karki", "https://github.com/prertik"] +--- + +Lisp Flavoured Erlang(LFE) is a functional, concurrent, general-purpose programming  +language and Lisp dialect(Lisp-2) built on top of Core Erlang and the Erlang Virtual Machine(BEAM).  + +LFE can be obtained from [LFE](https://github.com/rvirding/lfe) + +The classic starting point is [LFE DOCS.](http://docs.lfe.io) + +Another new site is being built to replace it.[LFE DEV.](http://docs.lfe.io/dev) + + + +```lisp + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 0. Syntax +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; General form. + +;; Lisp comprises of two syntax called: the ATOM and the S-expression. +;; `forms` are known as grouped S-expressions. + +8  ; an atom; it evaluates to itself + +:ERLANG ;Atom; evaluates to the symbol :ERLANG. + +t  ; another atom which denotes true. + +(* 2 21) ; an S- expression + +'(8 :foo t)  ;another one + + +;;; Comments + +;; Single line comments start with a semicolon; use two for normal +;; comments, three for section comments, and four fo file-level +;; comments. + +;; Block Comment + +   #| comment text |# + +;;; Environment + +;; LFE is the de-facto standard. + +;; Libraries can be used directly from the Erlang ecosystem. Rebar3 is the build tool. + +;; LFE is usually developed with a text editor(preferably Emacs) and a REPL +;; (Read Evaluate Print Loop) running at the same time. The REPL  +;; allows for interactive exploration of the program as it is "live" +;; in the system. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 1. Literals and Special Syntactic Rules +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Integers + +1234 -123	        ; Regular decimal notation +#b0 #b10101	        ; Binary notation +#0 #10101	        ; Binary notation (alternative form) +#o377 #o-111	    ; Octal notation +#d123456789 #d+123	; Explicitly decimal notation +#xc0ffe 0x-01	    ; Hexadecimal notation +#2r1010 #8r377 	    ;Notation with explicit base (up to 36) +#\a #$ #\ä #\🐭     ;Character notation (the value is the Unicode code point of the character) +#\x1f42d;	        ;Character notation with the value in hexadecimal + +;;; Floating point numbers +1.0 +2.0 -1.5 1.0e10 1.111e-10      + +;;; Strings + +"any text between double quotes where \" and other special characters like \n can be escaped". +; List String +"Cat: \x1f639;" ; writing unicode in string for regular font ending with semicolon. + +#"This is a binary string \n with some \"escaped\" and quoted (\x1f639;) characters" +; Binary strings are just strings but function different in the VM.  +; Other ways of writing it are:  #B("a"), #"a", and #B(97). + + +;;; Character escaping + +\b	; => Backspace +\t	; => Tab +\n	; => Newline +\v	; => Vertical tab +\f	; => Form Feed +\r	; => Carriage Return +\e	; => Escape +\s	; => Space +\d	; => Delete + +;;; Binaries +;; It is used to create binaries with any contents. +#B((#"a" binary) (#"b" binary))	               ; #"ab" (Evaluated form) + +;;; Lists are: () or (foo bar baz) + +;;; Tuples are written in: #(value1 value2 ...). Empty tuple #() is also valid. + +;;; Maps are written as: #M(key1 value1 key2 value2 ...). Empty map #M() is also valid. + +;;; Symbols: Things that cannot be parsed. Eg: foo, Foo, foo-bar, :foo +| foo | ; explicit construction of symbol by wrapping vertical bars. + +;;; Evaluation  + +;; #.(... some expression ...). E.g. '#.(+ 1 1) will evaluate the (+ 1 1) while it            ;; reads the expression and then be effectively '2. + +;; List comprehension in LFE REPL + +lfe> (list-comp +          ((<- x '(0 1 2 3))) +          (trunc (math:pow 3 x))) +       (1 3 9 27) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Core forms +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; These forms are same as those found at Common Lisp and Scheme. + +(quote e) +(cons head tail) +(car e) +(cdr e) +(list e ... ) +(tuple e ... ) +(binary seg ... ) +(map key val ...), (map-get m k), (map-set m k v ...), (map-update m k v ...) + +(lambda (arg ...) ...) +  (match-lambda +    ((arg ... ) {{(when e ...)}} ...) ; Matches clauses +    ... ) +(let ((pat {{(when e ...)}} e) +      ...) +  ... ) +(let-function ((name lambda|match-lambda) ; Only define local +               ... )                      ; functions +  ... ) +(letrec-function ((name lambda|match-lambda) ; Only define local +                  ... )                      ; functions +  ... ) +(let-macro ((name lambda-match-lambda) ; Only define local +            ...)                       ; macros +  ...) +(progn ... ) +(if test true-expr {{false-expr}}) +(case e +  (pat {{(when e ...)}} ...) +   ... )) +(receive +  (pat {{(when e ...)}} ... ) +  ... +  (after timeout ... )) +(catch ... ) +(try +  e +  {{(case ((pat {{(when e ...)}} ... ) +          ... ))}} +  {{(catch +     ; Next must be tuple of length 3! +     (((tuple type value ignore) {{(when e ...)}} +      ... ) +     ... )}} +  {{(after ... )}}) + +(funcall func arg ... ) +(call mod func arg ... ) - Call to Erlang Mod:Func(Arg, ... ) +(define-module name declaration ... ) +(extend-module declaration ... ) - Define/extend module and declarations. +(define-function name lambda|match-lambda) +(define-macro name lambda|match-lambda) - Define functions/macros at top-level. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros are part of the language to allow you to create abstractions  +;; on top of the core language and standard library that move you closer  +;; toward being able to directly express the things you want to express. + +;; Top-level function + +(defun name (arg ...) ...) + +;; Adding comments in functions + +(defun name +  "Toplevel function with pattern-matching arguments" +  ((argpat ...) ...) +  ...) + +;; Top-level macro + +(defmacro name (arg ...) ...) +(defmacro name arg ...) + +;; Top-level macro with pattern matching arguments + +(defmacro name +  ((argpat ...) ...) +  ...) + +;; Top-level macro using Scheme inspired syntax-rules format  + +(defsyntax name +  (pat exp) +  ...) + +;;; Local macros in macro or syntax-rule format + +(macrolet ((name (arg ... ) ... ) +            ... ) +    ... ) +     +(syntaxlet ((name (pat exp) ...) +             ...) + ...) + +;; Like CLISP + +(prog1 ...) +(prog2 ...) + +;; Erlang LFE module + +(defmodule name ...) + +;; Erlang LFE record + +(defrecord name ...) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Patterns and Guards +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Using patterns in LFE compared to that of Erlang + +;; Erlang                     ;; LFE +;; {ok, X}                       (tuple 'ok x) +;; error                         'error +;; {yes, [X|Xs]}                 (tuple 'yes (cons x xs)) +;; <<34,F/float>>                (binary 34 (f float)) +;; [P|Ps]=All                    (= (cons p ps) all) + +  _    ; => is don't care while pattern matching +   +  (= pattern1 pattern2)     ; => easier, better version of pattern matching +   +;; Guards + +;; Whenever pattern occurs(let, case, receive, lc, etc) it can be followed by an optional +;; guard which has the form (when test ...). + +(progn gtest ...)             ;; => Sequence of guard tests +(if gexpr gexpr gexpr) +(type-test e) +(guard-bif ...)               ;; => Guard BIFs, arithmetic, boolean and comparison operators + +;;; REPL + +lfe>(set (tuple len status msg) #(8 ok "Trillian")) +    #(8 ok "Trillian") +lfe>msg +    "Trillian" + +;;; Program illustrating use of Guards + +(defun right-number? +        ((x) (when (orelse (== x 42) (== x 276709))) +          'true) +        ((_) 'false)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Functions +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; A simple function using if. + +(defun max (x y) +  "The max function." +  (if (>= x y) x y)) + +;; Same function using more clause + +(defun max +  "The max function." +  ((x y) (when (>= x y)) x) +  ((x y) y)) + +;; Same function using similar style but using local functions defined by flet or fletrec + +(defun foo (x y) +  "The max function." +  (flet ((m (a b) "Local comment." +            (if (>= a b) a b))) +    (m x y))) + +;; LFE being Lisp-2 has separate namespaces for variables and functions +;; Both variables and function/macros are lexically scoped. +;; Variables are bound by lambda, match-lambda and let. +;; Functions are bound by top-level defun, flet and fletrec. +;; Macros are bound by top-level defmacro/defsyntax and by macrolet/syntaxlet. + +;; (funcall func arg ...) like CL to call lambdas/match-lambdas  +;; (funs) bound to variables are used. + +;; separate bindings and special for apply. +apply _F (...),  +apply _F/3 ( a1, a2, a3 ) +     +;; Cons'ing in function heads +(defun sum (l) (sum l 0)) +  (defun sum +    (('() total) total) +    (((cons h t) total) (sum t (+ h total)))) +     +;; ``cons`` literal instead of constructor form +      (defun sum (l) (sum l 0)) +      (defun sum +        (('() total) total) +        ((`(,h . ,t) total) (sum t (+ h total)))) + +;; Matching records in function heads + +(defun handle_info +  (('ping (= (match-state remote-pid 'undefined) state)) +    (gen_server:cast (self) 'ping) +    `#(noreply ,state)) +  (('ping state) +   `#(noreply ,state))) + +;; Receiving Messages +      (defun universal-server () +        (receive +          ((tuple 'become func) +           (funcall func)))) +            +;; another way for receiving messages + + (defun universal-server () +        (receive +          (`#(become ,func) +            (funcall func)))) + +;; Composing a complete function for specific tasks + +(defun compose (f g) +  (lambda (x) +   (funcall f +     (funcall g x)))) + +(defun check () +  (let* ((sin-asin (compose #'sin/1 #'asin/1)) +         (expected (sin (asin 0.5))) +         (compose-result (funcall sin-asin 0.5))) +    (io:format "Expected answer: ~p~n" (list expected)) +    (io:format "Answer with compose: ~p~n" (list compose-result)))) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Concurrency +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Message passing as done by Erlang's light-weight "processes". + +(defmodule messenger-back + (export (print-result 0) (send-message 2))) + +(defun print-result () +  (receive +    ((tuple pid msg) +      (io:format "Received message: '~s'~n" (list msg)) +      (io:format "Sending message to process ~p ...~n" (list pid)) +      (! pid (tuple msg)) +      (print-result)))) + +(defun send-message (calling-pid msg) +  (let ((spawned-pid (spawn 'messenger-back 'print-result ()))) +    (! spawned-pid (tuple calling-pid msg)))) +     +;; Multiple simultaneous HTTP Requests: + +(defun parse-args (flag) +  "Given one or more command-line arguments, extract the passed values. + +  For example, if the following was passed via the command line: + +    $ erl -my-flag my-value-1 -my-flag my-value-2 + +  One could then extract it in an LFE program by calling this function: + +    (let ((args (parse-args 'my-flag))) +      ... +      ) +  In this example, the value assigned to the arg variable would be a list +  containing the values my-value-1 and my-value-2." +  (let ((`#(ok ,data) (init:get_argument flag))) +    (lists:merge data))) + +(defun get-pages () +  "With no argument, assume 'url parameter was passed via command line." +  (let ((urls (parse-args 'url))) +    (get-pages urls))) + +(defun get-pages (urls) +  "Start inets and make (potentially many) HTTP requests." +  (inets:start) +  (plists:map +    (lambda (x) +      (get-page x)) urls)) + +(defun get-page (url) +  "Make a single HTTP request." +  (let* ((method 'get) +         (headers '()) +         (request-data `#(,url ,headers)) +         (http-options ()) +         (request-options '(#(sync false)))) +    (httpc:request method request-data http-options request-options) +    (receive +      (`#(http #(,request-id #(error ,reason))) +       (io:format "Error: ~p~n" `(,reason))) +      (`#(http #(,request-id ,result)) +       (io:format "Result: ~p~n" `(,result)))))) + + +;; Check out Erlang's documentation for more concurrency and OTP docs. +``` + +## Further Reading + +*    [LFE DOCS](http://docs.lfe.io) +*    [LFE GitBook](https://lfe.gitbooks.io/reference-guide/index.html) +*    [LFE Wiki](https://en.wikipedia.org/wiki/LFE_(programming_language)) + +## Extra Info +*    [LFE PDF](http://www.erlang-factory.com/upload/presentations/61/Robertvirding-LispFlavouredErlang.pdf) +*    [LFE mail](https://groups.google.com/d/msg/lisp-flavoured-erlang/XA5HeLbQQDk/TUHabZCHXB0J) + +## Credits + +Lots of thanks to Robert Virding for creating LFE, Duncan McGreggor for documenting it and other LFE contributors who made LFE awesome. + diff --git a/php.html.markdown b/php.html.markdown index f247ba77..ac9b45a8 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -132,9 +132,7 @@ echo 'This outputs ' . FOO;  // Returns 'This ouputs something'   * Arrays   */ -// All arrays in PHP are associative arrays (hashmaps), - -// Associative arrays, known as hashmaps in some languages. +// All arrays in PHP are associative arrays (hashmaps in some languages)  // Works with all PHP versions  $associative = array('One' => 1, 'Two' => 2, 'Three' => 3); diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index c9eb2a2e..c286366b 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -385,7 +385,7 @@ fun calculate_interest(n) = if n < 0.0  (* Exceptions can be caught using "handle" *)  val balance = calculate_interest ~180.0 -              handle Domain => ~180.0    (* x now has the value ~180.0 *) +              handle Domain => ~180.0    (* balance now has the value ~180.0 *)  (* Some exceptions carry extra information with them *)  (* Here are some examples of built-in exceptions *) | 
