diff options
-rw-r--r-- | Gemfile.lock | 15 | ||||
-rw-r--r-- | PULL_REQUEST_TEMPLATE.md | 1 | ||||
-rw-r--r-- | bash.html.markdown | 2 | ||||
-rw-r--r-- | c.html.markdown | 2 | ||||
-rw-r--r-- | de-de/java-de.html.markdown | 2 | ||||
-rw-r--r-- | elixir.html.markdown | 4 | ||||
-rw-r--r-- | fr-fr/rust-fr.html.markdown | 2 | ||||
-rw-r--r-- | it-it/logtalk-it.html.markdown | 550 | ||||
-rw-r--r-- | javascript.html.markdown | 56 | ||||
-rw-r--r-- | julia.html.markdown | 2 | ||||
-rw-r--r-- | logtalk.html.markdown | 4 | ||||
-rw-r--r-- | meteor.html.markdown | 567 | ||||
-rw-r--r-- | perl6.html.markdown | 173 | ||||
-rw-r--r-- | purescript.html.markdown | 2 | ||||
-rw-r--r-- | python3.html.markdown | 15 | ||||
-rw-r--r-- | rst.html.markdown | 2 | ||||
-rw-r--r-- | ru-ru/asymptotic-notation-ru.html.markdown | 225 | ||||
-rw-r--r-- | ru-ru/clojure-ru.html.markdown | 2 | ||||
-rw-r--r-- | ru-ru/forth-ru.html.markdown | 240 | ||||
-rw-r--r-- | solidity.html.markdown | 2 | ||||
-rw-r--r-- | standard-ml.html.markdown | 21 | ||||
-rw-r--r-- | tr-tr/dynamic-programming-tr.html.markdown | 44 | ||||
-rw-r--r-- | zh-cn/dynamic-programming-cn.html.markdown | 57 |
23 files changed, 1334 insertions, 656 deletions
diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 00000000..ba15ad75 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,15 @@ +GEM + remote: http://rubygems.org/ + specs: + charlock_holmes (0.7.3) + rake (12.0.0) + +PLATFORMS + ruby + +DEPENDENCIES + charlock_holmes + rake + +BUNDLED WITH + 1.13.7 diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 6f1f000d..fd9d1b31 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -1,3 +1,4 @@ +- [ ] I solemnly swear that this is all original content of which I am the original author - [ ] Pull request title is prepended with `[language/lang-code]` - [ ] Pull request touches only one file (or a set of logically related files with similar changes made) - [ ] Content changes are aimed at *intermediate to experienced programmers* (this is a poor format for explaining fundamental programming concepts) diff --git a/bash.html.markdown b/bash.html.markdown index 271ef62c..14366e4c 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -156,7 +156,7 @@ ls # These commands have options that control their execution: ls -l # Lists every file and directory on a separate line -ls -t # Sort the directory contents by last-modified date (descending) +ls -t # Sorts the directory contents by last-modified date (descending) ls -R # Recursively `ls` this directory and all of its subdirectories # Results of the previous command can be passed to the next command as input. diff --git a/c.html.markdown b/c.html.markdown index 57ce72d2..6d111be6 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -775,7 +775,7 @@ If you have a question, read the [compl.lang.c Frequently Asked Questions](http: It's very important to use proper spacing, indentation and to be consistent with your coding style in general. Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the -[Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle). +[Linux kernel coding style](https://www.kernel.org/doc/Documentation/process/coding-style.rst). Other than that, Google is your friend. diff --git a/de-de/java-de.html.markdown b/de-de/java-de.html.markdown index 001c6888..934819f9 100644 --- a/de-de/java-de.html.markdown +++ b/de-de/java-de.html.markdown @@ -13,7 +13,7 @@ lang: de-de Java ist eine Programmiersprache für vielfältige Aufgaben. Sie ist imperative und objektorientiert. Oftmals wird sie für Desktop- Webapplikationen sowie als Programmiersprache im Betriebssystem Android verwendet. -[Weitere Informationen \(Englisch\](http://docs.oracle.com/javase/tutorial/java/) +[Weitere Informationen \(Englisch\)](http://docs.oracle.com/javase/tutorial/java/) ```java // Einzeilige Kommentare starten mit // diff --git a/elixir.html.markdown b/elixir.html.markdown index 63b7aef2..9dfffc41 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -433,11 +433,11 @@ self() #=> #PID<0.27.0> # Create an agent with `Agent.start_link`, passing in a function # The initial state of the agent will be whatever that function returns -{ok, my_agent} = Agent.start_link(fn -> ["red, green"] end) +{ok, my_agent} = Agent.start_link(fn -> ["red", "green"] end) # `Agent.get` takes an agent name and a `fn` that gets passed the current state # Whatever that `fn` returns is what you'll get back -Agent.get(my_agent, fn colors -> colors end) #=> ["red, "green"] +Agent.get(my_agent, fn colors -> colors end) #=> ["red", "green"] # Update the agent's state the same way Agent.update(my_agent, fn colors -> ["blue" | colors] end) diff --git a/fr-fr/rust-fr.html.markdown b/fr-fr/rust-fr.html.markdown index 5a384864..b3675f5b 100644 --- a/fr-fr/rust-fr.html.markdown +++ b/fr-fr/rust-fr.html.markdown @@ -14,7 +14,7 @@ Il atteint ces objectifs sans avoir besoin d'un ramasse-miettes ou environnement La première version de Rust, 0.1, est sortie en janvier 2012 et a tellement évolué rapidement que jusqu'à récemment, l'utilisation de versions stables était déconseillée - à la place ce était conseillé d'utiliser les nightly builds. -Le 15 mai 2015, Rust 1.0 a été libéré avec une garantie complète de compatibilité ascendante. Améliorations aux temps de compilation et d'autres aspects du compilateur sont actuellement disponibles dans la nightly builds. Rust a adopté un modèle de libération à bord du train avec les versions régulières toutes les six semaines. Rust 1.1 beta a été mis à la disposition dans le même temps de la libération de Rust 1.0. +Le 15 mai 2015, Rust 1.0 a été libéré avec une garantie complète de compatibilité ascendante. Améliorations aux temps de compilation et d'autres aspects du compilateur sont actuellement disponibles dans la nightly builds. Rust a adopté un modèle de train de livraison avec les versions régulières toutes les six semaines. Rust 1.1 beta a été mis à disposition au moment de la livraison de Rust 1.0. Bien que Rust soit un langage relativement bas niveau, Rust a quelques concepts fonctionnels qui se trouvent généralement dans les langues de niveau supérieur. Cela rend Rust non seulement rapide, mais aussi efficace et facile à coder. diff --git a/it-it/logtalk-it.html.markdown b/it-it/logtalk-it.html.markdown new file mode 100644 index 00000000..7f1e9eeb --- /dev/null +++ b/it-it/logtalk-it.html.markdown @@ -0,0 +1,550 @@ +--- +language: Logtalk +filename: learnlogtalk-it.lgt +contributors: + - ["Paulo Moura", "http://github.com/pmoura"] +translators: + - ["Ugo Chirico", "https://github.com/ugochirico"] +lang: it-it +--- + +Logtalk è un linguaggio di programmazione logica orientata agli oggetti che estende il linguaggio Prolog con le moderne tecniche di Object-Oriented Programming quali incapsulamento, ereditarietà e riutilizzo del codice, senza compromettere le caratteristiche di programmazione dichiarativa del Prolog. Logtalk è implementato in codice altamente portabile e utilizza i più moderni standard di conformità del Prolog rispetto al compilatore backend. + +Per mantenere una dimensione ragionevole, questo tutorial presuppone necessariamente che il lettore abbia una conoscenza del linguaggio Prolog ed è inoltre focalizzato esclusivamente sulla descrizione delle caratteristiche object-oriented di Logtalk. + +# Sintassi + +Logtalk utilizza la sintassi standard del linguaggio Prolog con l'aggiunta di un paio di operatori e di alcune direttive per una curva di apprendimento morbida e per assicurare ampia portabilità. Una conseguenza importante è che il codice Prolog può essere facilmente incapsulato in oggetti con poche o nessuna modifica. Inoltre, Logtalk può interpretare come oggetti Logtalk, in modo trasparente, la maggior parte dei moduli Prolog già esistenti. + +I principali operatori sono: + +* `::/2` - per inviare un messaggio ad un oggetto +* `::/1` - per inviare un messaggio a se stesso _self_ (cioè all'oggetto che riceverà il messaggio) +* `^^/1` - _super_ per chiamare un predicato ereditato o importato + +Alcune delle più importanti entità e direttive saranno introdotte nelle sezioni successive. + +# Entità e Ruoli + +Logtalk tratta gli oggetti, i protocolli e le categorie come entità di prima classe. I rapporti tra le entità definiscono i _patterns of code reuse_ ossia i modelli di riutilizzo del codice e i _roles_ ossia i ruoli svolti da tali entità. Ad esempio, quando un oggetto istanzia un altro oggetto, il primo oggetto assume il ruolo di istanza e il secondo oggetto assume il ruolo di classe. Una relazione di tipo _extends_ tra due oggetti implica che entrambi gli oggetti svolgano il ruolo di prototipi, in cui uno di loro estende l'altro, che diventa quindi suo prototipo padre. + +# Definizione di un oggetto + +Un oggetto incapsula le dichiarazioni e le definizioni dei predicati. Gli oggetti possono essere creati in modo dinamico, ma di solito sono dichiarati come statici e definiti nel codice sorgente. Un singolo file sorgente può contenere un qualsiasi numero di definizioni di entità. Ecco un semplice oggetto `list` che definisce un membro pubblico `member/2`: + +```logtalk +:- object(list). + + :- public(member/2). + member(Head, [Head| _]). + member(Head, [_| Tail]) :- + member(Head, Tail). + +:- end_object. +``` + +# Compilazione dei file sorgenti + +Supponendo che il codice di cui sopra per l'oggetto `list` venga salvato in un file` list.lgt`, esso può essere compilato e caricato utilizzando il predicato predefiniti `logtalk_load/1` o la sua abbreviazione `{}/1`, con il percorso del file come argomento (l'estensione può essere omessa): + +```logtalk +?- {list}. +yes +``` + +# Inviare un messaggio ad un oggetto + +L'operatore infisso `::/2` è usato per inviare messaggi ad un oggetto. Analogamente al Prolog, è possibile fare backtracking per le soluzioni alternative: + +```logtalk +?- list::member(X, [1,2,3]). +X = 1 ; +X = 2 ; +X = 3 +yes +``` + +Analogamente alla programmazione object-oriented, logtalk consente anche l'Incapsulamento. +Un predicato può essere dichiarata pubblico, protetto o privato. Può anche essere _local_ quando non esiste una direttiva specifica per esso all'interno dello scope. Per esempio: + +```logtalk +:- object(scopes). + + :- private(bar/0). + bar. + + local. + +:- end_object. +``` + +Assumendo che l'oggetto è salvato nel file `scopes.lgt`: + +```logtalk +?- {scopes}. +yes + +?- catch(scopes::bar, Error, true). +Error = error( + permission_error(access, private_predicate, bar/0), + logtalk(scopes::bar, user) +) +yes + +?- catch(scopes::local, Error, true). +Error = error( + existence_error(predicate_declaration, local/0), + logtalk(scopes::local, user) +) +yes +``` + +Quando il predicato in un messaggio non è noto per l'oggetto (il ruolo dell'oggetto determina le procedure di ricerca), si ha un errore. +Per esempio: + +```logtalk +?- catch(scopes::unknown, Error, true). +Error = error( + existence_error(predicate_declaration, unknown/0), + logtalk(scopes::unknown, user) +) +yes +``` + +Un punto fondamentale da capire è che le direttive che specificano il predicato nello scope specificano la semantica di chiamata (_calling_) del predicato, e non la semantica di definizione (_definition_). Ad esempio, se un oggetto ha il ruolo di una classe e dichiara un predicato privato, tale predicato può essere definito nelle sue sottoclassi e nelle istanze * ma * può essere chiamato solo nelle sue istanza (_from_) dalla classe. + +# Definizione e implementazione di un protocollo + +Un Protocollo contiene le dichiarazioni dei predicati che possono essere implementati da un qualsivoglia numero di oggetti e categorie: + +```logtalk +:- protocol(listp). + + :- public(member/2). + +:- end_protocol. + +:- object(list, + implements(listp)). + + member(Head, [Head| _]). + member(Head, [_| Tail]) :- + member(Head, Tail). + +:- end_object. +``` + +Lo scope dei predicati di un protocollo può essere ristretto usando implementazioni protected e private. Ad esempio: + +```logtalk +:- object(stack, + implements(private::listp)). + +:- end_object. +``` + +Difatti, tutte le relazioni tra entità (nella direttiva di apertura di un entità) possono essere definite come public (default), protected, o private. + +# Prototipi + +Un oggetto senza una istanza o senza una relazione di specializzazione con un altro oggetto interpreta il ruolo di prototipo. Un prototipo può estendere un altro oggetto, il suo prototipo genitore. + +```logtalk +% clyde, our prototypical elephant +:- object(clyde). + + :- public(color/1). + color(grey). + + :- public(number_of_legs/1). + number_of_legs(4). + +:- end_object. + +% fred, another elephant, is like clyde, except that he's white +:- object(fred, + extends(clyde)). + + color(white). + +:- end_object. +``` + +Per rispondere ad un messaggio inviato ad un oggetto che ha il ruolo di prototipo, si cerca prima una risposta nel prototipo stesso e se il prototipo non sa rispondere si passa all'eventuale prototipo genitore (se esiste): + +```logtalk +?- fred::number_of_legs(N). +N = 4 +yes + +?- fred::color(C). +C = white +yes +``` + +Un messaggio è valido se il relativo predicato è dichiarato in un oggetto (e se il mittente è nel campo di applicazione), ma fallirà, piuttosto che lanciare un errore, se il predicato non è definito. Questa è chiamata la _closed-world assumption_. Ad esempio, si consideri il seguente oggetto, salvato in un file `foo.lgt`: + +```logtalk +:- object(foo). + + :- public(bar/0). + +:- end_object. +``` + +Caricando il file e cercando di chiamare il predicato `bar/0` questo fallisce come previsto. Si noti che ciò è diverso dal chiamare un predicato sconosciuto _unknown_, che invece genera un errore: + +```logtalk +?- {foo}. +yes + +?- foo::bar. +no + +?- catch(foo::baz, Error, true). +Error = error( + existence_error(predicate_declaration, baz/0), + logtalk(foo::baz, user) +) +yes +``` + +# Classi e istanze + +Per definire gli oggetti nei ruoli di classi e/o istanze, un oggetto deve avere almeno un istanziazione o una relazione di specializzazione con un altro oggetto. Gli oggetti che hanno il ruolo di meta-classi possono essere utilizzati quando abbiamo bisogno di usare una classe come se fosse un'istanza. Il seguente esempio mostra come creare dinamicamente nuovi oggetti in fase di esecuzione: + +```logtalk +% a simple, generic, metaclass defining a new/2 predicate for its instances +:- object(metaclass, + instantiates(metaclass)). + + :- public(new/2). + new(Instance, Clauses) :- + self(Class), + create_object(Instance, [instantiates(Class)], [], Clauses). + +:- end_object. + +% a simple class defining age/1 and name/1 predicate for its instances +:- object(person, + instantiates(metaclass)). + + :- public([ + age/1, name/1 + ]). + + % a default value for age/1 + age(42). + +:- end_object. + +% a static instance of the class person +:- object(john, + instantiates(person)). + + name(john). + age(12). + +:- end_object. +``` + +Nel rispondere ad un messaggio inviato ad un oggetto ha assunto il ruolo di istanza, tal messaggio viene convalidato partendo dalla sua classe e andando a ritroso nella gerarchia, se necessario, fino alle sue superclassi. Supponendo che il messaggio sia valido, allora si cerca una risposta a partire dall'istanza stessa: + +```logtalk +?- person::new(Instance, [name(paulo)]). +Instance = o1 +yes + +?- o1::name(Name). +Name = paulo +yes + +?- o1::age(Age). +Age = 42 +yes + +?- john::age(Age). +Age = 12 +yes +``` + +# Categorie + +Una categoria è un'unità atomica di codice riutilizzabile. Una categoria è usata per incapsulare una insieme coesivo (_cohesive_) di dichiarazioni e di definizioni di predicato ed è atta ad implementare una singola (_single_) funzionalità che può essere importata in qualsiasi oggetto. Una categoria può quindi essere concepita come il concetto duale di protocollo. Nel seguente esempio, si definiscono prima le categorie che rappresentano i motori di auto e poi si importano tali categorie negli oggetti auto: + +```logtalk +% a protocol describing engine characteristics +:- protocol(carenginep). + + :- public([ + reference/1, + capacity/1, + cylinders/1, + horsepower_rpm/2, + bore_stroke/2, + fuel/1 + ]). + +:- end_protocol. + +% a typical engine defined as a category +:- category(classic, + implements(carenginep)). + + reference('M180.940'). + capacity(2195). + cylinders(6). + horsepower_rpm(94, 4800). + bore_stroke(80, 72.8). + fuel(gasoline). + +:- end_category. + +% a souped up version of the previous engine +:- category(sport, + extends(classic)). + + reference('M180.941'). + horsepower_rpm(HP, RPM) :- + ^^horsepower_rpm(ClassicHP, ClassicRPM), % "super" call + HP is truncate(ClassicHP*1.23), + RPM is truncate(ClassicRPM*0.762). + +:- end_category. + +% with engines (and other components), we may start "assembling" some cars +:- object(sedan, + imports(classic)). + +:- end_object. + +:- object(coupe, + imports(sport)). + +:- end_object. +``` + +Le Categorie sono compilate in modo indipendente e, quindi, consentono l'importazione di oggetti da aggiornare mediante il semplice aggiornamento delle categorie importate, senza richiedere pertanto la ricompilazione dell'oggetto. Le Categorie forniscono anche la _runtime transparency_, cioè il protocollo della categoria si aggiunge al protocollo degli oggetti che importano tale categoria: + +```logtalk +?- sedan::current_predicate(Predicate). +Predicate = reference/1 ; +Predicate = capacity/1 ; +Predicate = cylinders/1 ; +Predicate = horsepower_rpm/2 ; +Predicate = bore_stroke/2 ; +Predicate = fuel/1 +yes +``` + +# Hot patching + +Le categorie possono essere anche usate per modificare gli oggetti al volo (_hot-patch_). Una categoria può aggiungere nuovi predicati ad un oggetto e/o sostituire le definizioni dei predicati dell'oggetto. Ad esempio, si consideri il seguente oggetto: + +```logtalk +:- object(buggy). + + :- public(p/0). + p :- write(foo). + +:- end_object. +``` + +Si supponga che l'oggetto stampi la stringa sbagliata quando riceve il messaggio `p/0`: + +```logtalk +?- {buggy}. +yes + +?- buggy::p. +foo +yes +``` + +Se il codice sorgente dell'oggetto non è disponibile e bisogna correggere l'applicazione che sta eseguendo il codice dell'oggetto, si può semplicemente definire una categoria che corregge il predicato non corretto: + +```logtalk +:- category(patch, + complements(buggy)). + + % fixed p/0 def + p :- write(bar). + +:- end_category. +``` + +Dopo la compilazione e il caricamento della categoria nell'applicazione in esecuzione si ottiene: + +```logtalk +?- {patch}. +yes + +?- buggy::p. +bar +yes +``` + +Poiché l'hot-patching pregiudica forzatamente l'incapsulamento, un apposito flag di compilazione `complementary` può essere impostato (a livello globale o per un singolo oggetto) per consentire, limitare o prevenire l'hot-patching. + +# Oggetti Parametrici e Categorie + +Gli oggetti e le categorie possono essere parametrizzati utilizzando come identificativo un compound-term al posto di un atomo. Oggetti e parametri di una categoria sono variabili logiche _logical variables_ condivise con tutti i predicati incapsulati. Ecco un esempio con cerchi geometrici: + +```logtalk +:- object(circle(_Radius, _Color)). + + :- public([ + area/1, perimeter/1 + ]). + + area(Area) :- + parameter(1, Radius), + Area is pi*Radius*Radius. + + perimeter(Perimeter) :- + parameter(1, Radius), + Perimeter is 2*pi*Radius. + +:- end_object. +``` + +Oggetti parametrici possono essere utilizzati come qualsiasi altro oggetto e di solito forniscono i valori da assegnare ai parametri quando si invia un messaggio: + +```logtalk +?- circle(1.23, blue)::area(Area). +Area = 4.75291 +yes +``` + +Gli oggetti parametrici forniscono anche un modo semplice per associare un insieme di predicati con un semplice predicato Prolog. Fatti Prolog possono essere interpretati come oggetti proxy parametrici ( _parametric object proxies_) quando hanno lo stesso funtore e arietà degli identificatori di oggetti parametrici. Per lavorare con i proxy viene fornita una sintassi maneggevole. Per esempio, si prendano le seguenti clausole per il predicato `circle/2`: + +```logtalk +circle(1.23, blue). +circle(3.71, yellow). +circle(0.39, green). +circle(5.74, black). +circle(8.32, cyan). +``` + +Con queste clausole, si può facilmente calcolare, ad esempio, un elenco con le aree di tutti i cerchi: + +```logtalk +?- findall(Area, {circle(_, _)}::area(Area), Areas). +Areas = [4.75291, 43.2412, 0.477836, 103.508, 217.468] +yes +``` + +In pratica, il costrutto `{Goal}::Message` prova il goal `Goal`, instanziando le variabili interne e inviando un messaggio `Message` al termine risultante. + +# Eventi and monitor + +Logtalk supporta l'_event-driven programming_ mediante la definizione di eventi e di monitor. Un evento è semplicemente l'invio di un messaggio ad un oggetto. Un monitor è un gestore di un evento. L'evento (con l'invio di un messaggio) è un'attività atomica, ed è preceduta da un evento _before_ e da un evento _after_. Il monitor gestisce tali eventi mediante i predicati, `before/3` e `after/3`, che sono chiamati rispettivamente prima e dopo il verificarsi dell'evento. Un monitor può inoltre interrogare, registrare e cancellare un evento nel registro eventi a livello di sistema il quale che associa gli eventi con i monitor. Ad esempio, un semplice tracer per ogni messaggio inviato utilizzando il costrutto `::/2` può essere definito come: + +```logtalk +:- object(tracer, + implements(monitoring)). % built-in protocol for event handlers + + :- initialization(define_events(_, _, _, _, tracer)). + + before(Object, Message, Sender) :- + write('call: '), writeq(Object), write(' <-- '), writeq(Message), + write(' from '), writeq(Sender), nl. + + after(Object, Message, Sender) :- + write('exit: '), writeq(Object), write(' <-- '), writeq(Message), + write(' from '), writeq(Sender), nl. + +:- end_object. +``` + +Supponendo che l'oggetto `tracer` e l'oggetto `list` definito in precedenza siano stati già compilati e caricati, si possono osservare i gestori di eventi in azione durante l'invio di un messaggio: + +```logtalk +?- list::member(X, [1,2,3]). + +call: list <-- member(X, [1,2,3]) from user +exit: list <-- member(1, [1,2,3]) from user +X = 1 ; +exit: list <-- member(2, [1,2,3]) from user +X = 2 ; +exit: list <-- member(3, [1,2,3]) from user +X = 3 +yes +``` + +Gli eventi possono essere impostati e cancellati dinamicamente in fase di esecuzione chiamando i predicati predefiniti `define_events/5` e` abolish_events/5` . + +La programmazione event-driven può essere vista come una forma di _computational reflection_. Si noti però che gli eventi sono generati solo quando si utilizza il costrutto di controllo per l'invio di messaggi `::/2`. + +# Espressioni lambda + +Logtalk supporta anche le espressioni lambda. I parametri della espressioni lambda sono rappresentati mediante una lista con l'operatore infisso `(>>)/2` che collega i parametri alla relativa lambda espressione. Ecco alcuni semplici esempi di che usano i meta-predicati. + + +```logtalk +?- {library(metapredicates_loader)}. +yes + +?- meta::map([X,Y]>>(Y is 2*X), [1,2,3], Ys). +Ys = [2,4,6] +yes +``` + +Logtalk supporta anche il _currying_: + +```logtalk +?- meta::map([X]>>([Y]>>(Y is 2*X)), [1,2,3], Ys). +Ys = [2,4,6] +yes +``` + +Infine, le variabili libere Lambda possono essere espresso usando la sintassi estesa `{Free1, ...}/[Parameter1, ...]>>Lambda`. + +# Macro + +I Termini e goal nel file sorgente possono essere _estesi_ al momento della compilazione specificando una hook ad un oggetto (_hook object_) che definisce le regole di riscrittura dei termini e riscrittura dei quesiti. Ad esempio, si consideri il seguente oggetto semplice, salvato nel file `source.lgt`: + +```logtalk +:- object(source). + + :- public(bar/1). + bar(X) :- foo(X). + + foo(a). foo(b). foo(c). + +:- end_object. +``` + +Si supponga il seguente hook all'oggetto, salvato nel file `my_macros.lgt`, che estende le clausole e chiama il predicato locale `foo/1`: + +```logtalk +:- object(my_macros, + implements(expanding)). % built-in protocol for expanding predicates + + term_expansion(foo(Char), baz(Code)) :- + char_code(Char, Code). % standard built-in predicate + + goal_expansion(foo(X), baz(X)). + +:- end_object. +``` + +Dopo aver caricato il file contenente la macro, si può espandere il nostro file sorgente usando il flag del compilatore `hook`: + +```logtalk +?- logtalk_load(my_macros), logtalk_load(source, [hook(my_macros)]). +yes + +?- source::bar(X). +X = 97 ; +X = 98 ; +X = 99 +true +``` + +La libreria Logtalk fornisce infine il supporto per combinare hook agli oggetti utilizzando diversi modi (ad esempio, definendo una pipeline di espansioni). + + +# Maggiori informazioni + +Visita il [Sito web di Logtalk (en)](http://logtalk.org) per maggiori informazioni. diff --git a/javascript.html.markdown b/javascript.html.markdown index 38119864..a85a7872 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -225,7 +225,7 @@ do { } while (!isValid(input)) // The `for` loop is the same as C and Java: -// initialisation; continue condition; iteration. +// initialization; continue condition; iteration. for (var i = 0; i < 5; i++){ // will run 5 times } @@ -241,26 +241,12 @@ for (var i = 0; i < 10; i++) { } } -// The for/in statement iterates over every property across the entire prototype chain. +// The for/in statement allows iteration over properties of an object. var description = ""; var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ description += person[x] + " "; -} - -// To only consider properties attached to the object itself -// and not its prototypes, use the `hasOwnProperty()` check. -var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; -for (var x in person){ - if (person.hasOwnProperty(x)){ - description += person[x] + " "; - } -} - -// For/in should not be used to iterate over an Array where the index order -// is important, as there is no guarantee that for/in will return the indexes -// in any particular order. +} // description = 'Paul Ken 18 ' // && is logical and, || is logical or if (house.size == "big" && house.colour == "blue"){ @@ -273,7 +259,6 @@ if (colour == "red" || colour == "blue"){ // && and || "short circuit", which is useful for setting default values. var name = otherName || "default"; - // The `switch` statement checks for equality with `===`. // Use 'break' after each case // or the cases after the correct one will be executed too. @@ -449,6 +434,10 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 +// Unlike most other popular object-oriented languages, JavaScript has no +// concept of 'instances' created from 'class' blueprints; instead, JavaScript +// combines instantiation and inheritance into a single concept: a 'prototype'. + // 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. @@ -485,6 +474,26 @@ myObj.myBoolean; // = true myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 +// The for/in statement allows iteration over properties of an object, +// walking up the prototype chain until it sees a null prototype. +for (var x in myObj){ + console.log(myObj[x]); +} +///prints: +// Hello world! +// 42 +// [Function: myFunc] + +// To only consider properties attached to the object itself +// and not its prototypes, use the `hasOwnProperty()` check. +for (var x in myObj){ + if (myObj.hasOwnProperty(x)){ + console.log(myObj[x]); + } +} +///prints: +// Hello world! + // We mentioned that `__proto__` was non-standard, and there's no standard way to // change the prototype of an existing object. However, there are two ways to // create a new object with a given prototype. @@ -570,12 +579,15 @@ of the language. [JavaScript: The Definitive Guide][6] is a classic guide and reference book. -[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal - -[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great derivative of Eloquent Javascript with extra explanations and clarifications for some of the more complicated examples. +[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with +attached terminal -[Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices. +[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great +derivative of Eloquent Javascript with extra explanations and clarifications for +some of the more complicated examples. +[Javascript: The Right Way][10] is a guide intended to introduce new developers +to JavaScript and help experienced developers learn more about its best practices. 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][7] on the diff --git a/julia.html.markdown b/julia.html.markdown index a3154f09..85033aa6 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -775,4 +775,4 @@ code_native(circle_area, (Float64,)) You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/#Manual-1) -The best place to get help with Julia is the (very friendly) [mailing list](https://groups.google.com/forum/#!forum/julia-users). +The best place to get help with Julia is the (very friendly) [Discourse forum](https://discourse.julialang.org/). diff --git a/logtalk.html.markdown b/logtalk.html.markdown index d4010f8b..5a52bd3c 100644 --- a/logtalk.html.markdown +++ b/logtalk.html.markdown @@ -106,7 +106,7 @@ Error = error( yes ``` -A subtle point is that predicate scope directives specify predicate _calling_ semantics, not _definitions_ semantics. For example, if an object playing the role of a class declares a predicate private, the predicate can be defined in subclasses and instances *but* can only be called in its instances _from_ the class. +A subtle point is that predicate scope directives specify predicate _calling_ semantics, not _definition_ semantics. For example, if an object playing the role of a class declares a predicate private, the predicate can be defined in subclasses and instances *but* can only be called in its instances _from_ the class. # Defining and implementing a protocol @@ -182,7 +182,7 @@ A message is valid if the corresponding predicate is declared (and the sender is ```logtalk :- object(foo). - :- public(bar). + :- public(bar/0). :- end_object. ``` diff --git a/meteor.html.markdown b/meteor.html.markdown deleted file mode 100644 index 1685e0be..00000000 --- a/meteor.html.markdown +++ /dev/null @@ -1,567 +0,0 @@ ---- -category: tool -tool: meteor.js -Filename: meteor.html.markdown -contributors: - - ["Mohammed Rafy", "https://github.com/IamRafy/"] ---- - - - -Meteor is an ultra-simple environment for building modern websites. What once took weeks, even with the best tools, now takes hours with Meteor. - -The web was originally designed to work in the same way that mainframes worked in the 70s. The application server rendered a screen and sent it over the network to a dumb terminal. Whenever the user did anything, that server rerendered a whole new screen. This model served the Web well for over a decade. It gave rise to LAMP, Rails, Django, PHP. - -But the best teams, with the biggest budgets and the longest schedules, now build applications in JavaScript that run on the client. These apps have stellar interfaces. They don't reload pages. They are reactive: changes from any client immediately appear on everyone's screen. - -They've built them the hard way. Meteor makes it an order of magnitude simpler, and a lot more fun. You can build a complete application in a weekend, or a sufficiently caffeinated hackathon. No longer do you need to provision server resources, or deploy API endpoints in the cloud, or manage a database, or wrangle an ORM layer, or swap back and forth between JavaScript and Ruby, or broadcast data invalidations to clients. -Meteor Supports OS X, Windows, and Linux. // https://github.com/meteor/meteor/wiki/Supported-Platforms -On Windows? https://install.meteor.com/windows -On OS X or Linux? Install the latest official Meteor release from your terminal: -$ curl https://install.meteor.com/ | sh -The Windows installer supports Windows 7, Windows 8.1, Windows Server 2008, and Windows Server 2012. The command line installer supports Mac OS X 10.7 (Lion) and above, and Linux on x86 and x86_64 architectures. - -Once you've installed Meteor, create a project: -meteor create myapp -Run it locally: - -cd myapp -meteor -# Meteor server running on: http://localhost:3000/ - -Then, open a new terminal tab and unleash it on the world (on a free server we provide): - -meteor deploy myapp.meteor.com - -Principles of Meteor - -* Data on the Wire. Meteor doesn't send HTML over the network. The server sends data and lets the client render it. - -* One Language. Meteor lets you write both the client and the server parts of your application in JavaScript. - -* Database Everywhere. You can use the same methods to access your database from the client or the server. - -* Latency Compensation. On the client, Meteor prefetches data and simulates models to make it look like server method calls return instantly. - -* Full Stack Reactivity. In Meteor, realtime is the default. All layers, from database to template, update themselves automatically when necessary. - -* Embrace the Ecosystem. Meteor is open source and integrates with existing open source tools and frameworks. - -* Simplicity Equals Productivity. The best way to make something seem simple is to have it actually be simple. Meteor's main functionality has clean, classically beautiful APIs. - -Developer Resources -------------------- - -If anything in Meteor catches your interest, we hope you'll get involved with the project! - -TUTORIAL -Get started fast with the official Meteor tutorial! https://www.meteor.com/install - -STACK OVERFLOW -The best place to ask (and answer!) technical questions is on Stack Overflow. Be sure to add the meteor tag to your question. -http://stackoverflow.com/questions/tagged/meteor - -FORUMS -Visit the Meteor discussion forumsto announce projects, get help, talk about the community, or discuss changes to core. -https://forums.meteor.com/ - -GITHUB -The core code is on GitHub. If you're able to write code or file issues, we'd love to have your help. Please read Contributing to Meteor for how to get started. https://github.com/meteor/meteor - -THE METEOR MANUAL -In-depth articles about the core components of Meteor can be found on the Meteor Manual. The first article is about Tracker, our transparent reactivity framework. More articles (covering topics like Blaze, Unibuild, and DDP) are coming soon! http://manual.meteor.com/ - -What is Meteor? ---------------- - -Meteor is two things: - -A library of packages: pre-written, self-contained modules that you might need in your app. - -There are about a dozen core Meteor packages that most any app will use. Two examples: webapp, which handles incoming HTTP connections, and templating, which lets you make HTML templates that automatically update live as data changes. Then there are optional packages like email, which lets your app send emails, or the Meteor Accounts series (accounts-password, accounts-facebook, accounts-ui, and others) which provide a full-featured user account system that you can drop right into your app. In addition to these "core" packages, there are thousands of community-written packages in Atmosphere, one of which might do just what you need. - -A command-line tool called meteor. - -meteor is a build tool analogous to make, rake, or the non-visual parts of Visual Studio. It gathers up all of the source files and assets in your application, carries out any necessary build steps (such as compiling CoffeeScript, minifying CSS, building npm modules, or generating source maps), fetches the packages used by your app, and outputs a standalone, ready-to-run application bundle. In development mode it can do all of this interactively, so that whenever you change a file you immediately see the changes in your browser. It's super easy to use out of the box, but it's also extensible: you can add support for new languages and compilers by adding build plugin packages to your app. - -The key idea in the Meteor package system is that everything should work identically in the browser and on the server (wherever it makes sense, of course: browsers can't send email and servers can't capture mouse events). Our whole ecosystem has been built from the ground up to support this. - -Structuring your application ----------------------------- - -A Meteor application is a mix of client-side JavaScript that runs inside a web browser or PhoneGap mobile app, server-side JavaScript that runs on the Meteor server inside a Node.js container, and all the supporting HTML templates, CSS rules, and static assets. Meteor automates the packaging and transmission of these different components, and it is quite flexible about how you choose to structure those components in your file tree. - -Special Directories -------------------- - -By default, any JavaScript files in your Meteor folder are bundled and sent to the client and the server. However, the names of the files and directories inside your project can affect their load order, where they are loaded, and some other characteristics. Here is a list of file and directory names that are treated specially by Meteor: - -client - -Any directory named client is not loaded on the server. Similar to wrapping your code in if (Meteor.isClient) { ... }. All files loaded on the client are automatically concatenated and minified when in production mode. In development mode, JavaScript and CSS files are not minified, to make debugging easier. (CSS files are still combined into a single file for consistency between production and development, because changing the CSS file's URL affects how URLs in it are processed.) - -HTML files in a Meteor application are treated quite a bit differently from a server-side framework. Meteor scans all the HTML files in your directory for three top-level elements: <head>, <body>, and <template>. The head and body sections are separately concatenated into a single head and body, which are transmitted to the client on initial page load. - -server -Any directory named server is not loaded on the client. Similar to wrapping your code in if (Meteor.isServer) { ... }, except the client never even receives the code. Any sensitive code that you don't want served to the client, such as code containing passwords or authentication mechanisms, should be kept in the server directory. - -Meteor gathers all your JavaScript files, excluding anything under the client, public, and private subdirectories, and loads them into a Node.js server instance. In Meteor, your server code runs in a single thread per request, not in the asynchronous callback style typical of Node. We find the linear execution model a better fit for the typical server code in a Meteor application. - -public - -All files inside a top-level directory called public are served as-is to the client. When referencing these assets, do not include public/ in the URL, write the URL as if they were all in the top level. For example, reference public/bg.png as <img src='/bg.png' />. This is the best place for favicon.ico, robots.txt, and similar files. - -private - -All files inside a top-level directory called private are only accessible from server code and can be loaded via the Assets API. This can be used for private data files and any files that are in your project directory that you don't want to be accessible from the outside. - -client/compatibility - -This folder is for compatibility JavaScript libraries that rely on variables declared with var at the top level being exported as globals. Files in this directory are executed without being wrapped in a new variable scope. These files are executed before other client-side JavaScript files. -tests - -Any directory named tests is not loaded anywhere. Use this for any local test code. - -node_modules - -For compatibility with node.js tools used alongside Meteor, any directory named node_modules is not loaded anywhere. node.js packages installed into node_modules directories will not be available to your Meteor code. Use Npm.depends in your package package.js file for that. - -Files outside special directories ---------------------------------- - -All JavaScript files outside special directories are loaded on both the client and the server. That's the place for model definitions and other functions. Meteor provides the variables Meteor.isClient and Meteor.isServer (http://docs.meteor.com/#/full/meteor_isserver)so that your code can alter its behavior depending on whether it's running on the client or the server. - -CSS and HTML files outside special directories are loaded on the client only, and cannot be used from server code. - -Example File Structure - -The file structure of your Meteor app is very flexible. Here is an example layout that takes advantage of some of the special folders mentioned above. - -lib/ # common code like collections and utilities -lib/methods.js # Meteor.methods definitions -lib/constants.js # constants used in the rest of the code - -client/compatibility # legacy libraries that expect to be global -client/lib/ # code for the client to be loaded first -client/lib/helpers.js # useful helpers for your client code -client/body.html # content that goes in the <body> of your HTML -client/head.html # content for <head> of your HTML: <meta> tags, etc -client/style.css # some CSS code -client/<feature>.html # HTML templates related to a certain feature -client/<feature>.js # JavaScript code related to a certain feature - -server/lib/permissions.js # sensitive permissions code used by your server -server/publications.js # Meteor.publish definitions - -public/favicon.ico # app icon -settings.json # configuration data to be passed to meteor --settings -mobile-config.js # define icons and metadata for Android/iOS - -You can also model your directory structure after the example apps. Run meteor create --example todos and explore the directories to see where all the files in a real app could go. - -File Load Order ---------------- - -It is best to write your application in such a way that it is insensitive to the order in which files are loaded, for example by using Meteor.startup (http://docs.meteor.com/#/full/meteor_startup) , or by moving load order sensitive code into packages (http://docs.meteor.com/#/full/usingpackages) , which can explicitly control both the load order of their contents and their load order with respect to other packages. However, sometimes load order dependencies in your application are unavoidable. - -There are several load ordering rules. They are applied sequentially to all applicable files in the application, in the priority given below: - -HTML template files are always loaded before everything else -Files beginning with main. are loaded last -Files inside any lib/ directory are loaded next -Files with deeper paths are loaded next -Files are then loaded in alphabetical order of the entire path -nav.html -main.html -client/lib/methods.js -client/lib/styles.js -lib/feature/styles.js -lib/collections.js -client/feature-y.js -feature-x.js -client/main.js -For example, the files above are arranged in the correct load order. main.html is loaded second because HTML templates are always loaded first, even if it begins with main., since rule 1 has priority over rule 2. However, it will be loaded after nav.html because rule 2 has priority over rule 5. - -client/lib/styles.js and lib/feature/styles.js have identical load order up to rule 4; however, since client comes before lib alphabetically, it will be loaded first. - -Organizing Your Project ------------------------ - -There are three main ways to organize your files into features or components. Let's say we have two types of objects in our project: apples and oranges. - -Method 1: Root-Level Folders -Since the special client, server, and lib directories work if they are anywhere in the path, you can use top-level folders to organize code into modules: - -apples/lib/ # code for apple-related features -apples/client/ -apples/server/ - -oranges/lib/ # code for orange-related features -oranges/client/ -oranges/server/ - -Method 2: Folders inside client/ and server/ - -lib/apples/ # common code for apples -lib/oranges/ # and oranges - -client/apples/ # client code for apples -client/oranges/ # and oranges - -server/apples/ # server code for apples -server/oranges/ # and oranges - -Method 3: Packages - -This is the ultimate in code separation, modularity, and reusability. If you put the code for each feature in a separate package, the code for one feature won't be able to access the code for the other feature except through exports, making every dependency explicit. This also allows for the easiest independent testing of features. You can also publish the packages and use them in multiple apps with meteor add. - -packages/apples/package.js # files, dependencies, exports for apple feature -packages/apples/<anything>.js # file loading is controlled by package.js - -packages/oranges/package.js # files, dependencies, exports for orange feature -packages/oranges/<anything>.js # file loading is controlled by package.js - -Data and security ------------------ - -Meteor makes writing distributed client code as simple as talking to a local database. It's a clean, simple, and secure approach that removes the need to implement individual RPC endpoints, manually cache data on the client to avoid slow roundtrips to the server, and carefully orchestrate invalidation messages to every client as data changes. - -In Meteor, the client and server share the same database API. The same exact application code — like validators and computed properties — can often run in both places. But while code running on the server has direct access to the database, code running on the client does not. This distinction is the basis for Meteor's data security model. - -By default, a new Meteor app includes the autopublish and insecure packages, which together mimic the effect of each client having full read/write access to the server's database. These are useful prototyping tools, but typically not appropriate for production applications. When you're ready, just remove the packages. - -Every Meteor client includes an in-memory database cache. To manage the client cache, the server publishes sets of JSON documents, and the client subscribes to those sets. As documents in a set change, the server patches each client's cache. - -Today most Meteor apps use MongoDB as their database because it is the best supported, though support for other databases is coming in the future. The Mongo.Collection class is used to declare Mongo collections and to manipulate them. Thanks to minimongo, Meteor's client-side Mongo emulator, Mongo.Collection can be used from both client and server code. - -// declare collections -// this code should be included in both the client and the server -Rooms = new Mongo.Collection("rooms"); -Messages = new Mongo.Collection("messages"); -Parties = new Mongo.Collection("parties"); - -// server: populate collections with some initial documents -Rooms.insert({name: "Conference Room A"}); -var myRooms = Rooms.find({}).fetch(); -Messages.insert({text: "Hello world", room: myRooms[0]._id}); -Parties.insert({name: "Super Bowl Party"}); -Each document set is defined by a publish function on the server. The publish function runs each time a new client subscribes to a document set. The data in a document set can come from anywhere, but the common case is to publish a database query. - -// server: publish all room documents -Meteor.publish("all-rooms", function () { - return Rooms.find(); // everything -}); - -// server: publish all messages for a given room -Meteor.publish("messages", function (roomId) { - check(roomId, String); - return Messages.find({room: roomId}); -}); - -// server: publish the set of parties the logged-in user can see. -Meteor.publish("parties", function () { - return Parties.find({$or: [{"public": true}, - {invited: this.userId}, - {owner: this.userId}]}); -}); -Publish functions can provide different results to each client. In the last example, a logged in user can only see Party documents that are public, that the user owns, or that the user has been invited to. - -Once subscribed, the client uses its cache as a fast local database, dramatically simplifying client code. Reads never require a costly round trip to the server. And they're limited to the contents of the cache: a query for every document in a collection on a client will only return documents the server is publishing to that client. - -// client: start a parties subscription -Meteor.subscribe("parties"); - -// client: return array of Parties this client can read -return Parties.find().fetch(); // synchronous! -Sophisticated clients can turn subscriptions on and off to control how much data is kept in the cache and manage network traffic. When a subscription is turned off, all its documents are removed from the cache unless the same document is also provided by another active subscription. - -When the client changes one or more documents, it sends a message to the server requesting the change. The server checks the proposed change against a set of allow/deny rules you write as JavaScript functions. The server only accepts the change if all the rules pass. - -// server: don't allow client to insert a party -Parties.allow({ - insert: function (userId, party) { - return false; - } -}); - -// client: this will fail -var party = { ... }; -Parties.insert(party); -If the server accepts the change, it applies the change to the database and automatically propagates the change to other clients subscribed to the affected documents. If not, the update fails, the server's database remains untouched, and no other client sees the update. - -Meteor has a cute trick, though. When a client issues a write to the server, it also updates its local cache immediately, without waiting for the server's response. This means the screen will redraw right away. If the server accepted the update — what ought to happen most of the time in a properly behaving client — then the client got a jump on the change and didn't have to wait for the round trip to update its own screen. If the server rejects the change, Meteor patches up the client's cache with the server's result. - -Putting it all together, these techniques accomplish latency compensation. Clients hold a fresh copy of the data they need, and never need to wait for a roundtrip to the server. And when clients modify data, those modifications can run locally without waiting for the confirmation from the server, while still giving the server final say over the requested change. - -The current release of Meteor supports MongoDB, the popular document database, and the examples in this section use the MongoDB API. Future releases will include support for other databases. - -Authentication and user accounts --------------------------------- - -Meteor includes Meteor Accounts, a state-of-the-art authentication system. It features secure password login using the bcrypt algorithm, and integration with external services including Facebook, GitHub, Google, Meetup, Twitter, and Weibo. Meteor Accounts defines a Meteor.users collection where developers can store application-specific user data. - -Meteor also includes pre-built forms for common tasks like login, signup, password change, and password reset emails. You can add Accounts UI to your app with just one line of code. The accounts-ui package even provides a configuration wizard that walks you through the steps to set up the external login services you're using in your app. - -Input validation ----------------- - -Meteor allows your methods and publish functions to take arguments of any JSON type. (In fact, Meteor's wire protocol supports EJSON, an extension of JSON which also supports other common types like dates and binary buffers.) JavaScript's dynamic typing means you don't need to declare precise types of every variable in your app, but it's usually helpful to ensure that the arguments that clients are passing to your methods and publish functions are of the type that you expect. - -Meteor provides a lightweight library for checking that arguments and other values are the type you expect them to be. Simply start your functions with statements like check(username, String) or check(office, {building: String, room: Number}). The check call will throw an error if its argument is of an unexpected type. - -Meteor also provides an easy way to make sure that all of your methods and publish functions validate all of their arguments. Just run meteor add audit-argument-checks and any method or publish function which skips checking any of its arguments will fail with an exception. - -Reactivity ----------- - -Meteor embraces the concept of reactive programming (https://en.wikipedia.org/wiki/Reactive_programming). This means that you can write your code in a simple imperative style, and the result will be automatically recalculated whenever data changes that your code depends on. - -Tracker.autorun(function () { - Meteor.subscribe("messages", Session.get("currentRoomId")); -}); -This example (taken from a chat room client) sets up a data subscription based on the session variable currentRoomId. If the value of Session.get("currentRoomId") changes for any reason, the function will be automatically re-run, setting up a new subscription that replaces the old one. - -This automatic recomputation is achieved by a cooperation between Session and Tracker.autorun. Tracker.autorun performs an arbitrary "reactive computation" inside of which data dependencies are tracked, and it will re-run its function argument as necessary. Data providers like Session, on the other hand, make note of the computation they are called from and what data was requested, and they are prepared to send an invalidation signal to the computation when the data changes. - -This simple pattern (reactive computation + reactive data source) has wide applicability. Above, the programmer is saved from writing unsubscribe/resubscribe calls and making sure they are called at the right time. In general, Meteor can eliminate whole classes of data propagation code which would otherwise clog up your application with error-prone logic. - -These Meteor functions run your code as a reactive computation: - -Templates -Tracker.autorun -Template.autorun -Blaze.render and Blaze.renderWithData -And the reactive data sources that can trigger changes are: - -Session variables -Database queries on Collections -Meteor.status -The ready() method on a subscription handle -Meteor.user -Meteor.userId -Meteor.loggingIn -In addition, the following functions which return an object with a stop method, if called from a reactive computation, are stopped when the computation is rerun or stopped: - -Tracker.autorun (nested) -Meteor.subscribe -observe() and observeChanges() on cursors -Meteor's implementation is a package called Tracker that is fairly short and straightforward. You can use it yourself to implement new reactive data sources. - -Live HTML templates -------------------- - -HTML templating is central to web applications. With Blaze, Meteor's live page update technology, you can render your HTML reactively, meaning that it will update automatically to track changes in the data used to generate it. - -Meteor makes it easy to use your favorite HTML templating language along with Meteor's live page update technology. Just write your template as you normally would, and Meteor will take care of making it update in realtime. - -Meteor ships with a templating language called Spacebars (https://github.com/meteor/meteor/blob/master/packages/spacebars/README.md), inspired by Handlebars (http://handlebarsjs.com/). It shares some of the spirit and syntax of Handlebars, but it has been tailored to produce reactive Meteor templates when compiled. - -Today, the only templating system that ships with Meteor is Spacebars, though our community has created packages for other languages such as Jade. - -To define templates, create a file in your project with the .html extension. In the file, make a <template> tag and give it a name attribute. Put the template contents inside the tag. Meteor will precompile the template, ship it down to the client, and make it available as on the global Template object. - -When your app is loaded, it automatically renders the special template called <body>, which is written using the <body> element instead of a <template>. You insert a template inside another template by using the {{> inclusion}} operator. - -The easiest way to get data into templates is by defining helper functions in JavaScript. Define helpers with the Template.templateName.helpers({ ... }) function. Putting it all together: - -<!-- in myapp.html --> -<body> - <h1>Today's weather!</h1> - {{> forecast}} -</body> - -<template name="forecast"> - <div>It'll be {{prediction}} tonight</div> -</template> -// in client/myapp.js: reactive helper function -Template.forecast.helpers({ - prediction: function () { - return Session.get("weather"); - } -}); -// in the JavaScript console -> Session.set("weather", "cloudy"); -> document.body.innerHTML - => "<h1>Today's weather!</h1> <div>It'll be cloudy tonight</div>" - -> Session.set("weather", "cool and dry"); -> document.body.innerHTML - => "<h1>Today's weather!</h1> <div>It'll be cool and dry tonight</div>" -To iterate over an array or database cursor, use {{#each}}: - -<!-- in myapp.html --> -<template name="players"> - {{#each topScorers}} - <div>{{name}}</div> - {{/each}} -</template> -// in myapp.js -Template.players.helpers({ - topScorers: function () { - return Users.find({score: {$gt: 100}}, {sort: {score: -1}}); - } -}); -In this case, the data is coming from a database query. When the database cursor is passed to {{#each}}, it will wire up all of the machinery to efficiently add and move DOM nodes as new results enter the query. - -Helpers can take arguments, and they receive the current template context data in this. Note that some block helpers change the current context (notably {{#each}} and {{#with}}): - -// in a JavaScript file -Template.players.helpers({ - leagueIs: function (league) { - return this.league === league; - } -}); -<!-- in a HTML file --> -<template name="players"> - {{#each topScorers}} - {{#if leagueIs "junior"}} - <div>Junior: {{name}}</div> - {{/if}} - {{#if leagueIs "senior"}} - <div>Senior: {{name}}</div> - {{/if}} - {{/each}} -</template> -Helpers can also be used to pass in constant data. - -// Works fine with {{#each sections}} -Template.report.helpers({ - sections: ["Situation", "Complication", "Resolution"] -}); -Finally, you can use the events function on a template to attach event handlers. The object passed into events is documented at Event Maps. The this argument to the event handler will be the data context of the element that triggered the event. - -<!-- myapp.html --> -<template name="scores"> - {{#each player}} - {{> playerScore}} - {{/each}} -</template> - -<template name="playerScore"> - <div>{{name}}: {{score}} - <span class="give-points">Give points</span> - </div> -</template> -// myapp.js -Template.playerScore.events({ - 'click .give-points': function () { - Users.update(this._id, {$inc: {score: 2}}); - } -}); -For more details about Spacebars, read the Spacebars README. (https://github.com/meteor/meteor/blob/master/packages/spacebars/README.md) - -Using packages --------------- - -All of the functionality you've read about so far is implemented in standard Meteor packages. This is possible thanks to Meteor's unusually powerful isomorphic package and build system. Isomorphic means the same packages work in the web browser, in mobile apps, and on the server. Packages can also contain plugins that extend the build process, such as coffeescript (CoffeeScript compilation : http://coffeescript.org/) or templating (compiling HTML templates). - -Anyone can publish a Meteor package, and thousands of community-written packages have been published to date. The easiest way to browse these packages is Atmosphere, by Percolate Studio. You can also use the meteor search and meteor show commands. - -You can add packages to your project with meteor add and remove them with meteor remove. Additionally, meteor list will tell you what packages your project is using, and meteor update will update them to the newest versions when possible. - -By default all apps include the meteor-base package. This pulls in the packages that make up the core of the Meteor stack. Most apps will have this package. - -All new apps also start with a set of packages that allow a friendly development experience. For more information about these packages, check out the comments in the packages file. - -Meteor uses a single-loading packaging system, meaning that it loads just one version of every package. Before adding or upgrading to a particular version of a package, Meteor uses a constraint solver to check if doing so will cause other packages to break. By default, Meteor will choose conservatively. When adding transitive dependencies (packages that other packages, but not the application itself) depend on, Meteor will try to choose the earlier version. - -In addition to the packages in the official Meteor release being used by your app, meteor list and meteor add also search the packages directory at the top of your app. You can also use the packages directory to break your app into subpackages for your convenience, or to test packages that you might want to publish. See Writing Packages (http://docs.meteor.com/#/full/writingpackages) . If you wish to add packages outside of your app's folder structure, set the environment variable PACKAGE_DIRS to a colon-delimited list of paths. - -Namespacing ------------ - -Meteor's namespacing support makes it easy to write large applications in JavaScript. Each package that you use in your app exists in its own separate namespace, meaning that it sees only its own global variables and any variables provided by the packages that it specifically uses. Here's how it works. - -When you declare a top-level variable, you have a choice. You can make the variable File Scope or Package Scope. - -// File Scope. This variable will be visible only inside this -// one file. Other files in this app or package won't see it. -var alicePerson = {name: "alice"}; - -// Package Scope. This variable is visible to every file inside -// of this package or app. The difference is that 'var' is -// omitted. -bobPerson = {name: "bob"}; -Notice that this is just the normal JavaScript syntax for declaring a variable that is local or global. Meteor scans your source code for global variable assignments and generates a wrapper that makes sure that your globals don't escape their appropriate namespace. - -In addition to File Scope and Package Scope, there are also Exports. An export is a variable that a package makes available to you when you use it. For example, the email package exports the Email variable. If your app uses the email package (and only if it uses the email package!) then your app can see Email and you can call Email.send. Most packages have only one export, but some packages might have two or three (for example, a package that provides several classes that work together). - -You see only the exports of the packages that you use directly. If you use package A, and package A uses package B, then you only see package A's exports. Package B's exports don't "leak" into your namespace just because you used package A. This keeps each namespace nice and tidy. Each app or package only sees their own globals plus the APIs of the packages that they specifically asked for. - -When debugging your app, your browser's JavaScript console behaves as if it were attached to your app's namespace. You see your app's globals and the exports of the packages that your app uses directly. You don't see the variables from inside those packages, and you don't see the exports of your transitive dependencies (packages that aren't used directly by your app, but that are used by packages that are used by your app). - -If you want to look inside packages from inside your in-browser debugger, you've got two options: - -Set a breakpoint inside package code. While stopped on that breakpoint, the console will be in the package's namespace. You'll see the package's package-scope variables, imports, and also any file-scope variables for the file you're stopped in. - -If a package foo is included in your app, regardless of whether your app uses it directly, its exports are available in Package.foo. For example, if the email package is loaded, then you can access Package.email.Email.send even from namespaces that don't use the email package directly. - -When declaring functions, keep in mind that function x () {} is just shorthand for var x = function x () {} in JavaScript. Consider these examples: - -// This is the same as 'var x = function x () ...'. So x() is -// file-scope and can be called only from within this one file. -function x () { ... } - -// No 'var', so x() is package-scope and can be called from -// any file inside this app or package. -x = function () { ... } -Technically speaking, globals in an app (as opposed to in a package) are actually true globals. They can't be captured in a scope that is private to the app code, because that would mean that they wouldn't be visible in the console during debugging! This means that app globals actually end up being visible in packages. That should never be a problem for properly written package code (since the app globals will still be properly shadowed by declarations in the packages). You certainly shouldn't depend on this quirk, and in the future Meteor may check for it and throw an error if you do. - -Deploying ---------- - -Meteor is a full application server. We include everything you need to deploy your application on the internet: you just provide the JavaScript, HTML, and CSS. - -Running on Meteor's infrastructure ----------------------------------- - -The easiest way to deploy your application is to use meteor -deploy. We provide it because it's what, personally, we've always wanted: an easy way to take an app idea, flesh it out over a weekend, and put it out there for the world to use, with nothing getting in the way of creativity. - -meteor deploy myapp.meteor.com -Your application is now available at myapp.meteor.com. If this is the first time deploying to this hostname, Meteor creates a fresh empty database for your application. If you want to deploy an update, Meteor will preserve the existing data and just refresh the code. - -You can also deploy to your own domain. Just set up the hostname you want to use as a CNAME to origin.meteor.com, then deploy to that name. - -meteor deploy www.myapp.com -We provide this as a free service so you can try Meteor. It is also helpful for quickly putting up internal betas, demos, and so on. For more information, see meteor deploy. - -Running on your own infrastructure ----------------------------------- - -You can also run your application on your own infrastructure or any hosting provider that can run Node.js apps. - -To get started, run - -meteor build my_directory -This command will generate a fully-contained Node.js application in the form of a tarball. To run this application, you need to provide Node.js 0.10 and a MongoDB server. (The current release of Meteor has been tested with Node 0.10.40.) You can then run the application by invoking node, specifying the HTTP port for the application to listen on, and the MongoDB endpoint. - -cd my_directory -(cd programs/server && npm install) -env PORT=3000 MONGO_URL=mongodb://localhost:27017/myapp node main.js -Some packages might require other environment variables. For example, the email package requires a MAIL_URL environment variable. - -Writing packages ----------------- - -Writing Meteor packages is easy. To initialize a meteor package, run meteor create --package username:packagename, where username is your Meteor Developer username. This will create a package from scratch and prefill the directory with a package.js control file and some javascript. By default, Meteor will take the package name from the name of the directory that contains the package.js file. Don't forget to run meteor add [packagename], even if the package is internal to the app, in order to use it. - -Meteor promises repeatable builds for both packages and applications. This means that, if you built your package on a machine, then checked the code into a repository and checked it out elsewhere, you should get the same result. In your package directory, you will find an automatically generated .versions file. This file specifies the versions of all packages used to build your package and is part of the source. Check it into version control to ensure repeatable builds across machines. - -Sometimes, packages do not just stand on their own, but function in the context of an app (specifically, packages in the packages directory of an app). In that case, the app's context will take precedence. Rather than using the .versions file as a guide, we will build the package with the same dependencies as used by the app (we think that, in practice, it would be confusing to find your local packages built with different versions of things). - -Meteor uses extended semver versioning for its packages: that means that the version number has three parts separated by dots: major version, minor version and patch version (for example: 1.2.3) with an optional pre-release version. You can read more about it on semver.org. Additionally, because some meteor packages wrap external libraries, Meteor supports the convention of using _ to denote a wrap number. - -You can read more about package.js (http://docs.meteor.com/#/full/packagejs) files in the API section. - -A word on testing: since testing is an important part of the development process, there are two common ways to test a package: - -Integration tests (putting a package directly into an application, and writing tests against the application) is the most common way to test a package. After creating your package, add it to your app's /packages directory and run meteor add. This will add your package to your app as a local package. You can then test and run your app as usual. Meteor will detect and respond to changes to your local package, just as it does to your app files. - -Unit tests are run with the command meteor test-packages package-name. As described in the package.js section, you can use the package.js file to specify where your unit tests are located. If you have a repository that contains only the package source, you can test your package by specifying the path to the package directory (which must contain a slash), such as meteor test-packages ./. - -To publish a package, run meteor publish from the package directory. There are some extra restrictions on published packages: they must contain a version (Meteor packages are versioned using strict semver versioning) and their names must be prefixed with the username of the author and a colon, like so: iron:router. This namespacing allows for more descriptive and on-topic package names. - - - - diff --git a/perl6.html.markdown b/perl6.html.markdown index e813978a..7485ed57 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -25,14 +25,20 @@ double paragraphs, and single notes. Multiline comments use #` and a quoting construct. (), [], {}, 「」, etc, will work. ) +``` -### Variables +## Variables +```perl6 # In Perl 6, you declare a lexical variable using `my` my $variable; # Perl 6 has 4 kinds of variables: +``` -## * Scalars. They represent a single value. They start with a `$` +### Scalars + +```perl6 +# Scalars represent a single value. They start with a `$` my $str = 'String'; # double quotes allow for interpolation (which we'll see later): @@ -46,8 +52,12 @@ my $bool = True; # `True` and `False` are Perl 6's boolean values. my $inverse = !$bool; # You can invert a bool with the prefix `!` operator my $forced-bool = so $str; # And you can use the prefix `so` operator # which turns its operand into a Bool +``` -## * Lists. They represent multiple values. Their name start with `@`. +### Lists + +```perl6 +# Lists represent multiple values. Their name start with `@`. my @array = 'a', 'b', 'c'; # equivalent to : @@ -66,8 +76,11 @@ say "Interpolate all elements of an array using [] : @array[]"; my @keys = 0, 2; @array[@keys] = @letters; # Assignment using an array containing index values say @array; #=> a 6 b +``` -## * Hashes, or key-value Pairs. +### Hashes, or key-value Pairs. + +```perl6 # Hashes are pairs of keys and values. # You can construct a Pair object using the syntax `Key => Value`. # Hash tables are very fast for lookup, and are stored unordered. @@ -96,9 +109,13 @@ my %hash = :w(1), # equivalent to `w => 1` say %hash{'key1'}; # You can use {} to get the value from a key say %hash<key2>; # If it's a string, you can actually use <> # (`{key1}` doesn't work, as Perl6 doesn't have barewords) +``` -## * Subs: subroutines or functions as most other languages call them are -# created with the `sub` keyword. +## Subs + +```perl6 +# subroutines or functions as most other languages call them are +# created with the `sub` keyword. sub say-hello { say "Hello, world" } sub say-hello-to(Str $name) { # You can provide the type of an argument @@ -186,8 +203,11 @@ sub concat3($a, $b, $c) { } concat3(|@array); #=> a, b, c # `@array` got "flattened" as a part of the argument list +``` -### Containers +## Containers + +```perl6 # In Perl 6, values are actually stored in "containers". # The assignment operator asks the container on the left to store the value on # its right. When passed around, containers are marked as immutable. @@ -216,11 +236,12 @@ sub x-store() is rw { $x } x-store() = 52; # in this case, the parentheses are mandatory # (else Perl 6 thinks `x-store` is an identifier) say $x; #=> 52 +``` +## Control Flow Structures +### Conditionals -### Control Flow Structures -## Conditionals - +```perl6 # - `if` # Before talking about `if`, we need to know which values are "Truthy" # (represent True), and which are "Falsey" (or "Falsy") -- represent False. @@ -249,7 +270,11 @@ say "Quite truthy" if True; my $age = 30; say $age > 18 ?? "You are an adult" !! "You are under 18"; +``` +### given/when, or switch + +```perl6 # - `given`-`when` looks like other languages' `switch`, but is much more # powerful thanks to smart matching and Perl 6's "topic variable", $_. # @@ -282,9 +307,11 @@ given "foo bar" { say "Something else" } } +``` -## Looping constructs +### Looping constructs +```perl6 # - `loop` is an infinite loop if you don't pass it arguments, # but can also be a C-style `for` loop: loop { @@ -327,9 +354,11 @@ for @array { if long-computation() -> $result { say "The result is $result"; } +``` -### Operators +## Operators +```perl6 ## Since Perl languages are very much operator-based languages, ## Perl 6 operators are actually just funny-looking subroutines, in syntactic ## categories, like infix:<+> (addition) or prefix:<!> (bool not). @@ -448,12 +477,18 @@ $b || $a; # 1 $a *= 2; # multiply and assignment. Equivalent to $a = $a * 2; $b %%= 5; # divisible by and assignment @array .= sort; # calls the `sort` method and assigns the result back +``` + +## More on subs ! -### More on subs ! +```perl6 # As we said before, Perl 6 has *really* powerful subs. We're going to see # a few more key concepts that make them better than in any other language :-). +``` + +### Unpacking ! -## Unpacking ! +```perl6 # It's the ability to "extract" arrays and keys (AKA "destructuring"). # It'll work in `my`s and in parameter lists. my ($f, $g) = 1, 2; @@ -521,7 +556,11 @@ sub list-of($n) { } } my @list3 = list-of(3); #=> (0, 1, 2) +``` + +### lambdas +```perl6 ## You can create a lambda with `-> {}` ("pointy block") or `{}` ("block") my &lambda = -> $argument { "The argument passed to this lambda is $argument" } # `-> {}` and `{}` are pretty much the same thing, except that the former can @@ -564,8 +603,11 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) # Note : those are sorted lexicographically. # `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` +``` + +### About types... -## About types... +```perl6 # Perl6 is gradually typed. This means you can specify the type # of your variables/arguments/return types, or you can omit them # and they'll default to "Any". @@ -579,8 +621,11 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) # You can specify the type you're subtyping (by default, Any), # and add additional checks with the "where" keyword: subset VeryBigInteger of Int where * > 500; +``` + +### Multiple Dispatch -## Multiple Dispatch +```perl6 # Perl 6 can decide which variant of a `sub` to call based on the type of the # arguments, or on arbitrary preconditions, like with a type or a `where`: @@ -624,9 +669,11 @@ multi with-or-without-you { # sub trait_mod:<is>(Routine $r, :$rw!) {} # # (commented because running this would be a terrible idea !) +``` +## Scoping -### Scoping +```perl6 # In Perl 6, unlike many scripting languages, (such as Python, Ruby, PHP), # you must declare your variables before using them. The `my` declarator # you have learned uses "lexical scoping". There are a few other declarators, @@ -646,9 +693,11 @@ outer()(); #=> 'Foo Bar' # As you can see, `$file_scoped` and `$outer_scoped` were captured. # But if we were to try and use `$bar` outside of `foo`, # the variable would be undefined (and you'd get a compile time error). +``` -### Twigils +## Twigils +```perl6 # There are many special `twigils` (composed sigil's) in Perl 6. # Twigils define the variables' scope. # The * and ? twigils work on standard variables: @@ -683,9 +732,11 @@ call_say_dyn(); #=> 25 100 # we are calling it from outside. say_dyn(); #=> 1 100 We changed the value of $*dyn_scoped_2 in call_say_dyn # so now its value has changed. +``` -### Object Model +## Object Model +```perl6 # To call a method on an object, add a dot followed by the method name: # => $object.method # Classes are declared with the `class` keyword. Attributes are declared @@ -730,8 +781,11 @@ say $class-obj.get-value; #=> 15 #$class-obj.attrib = 5; # This fails, because the `has $.attrib` is immutable $class-obj.other-attrib = 10; # This, however, works, because the public # attribute is mutable (`rw`). +``` + +### Object Inheritance -## Object Inheritance +```perl6 # Perl 6 also has inheritance (along with multiple inheritance) # While `method`'s are inherited, `submethod`'s are not. # Submethods are useful for object construction and destruction tasks, @@ -768,9 +822,12 @@ $Madison.talk; # prints "Goo goo ga ga" due to the overrided method. # `$a .= b` is the same as `$a = $a.b`) # Also note that `BUILD` (the method called inside `new`) # will set parent properties too, so you can pass `val => 5`. +``` +### Roles, or Mixins -## Roles are supported too (also called Mixins in other languages) +```perl6 +# Roles are supported too (also called Mixins in other languages) role PrintableVal { has $!counter = 0; method print { @@ -798,8 +855,11 @@ class Item does PrintableVal { # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods # will be shadowed, since the compiler will consider `ROLE` to be a class. } +``` + +## Exceptions -### Exceptions +```perl6 # Exceptions are built on top of classes, in the package `X` (like `X::IO`). # In Perl6 exceptions are automatically 'thrown' open 'foo'; #> Failed to open file foo: no such file or directory @@ -828,8 +888,11 @@ open 'foo' orelse say "Something happened $_"; #> Something happened # Both of those above work but in case we get an object from the left side that # is not a failure we will probably get a warning. We see below how we can use # `try` and `CATCH` to be more specific with the exceptions we catch. +``` + +### Using `try` and `CATCH` -## Using `try` and `CATCH` +```perl6 # By using `try` and `CATCH` you can contain and handle exceptions without # disrupting the rest of the program. `try` will set the last exception to # the special variable `$!` Note: This has no relation to $!variables. @@ -883,8 +946,11 @@ try { # Those are "good" exceptions, which happen when you change your program's flow, # using operators like `return`, `next` or `last`. # You can "catch" those with `CONTROL` (not 100% working in Rakudo yet). +``` + +## Packages -### Packages +```perl6 # Packages are a way to reuse code. Packages are like "namespaces", and any # element of the six model (`module`, `role`, `class`, `grammar`, `subset` # and `enum`) are actually packages. (Packages are the lowest common denominator) @@ -915,8 +981,11 @@ grammar Parse::Text::Grammar { # A grammar is a package, which you could `use` my $actions = JSON::Tiny::Actions.new; # We'll see how to export variables and subs in the next part: +``` + +## Declarators -### Declarators +```perl6 # In Perl 6, you get different behaviors based on how you declare a variable. # You've already seen `my` and `has`, we'll now explore the others. @@ -978,10 +1047,11 @@ for ^5 -> $a { # Next iteration will re-run `rand`. } } +``` +## Phasers - -### Phasers +```perl6 # Phasers in Perl 6 are blocks that happen at determined points of time in your # program. They are called phasers because they mark a change in the phase # of a program. For example, when the program is compiled, a for loop runs, @@ -1041,8 +1111,11 @@ sub do-db-stuff { KEEP $db.commit; # commit the transaction if all went well UNDO $db.rollback; # or rollback if all hell broke loose } +``` + +## Statement prefixes -### Statement prefixes +```perl6 # Those act a bit like phasers: they affect the behavior of the following code. # Though, they run in-line with the executable code, so they're in lowercase. # (`try` and `start` are theoretically in that list, but explained somewhere else) @@ -1085,8 +1158,11 @@ say join ',', gather if False { constant thrice = gather for ^3 { say take $_ }; # Doesn't print anything # versus: constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2 +``` + +## Iterables -### Iterables +```perl6 # Iterables are objects that can be iterated similar to the `for` construct # `flat`, flattens iterables: say (1, 10, (20, 10) ); #> (1 10 (20 10)) Notice how grouping is maintained @@ -1108,9 +1184,11 @@ quietly { warn 'This is a warning!' }; #=> No output # - `contend` - Attempts side effects under STM # Not yet implemented ! +``` -### More operators thingies ! +## More operators thingies ! +```perl6 ## Everybody loves operators ! Let's get more of them # The precedence list can be found here: @@ -1128,8 +1206,11 @@ $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` !$a! # with left-associative `!`, this is `(!$a)!` !$a! # with right-associative `!`, this is `!($a!)` !$a! # with non-associative `!`, this is illegal +``` -## Create your own operators ! +### Create your own operators ! + +```perl6 # Okay, you've been reading all of that, so I guess I should try # to show you something exciting. # I'll tell you a little secret (or not-so-secret): @@ -1193,8 +1274,11 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # (you are, obviously, recommended against making an operator out of # *everything* -- with great power comes great responsibility) +``` -## Meta operators ! +### Meta operators ! + +```perl6 # Oh boy, get ready. Get ready, because we're delving deep # into the rabbit's hole, and you probably won't want to go # back to other languages after reading that. @@ -1281,8 +1365,11 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55 # Note : as for ranges, once reified, elements aren't re-calculated. # That's why `@primes[^100]` will take a long time the first time you print # it, then be instant. +``` -### Regular Expressions +## Regular Expressions + +```perl6 # I'm sure a lot of you have been waiting for this one. # Well, now that you know a good deal of Perl 6 already, we can get started. # First off, you'll have to forget about "PCRE regexps" (perl-compatible regexps). @@ -1402,8 +1489,11 @@ so 'foo' ~~ / <-[ f o ]> + /; # False so 'foo' ~~ / <[ a..z ] - [ f o ]> + /; # False (any letter except f and o) so 'foo' ~~ / <-[ a..z ] + [ f o ]> + /; # True (no letter except f and o) so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left part) +``` -## Grouping and capturing +### Grouping and capturing + +```perl6 # Group: you can group parts of your regexp with `[]`. # These groups are *not* captured (like PCRE's `(?:)`). so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing @@ -1478,7 +1568,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... # and other things that can't traditionnaly be represented by normal regexps. # # Then, all the alternatives are tried at once, and the longest wins. -# Exemples: +# Examples: # DECLARATIVE | PROCEDURAL / 'foo' \d+ [ <subrule1> || <subrule2> ] /; # DECLARATIVE (nested groups are not a problem) @@ -1489,11 +1579,11 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... # Note: the first-matching `or` still exists, but is now spelled `||` 'foo' ~~ / fo || foo /; # `fo` now. +``` +## Extra: the MAIN subroutine - - -### Extra: the MAIN subroutine +```perl6 # The `MAIN` subroutine is called when you run a Perl 6 file directly. # It's very powerful, because Perl 6 actually parses the arguments # and pass them as such to the sub. It also handles named argument (`--foo`) @@ -1521,13 +1611,12 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name # As you can see, this is *very* powerful. # It even went as far as to show inline the constants. # (the type is only displayed if the argument is `$`/is named) +``` -### -### APPENDIX A: -### +## APPENDIX A: ### List of things -### +```perl6 # It's considered by now you know the Perl6 basics. # This section is just here to list some common operations, # but which are not in the "main part" of the tutorial to bloat it up diff --git a/purescript.html.markdown b/purescript.html.markdown index 19346760..9ea84d5b 100644 --- a/purescript.html.markdown +++ b/purescript.html.markdown @@ -65,7 +65,7 @@ true && (9 >= 19 || 1 < 2) -- true """Hello world""" -- "Hello\nworld" -- Concatenate -"such " ++ "amaze" -- "such amaze" +"such " <> "amaze" -- "such amaze" -- -- 2. Arrays are Javascript arrays, but must be homogeneous diff --git a/python3.html.markdown b/python3.html.markdown index 02745117..6a2a7ccd 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -208,9 +208,9 @@ li[4] # Raises an IndexError # You can look at ranges with slice syntax. # (It's a closed/open range for you mathy types.) li[1:3] # => [2, 4] -# Omit the beginning -li[2:] # => [4, 3] # Omit the end +li[2:] # => [4, 3] +# Omit the beginning li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] @@ -724,13 +724,16 @@ if __name__ == '__main__': # Call the static method print(Human.grunt()) # => "*grunt*" - print(i.grunt()) # => "*grunt*" - + + # Cannot call static method with instance of object + # because i.grunt() will automatically put "self" (the object i) as an argument + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + # Update the property for this instance i.age = 42 # Get the property - i.say(i.age) # => 42 - j.say(j.age) # => 0 + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" # Delete the property del i.age # i.age # => this would raise an AttributeError diff --git a/rst.html.markdown b/rst.html.markdown index 59a29daa..1fbff015 100644 --- a/rst.html.markdown +++ b/rst.html.markdown @@ -1,5 +1,5 @@ --- -language: restructured text +language: restructured text (RST) contributors: - ["DamienVGN", "https://github.com/martin-damien"] - ["Andre Polykanine", "https://github.com/Oire"] diff --git a/ru-ru/asymptotic-notation-ru.html.markdown b/ru-ru/asymptotic-notation-ru.html.markdown new file mode 100644 index 00000000..73ad80ba --- /dev/null +++ b/ru-ru/asymptotic-notation-ru.html.markdown @@ -0,0 +1,225 @@ +--- +category: Algorithms & Data Structures +name: Asymptotic Notation +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Divay Prakash", "http://github.com/divayprakash"] +translators: + - ["pru-mike", "http://gihub.com/pru-mike"] +lang: ru-ru +--- + +# О-cимволика + +## Что это такое? + +О-cимволика или асимптотическая запись это система символов позволяющая оценить +время выполнения алгоритма, устанавливая зависимость времени выполнения от +увеличения объема входных данных, так же известна как оценка +сложности алгоритмов. Быстро-ли алгоритм станет невероятно медленным, когда +объем входных данных увеличится? Будет-ли алгоритм выполняться достаточно быстро, +если объем входных данных возрастет? О-символика позволяет ответить на эти +вопросы. + +## Можно-ли по-другому найти ответы на эти вопросы? + +Один способ это подсчитать число элементарных операций в зависимости от +различных объемов входных данных. Хотя это и приемлемое решение, тот объем +работы которого оно потребует, даже для простых алгоритмов, делает его +использование неоправданным. + +Другой способ это измерить какое время алгоритм потребует для завершения на +различных объемах входных данных. В тоже время, точность и относительность +(полученное время будет относиться только к той машине на которой оно +вычислено) этого метода зависит от среды выполнения: компьютерного аппаратного +обеспечения, мощности процессора и т.д. + +## Виды О-символики + +В первом разделе этого документа мы определили, что О-символика +позволяет оценивать алгоритмы в зависимости от изменения размера входных +данных. Представим что алгоритм это функция f, n размер входных данных и +f(n) время выполнения. Тогда для данного алгоритма f c размером входных +данных n получим какое-то результирующее время выполнения f(n). +Из этого можно построить график, где ось Y время выполнения, ось X размер входных +данных и точки на графике это время выполнения для заданного размера входных +данных. + +С помощью О-символики можно оценить функцию или алгоритм +несколькими различными способами. Например можно оценить алгоритм исходя +из нижней оценки, верхней оценки, тождественной оценки. Чаще всего встречается +анализ на основе верхней оценки. Как правило не используется нижняя оценка, +потому что она не подходит под планируемые условия. Отличный пример алгоритмы +сортировки, особенно добавление элементов в древовидную структуру. Нижняя оценка +большинства таких алгоритмов может быть дана как одна операция. В то время как в +большинстве случаев, добавляемые элементы должны быть отсортированы +соответствующим образом при помощи дерева, что может потребовать обхода целой +ветви. Это и есть худший случай, для которого планируется верхняя оценка. + +### Виды функций, пределы и упрощения + +``` +Логарифмическая функция - log n +Линейная функция - an + b +Квадратическая функция - an^2 + bn +c +Полиномиальная функция - an^z + . . . + an^2 + a*n^1 + a*n^0, где z константа +Экспоненциальная функция - a^n, где a константа +``` + +Приведены несколько базовых функций используемых при определении сложности в +различных оценках. Список начинается с самой медленно возрастающей функции +(логарифм, наиболее быстрое время выполнения) и следует до самой быстро +возрастающей функции (экспонента, самое медленное время выполнения). Отметим, +что в то время как 'n' или размер входных данных, возрастает в каждой из этих функций, +результат намного быстрее возрастает в квадратической, полиномиальной +и экспоненциальной по сравнению с логарифмической и линейной. + +Крайне важно понимать, что при использовании описанной далее нотации необходимо +использовать упрощенные выражения. +Это означает, что необходимо отбрасывать константы и слагаемые младших порядков, +потому что если размер входных данных (n в функции f(n) нашего примера) +увеличивается до бесконечности (в пределе), тогда слагаемые младших порядков +и константы становятся пренебрежительно малыми. Таким образом, если есть +константа например размера 2^9001 или любого другого невообразимого размера, +надо понимать, что её упрощение внесёт значительные искажения в точность +оценки. + +Т.к. нам нужны упрощенные выражения, немного скорректируем нашу таблицу... + +``` +Логарифм - log n +Линейная функция - n +Квадратическая функция - n^2 +Полиномиальная функция - n^z, где z константа +Экспонента - a^n, где a константа +``` + +### О-Большое +О-Большое, записывается как **О**, это асимптотическая запись для оценки худшего +случая или для ограничения заданой функции сверху. Это позволяет сделать +_**асимптотическую оценку верхней границы**_ скорости роста времени выполнения +алгоритма. Допустим `f(n)` время выполнения алгоритма и `g(n)` заданная временная +сложность которая проверяется для алгоритма. Тогда `f(n)` это O(g(n)), если +существуют действительные константы с (с > 0) и n<sub>0</sub>, такие +что `f(n)` <= `c g(n)` выполняется для всех n начиная с некоторого n<sub>0</sub> (n > n<sub>0</sub>). + +*Пример 1* + +``` +f(n) = 3log n + 100 +g(n) = log n +``` + +Является-ли `f(n)` O(g(n))? +Является-ли `3 log n + 100` O(log n)? +Посмотрим на определение О-Большого: + +``` +3log n + 100 <= c * log n +``` + +Существуют-ли константы c, n<sub>0</sub> такие что выражение верно для всех n > n<sub>0</sub> + +``` +3log n + 100 <= 150 * log n, n > 2 (неопределенно для n = 1) +``` + +Да! По определению О-Большого `f(n)` является O(g(n)). + +*Пример 2* + +``` +f(n) = 3 * n^2 +g(n) = n +``` + +Является-ли `f(n)` O(g(n))? +Является-ли `3 * n^2` O(n)? +Посмотрим на определение О-Большого: + +``` +3 * n^2 <= c * n +``` + +Существуют-ли константы c, n<sub>0</sub> такие что выражение верно для всех n > n<sub>0</sub>? +Нет, не существуют. `f(n)` НЕ ЯВЛЯЕТСЯ O(g(n)). + +### Омега-Большое +Омега-Большое, записывается как **Ω**, это асимптотическая запись для оценки +лучшего случая или для ограничения заданой функции снизу. Это позволяет сделать +_**асимптотическую оценку нижней границы**_ скорости роста времени выполнения +алгоритма. + +`f(n)` принадлежит Ω(g(n)), если существуют действительные константы +с (с > 0) и <sub>0</sub> (n<sub>0</sub> > 0), такие что `f(n)` >= `c g(n)` для всех n > n<sub>0</sub>. + +### Примечание + +Асимптотические оценки сделаные при помощи О-Большое и Омега-Большое могут +как быть так и не быть точными. Для того что бы обозначить что границы не +являются асимптотически точными используются записи о-малое и омега-малое. + +### О-Малое +O-Малое, записывается как **о**, это асимптотическая запись для оценки верхней +границы времени выполнения алгоритма, при условии что граница не является +асимптотически точной. + +`f(n)` является o(g(n)), если можно подобрать такие действительные константы, +что для всех c (c > 0) найдется n<sub>0</sub> (n<sub>0</sub> > 0), так +что `f(n)` < `c g(n)` выполняется для всех n (n > n<sub>0</sub>). + +Определения О-символики для О-Большое и О-Малое похожи. Главное отличие в том, +что если f(n) = O(g(n)), тогда условие f(n) <= c g(n) выполняется если _**существует**_ +константа c > 0, но если f(n) = o(g(n)), тогда условие f(n) < c g(n) выполняется +для _**всех**_ констант с > 0. + +### Омега-малое +Омега-малое, записывается как **ω**, это асимптотическая запись для оценки +верней границы времени выполнения алгоритма, при условии что граница не является +асимптотически точной. + +`f(n)` является ω(g(n)), если можно подобрать такие действительные константы, +что для всех c (c > 0) найдется n<sub>0</sub> (n<sub>0</sub> > 0), так +что `f(n)` > `c g(n)` выполняется для всех n (n > n<sub>0</sub>) + +Определения Ω-символики и ω-символики похожи. Главное отличие в том, что +если f(n) = Ω(g(n)), тогда условие f(n) >= c g(n) выполняется если _**существует**_ +константа c > 0, но если f(n) = ω(g(n)), тогда условие f(n) > c g(n) +выполняется для _**всех**_ констант с > 0. + +### Тета +Тета, записывается как **Θ**, это асимптотическая запись для оценки +_***асимптотически точной границы***_ времени выполнения алгоритма. + +`f(n)` является Θ(g(n)), если для некоторых действительных +констант c1, c2 и n<sub>0</sub> (c1 > 0, c2 > 0, n<sub>0</sub> > 0), +`c1 g(n)` < `f(n)` < `c2 g(n)` для всех n (n > n<sub>0</sub>). + +∴ `f(n)` является Θ(g(n)) означает что `f(n)` является O(g(n)) +и `f(n)` является Ω(g(n)). + +О-Большое основной инструмент для анализа сложности алгоритмов. +Так же смотрите примеры по ссылкам. + +### Заключение +Такую тему сложно изложить кратко, поэтому обязательно стоит пройти по ссылкам и +посмотреть дополнительную литературу. В них дается более глубокое описание с +определениями и примерами. + + +## Дополнительная литература + +* [Алгоритмы на Java](https://www.ozon.ru/context/detail/id/18319699/) +* [Алгоритмы. Построение и анализ](https://www.ozon.ru/context/detail/id/33769775/) + +## Ссылки + +* [Оценки времени исполнения. Cимвол O()](http://algolist.manual.ru/misc/o_n.php) +* [Асимптотический анализ и теория вероятностей](https://www.lektorium.tv/course/22903) + +## Ссылки (Eng) + +* [Algorithms, Part I](https://www.coursera.org/learn/algorithms-part1) +* [Cheatsheet 1](http://web.mit.edu/broder/Public/asymptotics-cheatsheet.pdf) +* [Cheatsheet 2](http://bigocheatsheet.com/) + diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown index 451da312..356d1cc0 100644 --- a/ru-ru/clojure-ru.html.markdown +++ b/ru-ru/clojure-ru.html.markdown @@ -321,7 +321,7 @@ keymap ; => {:a 1, :b 2, :c 3} - оригинал не был затронут ; Также модуль может быть импортирован формой require (require 'clojure.string) -; После этого модуль становится доступе в текущем пространстве имен, +; После этого модуль становится доступен в текущем пространстве имен, ; а вызов его функций может быть осуществлен указанием полного имени функции: (clojure.string/blank? "") ; => true diff --git a/ru-ru/forth-ru.html.markdown b/ru-ru/forth-ru.html.markdown new file mode 100644 index 00000000..05316578 --- /dev/null +++ b/ru-ru/forth-ru.html.markdown @@ -0,0 +1,240 @@ +--- +language: forth +contributors: + - ["Horse M.D.", "http://github.com/HorseMD/"] +translators: + - ["Dmitrii Kuznetsov", "https://github.com/torgeek"] +filename: learnforth-ru.fs +lang: ru-ru +--- + +Форт создан Чарлзом Муром в 70-е годы. Это императивный, стековый язык программирования и среда исполнения программ. Использовался в таких проектах как Open Firmware. Продолжает применятся в проектах. Применяется в НАСА. + +Внимание: эта материал использует реализацию Форта - Gforth, но большая часть написанного будет работать в других средах. + +``` +\ Это комментарий +( Это тоже комментарий, но использыется для предоределённых слов ) + +\ --------------------------------- Прекурсор -------------------------------- + +\ Всё программирование на Форте заключается в манипулировании +\ параметрами на стеке. +5 2 3 56 76 23 65 \ ok + +\ Эти числа добавляются в стек слева направо +.s \ <7> 5 2 3 56 76 23 65 ok + +\ В Форте всё - это слова-команды или числа. Слова разделяются любым числом +\ пробелов и переходов на новую строку. Длина слова не больше 31 литеры. + +\ ---------------------------- Базовая арифметика ---------------------------- + +\ Арифметика (фактически все ключевые слова требуют данных) - это манипуляция +\ данными на стеке. +5 4 + \ ok + +\ `.` показывает верхнее значение в стеке: +. \ 9 ok + +\ Ещё примеры арифметических выражений: +6 7 * . \ 42 ok +1360 23 - . \ 1337 ok +12 12 / . \ 1 ok +13 2 mod . \ 1 ok + +99 negate . \ -99 ok +-99 abs . \ 99 ok +52 23 max . \ 52 ok +52 23 min . \ 23 ok + +\ --------------------------- Манипуляции со стеком --------------------------- + +\ Естественно, когда мы работаем со стеком, то используем +\ больше полезных методов: + +3 dup - \ дублировать верхний элемент в стеке + \ (1-й становится эквивалентным 2-му): 3 - 3 +2 5 swap / \ поменять местами верхний элемент со 2-м элементом: 5 / 2 +6 4 5 rot .s \ сменять по очереди 3-и верхних элемента: 4 5 6 +4 0 drop 2 / \ снять верхний элемент (не печатается на экране): 4 / 2 +1 2 3 nip .s \ снять второй элемент (подобно исключению элемента): 1 3 + +\ ------------------ Более продвинутые манипуляции со стеком ------------------ + +1 2 3 4 tuck \ дублировать верхний елемент стека во вторую позицию: + \ 1 2 4 3 4 ok +1 2 3 4 over \ диблировать второй елемент наверх стека: + \ 1 2 3 4 3 ok +1 2 3 4 2 roll \ *переместить* элемент в заданной позиции наверх стека: + \ 1 3 4 2 ok +1 2 3 4 2 pick \ *дублировать* элемент в заданной позиции наверх: + \ 1 2 3 4 2 ok + +\ Внимание! Обращения к стеку индексируются с нуля. + +\ --------------------------- Создание новых слов ----------------------------- + +\ Определение новых слов через уже известные. Двоеточие `:` переводит Форт +\ в режим компиляции выражения, которое заканчивается точкой с запятой `;`. +: square ( n -- n ) dup * ; \ ok +5 square . \ 25 ok + +\ Мы всегда можем посмотреть, что содержится в слове: +see square \ : square dup * ; ok + +\ -------------------------------- Зависимости -------------------------------- + +\ -1 == true, 0 == false. Однако, некоторые ненулевые значения +\ обрабатываются как true: +42 42 = \ -1 ok +12 53 = \ 0 ok + +\ `if` это компилируемое слово. `if` <stuff to do> `then` <rest of program>. +: ?>64 ( n -- n ) dup 64 > if ." Больше чем 64!" then ; +\ ok +100 ?>64 +\ Больше чем 64! ok + +\ Else: +: ?>64 ( n -- n ) dup 64 > if ." Больше чем 64!" else ." меньше чем 64!" then ; +100 ?>64 \ Больше чем 64! ok +20 ?>64 \ меньше чем 64! ok + +\ ------------------------------------ Циклы ----------------------------------- + +\ `do` это тоже компилируемое слово. +: myloop ( -- ) 5 0 do cr ." Hello!" loop ; \ ok +myloop +\ Hello! +\ Hello! +\ Hello! +\ Hello! +\ Hello! ok + +\ `do` предполагает наличие двух чисел на стеке: конечное и начальное число. + +\ Мы можем назначить в цикле переменную `i` для значения индекса: +: one-to-12 ( -- ) 12 0 do i . loop ; \ ok +one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok + +\ `?do` работает подобным образом, за исключением пропуска начального +\ и конечного значения индекса цикла. +: squares ( n -- ) 0 ?do i square . loop ; \ ok +10 squares \ 0 1 4 9 16 25 36 49 64 81 ok + +\ Изменение "шага" цикла проиводится командой `+loop`: +: threes ( n n -- ) ?do i . 3 +loop ; \ ok +15 0 threes \ 0 3 6 9 12 ok + +\ Запуск бесконечного цикла - `begin` <stuff to do> <flag> `until`: +: death ( -- ) begin ." Вы всё ещё здесь?" 0 until ; \ ok + +\ ---------------------------- Переменные и память ---------------------------- + +\ Используйте `variable`, что бы объявить `age` в качестве переменной. +variable age \ ok + +\ Затем мы запишем число 21 в переменную 'age' (возраст) словом `!`. +21 age ! \ ok + +\ В заключении мы можем напечатать значение переменной прочитав его словом `@`, +\ которое добавит значение на стек или использовать слово `?`, +\ что бы прочитать и распечатать в одно действие. +age @ . \ 21 ok +age ? \ 21 ok + +\ Константы объявляются аналогично, за исключем того, что мы не должны +\ беспокоиться о выделении адреса в памяти: +100 constant WATER-BOILING-POINT \ ok +WATER-BOILING-POINT . \ 100 ok + +\ ---------------------------------- Массивы ---------------------------------- + +\ Создание массива похоже на объявление переменной, но нам нужно выделить +\ больше памяти. + +\ Вы можете использовать слова `2 cells allot` для создания массива +\ размером 3 элемента: +variable mynumbers 2 cells allot \ ok + +\ Инициализировать все значения в 0 +mynumbers 3 cells erase \ ok + +\ В качестве альтернативы мы можем использовать `fill`: +mynumbers 3 cells 0 fill + +\ или мы можем пропустить все слова выше и инициализировать массив +\ нужными значениями: +create mynumbers 64 , 9001 , 1337 , \ ok (the last `,` is important!) + +\ ... что эквивалентно: + +\ Ручная запись значений по индексам ячеек: +64 mynumbers 0 cells + ! \ ok +9001 mynumbers 1 cells + ! \ ok +1337 mynumbers 2 cells + ! \ ok + +\ Чтение значений по индексу: +0 cells mynumbers + ? \ 64 ok +1 cells mynumbers + ? \ 9001 ok + +\ Мы можем просто сделать собственное слово для манипуляции массивом: +: of-arr ( n n -- n ) cells + ; \ ok +mynumbers 2 of-arr ? \ 1337 ok + +\ Которую тоже можно использовать для записи значений: +20 mynumbers 1 of-arr ! \ ok +mynumbers 1 of-arr ? \ 20 ok + +\ ------------------------------ Стек возвратов ------------------------------ + +\ Стек возвратов используется для удержания ссылки, +\ когда одно слово запускает другое, например, в цикле. + +\ Мы всегда видим это, когда используем `i`, которая возвращает дубль верхнего +\ значения стека. `i` это эквивалент `r@`. +: myloop ( -- ) 5 0 do r@ . loop ; \ ok + +\ Так же как при чтении мы можем добавить ссылку в стек возвратов и удалить её: +5 6 4 >r swap r> .s \ 6 5 4 ok + +\ Внимание: так как Форт использует стек возвратов для указателей на слово `>r` +\ следует всегда пользоваться `r>`. + +\ ---------------- Операции над числами с плавающей точкой -------------------- + +\ Многие фортовцы стараются избегать использование слов с вещественными числами. +8.3e 0.8e f+ f. \ 9.1 ok + +\ Обычно мы просто используем слово 'f', когда обращаемся к вещественным числам: +variable myfloatingvar \ ok +4.4e myfloatingvar f! \ ok +myfloatingvar f@ f. \ 4.4 ok + +\ ---------- В завершение несколько полезных замечаний и слов ----------------- + +\ Указание несуществующего слова очистит стек. Тем не менее, есть специальное +\ слово для этого: +clearstack + +\ Очистка экрана: +page + +\ Загрузка форт-файла: +\ s" forthfile.fs" included + +\ Вы можете вывести список всех слов словаря Форта (это большой список!): +words + +\ Выход из Gforth: +bye + +``` + +##Готовы к большему? + +* [Начала Форта (англ.)](http://www.forth.com/starting-forth/) +* [Простой Форт (англ.)](http://www.murphywong.net/hello/simple.htm) +* [Мышление Форта (англ.)](http://thinking-forth.sourceforge.net/) +* [Учебники Форта (рус.)](http://wiki.forth.org.ru/УчебникиФорта) diff --git a/solidity.html.markdown b/solidity.html.markdown index 5b0ac3a3..602d74f0 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -62,7 +62,7 @@ contract SimpleBank { // CapWords event LogDepositMade(address accountAddress, uint amount); // Constructor, can receive one or many variables here; only one allowed - function AcmeBank() { + function SimpleBank() { // msg provides details about the message that's sent to the contract // msg.sender is contract caller (address of contract creator) owner = msg.sender; diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 133e4f54..c9eb2a2e 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -235,17 +235,18 @@ val hmm = answer "What is the meaning of life, the universe and everything?" (* Functions can take several arguments by taking one tuples as argument: *) fun solve2 (a : real, b : real, c : real) = - ( (~b + Math.sqrt(b * b - 4.0*a*c)) / (2.0 * a), - (~b - Math.sqrt(b * b - 4.0*a*c)) / (2.0 * a) ) + ((~b + Math.sqrt(b * b - 4.0 * a * c)) / (2.0 * a), + (~b - Math.sqrt(b * b - 4.0 * a * c)) / (2.0 * a)) (* Sometimes, the same computation is carried out several times. It makes sense to save and re-use the result the first time. We can use "let-bindings": *) fun solve2 (a : real, b : real, c : real) = - let val discr = b * b - 4.0*a*c + let val discr = b * b - 4.0 * a * c val sqr = Math.sqrt discr val denom = 2.0 * a in ((~b + sqr) / denom, - (~b - sqr) / denom) end + (~b - sqr) / denom) + end (* Pattern matching is a funky part of functional programming. It is an @@ -292,6 +293,9 @@ val thermometer = val some_result = (fn x => thermometer (x - 5) ^ thermometer (x + 5)) 37 (* Here is a higher-order function that works on lists (a list combinator) *) +(* map f l + applies f to each element of l from left to right, + returning the list of results. *) val readings = [ 34, 39, 37, 38, 35, 36, 37, 37, 37 ] (* first an int list *) val opinions = List.map thermometer readings (* gives [ "Cold", "Warm", ... ] *) @@ -324,7 +328,11 @@ val n = op + (5, 5) (* n is now 10 *) (* 'op' is useful when combined with high order functions because they expect functions and not operators as arguments. Most operators are really just infix functions. *) -val sum_of_numbers = foldl op+ 0 [1,2,3,4,5] +(* foldl f init [x1, x2, ..., xn] + returns + f(xn, ...f(x2, f(x1, init))...) + or init if the list is empty. *) +val sum_of_numbers = foldl op+ 0 [1, 2, 3, 4, 5] (* Datatypes are useful for creating both simple and complex structures *) @@ -407,7 +415,8 @@ fun writePoem(filename) = let val file = TextIO.openOut(filename) val _ = TextIO.output(file, "Roses are red,\nViolets are blue.\n") val _ = TextIO.output(file, "I have a gun.\nGet in the van.\n") - in TextIO.closeOut(file) end + in TextIO.closeOut(file) + end (* Read a nice poem from a file into a list of strings *) fun readPoem(filename) = diff --git a/tr-tr/dynamic-programming-tr.html.markdown b/tr-tr/dynamic-programming-tr.html.markdown new file mode 100644 index 00000000..1900ee93 --- /dev/null +++ b/tr-tr/dynamic-programming-tr.html.markdown @@ -0,0 +1,44 @@ +--- +language: Dynamic Programming +contributors: + - ["Akashdeep Goel", "https://github.com/akashdeepgoel"] +translators: + - ["Mehmet Cem Yaraş", "https://www.linkedin.com/in/yarascem/"] +lang: tr-tr +--- + +Dinamik Programlama +Giriş +Dinamik Programlama, göreceğimiz gibi belirli bir problem sınıfını çözmek için kullanılan güçlü bir tekniktir. Fikir çok basittir, verilen girdiyle ilgili bir sorunu çözdüyseniz, aynı sorunun tekrar çözülmesini önlemek için sonucunu gelecekte referans olarak kaydedilmesine dayanır. + +Her zaman hatırla! "Geçmiş hatırlayamayanlar, aynı şeyleri tekrar yaşamaya mahkumlardır!" + +Bu tür sorunların çözüm yolları + +1-Yukarıdan aşağıya: +Verilen problemi çözerek çözmeye başlayın. Sorunun zaten çözüldüğünü görürseniz, kaydedilen cevabı döndürmeniz yeterlidir. Çözülmemişse, çözünüz ve cevabı saklayınız. Bu genellikle düşünmek kolaydır ve çok sezgiseldir. Buna Ezberleştirme denir. + +2-Aşağıdan yukarıya: +Sorunu analiz edin ve alt problemlerin çözülme sırasını görün ve önemsiz alt sorundan verilen soruna doğru başlayın. Bu süreçte, problemi çözmeden önce alt problemlerin çözülmesi gerekmektedir. Buna Dinamik Programlama denir. + +Örnek +En Uzun Artan Subsequence problemi belirli bir dizinin en uzun artan alt dizini bulmaktır. S = {a1, a2, a3, a4, ............., an-1} dizisi göz önüne alındığında, en uzun bir alt kümeyi bulmak zorundayız, böylece tüm j ve i, j için <I, aj <ai alt kümesinde. Her şeyden önce, en son alt dizgenin (LSi) değerini dizinin son elemanı olan ai'nin her indeksinde bulmalıyız. Daha sonra en büyük LSi, verilen dizideki en uzun alt dizin olacaktır. Başlamak için, ai, dizinin elemanı olduğundan (Son öğe) LSi atanır. Sonra tüm j için j <i ve aj <ai gibi, En Büyük LSj'yi buluruz ve LSi'ye ekleriz. Sonra algoritma O (n2) zaman alır. + +En uzun artan alt dizinin uzunluğunu bulmak için sözde kod: Bu algoritmaların karmaşıklığı dizi yerine daha iyi veri yapısı kullanılarak azaltılabilir. Büyük dizin ve dizin gibi selefi dizi ve değişkeni saklama çok zaman kazandıracaktır. + +Yönlendirilmiş asiklik grafiğinde en uzun yolu bulmak için benzer bir kavram uygulanabilir. +for i=0 to n-1 + LS[i]=1 + for j=0 to i-1 + if (a[i] > a[j] and LS[i]<LS[j]) + LS[i] = LS[j]+1 +for i=0 to n-1 + if (largest < LS[i]) + +Bazı Ünlü Dinamik Programlama Problemleri +-Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs—floyd-warshall-algorithm-with-c-program-source-code +-Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming—the-integer-knapsack-problem +-Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming—longest-common-subsequence + +Online Kaynaklar +https://www.codechef.com/wiki/tutorial-dynamic-programming diff --git a/zh-cn/dynamic-programming-cn.html.markdown b/zh-cn/dynamic-programming-cn.html.markdown new file mode 100644 index 00000000..b75c5404 --- /dev/null +++ b/zh-cn/dynamic-programming-cn.html.markdown @@ -0,0 +1,57 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] +filename: dynamic-programming-cn.html.markdown +lang: zh-cn +translators: + - ["EtaoinWu", "https://github.com/EtaoinWu"] +--- + +# 动态规划 + +## 简介 + +动态规划是一种实用的技巧,它可以用来解决一系列特定问题。它的思路很简单,如果你对某个给定的输入解决了一个问题,那么你可以保存已有信息,以避免重复计算,节约计算时间。 + +记住,只有那些没有办法记住历史的才被迫做更多的苦力。(Fibonacci就是一个显然的例子) + +## 解决问题的方式 + +1. *自顶向下* : 利用分支策略分解问题。如果你已经解决过当前子问题了,那么就返回已有信息。如果当前子问题没有计算过,那么就对它进行计算。这样的方法很易于思考、很直观。这被称作“记忆化”。 + +2. *自底向上* : 首先分析问题,将问题分解为不同规模的问题,并决定它们的顺序,按顺序计算,直到解决给定规模的问题。这样的流程可以保证在解决较大的问题之前解决(它所依赖的)较小的问题。这种流程被称作“动态规划”。 + +## 动态规划的例子 + +最长上升子序列问题。给定`S= {a[1] , a[2] , a[3], a[4], ............., a[n-1], a[n] }`,求出一个子序列,使得对于所有在这个子序列中所有满足`j<i`的`j`与`i`,满足`aj<ai`。首先我们要讨论以原序列的第`i`个元素结尾的最长上升子序列`dp[i]`。那么答案是整个dp序列的最大值。考虑`dp[i]`,它的最后一个元素为`a[i]`。枚举它的倒数第二个元素`a[j]`,则`a[j]<a[i]`成立。则`dp[i]`就是所有这样的`dp[j]`的最大值加上1(最后一个元素)。这个算法具有*O(n^2)*的时间复杂度。 + +此算法的伪代码: + +```python +for i=0 to n-1 + dp[i]=0 + for j=0 to i-1 + if (a[i] > a[j] and dp[i]<dp[j]) + LS[i] = LS[j] + dp[i]=dp[i]+1 +for i=0 to n-1 + if (largest < dp[i]) + largest = dp[i] +``` + +这个算法的复杂度可以通过将数组换为其他数据结构来优化,来获得*O(n * log n)*的时间复杂度。 + +同样的思路可以求出有向无环图上的最大路径。 + +### 一些著名的动态规划问题及其实现 + +- Floyd Warshall 算法 - [教程与C实现源码](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code) +- 整数背包问题 - [教程与C实现源码](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) +- 最长公共子序列问题 - [教程与C实现源码](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) + +## 在线资源 + +* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming) +* [洛谷](https://www.luogu.org/problem/lists?name=&orderitem=pid&tag=3) |