diff options
| -rw-r--r-- | de-de/ruby-de.html.markdown | 782 | ||||
| -rw-r--r-- | elixir.html.markdown | 1 | ||||
| -rw-r--r-- | git.html.markdown | 4 | ||||
| -rw-r--r-- | jsonnet.html.markdown | 139 | ||||
| -rw-r--r-- | matlab.html.markdown | 2 | ||||
| -rw-r--r-- | nl-nl/json-nl.html.markdown | 13 | ||||
| -rw-r--r-- | p5.html.markdown | 2 | ||||
| -rw-r--r-- | rst.html.markdown | 6 | ||||
| -rw-r--r-- | ru-ru/pascal-ru.html.markdown | 216 | ||||
| -rw-r--r-- | set-theory.html.markdown | 162 | ||||
| -rw-r--r-- | smalltalk.html.markdown | 2 | 
11 files changed, 963 insertions, 366 deletions
| diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown index e14603cd..8025a8c0 100644 --- a/de-de/ruby-de.html.markdown +++ b/de-de/ruby-de.html.markdown @@ -1,5 +1,6 @@  ---  language: ruby +filename: ruby-de.rb  contributors:    - ["David Underwood", "http://theflyingdeveloper.com"]    - ["Joel Walden", "http://joelwalden.net"] @@ -11,602 +12,677 @@ contributors:    - ["Dzianis Dashkevich", "https://github.com/dskecse"]    - ["Levi Bostian", "https://github.com/levibostian"]    - ["Rahil Momin", "https://github.com/iamrahil"] +  - ["Gabriel Halley", "https://github.com/ghalley"] +  - ["Persa Zula", "http://persazula.com"] +  - ["Jake Faris", "https://github.com/farisj"] +  - ["Corey Ward", "https://github.com/coreyward"] +  - ["Jannik Siebert", "https://github.com/janniks"] +  - ["Keith Miyake", "https://github.com/kaymmm"]  translators:    - ["Christian Albrecht", "https://github.com/coastalchief"]    - ["Dennis Keller", "https://github.com/denniskeller"] -filename: ruby-de.rb +  - ["Paul Götze", "https://gitub.com/paulgoetze"]  lang: de-de  --- -# Dies ist ein Kommentar +```ruby +# Das ist ein Kommentar  =begin -Dies sind multi-line -Kommentare. Niemand benutzt -die wirklich. +Das ist ein mehrzeiliger Kommentar. +Die Anfangszeile muss mit "=begin" beginnen +und die Endzeile muss mit "=end" beginnen.  + +Alternativ kannst du jede Zeile in einem  +mehrzeiligen Kommentar mit dem # Zeichen beginnen.   =end -# Objekte - Alles ist ein Objekt +# In Ruby ist (fast) alles ein Objekt. +# Das schließt Zahlen ein... +3.class #=> Integer -## Zahlen sind Objekte -``` -3.class #=> Fixnum -3.to_s #=> "3" -``` +# ...und Zeichenketten (Strings)... +"Hallo".class #=> String -### Simple Arithmetik -``` +# ...und sogar Methoden! +"Hallo".method(:class).class #=> Method + +# Simple Arithmetik  1 + 1 #=> 2  8 - 1 #=> 7  10 * 2 #=> 20  35 / 5 #=> 7 -2**5 #=> 32 -``` +2 ** 5 #=> 32 +5 % 3 #=> 2 -// Arithmetik ist aber eigentlich nur syntaktischer Zucker -// um eine Methode eines Objekt aufzurufen -``` +# Bitweise Operatoren +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 + +# Arithmetik ist aber eigentlich nur syntaktischer Zucker +# um eine Methode eines Objekts aufzurufen  1.+(3) #=> 4  10.* 5 #=> 50 -``` +100.methods.include?(:/) #=> true -## Special values sind Objekte -``` -nil # Nothing to see here -true # truth -false # falsehood +## Spezielle Werte sind Objekte +nil # Equivalent zu null in anderen Sprachen +true # Wahrheitswert +false # Falschheitswert  nil.class #=> NilClass  true.class #=> TrueClass  false.class #=> FalseClass -``` -## Objektvergleiche -### Gleicheit -``` +# Gleicheit  1 == 1 #=> true  2 == 1 #=> false -``` -### Ungleichheit -``` + +# Ungleichheit  1 != 1 #=> false  2 != 1 #=> true -``` -### Neben false selbst, nil ist ein anderer 'falsey' Wert -``` -!nil   #=> true -!false #=> true -!0     #=> false -``` -### Weitere Vergleiche -``` + +# Neben false selbst, ist nil der einzige andere  +# zu Falsch evaluierende Wert + +!!nil   #=> false +!!false #=> false +!!0     #=> true +!!""    #=> true + +# Weitere Vergleiche  1 < 10 #=> true  1 > 10 #=> false  2 <= 2 #=> true  2 >= 2 #=> true -``` + +# Kombinierter Vergleichsoperator (gibt `1` zurück wenn das erste Argument  +# größer ist, und `-1`, wenn das zweite Argument größer ist, sonst `0`) +1 <=> 10 #=> -1 (1 < 10) +10 <=> 1 #=> 1 (10 > 1) +1 <=> 1 #=> 0 (1 == 1) +  ### Logische Operatoren -```  true && false #=> false  true || false #=> true -!true #=> false -``` -Es gibt alternative Versionen der logischen Operatoren mit niedrigerer -Wertigkeit. Diese werden meistens bei Flow-Control eingesetzt, um -verschiedenen Ausdrücke zu verketten bis einer true oder false zurück -liefert. +# Es gibt alternative Versionen der logischen Operatoren mit niedrigerer +# Wertigkeit. Diese werden meistens zur Flusskontrolle eingesetzt, um +# verschiedenen Ausdrücke zu verketten bis einer true oder false zurück +# liefert. -#### and -##### `do_something_else` wird nur ausgewertet wenn `do_something` true ist. +# `do_something_else` wird nur ausgewertet wenn `do_something` true ist.  do_something() and do_something_else() - -#### or -#####`log_error` wird nur ausgewertet wenn `do_something` false ist. +# `log_error` wird nur ausgewertet wenn `do_something` false ist.  do_something() or log_error() -## Strings sind Objekte -``` -'I am a string'.class #=> String -"I am a string too".class #=> String +# String Interpolation +placeholder = 'Ruby' +"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungszeichen füllen." +#=> "Ich kann in Ruby Platzhalter mit doppelten Anführungszeichen füllen." -platzhalter = 'Ruby' -"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungsstrichen füllen." -``` -Einfache Anführungszeichen sollten bevorzugt werden. -Doppelte Anführungszeichen führen interne Berechnungen durch. +# Du kannst Strings mit `+` verbinden, nicht jedoch mit anderen Typen +'hallo ' + 'Welt'  #=> "hallo Welt" +'Hallo ' + 3 #=> TypeError: no implicit conversion of Integer into String +'hallo ' + 3.to_s #=> "hallo 3" +"hallo #{3}" #=> "hallo 3" + +# ...oder Strings mit Operatoren kombinieren +'hallo ' * 3 #=> "hallo hallo hallo " + +# ...oder Strings an andere Strings anhängen +'hallo' << ' Welt' #=> "hallo Welt" + +# Du kannst Text mit einer neuen Zeile am Ende ausgeben +puts "Ich gebe Text aus!" +#=> Ich gebe Text aus! +#=> nil + +# ...oder Text ohne einen Zeilenumbruch ausgeben +print "Ich gebe Text aus!" +#=> "Ich gebe Text aus!" => nil -### Strings können verbunden werden, aber nicht mit Zahlen -``` -'hello ' + 'world'  #=> "hello world" -'hello ' + 3 #=> TypeError: can't convert Fixnum into String -``` -#### Zahl muss in String konvertiert werden -``` -'hello ' + 3.to_s #=> "hello 3" -``` -### Text ausgeben -``` -puts "I'm printing!" -```  # Variablen -## Zuweisungen -### Diese Zuweisung gibt den zugeordneten Wert zurück -```  x = 25 #=> 25  x #=> 25 -``` -### Damit funktionieren auch mehrfache Zuweisungen -``` + +# Beachte, dass Zuweisungen den zugewiesenen Wert zurückgeben. +# D.h. du kannst mehrfache Zuweisungen machen. +  x = y = 10 #=> 10  x #=> 10  y #=> 10 -``` -## Benennung -### Konvention ist snake_case -``` + +# Nutze snake_case für Variablennamen.  snake_case = true -``` -### Benutze verständliche Variablennamen -``` -path_to_project_root = '/good/name/' -path = '/bad/name/' -``` -# Symbols (sind auch Objekte) -Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern -als integer repräsentiert werden. Sie werden häufig anstelle von Strings -verwendet, um sinnvoll Werte zu übermitteln. -Symbols werden mit dem Doppelpunkt gekennzeichnet. -``` +# Nutze verständliche Variablennamen. +path_to_project_root = '/guter/Name/' +m = '/schlechter/Name/' + + +# Symbole sind unveränderliche, wiederverwendbare Konstanten, welche intern +# als Integer repräsentiert werden. Sie werden häufig anstelle von Strings +# verwendet, um semantisch sinnvoll Werte zu übermitteln. +# Symbols werden mit dem Doppelpunkt gekennzeichnet. +  :pending.class #=> Symbol +  status = :pending +  status == :pending #=> true +  status == 'pending' #=> false +  status == :approved #=> false -``` + +# Strings können in Symbole konvertiert werden und umgekehrt. +status.to_s #=> "pending" +"argon".to_sym #=> :argon +  # Arrays -## Ein Array anlegen -``` +# Das ist ein Array.  array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] -``` -## Array können verschiedene Typen beinhalten -``` +# Array können verschiedene Typen beinhalten  [1, 'hello', false] #=> [1, "hello", false] -``` -## Wie bei arithmetischen Ausdrücken auch wird beim Zugriff auf -## [0] eigentlich die Methode [] des Array Objekts aufgerufen. -``` -array.[] 0 #=> 1 -array.[] 12 #=> nil -``` +## Arrays könnenindiziert werden. -## Arrays können von vorne indiziert werden -``` +# Von vorne...  array[0] #=> 1 +array.first #=> 1  array[12] #=> nil -``` -## Arrays können von hinten indiziert werden -``` +# ...oder von hinten...  array[-1] #=> 5 -``` +array.last #=> 5 -## Arrays können mit Start Index und Länge indiziert werden -``` +# ...oder mit einem Startindex und einer Länge...  array[2, 3] #=> [3, 4, 5] -``` -## Arrays können mit einer Range indiziert werden -``` +# ...oder mit einem Range...  array[1..3] #=> [2, 3, 4] -``` -## Einen Wert hinzufügen -``` +# Du kanns ein Array umkehren. +# Gib ein neues Array mit umgkehrten Werten zurück +[1,2,3].reverse #=> [3,2,1] + +# Kehre ein Array an Ort und Stelle um, um die Variable mit den  +# umgekehrten Werten zu aktualisieren. +a = [1,2,3] +a.reverse! #=> a==[3,2,1] wegen des Aufrufs von reverse mit Ausrufezeichens ('!') + +# Wie bei der Arithmetik, ist Zugriff mit [index] nur  +# syntaktischer Zucker für den Aufruf der `[]` Methode auf dem Objekt. +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Du kannst Werte zu einem Array hinzufügen...  array << 6 #=> [1, 2, 3, 4, 5, 6] +# Oder so  array.push(6) #=> [1, 2, 3, 4, 5, 6] -``` -## Testen, ob ein Element schon vorhanden ist -``` +# ...und testen ob ein Element schon vorhanden ist  array.include?(1) #=> true -``` -# Hashes -Hashes sind das Hauptfeature um Key/Values zu speichern +# Hashes sind Rubys Hauptdatenstruktur for Schlüssel/Wert Paare. +# Hashes werden durch geschweifte Klammern gekennzeichnet. +hash = { 'Farbe' => 'grün', 'Nummer' => 5 } -## Ein Hash anlegen -``` -hash = { 'color' => 'green', 'number' => 5 } -hash.keys #=> ['color', 'number'] -``` +hash.keys #=> ['farbe', 'nummer'] -## Wert per key herausfinden -``` -hash['color'] #=> 'green' -hash['number'] #=> 5 -hash['nothing here'] #=> nil -// Fragen an einen Hash nach einem Schlüssel, der nicht existiert, ruft nil hervor: -``` +# Hashes can be quickly looked up by key. +hash['Farbe'] #=> "grün" +hash['Nummer'] #=> 5 -##  Symbols können auch keys sein -``` -new_hash = { defcon: 3, action: true } -new_hash.keys #=> [:defcon, :action] -``` +# Abfragen eines nicht vorhandenen Schlüssels, gibt nil zurück.  +hash['nicht vorhanden'] #=> nil -## Testen ob ein Key oder ein Value existiert -``` -new_hash.has_key?(:defcon) #=> true -new_hash.has_value?(3) #=> true -``` +# Wenn du Symbole als Schlüssel in einem Hash verwendest, kannst du +# eine alternative Syntax verwenden. +hash = { :defcon => 3, :action => true } +hash.keys #=> [:defcon, :action] -### Tipp:  Arrays und Hashes sind Enumerable -### Und haben gemeinsame, hilfreiche Methoden wie: -### each, map, count, and more +hash = { defcon: 3, action: true } +hash.keys #=> [:defcon, :action] + +# Testen ob ein Schlüssel oder Wert im Hash existiert +hash.key?(:defcon) #=> true +hash.value?(3) #=> true + +# Tipp: Arrays und Hashes sind Enumerables! +# Sie haben viele nützliche Methoden gemein, wie each, map, count, und andere.  # Kontrolstrukturen -## if -``` + +# Bedingungen  if true -  'if statement' +  'wenn Bedingung'  elsif false -  'else if, optional' +  'sonst wenn, optional'  else -  'else, also optional' +  'sonst, auch optional'  end -``` -## for - Allerdings werden for Schleifen nicht oft vewendet. -``` -for counter in 1..5 -  puts "iteration #{counter}" -end -``` -## Stattdessen: "each" Methode und einen Bloch übergeben -Ein Block ist ein Codeteil, den man einer Methode übergeben kann -Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen -Programmiersprachen. -``` +# Wenn eine Kontrollstruktur keinen Code-Block, sondern einen einzigen  +# Ausdruck ausführt, dann kannst du die nachgestellte if-Notation verwenden +warnings = ['Nachname fehlt', 'Adresse zu kurz'] +puts("Vorhandene Warnungen:\n" + warnings.join("\n"))  if !warnings.empty? + +# Formuliere die Bedingung um, wenn sich `unless` besser liest als `if` +puts("Vorhandene Warnungen:\n" + warnings.join("\n")) unless warnings.empty? + +# Schleifen +# Traditionell ist das Benutzen von `for` Schleifen in Ruby eher unüblich. +# Stattdessen werden diese mit Hilfe von Enumerables implementiert, was mit +# dem Aufrufen von `each` einhergeht.  (1..5).each do |counter| -  puts "iteration #{counter}" +  puts "Iteration #{counter}" +end + +# Was in etwa das selbe ist wie Folgendes (selten in Ruby zu sehen). +for counter in 1..5 +  puts "Iteration #{counter}"  end -``` -Die each Methode einer Range führt den Block für jedes Element der Range aus. +# Das `do |variable| ... end` Konstrukt wird `block` genannt.  +# Blocks sind vergleichbar mit Lambdas, anonymen Funktionen  +# oder Closures in anderen Programmiersprachen. +# Sie können als Objekte übergeben, aufgerufen oder als Methoden  +# zugewiesen werden. -Dem Block wird ein "counter" parameter übergeben. +# Die `each` Methode eines Ranges führt den Block einmal für jedes  +# Element des Ranges aus.  +# Dem Block wird eine counter Variable als Parameter übergeben. -### Den Block kann man auch in geschweiften Klammern schreiben -``` -(1..5).each { |counter| puts "iteration #{counter}" } -``` +# Du kannst einen Block auch mit geschweiften Klammern schreiben. +(1..5).each { |counter| puts "Iteration #{counter}" } -### Each kann auch über den Inhalt von Datenstrukturen iterieren -``` +# Each kann auch über den Inhalt von Datenstrukturen iterieren.  array.each do |element| -  puts "#{element} is part of the array" +  puts "#{element} is Teil des Arrays"  end +  hash.each do |key, value| -  puts "#{key} is #{value}" +  puts "#{key} ist #{value}" +end + +# Um auf den Laufindex zuzugreifen kannst du `each_with_index` verwenden +# und eine index Variable definieren.  +array.each_with_index do |element, index| +  puts "#{element} ist Nummer #{index} im Array"  end  counter = 1  while counter <= 5 do -  puts "iteration #{counter}" +  puts "Iteration #{counter}"    counter += 1  end -``` +#=> Iteration 1 +#=> Iteration 2 +#=> Iteration 3 +#=> Iteration 4 +#=> Iteration 5 + +# Es gibt einige andere hilfreiche Schleifenfunktionen in Ruby. +# Wie etwa 'map', 'reduce', 'inject' und viele andere mehr.  +# Map zum Beispiel iteriert über das Array, führt für jedes Element  +# die Anweisungen aus,  +# die im Block definiert sind und gibt ein völlig neues Array zurück. +array = [1,2,3,4,5] +doubled = array.map do |element| +  element * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] -## case -``` +# Case Konstruct  grade = 'B'  case grade  when 'A' -  puts 'Way to go kiddo' +  puts 'So wird’s gemacht'  when 'B' -  puts 'Better luck next time' +  puts 'Viel Glück beim nächsten Mal'  when 'C' -  puts 'You can do better' +  puts 'Das kannst du besser'  when 'D' -  puts 'Scraping through' +  puts 'Gerade so durch'  when 'F' -  puts 'You failed!' +  puts 'Durchgefallen!'  else -  puts 'Alternative grading system, eh?' +  puts 'Anderes Bewertungssystem, was?'  end -=> "Better luck next time" -``` +#=> "Viel Glück beim nächsten Mal" -### Case können auch ranges -``` +# Case kann auch Ranges benutzen  grade = 82  case grade  when 90..100 -  puts 'Hooray!' +  puts 'Hurra!'  when 80...90 -  puts 'OK job' +  puts 'OK gemacht'  else -  puts 'You failed!' +  puts 'Durchgefallen!'  end -=> "OK job" -``` +#=> "OK gemacht" -# Exception handling: -``` +# Fehlerbehandlung  begin -  # code here that might raise an exception -  raise NoMemoryError, 'You ran out of memory.' +  # Code der einen Fehler wirft... +  raise NoMemoryError, 'Dein Speicher ist voll.'  rescue NoMemoryError => exception_variable -  puts 'NoMemoryError was raised', exception_variable +  puts 'NoMemoryError ist aufgetreten', exception_variable  rescue RuntimeError => other_exception_variable -  puts 'RuntimeError was raised now' +  puts 'RuntimeError ist aufgetreten'  else -  puts 'This runs if no exceptions were thrown at all' +  puts 'Das wird ausgeführt, wenn keine Fehler geworfen wurden'  ensure -  puts 'This code always runs no matter what' +  puts 'Dieser Code wird immer ausgeführt, egal was vorher passiert'  end -``` -# Funktionen -``` + +# Methoden +  def double(x)    x * 2  end -``` -## Funktionen (und Blocks) -## geben implizit den Wert des letzten Statements zurück -``` + +# Methoden (und Blocks) geben implizit den Wert des letzten Anweisung zurück.  double(2) #=> 4 -``` -### Klammern sind optional wenn das Ergebnis nicht mehrdeutig ist -``` +# Klammern sind optional wenn die Anweisung dadurch nicht mehrdeutig wird.  double 3 #=> 6 +  double double 3 #=> 12 +  def sum(x, y)    x + y  end -``` -### Methoden Parameter werden per Komma getrennt -``` +# Die Argumente einer Methode werden durch ein Komma getrennt.  sum 3, 4 #=> 7 +  sum sum(3, 4), 5 #=> 12 -``` -## yield -### Alle Methoden haben einen impliziten, optionalen block Parameter -### Dieser wird mit dem Schlüsselword "yield" aufgerufen -``` +# yield +# Alle Methoden haben implizit einen optionalen block Parameter. +# Dieser kann durch das Schlüsselwort 'yield' ausgeführt werden.  def surround    puts '{'    yield    puts '}'  end -surround { puts 'hello world' } -``` -## Einen Block kann man auch einer Methoden übergeben -### "&" kennzeichnet die Referenz zum übergebenen Block -``` +surround { puts 'hallo Welt' } + +#=> { +#=> hallo Welt +#=> } + +# Blocks können in ein 'Proc' Objekt umgewandelt werden.  +# Dieses ist eine Art Container um den Block und erlaubt ihn an eine  +# andere Methode zu übergeben, ihn in einen anderen Gültigkeitsbereicht  +# einzubinden oder ihn andersweitig zu verändern. +# Am häufigsten findet man dies bei Parameterlisten von Methoden, in Form  +# eines letzten '&block' Parameters, der den Block – wenn es einen gibt –  +# entgegen nimmt und ihn in ein 'Proc' umwandelt. Die Benennung '&block' ist  +# hier nur eine Konvention; es würde genauso mit '&pineapple' funktionieren.   def guests(&block) -  block.call 'some_argument' +  block.class #=> Proc +  block.call(4)  end -``` -### Eine Liste von Parametern kann man auch übergeben, -### Diese wird in ein Array konvertiert -### "*" kennzeichnet dies. -``` +# Die 'call' Methode eines Proc ist ganz ähnlich zum Aufruf von 'yield', wenn  +# ein Block vorhanden ist. Die Argumente, die 'call' übergeben werden, werden  +# als Argumente and den Block weitergereicht. + +guests { |n| "Du hast #{n} Gäste." } +# => "Du hast 4 Gäste." + +# Du kannst eine Liste von Argumenten übergeben, die dann in ein Array  +# umgewandelt werden. Dafür gibt es den splat-Operator (`*`).  def guests(*array)    array.each { |guest| puts guest }  end -``` + +# Destrukturierung + +# Ruby destrukturiert Arrays automatisch beim Zuweisen mehrerer Variablen. +a, b, c = [1, 2, 3] +a #=> 1 +b #=> 2 +c #=> 3 + +# In manchen Fällen will man den splat-Operator (`*`) verwenden um ein Array in +# eine Liste zu destrukturieren. +ranked_competitors = ["John", "Sally", "Dingus", "Moe", "Marcy"] + +def best(first, second, third) +  puts "Gewinner sind #{first}, #{second} und #{third}." +end + +best *ranked_competitors.first(3) #=> Gewinner sind John, Sally and Dingus. + +# Der splat-Operator kann auch in Parametern verwendet werden. +def best(first, second, third, *others) +  puts "Gewinner sind #{first}, #{second} und #{third}." +  puts "Es gab #{others.count} andere Teilnehmer." +end + +best *ranked_competitors  +#=> Gewinner sind John, Sally und Dingus. +#=> Es gab 2 andere Teilnehmer. + +# Per Konvention enden alle Methoden, die einen Wahrheitswert zurück geben, mit einem +# Fragezeichen. +5.even? #=> false +5.odd? #=> true + +# Wenn ein Methodenname mit einem Ausrufezeichen endet, dann tut diese Methode  +# per Konvention etwas Destruktives, wie z.B. das aufrufende Objekt zu  +# verändern. +# Viele Mehtoden haben eine !-Version um eine direkte Änderung zu machen und  +# eine Nicht-!-Version, die ein neues Objekt mit den Veränderungen zurück gibt. +company_name = "Dunder Mifflin" +company_name.upcase #=> "DUNDER MIFFLIN" +company_name #=> "Dunder Mifflin" +# Diesmal verändern wir company_name direkt. +company_name.upcase! #=> "DUNDER MIFFLIN" +company_name #=> "DUNDER MIFFLIN" +  # Klassen -## Werden mit dem class Schlüsselwort definiert -``` + +# Du kannst eine Klasse mit dem Schlüsselwort 'class' definieren.  class Human -``` -### Konstruktor bzw. Initializer -``` +  # Eine Klassenvariable. Sie wird von allen Instanzen einer Klasse geteilt. +  @@species = 'H. sapiens' + +  # Konstruktor bzw. Initializer    def initialize(name, age = 0) -    # Assign the argument to the "name" instance variable for the instance +    # Weise das Argument der Instanzvariable 'name' zu.      @name = name -    # If no age given, we will fall back to the default in the arguments list. +    # Wenn kein 'age' angegeben wurde wird der Standartwert aus der Argumentenlist verwendet.      @age = age    end -``` -### setter Methode -``` +  # Setter Methode    def name=(name)      @name = name    end -``` -### getter Methode -``` + +  # Getter Methode    def name      @name    end -``` -#### getter können mit der attr_accessor Methode vereinfacht definiert werden -``` +  # Getter & Setter können auch kürzer mit der attr_accessor Methode erstellt werden.    attr_accessor :name -  # Getter/setter methods can also be created individually like this + +  # Getter & Setter Methoden können auch einzeln erstellt werden.    attr_reader :name    attr_writer :name -  # A class method uses self to distinguish from instance methods. -  # It can only be called on the class, not an instance. + +  # Eine Klassenmethode unterscheidet sich durch ein 'self' von einer  +  # Instanzmethode. +  # Sie kann nur auf der Klasse und nicht auf einer Instanz der Klasse  +  # aufgerufen werden.      def self.say(msg)      puts msg    end +    def species      @@species    end  end -``` -## Eine Klasse instanziieren -``` +# Instanziieren einer Klasse  jim = Human.new('Jim Halpert')  dwight = Human.new('Dwight K. Schrute') -``` -## Methodenaufrufe -``` +# Du kannst die Methoden des erstellten Objekts aufrufen.  jim.species #=> "H. sapiens"  jim.name #=> "Jim Halpert"  jim.name = "Jim Halpert II" #=> "Jim Halpert II"  jim.name #=> "Jim Halpert II"  dwight.species #=> "H. sapiens"  dwight.name #=> "Dwight K. Schrute" -``` -## Eine Klassenmethode aufrufen -``` +# Aufrufen einer Klassenmethode  Human.say('Hi') #=> "Hi" -``` -## Variable Gültigkeit -### Variablen die mit "$" starten, gelten global -``` -$var = "I'm a global var" +# Der Gültigkeitsbereich einer Variablen wird durch ihren Namen definiert. +# Variablen, die mit $ beginnen sind global gültig. +$var = "Ich bin eine globale Variable"  defined? $var #=> "global-variable" -``` -### Variablen die mit "@" starten, gelten für die Instanz -``` -@var = "I'm an instance var" +# Variablen, die mit @ beginnen, sind innerhalb einer Instanz gültig. +@var = "Ich bin eine Instanzvariable"  defined? @var #=> "instance-variable" -``` -### Variablen die mit "@@" starten, gelten für die Klasse -``` -@@var = "I'm a class var" +# Variablen, die mit @@ beginnen, sind für die Klasse gültig. +@@var = "Ich bin eine Klassenvariable"  defined? @@var #=> "class variable" -``` -### Variablen die mit einem Großbuchstaben anfangen, sind Konstanten -``` -Var = "I'm a constant" +# Variablen, die mit einem Großbuchstaben beginnen, sind Konstanten +Var = "Ich bin eine Konstante"  defined? Var #=> "constant" -``` -## Class ist auch ein Objekt -### Hat also auch Instanzvariablen -### Eine Klassenvariable wird innerhalb der Klasse und Ableitungen geteilt. +# Class ist in Ruby auch ein Objekt. Deshalb kann eine Klasse Instanzvariablen +# haben. Eine Klassenvariable wird zwischen der Klasse und all ihren  +# Ableitungen geteilt. -### Basis Klasse -``` +# Basis Klasse  class Human    @@foo = 0 +    def self.foo      @@foo    end +    def self.foo=(value)      @@foo = value    end  end -``` -### Abgeleitete Klasse -``` +# Abgeleitete Klasse  class Worker < Human  end -Human.foo # 0 -Worker.foo # 0 -Human.foo = 2 # 2 -Worker.foo # 2 -``` -### Eine Klasseninstanzvariable wird nicht geteilt -``` +Human.foo #=> 0 +Worker.foo #=> 0 + +Human.foo = 2 +Worker.foo #=> 2 + +# Ableitungen einer Klasse haben keinen Zugriff auf eine Eine Klassen-Instanzvariable.  class Human    @bar = 0 +    def self.bar      @bar    end +    def self.bar=(value)      @bar = value    end  end -``` -``` +  class Doctor < Human  end -``` -``` -Human.bar # 0 -Doctor.bar # nil -``` -``` + +Human.bar #=> 0 +Doctor.bar #=> nil +  module ModuleExample    def foo      'foo'    end  end -``` -### Module einbinden, heisst ihre Methoden an die Instanzen der Klasse zu binden -### Module erweitern, heisst ihre Mothden an die Klasse selbst zu binden -``` + +# Ein Einbinden (include) eines Moduls bindet seine Methoden an die Instanzen  +# der Klasse. +# Ein Erweitern (extend) eines Moduls bindet seine Methoden an die Klasse  +# selbst.  class Person    include ModuleExample  end -``` -``` +  class Book    extend ModuleExample  end -``` -``` -Person.foo     # => NoMethodError: undefined method `foo' for Person:Class -Person.new.foo # => 'foo' -Book.foo       # => 'foo' -Book.new.foo   # => NoMethodError: undefined method `foo' -``` -### Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird -``` -  module ConcernExample -    def self.included(base) -      base.extend(ClassMethods) -      base.send(:include, InstanceMethods) -    end -    module ClassMethods -      def bar -        'bar' -      end -    end -    module InstanceMethods -      def qux -        'qux' -      end + +Person.foo     #=> NoMethodError: undefined method `foo' for Person:Class +Person.new.foo #=> "foo" +Book.foo       #=> "foo" +Book.new.foo   #=> NoMethodError: undefined method `foo' + + +# Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird. +module ConcernExample +  def self.included(base) +    base.extend(ClassMethods) +    base.send(:include, InstanceMethods) +  end + +  module ClassMethods +    def bar +      'bar'      end    end -  class Something -    include ConcernExample + +  module InstanceMethods +    def qux +      'qux' +    end    end -``` -``` -Something.bar     # => 'bar' -Something.qux     # => NoMethodError: undefined method `qux' -Something.new.bar # => NoMethodError: undefined method `bar' -Something.new.qux # => 'qux' +end + +class Something +  include ConcernExample +end + +Something.bar     #=> "bar" +Something.qux     #=> NoMethodError: undefined method `qux' +Something.new.bar #=> NoMethodError: undefined method `bar' +Something.new.qux #=> "qux"  ``` -## Weiterführende Hinweise +## Weitere Links -//EN +_(z.T. auf Englisch)_ -- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. -- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Offizielle Ruby Website](https://www.ruby-lang.org/de/) +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Eine Variante dieses Dokuments mit in-Browser Challenges. +- [RubyMonk](https://rubymonk.com/) - Lerne Ruby mit einer Reihe interaktiver Tutorials. +- [Offizielle Dokumentation](http://ruby-doc.org/core)  - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) -- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. -- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Eine ältere [freie Ausgabe](http://ruby-doc.com/docs/ProgrammingRuby/) ist online verfügbar. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Ein von der Community erstellter Ruby coding style guide. +- [Try Ruby](http://tryruby.org) - Lerne die Grundlagen der Ruby Programmiersprache, interaktiv im Browser. diff --git a/elixir.html.markdown b/elixir.html.markdown index 0b717ca6..0226ecaf 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -457,3 +457,4 @@ Agent.update(my_agent, fn colors -> ["blue" | colors] end)  * [Elixir Cheat Sheet](https://media.pragprog.com/titles/elixir/ElixirCheat.pdf)  * ["Learn You Some Erlang for Great Good!"](https://learnyousomeerlang.com/) by Fred Hebert  * ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong +* [Introduction to Elixir](https://learn-elixir.com/) diff --git a/git.html.markdown b/git.html.markdown index aa96c90a..a40ef01b 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -82,12 +82,12 @@ pushed to other repositories, or not!  ### Branch  A branch is essentially a pointer to the last commit you made. As you go on -committing, this pointer will automatically update to point the latest commit. +committing, this pointer will automatically update to point to the latest commit.  ### Tag  A tag is a mark on specific point in history. Typically people use this -functionality to mark release points (v1.0, and so on) +functionality to mark release points (v1.0, and so on).  ### HEAD and head (component of .git dir) diff --git a/jsonnet.html.markdown b/jsonnet.html.markdown new file mode 100644 index 00000000..175642d4 --- /dev/null +++ b/jsonnet.html.markdown @@ -0,0 +1,139 @@ +--- +language: jsonnet +filename: learnjsonnet.jsonnet +contributors: +  - ["Huan Wang", "https://github.com/fredwangwang"] +--- + +Jsonnet is a powerful templating language for JSON. Any valid JSON +document is a valid Jsonnet object. For an interactive demo/tutorial, +click [here](https://jsonnet.org/learning/tutorial.html) + +```python +// single line comment + +/* +    multiline comment +*/ + +// as well as python style comment + +# define a variable. +# Variables have no effect in the generated JSON without being used. +local num1 = 1; +local num2 = 1 + 1; +local num3 = 5 - 2; +local num4 = 9 % 5; +local num5 = 10 / 2.0; +# jsonnet is a lazy language, if a variable is not used, it is not evaluated. +local num_runtime_error = 1 / 0; + +# fields are valid identifiers without quotes +local obj1 = { a: 'letter a', B: 'letter B' }; + +local arr1 = ['a', 'b', 'c']; + +# string literals use " or '. +local str1 = 'a' + 'B'; +# multiline text literal in between ||| +# Each line must start with a white space. +local str_multiline = ||| +  this is a +  multiline string +|||; +# Python-compatible string formatting is available via % +# When combined with ||| this can be used for templating text files. +local str_templating = ||| +  %(f1)0.3f +||| % { f1: 1.2345678 }; +assert str_templating == '1.235\n'; + +# if b then e else e. The else branch is optional and defaults to null +local var1 = if 3 < 2 then "YES"; +assert var1 == null; + +local obj2 = { +  # variable defined inside the object ends with ',' +  local var_in_obj = 0, + +  local vowels = ['a', 'e', 'i', 'o', 'u'], +  local numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + +  # [num] to look up an array element +  first_vowel: vowels[0], +  # can also slice the array like in Python +  even_numbers: numbers[1::2], + +  # python-style list and object comprehensions are also supported +  double_numbers: [x * 2 for x in numbers], +  even_numbers_map: { +      # [ ] syntax in field name is to compute the field name dynamically +      [x + '_is_even']: true for x in numbers if x % 2 == 0 +  }, + +  nested: { +    nested_field1: 'some-value', +    # self refers to the current object +    # ["field-name"] or .field-name can be used to look up a field +    nested_field2: self.nested_field1, +    nested_field3: self.nested_field1, +    # $ refers to outer-most object +    nested_field4: $.first_vowel, + +    assert self.nested_field1 == self.nested_field2, +    assert self.nested_field1 == self.nested_field3, +  }, + +  special_field: 'EVERYTHING FEELS BAD', +}; + +local obj3 = { +  local var_in_obj = 1.234, +  local var_in_obj2 = { a: { b: 'c' } }, + +  concat_array: [1, 2, 3] + [4], +  # strings can be concat with +, +  # which implicitly converts one operand to string if needed. +  concat_string: '123' + 4, + +  # == tests deep equality +  equals: { a: { b: 'c', d: {} } } == var_in_obj2, + +  special_field: 'this feels good', +}; + +# objects can be merged with + where the right-hand side wins field conflicts +local obj4 = obj2 + obj3; +assert obj4.special_field == 'this feels good'; + +# define a function +# functions have positional parameters, named parameters, and default arguments +local my_function(x, y, z=1) = x + y - z; +local num6 = my_function(7, 8, 9); +local num7 = my_function(8, z=10, y=9); +local num8 = my_function(4, 5); +# inline anonymous function +local num9 = (function(x) x * x)(3); + +local obj5 = { +  # define a method +  # fields defined with :: are hidden, which does not apper in generated JSON +  # function cannot be serialized so need to be hidden +  # if the object is used in the generated JSON. +  is_odd(x):: x % 2 == 1, +}; +assert obj5 == {}; + +# a jsonnet doucment have to evaluate to something +# be it an object, list, number or just string literal +"FIN" + +``` + +## Further Reading +There are a few but important concepts that are not touched in this exmaple, including: + +- Passing variables from command line: [Parameterize Entire Config](https://jsonnet.org/learning/tutorial.html#parameterize-entire-config) +- Import other jsonnet libraries/files: [Imports](https://jsonnet.org/learning/tutorial.html#imports) +- In depth example of OOP aspect of Jsonnet: [Object-Orientation](https://jsonnet.org/learning/tutorial.html#Object-Orientation) +- Useful standard library: [Stdlib](https://jsonnet.org/ref/stdlib.html) diff --git a/matlab.html.markdown b/matlab.html.markdown index 5790bcc6..4ca31857 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -234,7 +234,7 @@ A'  % Concise version of complex transpose  % On their own, the arithmetic operators act on whole matrices. When preceded  % by a period, they act on each element instead. For example:  A * B % Matrix multiplication -A .* B % Multiple each element in A by its corresponding element in B +A .* B % Multiply each element in A by its corresponding element in B  % There are several pairs of functions, where one acts on each element, and  % the other (whose name ends in m) acts on the whole matrix. diff --git a/nl-nl/json-nl.html.markdown b/nl-nl/json-nl.html.markdown index 906112ff..d243802d 100644 --- a/nl-nl/json-nl.html.markdown +++ b/nl-nl/json-nl.html.markdown @@ -5,26 +5,27 @@ contributors:    - ["Anna Harren", "https://github.com/iirelu"]    - ["Marco Scannadinari", "https://github.com/marcoms"]    - ["himanshu", "https://github.com/himanshu81494"] +  - ["Maarten Jacobs", "https://github.com/maartenJacobs"]  translators:    - ["Niels van Velzen", "https://nielsvanvelzen.me"]  lang: nl-nl  --- -Gezien JSON een zeer eenvouding formaat heeft zal dit een van de simpelste +Gezien JSON een zeer eenvouding formaat heeft zal dit één van de simpelste  Learn X in Y Minutes ooit zijn. -JSON heeft volgens de specificaties geen commentaar, ondanks dat hebben de +JSON heeft volgens de specificaties geen commentaar. Ondanks dat hebben de  meeste parsers support voor C-stijl (`//`, `/* */`) commentaar.  Sommige parsers staan zelfs trailing komma's toe. -(Een komma na het laatste element in een array of ahter de laatste eigenshap van een object). -Het is wel beter om dit soort dingen te vermijden omdat het niet overal zal werken. +(Een komma na het laatste element in een array of achter de laatste eigenschap van een object). +Het is wel beter om dit soort dingen te vermijden omdat het niet in elke parser zal werken.  In het voorbeeld zal alleen 100% geldige JSON gebruikt worden.  Data types gesupport door JSON zijn: nummers, strings, booleans, arrays, objecten en null.  Gesupporte browsers zijn: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. -De extensie voor JSON bestanden is ".json". De MIME type is "application/json" -Enkele nadelen van JSON zijn het gebrek een type definities en een manier van DTD. +De extensie voor JSON bestanden is ".json". De MIME type is "application/json". +Enkele nadelen van JSON zijn het gebrek aan type definities en een manier van DTD.  ```json  { diff --git a/p5.html.markdown b/p5.html.markdown index be22d3e5..f6084b98 100644 --- a/p5.html.markdown +++ b/p5.html.markdown @@ -7,7 +7,7 @@ contributors:  filename: p5.js  --- -p5.js is a JavaScript library that starts with the original goal of [Processing](http://processing.org"), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web. +p5.js is a JavaScript library that starts with the original goal of [Processing](https://processing.org), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web.  Since p5 is a JavaScript library, you should learn [Javascript](https://learnxinyminutes.com/docs/javascript/) first.  ```js diff --git a/rst.html.markdown b/rst.html.markdown index 2423622e..bdc73c7a 100644 --- a/rst.html.markdown +++ b/rst.html.markdown @@ -49,9 +49,11 @@ Subtitles with dashes  You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``print()``. +Special characters can be escaped using a backslash, e.g. \\ or \*. +  Lists are similar to Markdown, but a little more involved. -Remember to line up list symbols (like - or *) with the left edge of the previous text block, and remember to use blank lines to separate new lists from parent lists:     +Remember to line up list symbols (like - or \*) with the left edge of the previous text block, and remember to use blank lines to separate new lists from parent lists:      - First item  - Second item @@ -86,7 +88,7 @@ There are multiple ways to make links:  - By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link)  - By making a more Markdown-like link: `Github <https://github.com/>`_ . -.. _Github https://github.com/ +.. _Github: https://github.com/  ``` diff --git a/ru-ru/pascal-ru.html.markdown b/ru-ru/pascal-ru.html.markdown new file mode 100644 index 00000000..8a41918f --- /dev/null +++ b/ru-ru/pascal-ru.html.markdown @@ -0,0 +1,216 @@ +--- +language: Pascal +filename: learnpascal-ru.pas +contributors: +    - ["Ganesha Danu", "http://github.com/blinfoldking"] +    - ["Keith Miyake", "https://github.com/kaymmm"] +translators: +    - ["Anton 'Dart' Nikolaev", "https://github.com/dartfnm"] +--- + + +>Pascal - это процедурный язык программирования, который Никлаус Вирт разработал в 1968–69 годах и опубликовал в 1970 году как небольшой эффективный язык, предназначенный для поощрения хороших методов программирования с использованием структурированного программирования и структурирования данных. Он назван в честь французского математика, философа и физика Блеза Паскаля. +> +>source : [wikipedia](https://ru.wikipedia.org/wiki/Паскаль_(язык_программирования))) + + + +Для компиляции и запуска программы на языке Паскаль вы можете использовать бесплатный компилятор FreePascal. [Скачать здесь](https://www.freepascal.org/)  + +Либо современный бесплатный компилятор Паскаля нового поколения под платформу .Net [PascalABC.NET](http://pascalabc.net) + +```pascal +// это комментарий +{ +    а вот это:   +    - комментарий на несколько строк +} + +//объявляем имя программы +program learn_pascal; //<-- не забываем ставить точку с запятой (;) + +const +    { +        это секция в которой вы должны объявлять константы +    } +type +    { +    	здесь вы можете объявлять собственные типы данных +    } +var +    { +        секция для объявления переменных +    } + +begin //начало основной программы +    { +        тело вашей программы +    } +end. // В конце основной программы обязательно должна стоять точка "." +``` + +```pascal +//объявление переменных +//вы можете сделать так +var a:integer; +var b:integer; +//или так +var  +    a : integer; +    b : integer; +//или даже так +var a,b : integer; +``` + +```pascal +program Learn_More; + +// Познакомимся с типами данных и с их операциями +const +    PI = 3.141592654; +    GNU = 'GNU''s Not Unix'; +        // имена константам принято давать ЗАГЛАВНЫМИ_БУКВАМИ (в верхнем регистре) +        // их значения фиксированны т.е никогда не меняются во время выполнения программы +        // содержат любой стандартный тип данных (integer, real, boolean, char, string) + +type +    ch_array : array [0..255] of char; +        // массивы - это составной тип данных +        // мы указываем индекс первого и последнего элемента массива ([0..255]) +        // здесь мы объявили новый тип данных содержащий 255 символов 'char' +        // (по сути, это просто строка - string[256]) +         +    md_array : array of array of integer; +        // массив в массиве - по сути является двумерным массивом +        // можно задать массив нулевой (0) длины, а потом динамически расширить его +        // это двумерный массив целых чисел + +//Объявление переменных +var +    int, c, d  : integer; +           // три переменные, которые содержат целые числа +           // Тип "integer" это 16-битное число в диапазоне [-32,768..32,767] +    r    : real; +           // переменная типа "real" принимает вещественные (дробные) значения +           // в диапазоне [3.4E-38..3.4E38] +    bool : boolean; +           // переменная логического типа, принимающая булевы-значения: True/False (Правда/Ложь) +    ch   : char; +           // эта переменная содержит значение кода одного символа +           // тип 'char' это 8-битное число (1 байт), так что никакого Юникода +    str  : string; +           // это переменная составного типа, являющееся строкой +           // по сути, строка это массив в 255 символов длиною, по умолчанию +           +    s    : string[50]; +           // эта строка может содержать максимум 50 символов +           // вы можете сами указать длину строки, чтобы минимизировать использование памяти +    my_str: ch_array; +           // вы можете объявлять переменные собственных типов +    my_2d : md_array; +           // динамически расширяемые массивы требуют указания длины перед их использованием. + +    // дополнительные целочисленные типы данных +    b    : byte;     // диапазон [0..255] +    shi  : shortint; // диапазон [-128..127] +    smi  : smallint; // диапазон [-32,768..32,767] (стандартный Integer) +    w    : word;     // диапазон [0..65,535] +    li   : longint;  // диапазон [-2,147,483,648..2,147,483,647] +    lw   : longword; // диапазон [0..4,294,967,295] +    c    : cardinal; // тоже что и longword +    i64  : int64;    // диапазон [-9223372036854775808..9223372036854775807] +    qw   : qword;    // диапазон [0..18,446,744,073,709,551,615] + +    // дополнительные вещественные типы данных (дробные) +    rr   : real;     // диапазон зависит от платформы (т.е. 8-бит, 16-бит и т.д.) +    rs   : single;   // диапазон [1.5E-45..3.4E38] +    rd   : double;   // диапазон [5.0E-324 .. 1.7E308] +    re   : extended; // диапазон [1.9E-4932..1.1E4932] +    rc   : comp;     // диапазон [-2E64+1 .. 2E63-1] + +Begin +    int := 1; // так мы присваиваем значение переменной +    r   := 3.14; +    ch  := 'a'; +    str := 'apple'; +    bool := true; +    // Паскаль не чувствителен к регистру +     +    // арифметические операции +    int := 1 + 1; // int = 2; заменяет предыдущее значение +    int := int + 1; // int = 2 + 1 = 3; +    int := 4 div 2; //int = 2; 'div' операция деления, с отбрасыванием дробной части +    int := 3 div 2; //int = 1; +    int := 1 div 2; //int = 0; + +    bool := true or false; // bool = true +    bool := false and true; // bool = false +    bool := true xor true; // bool = false + +    r := 3 / 2; // деления вещественных чисел с дробной частью +    r := int; // вещественной переменной можно присвоить целочисленное значение, но не наоборот + +    my_str[0] := 'a'; // для доступа к элементу массива нужно указать его индекс в квадратных скобках ([0]) + +    c := str[1]; // первая буква во всех Строках находится по индексу [1] +    str := 'hello' + 'world'; //объединяем 2 строки в одну +	 +    SetLength(my_2d,10,10); // инициализируем динамически расширяемый массив +                            // задаём размер 2х-мерного массива 10×10  +     +    // первый элемент массива лежит в индексе [0], последний [длина_массива-1] +    for c := 0 to 9 do +        for d := 0 to 9 do // переменные для счетчиков циклов должны быть объявлены +        my_2d[c,d] := c * d; +          // обращаться к многомерным массивам нужно с помощью одного набора скобок + +End. +``` + +```pascal +program Functional_Programming; + +Var +    i, dummy : integer; + +function factorial_recursion(const a: integer) : integer; +{ Функция расчёта Факториала целочисленного параметра 'a', рекурсивно. Возвращает целое значение } + +// Мы можем объявлять локальные переменные внутри своей функции: +// Var +//    local_a : integer; + +Begin +    If a >= 1 Then +        factorial_recursion := a * factorial_recursion(a-1) +        // возвращаем результат, присваивая найденное значение переменной с тем же именем, как у функции +    Else +        factorial_recursion := 1; +End; // Для завершения функции, используется символ ";" после оператора "End;" + + + +procedure get_integer( var i : integer; dummy : integer ); +{   Эта процедура ждёт от пользователя ввода целого числа и возвращает его значение через параметр i. +    Если параметр функции начинается с 'var', это означает, что его значение было передано, по ссылке, то есть, оно может использоваться не только как входное значение, но и для возвращения дополнительных результатов работы функции. +    Параметры функции (без 'var'), (такие как "dummy" (пустышка)), передаются по значению, и по сути являются - локальными переменными, таким образом изменения, внесенные внутри функции/процедуры, не влияют на значение переменной за её пределами. +} +Begin // начало процедуры +    write('Введите целое число: '); +    readln(i); // число, введённое пользователем, сохранится в переменной i +               // и её значение будет доступно вызывающей подпрограмме +     +    dummy := 4; // значение 'dummy' не будет влиять на значения переменной вне процедуры +End; // конец процедуры + +Begin // главный блок программы +    dummy := 3; +    get_integer(i, dummy); // вызываем процедуру получения числа от пользователя     +    writeln(i, '! = ', factorial_recursion(i)); // ввыводим значение факториала от i +     +    writeln('dummy = ', dummy);  +    // всегда выводит "3", поскольку фиктивная переменная не изменяется. +End. // конец программы + +``` + diff --git a/set-theory.html.markdown b/set-theory.html.markdown new file mode 100644 index 00000000..c6bc39c5 --- /dev/null +++ b/set-theory.html.markdown @@ -0,0 +1,162 @@ +--- +category: Algorithms & Data Structures +name: Set theory +contributors: +--- +The set theory is a study for sets, their operations, and their properties. It is the basis of the whole mathematical system. + +* A set is a collection of definite distinct items. + +## Basic operators +These operators don't require a lot of text to describe. + +* `∨` means or. +* `∧` means and. +* `,` separates the filters that determine the items in the set. + +## A brief history of the set theory +### Naive set theory +* Cantor invented the naive set theory. +* It has lots of paradoxes and initiated the third mathematical crisis. + +### Axiomatic set theory +* It uses axioms to define the set theory. +* It prevents paradoxes from happening. + +## Built-in sets +* `∅`, the set of no items. +* `N`, the set of all natural numbers. `{0,1,2,3,…}` +* `Z`, the set of all integers. `{…,-2,-1,0,1,2,…}` +* `Q`, the set of all rational numbers. +* `R`, the set of all real numbers. + +### The empty set +* The set containing no items is called the empty set. Representation: `∅` +* The empty set can be described as `∅ = {x|x ≠ x}` +* The empty set is always unique. +* The empty set is the subset of all sets. + +``` +A = {x|x∈N,x < 0} +A = ∅ +∅ = {}              (Sometimes) + +|∅|   = 0 +|{∅}| = 1 +``` + +## Representing sets +### Enumeration +* List all items of the set, e.g. `A = {a,b,c,d}` +* List some of the items of the set. Ignored items are represented with `…`. E.g. `B = {2,4,6,8,10,…}` + +### Description +* Describes the features of all items in the set. Syntax: `{body|condtion}` + +``` +A = {x|x is a vowel} +B = {x|x ∈ N, x < 10l} +C = {x|x = 2k, k ∈ N} +C = {2x|x ∈ N} +``` + +## Relations between sets +### Belongs to +* If the value `a` is one of the items of the set `A`, `a` belongs to `A`. Representation: `a∈A` +* If the value `a` is not one of the items of the set `A`, `a` does not belong to `A`. Representation: `a∉A` + +### Equals +* If all items in a set are exactly the same to another set, they are equal. Representation: `a=b` +* Items in a set are not order sensitive. `{1,2,3,4}={2,3,1,4}` +* Items in a set are unique. `{1,2,2,3,4,3,4,2}={1,2,3,4}` +* Two sets are equal if and only if all of their items are exactly equal to each other. Representation: `A=B`. Otherwise, they are not equal. Representation: `A≠B`. +* `A=B` if `A ⊆ B` and `B ⊆ A` + +### Belongs to +* If the set A contains an item `x`, `x` belongs to A (`x∈A`). +* Otherwise, `x` does not belong to A (`x∉A`). + +### Subsets +* If all items in a set `B` are items of set `A`, we say that `B` is a subset of `A` (`B⊆A`). +* If B is not a subset of A, the representation is `B⊈A`. + +### Proper subsets +* If `B ⊆ A` and `B ≠ A`, B is a proper subset of A (`B ⊂ A`). Otherwise, B is not a proper subset of A (`B ⊄ A`). + +## Set operations +### Base number +* The number of items in a set is called the base number of that set. Representation: `|A|` +* If the base number of the set is finite, this set is a finite set. +* If the base number of the set is infinite, this set is an infinite set. + +``` +A   = {A,B,C} +|A| = 3 +B   = {a,{b,c}} +|B| = 2 +|∅| = 0         (it has no items) +``` + +### Powerset +* Let `A` be any set. The set that contains all possible subsets of `A` is called a powerset (written as `P(A)`). + +``` +P(A) = {x|x ⊆ A} + +|A| = N, |P(A)| = 2^N +``` + +## Set operations among two sets +### Union +Given two sets `A` and `B`, the union of the two sets are the items that appear in either `A` or `B`, written as `A ∪ B`. + +``` +A ∪ B = {x|x∈A∨x∈B} +``` + +### Intersection +Given two sets `A` and `B`, the intersection of the two sets are the items that appear in both `A` and `B`, written as `A ∩ B`. + +``` +A ∩ B = {x|x∈A,x∈B} +``` + +### Difference +Given two sets `A` and `B`, the set difference of `A` with `B` is every item in `A` that does not belong to `B`. + +``` +A \ B = {x|x∈A,x∉B} +``` + +### Symmetrical difference +Given two sets `A` and `B`, the symmetrical difference is all items among `A` and `B` that doesn't appear in their intersections. + +``` +A △ B = {x|(x∈A∧x∉B)∨(x∈B∧x∉A)} + +A △ B = (A \ B) ∪ (B \ A) +``` + +### Cartesian product +Given two sets `A` and `B`, the cartesian product between `A` and `B` consists of a set containing all combinations of items of `A` and `B`. + +``` +A × B = { {x, y} | x ∈ A, y ∈ B } +``` + +## "Generalized" operations +### General union +Better known as "flattening" of a set of sets. + +``` +∪A = {x|X∈A,x∈X} +∪A={a,b,c,d,e,f} +∪B={a} +∪C=a∪{c,d} +``` + +### General intersection + +``` +∩ A = A1 ∩ A2 ∩ … ∩ An +``` diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index d6d369cc..58dccae4 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -388,7 +388,7 @@ y := $A max: $B.  ```smalltalk  | b x y |  x := #Hello.                                      "symbol assignment" -y := 'String', 'Concatenation'.                   "symbol concatenation (result is string)" +y := #Symbol, #Concatenation.                     "symbol concatenation (result is string)"  b := x isEmpty.                                   "test if symbol is empty"  y := x size.                                      "string size"  y := x at: 2.                                     "char at location" | 
