From d2d89cfa9742ef437e45885498677038563d56f5 Mon Sep 17 00:00:00 2001 From: Ankit Aggarwal Date: Mon, 19 Oct 2015 11:47:24 +0530 Subject: Adding documentation on ternary operator --- python3.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index 2398e7ac..6d657395 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -174,6 +174,10 @@ some_var # => 5 # See Control Flow to learn more about exception handling. some_unknown_var # Raises a NameError +# if can be used as an expression +# Equivalent of C's '?:' ternary operator +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + # Lists store sequences li = [] # You can start with a prefilled list -- cgit v1.2.3 From f6b8b079b49a1fcfdc6143fc51bc5d3738ade8f0 Mon Sep 17 00:00:00 2001 From: Patrik Jansson Date: Fri, 23 Oct 2015 23:31:10 +0200 Subject: Some minor fixes I just noted that the example claiming that (add 10) is the same as (+10) was wrong. (A detail - it should be (10+) to match the argument order.) Then I just continued down making a few similar fixes and terminology updates. /Patrik PS. I've been teaching [Advanced Functional Programming](http://www.cse.chalmers.se/edu/course/afp/) (in Haskell) for a few years at Chalmers. --- haskell.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 08611e63..2f58b357 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -189,16 +189,16 @@ foo = add 10 -- foo is now a function that takes a number and adds 10 to it foo 5 -- 15 -- Another way to write the same thing -foo = (+10) +foo = (10+) foo 5 -- 15 -- function composition -- the (.) function chains functions together. -- For example, here foo is a function that takes a value. It adds 10 to it, -- multiplies the result of that by 4, and then returns the final value. -foo = (*4) . (+10) +foo = (4*) . (10+) --- (5 + 10) * 4 = 60 +-- 4*(10 + 5) = 60 foo 5 -- 60 -- fixing precedence @@ -222,7 +222,7 @@ even . fib $ 7 -- false -- 5. Type signatures ---------------------------------------------------- --- Haskell has a very strong type system, and everything has a type signature. +-- Haskell has a very strong type system, and every valid expression has a type. -- Some basic types: 5 :: Integer @@ -259,7 +259,7 @@ case args of _ -> putStrLn "bad args" -- Haskell doesn't have loops; it uses recursion instead. --- map applies a function over every element in an array +-- map applies a function over every element in a list map (*2) [1..5] -- [2, 4, 6, 8, 10] @@ -279,7 +279,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 -- This is the same as (2 * (2 * (2 * 4 + 1) + 2) + 3) --- foldl is left-handed, foldr is right- +-- foldl is left-handed, foldr is right-handed foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 -- This is now the same as @@ -318,7 +318,7 @@ Nothing -- of type `Maybe a` for any `a` -- it is not hard to explain enough to get going. -- When a Haskell program is executed, `main` is --- called. It must return a value of type `IO ()`. For example: +-- called. It must return a value of type `IO a` for some type `a`. For example: main :: IO () main = putStrLn $ "Hello, sky! " ++ (say Blue) @@ -361,7 +361,7 @@ sayHello = do -- You can think of a value of type `IO a` as representing a -- computer program that will generate a value of type `a` -- when executed (in addition to anything else it does). We can --- store and reuse this value using `<-`. We can also +-- name and reuse this value using `<-`. We can also -- make our own action of type `IO String`: action :: IO String @@ -417,7 +417,7 @@ Hello, Friend! There's a lot more to Haskell, including typeclasses and monads. These are the big ideas that make Haskell such fun to code in. I'll leave you with one final -Haskell example: an implementation of quicksort in Haskell: +Haskell example: an implementation of a quicksort variant in Haskell: ```haskell qsort [] = [] -- cgit v1.2.3 From 08b430d2158bc93043385ba77fccb6af4fe77d50 Mon Sep 17 00:00:00 2001 From: Ryan Mavilia Date: Wed, 13 Jan 2016 23:50:24 -0500 Subject: Created the first asciidoc tutorial --- asciidoc.markdown | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 asciidoc.markdown diff --git a/asciidoc.markdown b/asciidoc.markdown new file mode 100644 index 00000000..d6cfeca0 --- /dev/null +++ b/asciidoc.markdown @@ -0,0 +1,66 @@ +--- +language: asciidoc +contributors: + - ["Ryan Mavilia", "http://unoriginality.rocks/:] +filename: asciidoc.md +--- + +AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization. + +Document Header + +Headers are optional and can't contain blank lines. It must be offset from content by at least one blank line. + +Title Only + +```asciidoc += Document Title + +First sentence of document. +``` + +Title and Author + +```asciidoc += Document Title +First Last + +Start of this document. +``` + +Multiple Authors +```asciidoc += Document Title +John Doe ; Jane Doe; Black Beard + +Start of a doc with multiple authors. +``` + +Revision Line (requires an author line) +```asciidoc += Doc Title V1 +Potato Man +v1.0, 2016-01-13 + +This article about chips is going to be fun. +``` + +Section Titles + +```asciidoc += Level 0 (may only be used in document's header) + +== Level 1

+ +=== Level 2

+ +==== Level 3

+ +===== Level 4

+ +====== Level 5
+ +======= Level 6 + +``` + -- cgit v1.2.3 From 0bd64705a8096ed1ad808653bd88f1372533dd47 Mon Sep 17 00:00:00 2001 From: Ryan Mavilia Date: Sun, 17 Jan 2016 03:55:54 -0500 Subject: Update asciidoc.markdown --- asciidoc.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/asciidoc.markdown b/asciidoc.markdown index d6cfeca0..b98d0fa9 100644 --- a/asciidoc.markdown +++ b/asciidoc.markdown @@ -45,22 +45,22 @@ v1.0, 2016-01-13 This article about chips is going to be fun. ``` -Section Titles +Section Titles ```asciidoc = Level 0 (may only be used in document's header) -== Level 1

+== Same as

-=== Level 2

+=== Same as

-==== Level 3

+==== Same as

-===== Level 4

+===== Same as
-====== Level 5
+====== Same as
-======= Level 6 +======= Same as ``` -- cgit v1.2.3 From b253b8e4cba10dc28023e613498473f78e3a17ad Mon Sep 17 00:00:00 2001 From: Ryan Mavilia Date: Sun, 17 Jan 2016 04:04:41 -0500 Subject: Rename asciidoc.markdown to asciidoc.html.markdown --- asciidoc.html.markdown | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++ asciidoc.markdown | 66 -------------------------------------------------- 2 files changed, 66 insertions(+), 66 deletions(-) create mode 100644 asciidoc.html.markdown delete mode 100644 asciidoc.markdown diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown new file mode 100644 index 00000000..b98d0fa9 --- /dev/null +++ b/asciidoc.html.markdown @@ -0,0 +1,66 @@ +--- +language: asciidoc +contributors: + - ["Ryan Mavilia", "http://unoriginality.rocks/:] +filename: asciidoc.md +--- + +AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization. + +Document Header + +Headers are optional and can't contain blank lines. It must be offset from content by at least one blank line. + +Title Only + +```asciidoc += Document Title + +First sentence of document. +``` + +Title and Author + +```asciidoc += Document Title +First Last + +Start of this document. +``` + +Multiple Authors +```asciidoc += Document Title +John Doe ; Jane Doe; Black Beard + +Start of a doc with multiple authors. +``` + +Revision Line (requires an author line) +```asciidoc += Doc Title V1 +Potato Man +v1.0, 2016-01-13 + +This article about chips is going to be fun. +``` + +Section Titles + +```asciidoc += Level 0 (may only be used in document's header) + +== Same as

+ +=== Same as

+ +==== Same as

+ +===== Same as

+ +====== Same as
+ +======= Same as + +``` + diff --git a/asciidoc.markdown b/asciidoc.markdown deleted file mode 100644 index b98d0fa9..00000000 --- a/asciidoc.markdown +++ /dev/null @@ -1,66 +0,0 @@ ---- -language: asciidoc -contributors: - - ["Ryan Mavilia", "http://unoriginality.rocks/:] -filename: asciidoc.md ---- - -AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization. - -Document Header - -Headers are optional and can't contain blank lines. It must be offset from content by at least one blank line. - -Title Only - -```asciidoc -= Document Title - -First sentence of document. -``` - -Title and Author - -```asciidoc -= Document Title -First Last - -Start of this document. -``` - -Multiple Authors -```asciidoc -= Document Title -John Doe ; Jane Doe; Black Beard - -Start of a doc with multiple authors. -``` - -Revision Line (requires an author line) -```asciidoc -= Doc Title V1 -Potato Man -v1.0, 2016-01-13 - -This article about chips is going to be fun. -``` - -Section Titles - -```asciidoc -= Level 0 (may only be used in document's header) - -== Same as

- -=== Same as

- -==== Same as

- -===== Same as

- -====== Same as
- -======= Same as - -``` - -- cgit v1.2.3 From 5edee6c0d2afac2ab2690af4da1ebb88f06d2ca4 Mon Sep 17 00:00:00 2001 From: Oliver Vartiainen Date: Wed, 20 Jan 2016 22:15:20 +0200 Subject: Translate Ruby docs to Finnish --- fi-fi/ruby-fi.html.markdown | 607 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 607 insertions(+) create mode 100644 fi-fi/ruby-fi.html.markdown diff --git a/fi-fi/ruby-fi.html.markdown b/fi-fi/ruby-fi.html.markdown new file mode 100644 index 00000000..b4f7583d --- /dev/null +++ b/fi-fi/ruby-fi.html.markdown @@ -0,0 +1,607 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["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"] +translators: + - ["Oliver Vartiainen", "https://github.com/firoxer"] +--- + +```ruby +# Tässä yhden rivin kommentti + +=begin +Tässä usean rivin kommentti +Näitä ei kylläkään käytetä +Joten käytetään vastedes vain yksirivisiä +=end + +# Tärkeintä on muistaa, että Rubyssa kaikki pohjautuu olioihin. + +# Luvutkin ovat olioita: + +3.class #=> Fixnum + +3.to_s #=> "3" + +# Peruslaskutoimituksia: +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 + +# Bittioperaatioita: +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 + +# Laskutoimitukset ovat vain syntaksisokeria lukuolion laskumetodin kutsulle: +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Erityisarvotkin ovat olioita: + +nil # vastaa joidenkin kielten "null"-arvoa +true # tosi +false # epätosi + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Samanvertaisuuden testaus: +1 == 1 #=> true +2 == 1 #=> false + +# ...ja sama eriarvoisuudelle: +1 != 1 #=> false +2 != 1 #=> true + +# "nil" ja "false" ovat ainoat epätodet arvot; kaikki muu ymmärretään todeksi: +!nil #=> true +!false #=> true +!0 #=> false + +# Lisää vertailuoperaatioita: +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Kahdensuuntainen vertailuoperaattori: +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# Logiikkaoperaattorit: +true && false #=> false +true || false #=> true +!true #=> false + +# Merkkipohjaisten logiikkaoperaattorien vaihtoehtona on sanalliset muodot, +# joilla on hyvin matala presedenssi. Niillä voi muokata ohjelman kulkua +# esimerkiksi väitelausekkeita ketjuttaen. + +# Metodia `do_something_else` kutsutaan vain, jos `do_something` onnistuu: +do_something() and do_something_else() +# Metodia `log_error` kutsutaan vain, jos `do_something` epäonnistuu: +do_something() or log_error() + +# Merkkijonot ovat olioita: + +'Tässä on merkkijono'.class #=> String +"Rajaavat lainausmerkit voivat olla yksin- tai kaksinkertaisia".class #=> String + +täyte = 'sisällyttää muita merkkijonoja' +"Kaksinkertaisilla lainausmerkeillä voi #{täyte}" +#=> "Kaksinkertaisilla lainausmerkeillä voi sisällyttää muita merkkijonoja" + +# Yksinkertaisia lainausmerkkejä kannattaa silti suosia, sillä kaksinkertaiset +# merkit saattavat aiheuttaa turhia kielensisäisiä tarkistuksia. + +# Merkkijonoja voi yhdistellä toisiinsa: +'hello ' + 'world' #=> "hello world" + +# ...mutta luvut vaativat ensin tyyppimuunnoksen: +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# Merkkijonoja voi soveltaa laskutoimituksiin... odotettavin seurauksin: +'hello ' * 3 #=> "hello hello hello " + +# Merkkijonoa voi jatkaa toisella: +'hello' << ' world' #=> "hello world" + +# Tulosteen luonti kera rivinvaihdon: +puts "I'm printing!" +#=> I'm printing! +#=> nil + +# ...ja ilman rivinvaihtoa: +print "I'm printing!" +#=> I'm printing! => nil + +# Muuttujien määrittely: +x = 25 #=> 25 +x #=> 25 + +# Arvon asettaminen palauttaa arvon itsensä, joten usean muuttujan arvon +# yhtäaikainen määrittely käy vaivatta: +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Muuttujien sanaerottimena käytetään alaviivaa: +snake_case = true + +# Lisäksi Rubyssa suositaan ytimekkäitä nimiä: +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Symbolit + +# Symbolit ovat muuttumattomia, uudelleenkäytettäviä vakioita. +# Niitä käytetään merkkijonojen sijaan, kun tarkoitus on viitata arvoon, +# jolla on tietty, pysyvä merkitys: + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# Taulukot + +# Tässä taulukko: +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Taulukko saa koostua erityyppisistä arvoista: +[1, 'hello', false] #=> [1, "hello", false] + +# Taulukon alkioihin voi viitata järjestysnumerolla nollasta alkaen: +array[0] #=> 1 +array.first #=> 1 +array[12] #=> nil + +# Kuten laskutoimituksissa nähty syntaksisokeri on myös taulukon alkioiden haku +# pohjimmiltaan vain taulukko-olioon kuuluvan "[]"-metodin kutsu: +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Haku käy myös lopustapäin: +array[-1] #=> 5 +array.last #=> 5 + +# Alitaulukon haku käy indeksiparilla... +array[2, 3] #=> [3, 4, 5] + +# ...tai määrittelemällä väli: +array[1..3] #=> [2, 3, 4] + +# Taulukon voi kääntää: +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Ja sitä voi jatkaa näin... +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# ...tai näin: +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Alkion olemassaolon tarkistus: +array.include?(1) #=> true + +# Hashit eli assosiaatiotaulut ovat Rubyn tärkein avain-/arvoparirakenne. +# Hash luodaan aaltosulkeilla: +hash = { 'color' => 'green', 'number' => 5 } + +hash.keys #=> ['color', 'number'] + +# Hash toimii erityisen nopeasti, kun haetaan arvoa avaimen perusteella: +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# Jos hashistä ei löyty avainta vastaavaa arvoa, palautetaan nil-arvo: +hash['nothing here'] #=> nil + +# Symbolihashin määrittelylle on oma syntaksinsa (alkaen Rubyn versiosta 1.9): +new_hash = { defcon: 3, action: true } +new_hash.keys #=> [:defcon, :action] + +# Hashin avaimen ja arvon olemassaolon tarkistus: +new_hash.key?(:defcon) #=> true +new_hash.value?(3) #=> true + +# Vinkki! Sekä taulukot että hashit sisältävät Enumerable-moduulin, +# johon kuuluu useita hyödyllisiä iterointimetodeja kuten .each, .map, +# .reduce ja .count + +# Rakenteita + +if true + 'if statement' +elsif false + 'else if, optional' +else + 'else, also optional' +end + +for counter in 1..5 + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# HUOMAA, että for-rakennetta kannattaa välttää, sillä Rubyssa suosittu +# each-metodi ajaa saman asian idiomaattisemmin. Each-metodi ottaa ainoana +# argumenttinaan lohkon. Lohkot toimivat pitkälti samoin kuin muiden kielten +# anonyymit funktiot, lambdat tai sulkeumat. + +# Lukuvälit vastaavat each-metodiin, jolloin sille annettu lohko ajetaan +# kerran jokaiselle välin kokonaisluvulle. +# Lukuvälin each-rakenne lohkoineen näyttää tältä: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# Lohkoa ympäröivät do/end-avainsanat voi korvata myös aaltosulkeilla: +(1..5).each { |counter| puts "iteration #{counter}" } + +# Lukuvälien lisäksi myös tietorakenteita voidaan iteroida each-metodilla: +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +# Taulukoita voi iteroida metodilla each_with_index, jolloin lohko saa +# argumenteikseen sekä alkion että indeksin: +array.each_with_index do |element, index| + puts "#{element} is number #{index} in the array" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# Each-metodin lisäksi Rubyssa on useita muita iterointimetodeja kuten +# "map" ja "reduce". Näistä "map" kutsuttuna taulukolla ottaa argumentikseen +# lohkon, suorittaa sen kerran jokaiselle rakenteen jäsenelle, ja lopuksi +# palauttaa uuden taulukon, jonka jäsenet ovat lohkon suorituksen tuloksia. + +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-rakenne siirtää ohjelman kulun yhdelle monista määritellyistä poluista: + +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +#=> "Better luck next time" + +# Case-rakenteessa voidaan hyödyntää lukuvälejä: +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +#=> "OK job" + +# Virheidenkäsittely: +begin + # Seuraava koodinpätkä aiheuttaa NoMemoryError-poikkeuksen + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end + +# Ylimmän näkyvyysalueen metodi näyttää itsenäiseltä funktiolta: +def double(x) + x * 2 +end + +# Funktiot (ja lohkot) palauttavat implisiittisesti +# viimeiseksi ajamansa lausekkeen arvon: +double(2) #=> 4 + +# Metodikutsun argumentteja ympäröivät kaarisulkeet voi jättää pois, +# kunhan koodi ei muutu monitulkintaiseksi: + +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# Argumentit erotetaan pilkuilla: + +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# Kaikilla metodeilla on implisiittinen lohkoparametri, +# joka voidaan suorittaa yield-avainsanalla: + +def surround + puts '{' + yield + puts '}' +end + +surround { puts 'hello world' } + +# { +# hello world +# } + +# Metodille annetun lohkon voi nimetä parametrilistassa &-merkin avulla, +# minkä jälkeen se suoritetaan call-metodilla: +def guests(&block) + block.call 'some_argument' +end + +# Metodille voi antaa vaihtelevan määrän muuttujia. Ne siirretään taulukkoon, +# jolle annetaan parametrilistassa nimi \*-merkin avulla +def guests(*array) + array.each { |guest| puts guest } +end + +# Luokan määritys aloitetaan class-avainsanalla: + +class Human + + # Tässä luokkamuuttuja, joka on yhteinen kaikille luokan olioille: + @@species = 'H. sapiens' + + # Alustusmetodin määrittely: + def initialize(name, age = 0) + # name-oliomuuttujan arvon asetus metodille annetun name-muuttujan mukaan: + @name = name + + # Jos tätä metodia kutsuessa jätetään toinen argumentti (age) antamatta, + # saa se parametriluettelossa määritetyn arvon 0: + @age = age + end + + # Tyypillinen oliomuuttujan arvon asettava metodi: + def name=(name) + @name = name + end + + # Tyypillinen oliomuuttujan arvon palauttava metodi: + def name + @name + end + + # Edelliset kaksi metodia voi ilmaista idiomaattisemmin myös näin: + attr_accessor :name + + # Lisäksi arvon palauttavan ja asettavan metodin voi määritellä erikseen: + attr_reader :name + attr_writer :name + + # Luokkametodeissa käytetään avainsanaa self erotuksena oliometodeista. + # Luokkametodia voi kutsua vain luokalla itsellään, ei olioilla: + def self.say(msg) + puts msg + end + + def species + @@species + end +end + +# Olion luonti: + +jim = Human.new('Jim Halpert') + +dwight = Human.new('Dwight K. Schrute') + +# Olion metodien kutsuja: +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" + +# Luokkametodin kutsu: +Human.say('Hi') #=> "Hi" + +# Muuttujan näkyvyysalueen voi määritellä etuliitteellä. + +# $-alkuiset muuttujat ovat globaaleja: +$var = "I'm a global var" +defined? $var #=> "global-variable" + +# @-alkuiset muuttujat kuuluvat oliolle, +# jonka näkyvyysalueella määrittely tehdään: +@var = "I'm an instance var" +defined? @var #=> "instance-variable" + +# @@-alkuiset muuttujat kuuluvat vastaavasti näkyvyysalueensa luokalle: +@@var = "I'm a class var" +defined? @@var #=> "class variable" + +# Isolla alkukirjaimella nimetyt muuttujat ovatkin vakioita: +Var = "I'm a constant" +defined? Var #=> "constant" + +# Kuten odottaa saattaa, myös luokat itsessään ovat olioita. +# Siksi niille voi määritellä muuttujia, jotka ovat yhteisiä kaikille +# luokan ilmentymille ja perillisille. + +# Tavallisen luokan määrittely: + +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Perillisluokan määrittely: + +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# Oliomuuttuja on kuitenkin olion oma eikä periydy: + +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 + +module ModuleExample + def foo + 'foo' + end +end + +# Moduulien lisääminen luokkaan "include"-avainsanalla siirtää moduulin metodit +# luokan ilmentymille, kun taas "extend" avainsana siirtää metodit +# luokalle itselleen: + +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' + +# Callback-tyyppiset metodit suoritetaan moduulia sisällyttäessä: + +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 + end +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' +``` + +## Lisämateriaalia englanniksi + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Selaimessa tehtäviä harjoituksia tämän dokumentin hengessä +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) - Virallinen dokumentaatio +- [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/) - Vanhempi, mutta [ilmainen painos](http://ruby-doc.com/docs/ProgrammingRuby/) on luettavissa netissä +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Yhteisön luoma Ruby-tyyliopas +- [Try Ruby](http://tryruby.org) - Rubyn perusteet interaktiivisesti -- cgit v1.2.3 From f22810e6829ee005ac4051f4dc2b1c4ae35b33ac Mon Sep 17 00:00:00 2001 From: Oliver Vartiainen Date: Mon, 25 Jan 2016 12:21:51 +0200 Subject: Fix file metadata --- fi-fi/ruby-fi.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fi-fi/ruby-fi.html.markdown b/fi-fi/ruby-fi.html.markdown index b4f7583d..52c60182 100644 --- a/fi-fi/ruby-fi.html.markdown +++ b/fi-fi/ruby-fi.html.markdown @@ -1,6 +1,6 @@ --- language: ruby -filename: learnruby.rb +filename: learnruby-fi.rb contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] @@ -17,6 +17,7 @@ contributors: - ["Jake Faris", "https://github.com/farisj"] translators: - ["Oliver Vartiainen", "https://github.com/firoxer"] +lang: fi-fi --- ```ruby -- cgit v1.2.3 From f60cb8316e21197e369311df91a1f9576878785d Mon Sep 17 00:00:00 2001 From: Ryan Mavilia Date: Tue, 26 Jan 2016 03:27:17 -0500 Subject: Added paragraphs, lists, and formatted text. --- asciidoc.html.markdown | 66 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 6 deletions(-) diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown index b98d0fa9..4196e424 100644 --- a/asciidoc.html.markdown +++ b/asciidoc.html.markdown @@ -44,23 +44,77 @@ v1.0, 2016-01-13 This article about chips is going to be fun. ``` +Paragraphs + +```asciidoc +You don't need anything special for paragraphs. + +Add a blank line between paragraphs to seperate them. + +To create a line blank add a + +and you will recieve a line break! +``` + +Formatting Text + +```asciidoc +_underscore creates italics_ +*asterisks for bold* +*_combine for extra fun_* +`use ticks to signify monospace` +`*bolded monospace*` +``` Section Titles ```asciidoc = Level 0 (may only be used in document's header) -== Same as

+== Level 1

-=== Same as

+=== Level 2

-==== Same as

+==== Level 3

-===== Same as

+===== Level 4
-====== Same as
+====== Level 5
-======= Same as +======= Level 6 ``` +Lists + +To create a bulleted list use asterisks. +```asciidoc +* foo +* bar +* baz +``` + +To create a numbered list use periods. +```asciidoc +. item 1 +. item 2 +. item 3 +``` + +You can nest lists by adding extra asterisks or periods up to five times. +```asciidoc +* foo 1 +** foo 2 +*** foo 3 +**** foo 4 +***** foo 5 +``` +```asciidoc +. foo 1 +.. foo 2 +... foo 3 +.... foo 4 +..... foo 5 +``` + + + -- cgit v1.2.3 From 083aa4fa4c462cbd9b5f9b3c671969d7d3d6976c Mon Sep 17 00:00:00 2001 From: Ryan Mavilia Date: Tue, 26 Jan 2016 03:32:28 -0500 Subject: Edit my website! --- asciidoc.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown index 4196e424..f9ca8e21 100644 --- a/asciidoc.html.markdown +++ b/asciidoc.html.markdown @@ -1,7 +1,7 @@ --- language: asciidoc contributors: - - ["Ryan Mavilia", "http://unoriginality.rocks/:] + - ["Ryan Mavilia", "http://unoriginality.rocks/"] filename: asciidoc.md --- -- cgit v1.2.3 From 89f24b7c255686723a8e7e89a3c820fc203c0243 Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Sat, 30 Jan 2016 12:07:45 +0700 Subject: [php/id-id] add ID translation --- id-id/php-id.html.markdown | 851 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 851 insertions(+) create mode 100644 id-id/php-id.html.markdown diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown new file mode 100644 index 00000000..491a190e --- /dev/null +++ b/id-id/php-id.html.markdown @@ -0,0 +1,851 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +filename: learnphp-id.php +translators: + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] +lang: id-id +--- + +Dokumen ini menjelaskan tentang PHP5 keatas. + +```php + +Halo Dunia, lagi! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (awalan 0 menandakan bilangan Oktal) +$int4 = 0x0F; // => 15 (awalan 0x menandakan bilangan Heksadesimal) +// Bilangan Biner Integer tersedia mulai dari PHP 5.4.0. +$int5 = 0b11111111; // 255 (awalan 0b menandakan bilangan Biner) + +// Nilai Floats (dikenal juga sebagai Doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Menghapus variable +unset($int1); + +// Aritmatika +$jumlah = 1 + 1; // 2 +$selisih = 2 - 1; // 1 +$perkalian = 2 * 2; // 4 +$pembagian = 2 / 1; // 2 + +// Aritmatika singkat +$angka = 0; +$angka += 1; // Menjumlahkan $angka dengan 1 +echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah ditampilkan) +echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum ditampilkan) +$angka /= $float; // Membagi dan menyimpan hasil pembagian pada $angka; + +// String biasanya diawali dan ditutup dengan petik satu. +$sgl_quotes = '$String'; // => '$String' + +// Hindari menggunakan petik dua kecuali menyertakan variabel lain +$dbl_quotes = "Ini adalah $sgl_quotes."; // => 'Ini adalah $String.' + +// Karakter khusus hanya berlaku pada petik dua +$berfungsi = "Ini mengandung \t karakter tab."; +$tidak_berfungsi = 'Ini hanya mengandung garis miring dan huruf t: \t'; + +// Batasi variabel dengan kurung kurawal jika diperlukan +$uang = "Saya memiliki $${angka} di Bank."; + +// Sejak PHP 5.3, nowdocs dapat digunakan untuk tak-terinterpolasi banyak-baris +$nowdoc = <<<'END' +Banyak baris +string +END; + +// Heredocs akan melakukan interpolasi +$heredoc = << 1, 'Dua' => 2, 'Tiga' => 3); + +// Pada PHP 5.4 diperkenalkan cara penulisan (sintaks) baru +$asosiatif = ['Satu' => 1, 'Dua' => 2, 'Tiga' => 3]; + +echo $asosiatif['Satu']; // menampilkan 1 + +// Daftar literal secara tidak langsung ditentukan oleh kunci integer +$larik = ['Satu', 'Dua', 'Tiga']; +echo $larik[0]; // => "Satu" + +// Menambahkan sebuah elemen pada akhir larik +$larik[] = 'Empat'; +// atau +array_push($larik, 'Lima'); + +// Menghapus elemen dari larik +unset($larik[3]); + +/******************************** + * Keluaran + */ + +echo('Halo Dunia!'); +// Menampilkan Halo Dunia! ke "stdout". +// "stdout" adalah sebuah halaman web ketika dijalankan dalam peramban (browser). + +print('Halo Dunia!'); // Sama seperti "echo" + +// "echo" dan "print" merupakan bahasa konstruksi, jadi tanda kurung dapat dihilangkan +echo 'Halo Dunia!'; +print 'Halo Dunia!'; + +$paragraf = 'paragraf'; + +echo 100; // Menampilkan variabel skalar secara langsung +echo $paragraf; // atau sebuat variabel + +// Jika PHP tag-singkat telah dikonfigurasi, atau versi PHP yang digunakan +// adalah 5.4.0 keatas, dapat digunakan sintaks "echo" singkat + +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Menampilkan tipe dan nilai dari variabel ke "stdout" +var_dump($z); // prints int(0) + +// Menampilkan variabel ke "stdout" dalam format yang mudah dibaca +print_r($larik); // menampilkan: Array ( [0] => Satu [1] => Dua [2] => Tiga ) + +/******************************** + * Logika + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// menegaskan lemparan sebuah peringatan jika pernyataan tidak benar + +// Perbandingan berikut akan selalu benar, meskipun memiliki tipe yang berbeda. +assert($a == $b); // kesamaan +assert($c != $a); // ketidak-samaan +assert($c <> $a); // versi lain dari ketidak-samaan +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Dibawah ini hanya akan bernilai benar jika nilainya memiliki tipe yang sama. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Operator 'Spaceship' (sejak PHP 7) +// Mengembalikan 0 jika nilai pada kedua sisi adalah sama +// Mengembalikan 1 jika nilai pada sisi kiri lebih besar +// Mengembalikan -1 jika nilai pada sisi kanan lebih besar + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 karena keduanya sama +echo $a <=> $b; // -1 karena $a < $b +echo $b <=> $a; // 1 karena $b > $a + +// Variabel dapat dikonversi menjadi tipe lain, sesuai penggunaannya. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (string dipaksa menjadi integer) + +$string = 'satu'; +echo $string + $string; // => 0 +// Menghasilkan 0 karena operator (+) tidak dapat memaksa string 'satu' menjadi sebuah integer + +// Perubahan tipe dapat dimanfaatkan untuk diperlakukan sebagai tipe lainnya + +$boolean = (boolean) 1; // => true + +$nol = 0; +$boolean = (boolean) $nol; // => false + +// Terdapat juga fungsi khusus untuk melakukan perubahan terhadap beberapa tipe +$integer = 5; +$string = strval($integer); + +$var = null; // Nilai Null + + +/******************************** + * Struktur Kontrol + */ + +if (true) { + print 'Saya tampil'; +} + +if (false) { + print 'Saya tidak tampil'; +} else { + print 'Saya tampil'; +} + +if (false) { + print 'Tidak tampil'; +} elseif(true) { + print 'Tampil'; +} + +// operator ternary +print (false ? 'Tidak tampil' : 'Tampil'); + +// cara pintas operator ternary mulai dirilis sejak PHP 5.3 +// persamaan dari "$x ? $x : 'Kerjakan'" +$x = false; +print($x ?: 'Kerjakan'); + +// operator null coalesce sejak PHP 7 +$a = null; +$b = 'Ditampilkan'; +echo $a ?? 'a belum di-set'; // menampilkan 'a belum di-set' +echo $b ?? 'b belum di-set'; // menampilkan 'Ditampilkan' + + +$x = 0; +if ($x === '0') { + print 'Tidak ditampilkan'; +} elseif($x == '1') { + print 'Tidak ditampilkan'; +} else { + print 'Tampil'; +} + + +// Alternatif sintaks untuk kebutuhan templat: +?> + + +Ini ditampilkan jika pengujian benar. + +Selain tersebut ini yang akan ditampilkan. + + + 2, 'mobil' => 4]; + +// Perulangan "foreach" dapat melakukan iterasi pada larik (array) +foreach ($roda as $jumlah_roda) { + echo $jumlah_roda; +} // Menampilkan "24" + +echo "\n"; + +// Iterasi dapat dilakukan terhadap "key" (kunci) dan "value" (nilai) +foreach ($roda as $mesin => $jumlah_roda) { + echo "$mesin memiliki $jumlah_roda buah roda"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Menghentikan proses perulangan + } + echo $i++; +} // Menampilkan "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Melewati tahapan iterasi saat ini + } + echo $i; +} // Menampilkan "0124" + + +/******************************** + * Fungsi + */ + +// Fungsi didefinisikan dengan "function": +function fungsi_saya () { + return 'Halo'; +} + +echo fungsi_saya(); // => "Halo" + +// Nama fungsi yang baik dan benar diawali dengan sebuah huruf atau garis-bawah, diikuti oleh +// beberapa huruf, angka, atau garis-bawah. + +function jumlah ($x, $y = 1) { // $y merupakan opsional, jika tidak ditentukan akan bernilai 1 + $hasil = $x + $y; + return $hasil; +} + +echo jumlah(4); // => 5 +echo jumlah(4, 2); // => 6 + +// $hasil tidak dapat diakses dari luar fungsi +// print $hasil; // Akan menghasilkan sebuah "warning". + +// Sejak PHP 5.3 fungsi dapat dideklarasikan menjadi tanpa-nama (anonymous); +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Fungsi dapat mengembalikan fungsi juga +function bar ($x, $y) { + // Gunakan "use" untuk mengakses variabel diluar fungsi + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Menampilkan "A - B - C" + +// Fungsi uang memiliki nama dapat dipanggil berdasarkan string +$nama_fungsi = 'jumlah'; +echo $nama_fungsi(1, 2); // => 3 +// Bermanfaat untuk menentukan fungsi mana yang akan dipanggil secara dinamis. +// Atau, dapat juga menggunakan fungsi call_user_func(callable $callback [, $parameter [, ... ]]); + +// Akses semua parameter yang dikirim ke sebuah fungsi +function parameter() { + $jumlah_param = func_num_args(); + if( $jumlah_param > 0 ) { + echo func_get_arg(0) . ' | '; + } + $daftar_param = func_get_args(); + foreach( $daftar_param as $kunci => $param ) { + echo $kunci . ' - ' . $param . ' | '; + } +} + +parameter('Halo', 'Dunia'); // Halo | 0 - Halo | 1 - Dunia | + +// Sejak PHP 5.6, mendapatkan jumlah variabel yang ada pada parameter +function variabel($kata, ...$daftar) { + echo $kata . " || "; + foreach ($daftar as $item) { + echo $item . ' | '; + } +} + +variable("Pemisah", "Halo", "Dunia") // Pemisah || Halo | Dunia | + +/******************************** + * Penyertaan ("include") + */ + +PropertiInstansi = $PropertiInstansi; + } + + // Method dideklarasikan sebagai fungsi didalam kelas + public function methodSaya() + { + print 'KelasSaya'; + } + + // Perintah "final" membuat sebuah fungsi tidak dapat di-override oleh kelas turunannya + final function tidakDapatDiOverride() + { + } + +/* + * Deklarasi properti atau method pada kelas sebagai statis membuat properti atau method tersebut + * dapat diakses tanpa melakukan instansiasi kelas. Properti statis tidak dapat diakses melalui + * objek kelas yang hasil instansiasi, sedangkan method statis bisa. + */ + + public static function methodStatisSaya() + { + print 'Saya adalah statis'; + } +} + +// Konstan pada kelas dapat diakses secara statis +echo KelasSaya::NILAI_KONSTAN; // Menampilkan 'nilai' + +echo KelasSaya::$nilaiStatis; // Menampilkan 'statis' +KelasSaya::methodStatisSaya(); // Menampilkan 'Saya adalah statis' + +// Instansi kelas menggunakan perintah "new" +$kelas_saya = new KelasSaya('Sebuah properti instansiasi'); +// Tanda kurung adalah opsional jika tidak ingin menggunakan argumen. + +// Akses anggota kelas menggunakan -> +echo $kelas_saya->properti; // => "publik" +echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" +$kelas_saya->methodSaya(); // => "KelasSaya" + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + + Date: Tue, 2 Feb 2016 07:34:19 +0700 Subject: [php/id-id] updates for ID translation --- id-id/php-id.html.markdown | 239 ++++++++++++++++++++++----------------------- 1 file changed, 118 insertions(+), 121 deletions(-) diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown index 491a190e..34d6e5f5 100644 --- a/id-id/php-id.html.markdown +++ b/id-id/php-id.html.markdown @@ -567,34 +567,34 @@ echo $kelas_saya->properti; // => "publik" echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" $kelas_saya->methodSaya(); // => "KelasSaya" -// Extend classes using "extends" -class MyOtherClass extends MyClass +// Menurunkan kelas menggunakan kata kunci "extends" +class KelasSayaLainnya extends KelasSaya { - function printProtectedProperty() + function tampilkanPropertiTerlindungi() { - echo $this->prot; + echo $this->properti; } - // Override a method - function myMethod() + // "override" terhadap sebuah method + function methodSaya() { - parent::myMethod(); - print ' > MyOtherClass'; + parent::methodSaya(); + print ' > KelasSayaLainnya'; } } -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" +$kelas_saya_lainnya = new KelasSayaLainnya('Instansiasi properti'); +$kelas_saya_lainnya->tampilkanPropertiTerlindung(); // => Menampilkan "terlindungi" +$kelas_saya_lainnya->methodSaya(); // Menampilkan "KelasSaya > KelasSayaLainnya" -final class YouCannotExtendMe +final class SayaTidakBisaDiturunkan { } -// You can use "magic methods" to create getters and setters -class MyMapClass +// Gunakan method ajaib (magic method) untuk membuat fungsi "getters" dan "setters" +class PetaKelasSaya { - private $property; + private $properti; public function __get($key) { @@ -607,127 +607,125 @@ class MyMapClass } } -$x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +$x = new PetaKelasSaya(); +echo $x->properti; // akan memanggil method __get() +$x->properti = 'Sesuatu'; // akan memanggil method __set(); -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// Kelas dapat dijadikan abstrak (menggunakan kata kunci "abstract"), atau +// meng-implementasikan interfaces (menggunakan kata kunci "implements"). +// Sebuah interface dideklarasikan dengan perintah "interface". -interface InterfaceOne +interface InterfaceSatu { - public function doSomething(); + public function kerjakanSesuatu(); } -interface InterfaceTwo +interface InterfaceDua { - public function doSomethingElse(); + public function kerjakanYangLain(); } -// interfaces can be extended -interface InterfaceThree extends InterfaceTwo +// interface dapat diturunkan +interface InterfaceTiga extends InterfaceDua { - public function doAnotherContract(); + public function kerjakanYangBerbeda(); } -abstract class MyAbstractClass implements InterfaceOne +abstract class KelasAbstrakSaya implements InterfaceSatu { - public $x = 'doSomething'; + public $x = 'kerjakanSesuatu'; } -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +class KelasKongkritSaya extends KelasAbstrakSaya implements InterfaceTwo { - public function doSomething() + public function kerjakanSesuatu() { echo $x; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } - -// Classes can implement more than one interface -class SomeOtherClass implements InterfaceOne, InterfaceTwo +// Kelas dapat diimplementasikan pada banyak interface +class KelasLainnya implements InterfaceSatu, InterfaceDua { - public function doSomething() + public function kerjakanSesuatu() { - echo 'doSomething'; + echo 'kerjakanSesuatu'; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } /******************************** - * Traits + * Sifat (Traits) */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// Traits mulai tersedia sejak PHP 5.4.0 dan dideklarasikan menggunakan kata kunci "trait" -trait MyTrait +trait TraitSaya { - public function myTraitMethod() + public function methodTraitSaya() { - print 'I have MyTrait'; + print 'Saya menggunakan Trait'; } } -class MyTraitfulClass +class KelasTraitSaya { - use MyTrait; + use TraitSaya; } -$cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$kls = new KelasTraitSaya(); +$kls->methodTraitSaya(); // menampilkan "Saya menggunakan Trait" /******************************** * Namespaces */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// Bagian ini telah dibatasi, karena deklarasi "namespace" +// karena harus ditempatkan diawal dokumen. Date: Sat, 30 Jan 2016 12:07:45 +0700 Subject: [php/id-id] add ID translation --- id-id/php-id.html.markdown | 851 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 851 insertions(+) create mode 100644 id-id/php-id.html.markdown diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown new file mode 100644 index 00000000..491a190e --- /dev/null +++ b/id-id/php-id.html.markdown @@ -0,0 +1,851 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +filename: learnphp-id.php +translators: + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] +lang: id-id +--- + +Dokumen ini menjelaskan tentang PHP5 keatas. + +```php + +Halo Dunia, lagi! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (awalan 0 menandakan bilangan Oktal) +$int4 = 0x0F; // => 15 (awalan 0x menandakan bilangan Heksadesimal) +// Bilangan Biner Integer tersedia mulai dari PHP 5.4.0. +$int5 = 0b11111111; // 255 (awalan 0b menandakan bilangan Biner) + +// Nilai Floats (dikenal juga sebagai Doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Menghapus variable +unset($int1); + +// Aritmatika +$jumlah = 1 + 1; // 2 +$selisih = 2 - 1; // 1 +$perkalian = 2 * 2; // 4 +$pembagian = 2 / 1; // 2 + +// Aritmatika singkat +$angka = 0; +$angka += 1; // Menjumlahkan $angka dengan 1 +echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah ditampilkan) +echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum ditampilkan) +$angka /= $float; // Membagi dan menyimpan hasil pembagian pada $angka; + +// String biasanya diawali dan ditutup dengan petik satu. +$sgl_quotes = '$String'; // => '$String' + +// Hindari menggunakan petik dua kecuali menyertakan variabel lain +$dbl_quotes = "Ini adalah $sgl_quotes."; // => 'Ini adalah $String.' + +// Karakter khusus hanya berlaku pada petik dua +$berfungsi = "Ini mengandung \t karakter tab."; +$tidak_berfungsi = 'Ini hanya mengandung garis miring dan huruf t: \t'; + +// Batasi variabel dengan kurung kurawal jika diperlukan +$uang = "Saya memiliki $${angka} di Bank."; + +// Sejak PHP 5.3, nowdocs dapat digunakan untuk tak-terinterpolasi banyak-baris +$nowdoc = <<<'END' +Banyak baris +string +END; + +// Heredocs akan melakukan interpolasi +$heredoc = << 1, 'Dua' => 2, 'Tiga' => 3); + +// Pada PHP 5.4 diperkenalkan cara penulisan (sintaks) baru +$asosiatif = ['Satu' => 1, 'Dua' => 2, 'Tiga' => 3]; + +echo $asosiatif['Satu']; // menampilkan 1 + +// Daftar literal secara tidak langsung ditentukan oleh kunci integer +$larik = ['Satu', 'Dua', 'Tiga']; +echo $larik[0]; // => "Satu" + +// Menambahkan sebuah elemen pada akhir larik +$larik[] = 'Empat'; +// atau +array_push($larik, 'Lima'); + +// Menghapus elemen dari larik +unset($larik[3]); + +/******************************** + * Keluaran + */ + +echo('Halo Dunia!'); +// Menampilkan Halo Dunia! ke "stdout". +// "stdout" adalah sebuah halaman web ketika dijalankan dalam peramban (browser). + +print('Halo Dunia!'); // Sama seperti "echo" + +// "echo" dan "print" merupakan bahasa konstruksi, jadi tanda kurung dapat dihilangkan +echo 'Halo Dunia!'; +print 'Halo Dunia!'; + +$paragraf = 'paragraf'; + +echo 100; // Menampilkan variabel skalar secara langsung +echo $paragraf; // atau sebuat variabel + +// Jika PHP tag-singkat telah dikonfigurasi, atau versi PHP yang digunakan +// adalah 5.4.0 keatas, dapat digunakan sintaks "echo" singkat + +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Menampilkan tipe dan nilai dari variabel ke "stdout" +var_dump($z); // prints int(0) + +// Menampilkan variabel ke "stdout" dalam format yang mudah dibaca +print_r($larik); // menampilkan: Array ( [0] => Satu [1] => Dua [2] => Tiga ) + +/******************************** + * Logika + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// menegaskan lemparan sebuah peringatan jika pernyataan tidak benar + +// Perbandingan berikut akan selalu benar, meskipun memiliki tipe yang berbeda. +assert($a == $b); // kesamaan +assert($c != $a); // ketidak-samaan +assert($c <> $a); // versi lain dari ketidak-samaan +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Dibawah ini hanya akan bernilai benar jika nilainya memiliki tipe yang sama. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Operator 'Spaceship' (sejak PHP 7) +// Mengembalikan 0 jika nilai pada kedua sisi adalah sama +// Mengembalikan 1 jika nilai pada sisi kiri lebih besar +// Mengembalikan -1 jika nilai pada sisi kanan lebih besar + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 karena keduanya sama +echo $a <=> $b; // -1 karena $a < $b +echo $b <=> $a; // 1 karena $b > $a + +// Variabel dapat dikonversi menjadi tipe lain, sesuai penggunaannya. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (string dipaksa menjadi integer) + +$string = 'satu'; +echo $string + $string; // => 0 +// Menghasilkan 0 karena operator (+) tidak dapat memaksa string 'satu' menjadi sebuah integer + +// Perubahan tipe dapat dimanfaatkan untuk diperlakukan sebagai tipe lainnya + +$boolean = (boolean) 1; // => true + +$nol = 0; +$boolean = (boolean) $nol; // => false + +// Terdapat juga fungsi khusus untuk melakukan perubahan terhadap beberapa tipe +$integer = 5; +$string = strval($integer); + +$var = null; // Nilai Null + + +/******************************** + * Struktur Kontrol + */ + +if (true) { + print 'Saya tampil'; +} + +if (false) { + print 'Saya tidak tampil'; +} else { + print 'Saya tampil'; +} + +if (false) { + print 'Tidak tampil'; +} elseif(true) { + print 'Tampil'; +} + +// operator ternary +print (false ? 'Tidak tampil' : 'Tampil'); + +// cara pintas operator ternary mulai dirilis sejak PHP 5.3 +// persamaan dari "$x ? $x : 'Kerjakan'" +$x = false; +print($x ?: 'Kerjakan'); + +// operator null coalesce sejak PHP 7 +$a = null; +$b = 'Ditampilkan'; +echo $a ?? 'a belum di-set'; // menampilkan 'a belum di-set' +echo $b ?? 'b belum di-set'; // menampilkan 'Ditampilkan' + + +$x = 0; +if ($x === '0') { + print 'Tidak ditampilkan'; +} elseif($x == '1') { + print 'Tidak ditampilkan'; +} else { + print 'Tampil'; +} + + +// Alternatif sintaks untuk kebutuhan templat: +?> + + +Ini ditampilkan jika pengujian benar. + +Selain tersebut ini yang akan ditampilkan. + + + 2, 'mobil' => 4]; + +// Perulangan "foreach" dapat melakukan iterasi pada larik (array) +foreach ($roda as $jumlah_roda) { + echo $jumlah_roda; +} // Menampilkan "24" + +echo "\n"; + +// Iterasi dapat dilakukan terhadap "key" (kunci) dan "value" (nilai) +foreach ($roda as $mesin => $jumlah_roda) { + echo "$mesin memiliki $jumlah_roda buah roda"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Menghentikan proses perulangan + } + echo $i++; +} // Menampilkan "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Melewati tahapan iterasi saat ini + } + echo $i; +} // Menampilkan "0124" + + +/******************************** + * Fungsi + */ + +// Fungsi didefinisikan dengan "function": +function fungsi_saya () { + return 'Halo'; +} + +echo fungsi_saya(); // => "Halo" + +// Nama fungsi yang baik dan benar diawali dengan sebuah huruf atau garis-bawah, diikuti oleh +// beberapa huruf, angka, atau garis-bawah. + +function jumlah ($x, $y = 1) { // $y merupakan opsional, jika tidak ditentukan akan bernilai 1 + $hasil = $x + $y; + return $hasil; +} + +echo jumlah(4); // => 5 +echo jumlah(4, 2); // => 6 + +// $hasil tidak dapat diakses dari luar fungsi +// print $hasil; // Akan menghasilkan sebuah "warning". + +// Sejak PHP 5.3 fungsi dapat dideklarasikan menjadi tanpa-nama (anonymous); +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Fungsi dapat mengembalikan fungsi juga +function bar ($x, $y) { + // Gunakan "use" untuk mengakses variabel diluar fungsi + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Menampilkan "A - B - C" + +// Fungsi uang memiliki nama dapat dipanggil berdasarkan string +$nama_fungsi = 'jumlah'; +echo $nama_fungsi(1, 2); // => 3 +// Bermanfaat untuk menentukan fungsi mana yang akan dipanggil secara dinamis. +// Atau, dapat juga menggunakan fungsi call_user_func(callable $callback [, $parameter [, ... ]]); + +// Akses semua parameter yang dikirim ke sebuah fungsi +function parameter() { + $jumlah_param = func_num_args(); + if( $jumlah_param > 0 ) { + echo func_get_arg(0) . ' | '; + } + $daftar_param = func_get_args(); + foreach( $daftar_param as $kunci => $param ) { + echo $kunci . ' - ' . $param . ' | '; + } +} + +parameter('Halo', 'Dunia'); // Halo | 0 - Halo | 1 - Dunia | + +// Sejak PHP 5.6, mendapatkan jumlah variabel yang ada pada parameter +function variabel($kata, ...$daftar) { + echo $kata . " || "; + foreach ($daftar as $item) { + echo $item . ' | '; + } +} + +variable("Pemisah", "Halo", "Dunia") // Pemisah || Halo | Dunia | + +/******************************** + * Penyertaan ("include") + */ + +PropertiInstansi = $PropertiInstansi; + } + + // Method dideklarasikan sebagai fungsi didalam kelas + public function methodSaya() + { + print 'KelasSaya'; + } + + // Perintah "final" membuat sebuah fungsi tidak dapat di-override oleh kelas turunannya + final function tidakDapatDiOverride() + { + } + +/* + * Deklarasi properti atau method pada kelas sebagai statis membuat properti atau method tersebut + * dapat diakses tanpa melakukan instansiasi kelas. Properti statis tidak dapat diakses melalui + * objek kelas yang hasil instansiasi, sedangkan method statis bisa. + */ + + public static function methodStatisSaya() + { + print 'Saya adalah statis'; + } +} + +// Konstan pada kelas dapat diakses secara statis +echo KelasSaya::NILAI_KONSTAN; // Menampilkan 'nilai' + +echo KelasSaya::$nilaiStatis; // Menampilkan 'statis' +KelasSaya::methodStatisSaya(); // Menampilkan 'Saya adalah statis' + +// Instansi kelas menggunakan perintah "new" +$kelas_saya = new KelasSaya('Sebuah properti instansiasi'); +// Tanda kurung adalah opsional jika tidak ingin menggunakan argumen. + +// Akses anggota kelas menggunakan -> +echo $kelas_saya->properti; // => "publik" +echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" +$kelas_saya->methodSaya(); // => "KelasSaya" + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + + Date: Tue, 2 Feb 2016 07:34:19 +0700 Subject: [php/id-id] updates for ID translation --- id-id/php-id.html.markdown | 239 ++++++++++++++++++++++----------------------- 1 file changed, 118 insertions(+), 121 deletions(-) diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown index 491a190e..34d6e5f5 100644 --- a/id-id/php-id.html.markdown +++ b/id-id/php-id.html.markdown @@ -567,34 +567,34 @@ echo $kelas_saya->properti; // => "publik" echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" $kelas_saya->methodSaya(); // => "KelasSaya" -// Extend classes using "extends" -class MyOtherClass extends MyClass +// Menurunkan kelas menggunakan kata kunci "extends" +class KelasSayaLainnya extends KelasSaya { - function printProtectedProperty() + function tampilkanPropertiTerlindungi() { - echo $this->prot; + echo $this->properti; } - // Override a method - function myMethod() + // "override" terhadap sebuah method + function methodSaya() { - parent::myMethod(); - print ' > MyOtherClass'; + parent::methodSaya(); + print ' > KelasSayaLainnya'; } } -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" +$kelas_saya_lainnya = new KelasSayaLainnya('Instansiasi properti'); +$kelas_saya_lainnya->tampilkanPropertiTerlindung(); // => Menampilkan "terlindungi" +$kelas_saya_lainnya->methodSaya(); // Menampilkan "KelasSaya > KelasSayaLainnya" -final class YouCannotExtendMe +final class SayaTidakBisaDiturunkan { } -// You can use "magic methods" to create getters and setters -class MyMapClass +// Gunakan method ajaib (magic method) untuk membuat fungsi "getters" dan "setters" +class PetaKelasSaya { - private $property; + private $properti; public function __get($key) { @@ -607,127 +607,125 @@ class MyMapClass } } -$x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +$x = new PetaKelasSaya(); +echo $x->properti; // akan memanggil method __get() +$x->properti = 'Sesuatu'; // akan memanggil method __set(); -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// Kelas dapat dijadikan abstrak (menggunakan kata kunci "abstract"), atau +// meng-implementasikan interfaces (menggunakan kata kunci "implements"). +// Sebuah interface dideklarasikan dengan perintah "interface". -interface InterfaceOne +interface InterfaceSatu { - public function doSomething(); + public function kerjakanSesuatu(); } -interface InterfaceTwo +interface InterfaceDua { - public function doSomethingElse(); + public function kerjakanYangLain(); } -// interfaces can be extended -interface InterfaceThree extends InterfaceTwo +// interface dapat diturunkan +interface InterfaceTiga extends InterfaceDua { - public function doAnotherContract(); + public function kerjakanYangBerbeda(); } -abstract class MyAbstractClass implements InterfaceOne +abstract class KelasAbstrakSaya implements InterfaceSatu { - public $x = 'doSomething'; + public $x = 'kerjakanSesuatu'; } -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +class KelasKongkritSaya extends KelasAbstrakSaya implements InterfaceTwo { - public function doSomething() + public function kerjakanSesuatu() { echo $x; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } - -// Classes can implement more than one interface -class SomeOtherClass implements InterfaceOne, InterfaceTwo +// Kelas dapat diimplementasikan pada banyak interface +class KelasLainnya implements InterfaceSatu, InterfaceDua { - public function doSomething() + public function kerjakanSesuatu() { - echo 'doSomething'; + echo 'kerjakanSesuatu'; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } /******************************** - * Traits + * Sifat (Traits) */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// Traits mulai tersedia sejak PHP 5.4.0 dan dideklarasikan menggunakan kata kunci "trait" -trait MyTrait +trait TraitSaya { - public function myTraitMethod() + public function methodTraitSaya() { - print 'I have MyTrait'; + print 'Saya menggunakan Trait'; } } -class MyTraitfulClass +class KelasTraitSaya { - use MyTrait; + use TraitSaya; } -$cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$kls = new KelasTraitSaya(); +$kls->methodTraitSaya(); // menampilkan "Saya menggunakan Trait" /******************************** * Namespaces */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// Bagian ini telah dibatasi, karena deklarasi "namespace" +// karena harus ditempatkan diawal dokumen. Date: Sat, 6 Feb 2016 00:00:12 +0530 Subject: Removed ! --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index e82c1c36..745605ed 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -48,7 +48,7 @@ println(10) // Printing, without forcing a new line on next print print("Hello world") print(10) -// Hello world!10 +// Hello world10 // Declaring values is done using either var or val. // val declarations are immutable, whereas vars are mutable. Immutability is -- cgit v1.2.3 From 2b2951d0e0ae4de8f212ff4f9ee8c77db8e9458d Mon Sep 17 00:00:00 2001 From: oscarb-se Date: Mon, 8 Feb 2016 02:54:41 +0100 Subject: Fixed statement about many classes in one file Fixed statement on line 441 to say that it is _not_ good practice to keep many classes in the same file. --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 74140120..073135c9 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -438,7 +438,7 @@ public class LearnJava { // You can include other, non-public outer-level classes in a .java file, -// but it is good practice. Instead split classes into separate files. +// but it is not good practice. Instead split classes into separate files. // Class Declaration Syntax: -- cgit v1.2.3 From 39a6ab4d7a42bc76f14cd45882275f6754e4840d Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Fri, 12 Feb 2016 08:12:51 -0700 Subject: fix a typo --- zfs.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zfs.html.markdown b/zfs.html.markdown index 74487e35..de8c81f0 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -9,7 +9,7 @@ filename: LearnZfs.txt [ZFS](http://open-zfs.org/wiki/Main_Page) is a rethinking of the storage stack, combining traditional file systems as well as volume -managers into one cohesive tool. ZFS has some specific teminology that sets it appart from +managers into one cohesive tool. ZFS has some specific terminology that sets it appart from more traditional storage systems, however it has a great set of features with a focus on usability for systems administrators. -- cgit v1.2.3 From 85b4e2084e625ebbdfe8899b85bc207e9e5184f6 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Fri, 12 Feb 2016 08:15:27 -0700 Subject: fix a few more typos --- zfs.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/zfs.html.markdown b/zfs.html.markdown index de8c81f0..39ff84cd 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -9,7 +9,7 @@ filename: LearnZfs.txt [ZFS](http://open-zfs.org/wiki/Main_Page) is a rethinking of the storage stack, combining traditional file systems as well as volume -managers into one cohesive tool. ZFS has some specific terminology that sets it appart from +managers into one cohesive tool. ZFS has some specific terminology that sets it apart from more traditional storage systems, however it has a great set of features with a focus on usability for systems administrators. @@ -23,7 +23,7 @@ types of VDEV's that offer various advantages, including redundancy and speed. VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. -Types of VDEV's +Types of VDEV's * stripe (a single disk, no redundancy) * mirror (n-way mirrors supported) * raidz @@ -39,13 +39,13 @@ increase your IOPS. ### Storage Pools ZFS uses Storage Pools as an abstraction over the lower level storage provider (VDEV), allow -you to separate the user visable file system from the physcal layout. +you to separate the user visible file system from the physical layout. ### ZFS Dataset -ZFS datasets are analagous to traditional filesystems but with many more features. They +ZFS datasets are analogous to traditional filesystems but with many more features. They provide many of ZFS's advantages. Datasets support [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) -snapshots, quota's, compression and deduplication. +snapshots, quota's, compression and de-duplication. ### Limits @@ -68,7 +68,7 @@ Actions: List zpools ```bash -# Create a raidz zpool +# Create a raidz zpool $ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 # List ZPools @@ -347,7 +347,7 @@ $ zfs promote tank/home/sarlalian_new ### Putting it all together -This following a script utilizing FreeBSD, jails and ZFS to automate +This following a script utilizing FreeBSD, jails and ZFS to automate provisioning a clean copy of a mysql staging database from a live replication slave. @@ -384,7 +384,7 @@ mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local echo "==== Starting the staging db server ====" jail -c staging -echo "==== Make sthe staging database not pull from the master ====" +echo "==== Makes the staging database not pull from the master ====" echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging ``` -- cgit v1.2.3 From 5aa692f5f3bbfa7b79224748dcfd8ca5fba7a8bc Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 12 Feb 2016 11:42:25 -0800 Subject: brainfuck->bf --- bf.html.markdown | 81 ++++++++++++++++++++++++++++++++++ brainfuck.html.markdown | 81 ---------------------------------- es-es/bf-es.html.markdown | 89 ++++++++++++++++++++++++++++++++++++++ es-es/brainfuck-es.html.markdown | 89 -------------------------------------- fa-ir/bf-fa.html.markdown | 81 ++++++++++++++++++++++++++++++++++ fa-ir/brainfuck-fa.html.markdown | 81 ---------------------------------- fr-fr/bf-fr.html.markdown | 87 +++++++++++++++++++++++++++++++++++++ fr-fr/brainfuck-fr.html.markdown | 87 ------------------------------------- it-it/bf-it.html.markdown | 92 +++++++++++++++++++++++++++++++++++++++ it-it/brainfuck-it.html.markdown | 92 --------------------------------------- ko-kr/bf-kr.html.markdown | 84 ++++++++++++++++++++++++++++++++++++ ko-kr/brainfuck-kr.html.markdown | 84 ------------------------------------ nl-nl/bf.html.markdown | 86 +++++++++++++++++++++++++++++++++++++ nl-nl/brainfuck-nl.html.markdown | 86 ------------------------------------- pl-pl/bf-pl.html.markdown | 93 ++++++++++++++++++++++++++++++++++++++++ pl-pl/brainfuck-pl.html.markdown | 93 ---------------------------------------- pt-br/bf.html.markdown | 85 ++++++++++++++++++++++++++++++++++++ pt-br/brainfuck-pt.html.markdown | 85 ------------------------------------ pt-pt/bf.html.markdown | 84 ++++++++++++++++++++++++++++++++++++ pt-pt/brainfuck-pt.html.markdown | 84 ------------------------------------ ru-ru/bf.html.markdown | 85 ++++++++++++++++++++++++++++++++++++ ru-ru/brainfuck-ru.html.markdown | 85 ------------------------------------ tr-tr/bf-tr.html.markdown | 87 +++++++++++++++++++++++++++++++++++++ tr-tr/brainfuck-tr.html.markdown | 87 ------------------------------------- zh-cn/bf-cn.html.markdown | 70 ++++++++++++++++++++++++++++++ zh-cn/brainfuck-cn.html.markdown | 70 ------------------------------ 26 files changed, 1104 insertions(+), 1104 deletions(-) create mode 100644 bf.html.markdown delete mode 100644 brainfuck.html.markdown create mode 100644 es-es/bf-es.html.markdown delete mode 100644 es-es/brainfuck-es.html.markdown create mode 100644 fa-ir/bf-fa.html.markdown delete mode 100644 fa-ir/brainfuck-fa.html.markdown create mode 100644 fr-fr/bf-fr.html.markdown delete mode 100644 fr-fr/brainfuck-fr.html.markdown create mode 100644 it-it/bf-it.html.markdown delete mode 100644 it-it/brainfuck-it.html.markdown create mode 100644 ko-kr/bf-kr.html.markdown delete mode 100644 ko-kr/brainfuck-kr.html.markdown create mode 100644 nl-nl/bf.html.markdown delete mode 100644 nl-nl/brainfuck-nl.html.markdown create mode 100644 pl-pl/bf-pl.html.markdown delete mode 100644 pl-pl/brainfuck-pl.html.markdown create mode 100644 pt-br/bf.html.markdown delete mode 100644 pt-br/brainfuck-pt.html.markdown create mode 100644 pt-pt/bf.html.markdown delete mode 100644 pt-pt/brainfuck-pt.html.markdown create mode 100644 ru-ru/bf.html.markdown delete mode 100644 ru-ru/brainfuck-ru.html.markdown create mode 100644 tr-tr/bf-tr.html.markdown delete mode 100644 tr-tr/brainfuck-tr.html.markdown create mode 100644 zh-cn/bf-cn.html.markdown delete mode 100644 zh-cn/brainfuck-cn.html.markdown diff --git a/bf.html.markdown b/bf.html.markdown new file mode 100644 index 00000000..c8bbee61 --- /dev/null +++ b/bf.html.markdown @@ -0,0 +1,81 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +--- + +Brainfuck (not capitalized except at the start of a sentence) is an extremely +minimal Turing-complete programming language with just 8 commands. + +You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Any character not "><+-.,[]" (excluding quotation marks) is ignored. + +Brainfuck is represented by an array with 30,000 cells initialized to zero +and a data pointer pointing at the current cell. + +There are eight commands: ++ : Increments the value at the current cell by one. +- : Decrements the value at the current cell by one. +> : Moves the data pointer to the next cell (cell on the right). +< : Moves the data pointer to the previous cell (cell on the left). +. : Prints the ASCII value at the current cell (i.e. 65 = 'A'). +, : Reads a single input character into the current cell. +[ : If the value at the current cell is zero, skips to the corresponding ] . + Otherwise, move to the next instruction. +] : If the value at the current cell is zero, move to the next instruction. + Otherwise, move backwards in the instructions to the corresponding [ . + +[ and ] form a while loop. Obviously, they must be balanced. + +Let's look at some basic brainfuck programs. + +++++++ [ > ++++++++++ < - ] > +++++ . + +This program prints out the letter 'A'. First, it increments cell #1 to 6. +Cell #1 will be used for looping. Then, it enters the loop ([) and moves +to cell #2. It increments cell #2 10 times, moves back to cell #1, and +decrements cell #1. This loop happens 6 times (it takes 6 decrements for +cell #1 to reach 0, at which point it skips to the corresponding ] and +continues on). + +At this point, we're on cell #1, which has a value of 0, while cell #2 has a +value of 60. We move on cell #2, increment 5 times, for a value of 65, and then +print cell #2's value. 65 is 'A' in ASCII, so 'A' is printed to the terminal. + + +, [ > + < - ] > . + +This program reads a character from the user input and copies the character into +cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, +move back to cell #1, and decrement the value at cell #1. This continues on +until cell #1 is 0, and cell #2 holds cell #1's old value. Because we're on +cell #1 at the end of the loop, move to cell #2, and then print out the value +in ASCII. + +Also keep in mind that the spaces are purely for readability purposes. You +could just as easily write it as: + +,[>+<-]>. + +Try and figure out what this program does: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +This program takes two numbers for input, and multiplies them. + +The gist is it first reads in two inputs. Then it starts the outer loop, +conditioned on cell #1. Then it moves to cell #2, and starts the inner +loop conditioned on cell #2, incrementing cell #3. However, there comes a +problem: At the end of the inner loop, cell #2 is zero. In that case, +inner loop won't work anymore since next time. To solve this problem, +we also increment cell #4, and then recopy cell #4 into cell #2. +Then cell #3 is the result. +``` + +And that's brainfuck. Not that hard, eh? For fun, you can write your own +brainfuck programs, or you can write a brainfuck interpreter in another +language. The interpreter is fairly simple to implement, but if you're a +masochist, try writing a brainfuck interpreter… in brainfuck. diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown deleted file mode 100644 index a76169c8..00000000 --- a/brainfuck.html.markdown +++ /dev/null @@ -1,81 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] ---- - -Brainfuck (not capitalized except at the start of a sentence) is an extremely -minimal Turing-complete programming language with just 8 commands. - -You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - -``` -Any character not "><+-.,[]" (excluding quotation marks) is ignored. - -Brainfuck is represented by an array with 30,000 cells initialized to zero -and a data pointer pointing at the current cell. - -There are eight commands: -+ : Increments the value at the current cell by one. -- : Decrements the value at the current cell by one. -> : Moves the data pointer to the next cell (cell on the right). -< : Moves the data pointer to the previous cell (cell on the left). -. : Prints the ASCII value at the current cell (i.e. 65 = 'A'). -, : Reads a single input character into the current cell. -[ : If the value at the current cell is zero, skips to the corresponding ] . - Otherwise, move to the next instruction. -] : If the value at the current cell is zero, move to the next instruction. - Otherwise, move backwards in the instructions to the corresponding [ . - -[ and ] form a while loop. Obviously, they must be balanced. - -Let's look at some basic brainfuck programs. - -++++++ [ > ++++++++++ < - ] > +++++ . - -This program prints out the letter 'A'. First, it increments cell #1 to 6. -Cell #1 will be used for looping. Then, it enters the loop ([) and moves -to cell #2. It increments cell #2 10 times, moves back to cell #1, and -decrements cell #1. This loop happens 6 times (it takes 6 decrements for -cell #1 to reach 0, at which point it skips to the corresponding ] and -continues on). - -At this point, we're on cell #1, which has a value of 0, while cell #2 has a -value of 60. We move on cell #2, increment 5 times, for a value of 65, and then -print cell #2's value. 65 is 'A' in ASCII, so 'A' is printed to the terminal. - - -, [ > + < - ] > . - -This program reads a character from the user input and copies the character into -cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, -move back to cell #1, and decrement the value at cell #1. This continues on -until cell #1 is 0, and cell #2 holds cell #1's old value. Because we're on -cell #1 at the end of the loop, move to cell #2, and then print out the value -in ASCII. - -Also keep in mind that the spaces are purely for readability purposes. You -could just as easily write it as: - -,[>+<-]>. - -Try and figure out what this program does: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -This program takes two numbers for input, and multiplies them. - -The gist is it first reads in two inputs. Then it starts the outer loop, -conditioned on cell #1. Then it moves to cell #2, and starts the inner -loop conditioned on cell #2, incrementing cell #3. However, there comes a -problem: At the end of the inner loop, cell #2 is zero. In that case, -inner loop won't work anymore since next time. To solve this problem, -we also increment cell #4, and then recopy cell #4 into cell #2. -Then cell #3 is the result. -``` - -And that's brainfuck. Not that hard, eh? For fun, you can write your own -brainfuck programs, or you can write a brainfuck interpreter in another -language. The interpreter is fairly simple to implement, but if you're a -masochist, try writing a brainfuck interpreter… in brainfuck. diff --git a/es-es/bf-es.html.markdown b/es-es/bf-es.html.markdown new file mode 100644 index 00000000..c93b8c3a --- /dev/null +++ b/es-es/bf-es.html.markdown @@ -0,0 +1,89 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Daniel Zendejas", "https://github.com/DanielZendejas"] +lang: es-es +--- + +Brainfuck (con mayúscula sólo al inicio de una oración) es un +lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos. + +Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + + +``` + +Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas) +será ignorado. + +Brainfuck es representado por un arreglo de 30,000 celdas inicializadas +en cero y un puntero apuntando la celda actual. + +Existen ocho comandos: + ++ : Incrementa 1 al valor de la celda actual. +- : Decrementa 1 al valor de la celda actual. +> : Mueve el apuntador a la siguiente celda. (a la derecha) +< : Mueve el apuntador a la celda anterior. (a la izquierda) +. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A') +, : Lee un caracter como input y lo escribe en la celda actual. +[ : Si el valor en la celda actual es cero mueve el apuntador + hasta el primer ']' que encuentre. Si no es cero sigue a la + siguiente instrucción. +] : Si el valor en la celda actual es cero, entonces sigue con + la siguiente instrucción. Si no entonces mueve el apuntador + hacia atrás hasta encontrar el primer '['. + +[ y ] forman un while. Obviamente, deben estar balanceados. + +Estos son algunos ejemplos de programas escritos con brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime la letra 'A'. Primero, incrementa la celda #1 a +6. La celda #1 será usada para hacer los ciclos. Después entra al ciclo +([) y se mueve a la celda #2 (>). Después incrementa la celda #2 10 veces, +y se regresa a la celda #1 (<), para después decrementarla en 1 (-). +Este ciclo ocurre 6 veces (le toma 6 decrementos a la celda #1 volverse 0), +cuando esto pasa se salta a (]) y continúa. + +En este punto estamos en la celda #1, que tiene un valor de 0, mientras +que la celda #2 tiene un valor de 60. Nos movemos a la celda #2 (>), +la incrementamos 5 veces para tener un valor de 65 y luego imprimimos +el valor de la celda #2 (.). 65 es 'A' en ASCII así que la letra 'A' +se imprime. + +, [ > + < - ] > . + +Este programa lee un caracter del input y lo copia en la celda #2 (,). +Después empieza un ciclo. Nos movemos a la celda #2 (>) e incrementamos su +valor (+). Regresamos a la celda #1 y decrementamos su valor en 1 (-). +Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un +cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre +terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.). + +Ten en cuenta que los espacios son sólo para fines de legibilidad. +Es lo mismo escribir el ejemplo de arriba que esto: +,[>+<-]>. + +Intenta descrifrar lo que hace este programa: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa toma dos números como input y los multiplica. + +Primero recibe dos números del usuario. Luego empieza el ciclo externo, +condicionado en la celda #1. Luego se mueve a la celda #2, comenzando +el ciclo interno condicionado en la celda #2 incrementando la celda #3. +Sin embargo viene un problema: El ciclo interior no funcionará nuevamente +hasta la próxima vez. Para resolver este problema también incrementamos la +celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene +el resultado. +``` +Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir +tu propio intérprete de brainfuck o tu propio programa en brainfuck. El +intérprete es relativamente sencillo de hacer, pero si eres masoquista, +puedes intentar construir tu propio intérprete de brainfuck... en brainfuck. diff --git a/es-es/brainfuck-es.html.markdown b/es-es/brainfuck-es.html.markdown deleted file mode 100644 index 550511da..00000000 --- a/es-es/brainfuck-es.html.markdown +++ /dev/null @@ -1,89 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Daniel Zendejas", "https://github.com/DanielZendejas"] -lang: es-es ---- - -Brainfuck (con mayúscula sólo al inicio de una oración) es un -lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos. - -Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - - -``` - -Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas) -será ignorado. - -Brainfuck es representado por un arreglo de 30,000 celdas inicializadas -en cero y un puntero apuntando la celda actual. - -Existen ocho comandos: - -+ : Incrementa 1 al valor de la celda actual. -- : Decrementa 1 al valor de la celda actual. -> : Mueve el apuntador a la siguiente celda. (a la derecha) -< : Mueve el apuntador a la celda anterior. (a la izquierda) -. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A') -, : Lee un caracter como input y lo escribe en la celda actual. -[ : Si el valor en la celda actual es cero mueve el apuntador - hasta el primer ']' que encuentre. Si no es cero sigue a la - siguiente instrucción. -] : Si el valor en la celda actual es cero, entonces sigue con - la siguiente instrucción. Si no entonces mueve el apuntador - hacia atrás hasta encontrar el primer '['. - -[ y ] forman un while. Obviamente, deben estar balanceados. - -Estos son algunos ejemplos de programas escritos con brainfuck. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Este programa imprime la letra 'A'. Primero, incrementa la celda #1 a -6. La celda #1 será usada para hacer los ciclos. Después entra al ciclo -([) y se mueve a la celda #2 (>). Después incrementa la celda #2 10 veces, -y se regresa a la celda #1 (<), para después decrementarla en 1 (-). -Este ciclo ocurre 6 veces (le toma 6 decrementos a la celda #1 volverse 0), -cuando esto pasa se salta a (]) y continúa. - -En este punto estamos en la celda #1, que tiene un valor de 0, mientras -que la celda #2 tiene un valor de 60. Nos movemos a la celda #2 (>), -la incrementamos 5 veces para tener un valor de 65 y luego imprimimos -el valor de la celda #2 (.). 65 es 'A' en ASCII así que la letra 'A' -se imprime. - -, [ > + < - ] > . - -Este programa lee un caracter del input y lo copia en la celda #2 (,). -Después empieza un ciclo. Nos movemos a la celda #2 (>) e incrementamos su -valor (+). Regresamos a la celda #1 y decrementamos su valor en 1 (-). -Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un -cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre -terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.). - -Ten en cuenta que los espacios son sólo para fines de legibilidad. -Es lo mismo escribir el ejemplo de arriba que esto: -,[>+<-]>. - -Intenta descrifrar lo que hace este programa: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Este programa toma dos números como input y los multiplica. - -Primero recibe dos números del usuario. Luego empieza el ciclo externo, -condicionado en la celda #1. Luego se mueve a la celda #2, comenzando -el ciclo interno condicionado en la celda #2 incrementando la celda #3. -Sin embargo viene un problema: El ciclo interior no funcionará nuevamente -hasta la próxima vez. Para resolver este problema también incrementamos la -celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene -el resultado. -``` -Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir -tu propio intérprete de brainfuck o tu propio programa en brainfuck. El -intérprete es relativamente sencillo de hacer, pero si eres masoquista, -puedes intentar construir tu propio intérprete de brainfuck... en brainfuck. diff --git a/fa-ir/bf-fa.html.markdown b/fa-ir/bf-fa.html.markdown new file mode 100644 index 00000000..bc5d8dc4 --- /dev/null +++ b/fa-ir/bf-fa.html.markdown @@ -0,0 +1,81 @@ +--- +language: bf +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] +lang: fa-ir +--- + +

برین فاک زبان برنامه نویسی تورینگ کامل بی نهایت ساده ایست که دارای فقط هشت

+

دستور است.

+ +

هر کارکتری به جر کارکتر های زیر در این زبان در نظر گرفته نمیشود.

+ + +`>` `<` `+` `-` `.` `,` `[` `]` + +

برین فاک به صورت یک آرایه ی سی هزار خانه ای کار میکند که در ابتدا تمامی خانه های آن صفر هستند.

+

همچنین یک اشاره گر در این برنامه به خانه ی فعلی اشاره میکند.

+ +

در زیر هشت دستور این زبان شرح داده شده است:

+ +

`+` : یک عدد به خانه ی فعلی اضافه می کند. +

`-` : یک عدد از خانه ی فعلی کم می کند.

+

`>` : اشاره گر به خانه ی بعدی میرود -- به راست

+

`<` : اشاره گر به خانه ی قبلی میرود -- به چپ

+

`.` : کارکتر اسکی معادل مقدار خانه ی فعلی را چاپ میکند. -- به عنوان مثال 65 برای A

+

`,` : یک کارکتر را از ورودی خوانده و مقدار آن را در خانه ی فعلی زخیره میکند.

+

`[` : اگر مقدار خانه ی فعلی صفر باشد به محل بسته شدن کروشه جهش میکند. -- و از همه ی دستور های بین آن صرف نظر میشود.

+

در غیر این صورت به دستور بعدی میرود.

+

`]` : اگر مقدار خانه ی فعلی صفر باشد به خانه ی بعدی و در غیر این صورت به محل باز شدن کروشه جهش می کند. -- به عقب

+ +

دو علامت کروشه امکان ایجاد حلقه را فراهم میکنند.

+ +

در اینجا یک برنامه ی ساره برین فاک را مشاهده میکنید.

+ +``` +++++++ [ > ++++++++++ < - ] > +++++ . +``` + +

این برنامه کارکتر A را بر روی خروجی چاپ میکند.

+

در این برنامه خانه ی اول به عنوان متغیر حلقه و خانه ی دوم برای مقدار عددی A

+

ابتدا عدد شش در خانه ی اول ایجاد شده. سپس برنامه وارد یک حلقه میشود که در هر بار

+

تکرار آن اشاره گر به خانه ی دوم رفته و ده بار به خانه ی فعلی اضافه می کند.

+

-- و در انتهای حلقه به خانه ی اول برگشته تا حلقه کنترل شود

+

بعد از اتمام حلقه به خانه ی دوم میرود و پنج بار به این خانه اضافه کرده و سپس آنرا چاپ میکند.

+ +``` +, [ > + < - ] > . +``` + +

در این برنامه ابتدا یک کارکتر از ورودی خوانده می شود. سپس یک حلقه به تعداد بار مقدار

+

عددی کارکتر، یک عدد به خانه ی دوم اضافه می کند. با این کار در واقع برنامه مقدار ورودی را در خانه ی

+

دوم کپی می کند. و در نهایت آن را برروی خروجی چاپ می کند.

+ +

توجه داشته باشید که ردر بالا فواصل بین دستور ها فقط برای خوانایی بیشتر گذاشته شده اند.

+

در واقع برنامه بالا به شکل زیر صحیح می باشد.

+ +``` +,[>+<-]>. +``` + +

حال سعی کنید ببینید که برنامه ی زیر چه کاری انجام می دهد؟

+ +``` +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> +``` + +

این برنامه دو عدد را از ورودی خوانده و با هم ضرب می کند.

+ +

ابتدا دو عدد از ورودی خوانده می شوند. سپس حلقه ی بیرونی بر روی خانه شماره یک شروع میشود.

+

و درون آن حلقه ی دیگری بر روی خانه ی دوم شروع میشود که خانه ی 3 را زیاد میکند.

+

ولی مشکلی که در اینجا به وجود می آید اینست که در پایان حلقه ی دوم مقدار خانه ی 2 صفر شده

+

و مقدار اولیه ی آن از دست رفته است. برای حل این مشکل خانه ی شماره چهار هم زیاد میشود

+

و در پایان حلقه مقدار آن به خانه 2 کپی میشود.

+

در پایان خانه ی شماره 2 حاوی حاصلضرب خواهد بود.

+ +
+ +

و این همه ی برین فاک بود! خیلی ساده برای یادگیری ولی سنگین برای به کار بردن.

+

حال می توانید برای تفریح مشغول نوشتن برنامه ی های مختلف با آن شوید.

+

و یا یک اجرا کننده برین فاک را با یک زبان دیگر پیاده سازی کنید.

+

و یا اگر خیلی دوست داشتید یک اجرا کننده ی برین فاک با برین فاک بنویسید!!

diff --git a/fa-ir/brainfuck-fa.html.markdown b/fa-ir/brainfuck-fa.html.markdown deleted file mode 100644 index ef2bcba3..00000000 --- a/fa-ir/brainfuck-fa.html.markdown +++ /dev/null @@ -1,81 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Mohammad Valipour", "https://github.com/mvalipour"] -lang: fa-ir ---- - -

برین فاک زبان برنامه نویسی تورینگ کامل بی نهایت ساده ایست که دارای فقط هشت

-

دستور است.

- -

هر کارکتری به جر کارکتر های زیر در این زبان در نظر گرفته نمیشود.

- - -`>` `<` `+` `-` `.` `,` `[` `]` - -

برین فاک به صورت یک آرایه ی سی هزار خانه ای کار میکند که در ابتدا تمامی خانه های آن صفر هستند.

-

همچنین یک اشاره گر در این برنامه به خانه ی فعلی اشاره میکند.

- -

در زیر هشت دستور این زبان شرح داده شده است:

- -

`+` : یک عدد به خانه ی فعلی اضافه می کند. -

`-` : یک عدد از خانه ی فعلی کم می کند.

-

`>` : اشاره گر به خانه ی بعدی میرود -- به راست

-

`<` : اشاره گر به خانه ی قبلی میرود -- به چپ

-

`.` : کارکتر اسکی معادل مقدار خانه ی فعلی را چاپ میکند. -- به عنوان مثال 65 برای A

-

`,` : یک کارکتر را از ورودی خوانده و مقدار آن را در خانه ی فعلی زخیره میکند.

-

`[` : اگر مقدار خانه ی فعلی صفر باشد به محل بسته شدن کروشه جهش میکند. -- و از همه ی دستور های بین آن صرف نظر میشود.

-

در غیر این صورت به دستور بعدی میرود.

-

`]` : اگر مقدار خانه ی فعلی صفر باشد به خانه ی بعدی و در غیر این صورت به محل باز شدن کروشه جهش می کند. -- به عقب

- -

دو علامت کروشه امکان ایجاد حلقه را فراهم میکنند.

- -

در اینجا یک برنامه ی ساره برین فاک را مشاهده میکنید.

- -``` -++++++ [ > ++++++++++ < - ] > +++++ . -``` - -

این برنامه کارکتر A را بر روی خروجی چاپ میکند.

-

در این برنامه خانه ی اول به عنوان متغیر حلقه و خانه ی دوم برای مقدار عددی A

-

ابتدا عدد شش در خانه ی اول ایجاد شده. سپس برنامه وارد یک حلقه میشود که در هر بار

-

تکرار آن اشاره گر به خانه ی دوم رفته و ده بار به خانه ی فعلی اضافه می کند.

-

-- و در انتهای حلقه به خانه ی اول برگشته تا حلقه کنترل شود

-

بعد از اتمام حلقه به خانه ی دوم میرود و پنج بار به این خانه اضافه کرده و سپس آنرا چاپ میکند.

- -``` -, [ > + < - ] > . -``` - -

در این برنامه ابتدا یک کارکتر از ورودی خوانده می شود. سپس یک حلقه به تعداد بار مقدار

-

عددی کارکتر، یک عدد به خانه ی دوم اضافه می کند. با این کار در واقع برنامه مقدار ورودی را در خانه ی

-

دوم کپی می کند. و در نهایت آن را برروی خروجی چاپ می کند.

- -

توجه داشته باشید که ردر بالا فواصل بین دستور ها فقط برای خوانایی بیشتر گذاشته شده اند.

-

در واقع برنامه بالا به شکل زیر صحیح می باشد.

- -``` -,[>+<-]>. -``` - -

حال سعی کنید ببینید که برنامه ی زیر چه کاری انجام می دهد؟

- -``` -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> -``` - -

این برنامه دو عدد را از ورودی خوانده و با هم ضرب می کند.

- -

ابتدا دو عدد از ورودی خوانده می شوند. سپس حلقه ی بیرونی بر روی خانه شماره یک شروع میشود.

-

و درون آن حلقه ی دیگری بر روی خانه ی دوم شروع میشود که خانه ی 3 را زیاد میکند.

-

ولی مشکلی که در اینجا به وجود می آید اینست که در پایان حلقه ی دوم مقدار خانه ی 2 صفر شده

-

و مقدار اولیه ی آن از دست رفته است. برای حل این مشکل خانه ی شماره چهار هم زیاد میشود

-

و در پایان حلقه مقدار آن به خانه 2 کپی میشود.

-

در پایان خانه ی شماره 2 حاوی حاصلضرب خواهد بود.

- -
- -

و این همه ی برین فاک بود! خیلی ساده برای یادگیری ولی سنگین برای به کار بردن.

-

حال می توانید برای تفریح مشغول نوشتن برنامه ی های مختلف با آن شوید.

-

و یا یک اجرا کننده برین فاک را با یک زبان دیگر پیاده سازی کنید.

-

و یا اگر خیلی دوست داشتید یک اجرا کننده ی برین فاک با برین فاک بنویسید!!

diff --git a/fr-fr/bf-fr.html.markdown b/fr-fr/bf-fr.html.markdown new file mode 100644 index 00000000..0fae6032 --- /dev/null +++ b/fr-fr/bf-fr.html.markdown @@ -0,0 +1,87 @@ +--- +language: bf +filename: learnbrainfuck-fr.bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Baptiste Fontaine", "http://bfontaine.net"] +lang: fr-fr +--- + +Brainfuck (sans majuscule à part au début d’une phrase) est un langage +Turing-complet extrêmement simple avec seulement 8 commandes. + +``` +Tout caractère en dehors de "><+-.,[]" (en dehors des guillemets) est ignoré. + +Brainfuck est représenté par un tableau de 30 000 cellules initialisées à 0 et +un pointeur de données pointant sur la cellule courante. + +Il y a huit commandes : ++ : Incrémente la valeur de la cellule courante de un. +- : Décrémente la valeur de la cellule courante de un. +> : Déplace le pointeur de données sur la cellule suivante (à droite). +< : Déplace le pointeur de données sur la cellule précédente (à gauche). +. : Affiche la valeur ASCII de la cellule courante (par ex. 65 = 'A'). +, : Lit un caractère et le place dans la cellule courante. +[ : Si la valeur dans la cellule courante vaut 0, saute au ] correspondant. + Sinon, continue avec la commande suivante. +] : Si la valeur dans la cellule courante vaut 0, continue avec la commande + suivante. Sinon, retourne au [ correspondant. + +[ et ] forment une boucle « tant que » (« while »). Ils doivent évidemment +aller par paires. + +Regardons quelques programmes simples en brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Ce programme affiche la lettre 'A'. Il commence par incrémenter la première +cellule à 6. Il entre ensuite dans une boucle et se déplace sur la seconde +cellule. Il l’incrémente 10 fois, retourne sur la première cellule, et la +décrémente. Cette boucle est exécutée 6 fois (ce qui correspond aux 6 +décrémentations de la première cellule pour la faire atteindre 0, ce qui fait +sortir de la boucle). + +À ce moment-là, nous sommes sur la première cellule, qui a une valeur de 0, +tandis que la seconde cellule a une valeur de 60. Nous nous déplaçons sur +celle-ci, l’incrémentons 5 fois, pour une valeur de 65, et affichons sa valeur. +En ASCII, 65 correspond à 'A' donc le programme affiche 'A' dans le terminal. + +, [ > + < - ] > . + +Ce programme lit un caractère sur l’entrée standard et le copie dans la +première cellule. Il commence ensuite une boucle : il bouge sur la seconde +cellule, incrémente sa valeur, retourne sur la première et décrémente sa +valeur. Il continue jusqu’à ce que la valeur de la première cellule soit à 0, +et que la seconde cellule contienne l’ancienne valeur de la première. Comme +nous sommes sur la première cellule à la fin de la boucle, il bouge sur la +seconde et affiche sa valeur en ASCII. + +Souvenez-vous que les espaces sont uniquement là pour favoriser la lisibilité, +vous pourriez tout aussi aisément écrire le programme comme ceci : + +,[>+<-]>. + +Essayez et devinez ce que ce programme fait : + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Ce programme prend deux nombres en entrée, et les multiplie. + +Il commence par lire deux entrées, puis commence une boucle externe, qui a une +condition sur la première cellule. Il bouge ensuite sur la seconde, et commence +une boucle interne sur celle-ci, en incrémentant la troisième cellule. Il y a +cependant un problème : à la fin de la boucle interne, la valeur de la seconde +cellule est à zéro. Dans ce cas, la boucle interne ne fonctionnera pas une +seconde fois. Pour régler le problème, nous incrémentons aussi la quatrième +cellule, puis recopions sa valeur dans la seconde cellule. +À la fin, la troisième cellule contient le résultat de la multiplication. +``` + +Et voilà ce qu’est le brainfuck. Pas très dur, hein ? Pour le fun, vous pouvez +écrire vos propres programmes en brainfuck, ou écrire un interpréteur brainfuck +dans un autre langage. L’interpréteur est relativement simple à implémenter, +mais si vous êtes un masochiste, essayez d’écrire un interpréteur brainfuck en… +brainfuck. diff --git a/fr-fr/brainfuck-fr.html.markdown b/fr-fr/brainfuck-fr.html.markdown deleted file mode 100644 index 545e407e..00000000 --- a/fr-fr/brainfuck-fr.html.markdown +++ /dev/null @@ -1,87 +0,0 @@ ---- -language: brainfuck -filename: learnbrainfuck-fr.bf -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Baptiste Fontaine", "http://bfontaine.net"] -lang: fr-fr ---- - -Brainfuck (sans majuscule à part au début d’une phrase) est un langage -Turing-complet extrêmement simple avec seulement 8 commandes. - -``` -Tout caractère en dehors de "><+-.,[]" (en dehors des guillemets) est ignoré. - -Brainfuck est représenté par un tableau de 30 000 cellules initialisées à 0 et -un pointeur de données pointant sur la cellule courante. - -Il y a huit commandes : -+ : Incrémente la valeur de la cellule courante de un. -- : Décrémente la valeur de la cellule courante de un. -> : Déplace le pointeur de données sur la cellule suivante (à droite). -< : Déplace le pointeur de données sur la cellule précédente (à gauche). -. : Affiche la valeur ASCII de la cellule courante (par ex. 65 = 'A'). -, : Lit un caractère et le place dans la cellule courante. -[ : Si la valeur dans la cellule courante vaut 0, saute au ] correspondant. - Sinon, continue avec la commande suivante. -] : Si la valeur dans la cellule courante vaut 0, continue avec la commande - suivante. Sinon, retourne au [ correspondant. - -[ et ] forment une boucle « tant que » (« while »). Ils doivent évidemment -aller par paires. - -Regardons quelques programmes simples en brainfuck. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Ce programme affiche la lettre 'A'. Il commence par incrémenter la première -cellule à 6. Il entre ensuite dans une boucle et se déplace sur la seconde -cellule. Il l’incrémente 10 fois, retourne sur la première cellule, et la -décrémente. Cette boucle est exécutée 6 fois (ce qui correspond aux 6 -décrémentations de la première cellule pour la faire atteindre 0, ce qui fait -sortir de la boucle). - -À ce moment-là, nous sommes sur la première cellule, qui a une valeur de 0, -tandis que la seconde cellule a une valeur de 60. Nous nous déplaçons sur -celle-ci, l’incrémentons 5 fois, pour une valeur de 65, et affichons sa valeur. -En ASCII, 65 correspond à 'A' donc le programme affiche 'A' dans le terminal. - -, [ > + < - ] > . - -Ce programme lit un caractère sur l’entrée standard et le copie dans la -première cellule. Il commence ensuite une boucle : il bouge sur la seconde -cellule, incrémente sa valeur, retourne sur la première et décrémente sa -valeur. Il continue jusqu’à ce que la valeur de la première cellule soit à 0, -et que la seconde cellule contienne l’ancienne valeur de la première. Comme -nous sommes sur la première cellule à la fin de la boucle, il bouge sur la -seconde et affiche sa valeur en ASCII. - -Souvenez-vous que les espaces sont uniquement là pour favoriser la lisibilité, -vous pourriez tout aussi aisément écrire le programme comme ceci : - -,[>+<-]>. - -Essayez et devinez ce que ce programme fait : - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Ce programme prend deux nombres en entrée, et les multiplie. - -Il commence par lire deux entrées, puis commence une boucle externe, qui a une -condition sur la première cellule. Il bouge ensuite sur la seconde, et commence -une boucle interne sur celle-ci, en incrémentant la troisième cellule. Il y a -cependant un problème : à la fin de la boucle interne, la valeur de la seconde -cellule est à zéro. Dans ce cas, la boucle interne ne fonctionnera pas une -seconde fois. Pour régler le problème, nous incrémentons aussi la quatrième -cellule, puis recopions sa valeur dans la seconde cellule. -À la fin, la troisième cellule contient le résultat de la multiplication. -``` - -Et voilà ce qu’est le brainfuck. Pas très dur, hein ? Pour le fun, vous pouvez -écrire vos propres programmes en brainfuck, ou écrire un interpréteur brainfuck -dans un autre langage. L’interpréteur est relativement simple à implémenter, -mais si vous êtes un masochiste, essayez d’écrire un interpréteur brainfuck en… -brainfuck. diff --git a/it-it/bf-it.html.markdown b/it-it/bf-it.html.markdown new file mode 100644 index 00000000..a79710d0 --- /dev/null +++ b/it-it/bf-it.html.markdown @@ -0,0 +1,92 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Ivan Sala", "http://slavni96.github.io/"] + - ["Christian Grasso", "http://chris54721.net"] +lang: it-it +--- + +Brainfuck è un linguaggio di programmazione +[Turing equivalente](https://it.wikipedia.org/wiki/Turing_equivalenza) +estremamente minimale, composto da solo 8 comandi. + +Puoi provarlo nel tuo browser utilizzando +[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` + +Qualsiasi carattere diverso da "><+-.,[]" (escludendo gli apici) +viene ignorato. +Branfuck è caratterizzato da un array di 30,000 celle inizializzate a zero +e da un puntatore che punta alla cella corrente. + +Vi sono otto comandi: ++ : Incrementa il valore della cella attuale di uno. +- : Decrementa il valore della cella attuale di uno. +> : Sposta il puntatore sulla cella seguente (sulla destra). +< : Sposta il puntatore sulla cella precendete (sulla sinistra). +. : Stampa il valore ASCII della cella corrente. (es. 65 = 'A') +, : Legge un singolo carattere come input e lo salva nella cella corrente. +[ : Se il valore della cella corrente è zero, prosegue fino alla ] corrispondente. + Altrimenti, passa alla prossima istruzione. +] : Se il valore della cella corrente è zero, passa alla prossima istruzione. + Altrimenti, torna indietro fino alla [ corrispondente. + +[ e ] formano un ciclo while. Ovviamente dovranno essere bilanciati. +(Ad ogni [ dovrà corrispondere una ]) + +Ecco alcuni semplici esempi di programmi scritti in Brainfuck: + +++++++ [ > ++++++++++ < - ] > +++++ . + +Questo programma stampa in output la lettera 'A'. Prima di tutto, incrementa +la cella #1 fino al valore 6. La cella #1 verrà utilizzata per il ciclo. +Poi, entra nel ciclo ([) e si sposta alla cella #2. Incrementa la cella #2 10 +volte, torna alla cella #1, e decrementa quest'ultima. +Il ciclo si ripete 6 volte (la cella #1 viene decrementata 6 volte prima di +raggiungere lo 0, quindi prosegue oltre la corrispondente ]). + +A questo punto, siamo sulla cella #1, che ha valore 0, mentre la cella #2 ha +valore 60. Ci spostiamo sulla cella #2, la incrementiamo per 5 volte, ottenendo +il valore 65, quindi stampiamo il valore della cella #2. +Il valore 65 equivale ad 'A' in ASCII, per cui viene stampato 'A' nel terminale. + + +, [ > + < - ] > . + +Questo programma legge un carattere come input dall'utente, quindi salva il +carattere nella cella #1. Dopodichè entra in un ciclo. Si sposta alla cella #2, +incrementa quest'ultima, torna alla cella #1, e decrementa quest'ultima. +Il ciclo continua fino a quando la cella #1 diventa 0, e quindi la cella #2 +avrà il valore iniziale della cella #1. Infine, visto che ci troviamo sulla +cella #1 alla fine del ciclo, si sposta sulla cella #2 e stampa il valore in +ASCII. + +Gli spazi nel codice sovrastante sono presenti solo a scopo di ottenere +una maggiore leggibilità. Lo stesso programma poteva essere scritto senza spazi: + +,[>+<-]>. + +Proviamo, adesso, a capire cosa fa invece questo programma: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Il programma legge 2 numeri come input dall'utente, e li moltiplica. + +Innanzitutto, legge in input i due numeri. Poi entra nel ciclo più esterno +basandosi sulla cella #1. Quindi si sposta sulla cella #2, e inizia il ciclo +più interno basandosi sul valore della cella #2, incrementando la cella #3. +Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno +la cella #2 avrà valore 0. Ciò impedirà di eseguire nuovamente il ciclo interno. +Per ovviare a questo problema, incrementiamo anche la cella #4, e copiamo il +valore di quest'ultima nella cella #2. +Il risultato sarà infine contenuto nella cella #3. +``` + +E questo è brainfuck. Non è così difficile, eh? Se vuoi, ora puoi scrivere per +divertimento altri programmi in brainfuck, oppure scrivere un interprete +brainfuck in un altro linguaggio. L'interprete è abbastanza semplice da +implementare, ma se sei veramente masochista, prova ad implementare un interprete brainfuck... in brainfuck. diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown deleted file mode 100644 index 08d2ede9..00000000 --- a/it-it/brainfuck-it.html.markdown +++ /dev/null @@ -1,92 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Ivan Sala", "http://slavni96.github.io/"] - - ["Christian Grasso", "http://chris54721.net"] -lang: it-it ---- - -Brainfuck è un linguaggio di programmazione -[Turing equivalente](https://it.wikipedia.org/wiki/Turing_equivalenza) -estremamente minimale, composto da solo 8 comandi. - -Puoi provarlo nel tuo browser utilizzando -[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - -``` - -Qualsiasi carattere diverso da "><+-.,[]" (escludendo gli apici) -viene ignorato. -Branfuck è caratterizzato da un array di 30,000 celle inizializzate a zero -e da un puntatore che punta alla cella corrente. - -Vi sono otto comandi: -+ : Incrementa il valore della cella attuale di uno. -- : Decrementa il valore della cella attuale di uno. -> : Sposta il puntatore sulla cella seguente (sulla destra). -< : Sposta il puntatore sulla cella precendete (sulla sinistra). -. : Stampa il valore ASCII della cella corrente. (es. 65 = 'A') -, : Legge un singolo carattere come input e lo salva nella cella corrente. -[ : Se il valore della cella corrente è zero, prosegue fino alla ] corrispondente. - Altrimenti, passa alla prossima istruzione. -] : Se il valore della cella corrente è zero, passa alla prossima istruzione. - Altrimenti, torna indietro fino alla [ corrispondente. - -[ e ] formano un ciclo while. Ovviamente dovranno essere bilanciati. -(Ad ogni [ dovrà corrispondere una ]) - -Ecco alcuni semplici esempi di programmi scritti in Brainfuck: - -++++++ [ > ++++++++++ < - ] > +++++ . - -Questo programma stampa in output la lettera 'A'. Prima di tutto, incrementa -la cella #1 fino al valore 6. La cella #1 verrà utilizzata per il ciclo. -Poi, entra nel ciclo ([) e si sposta alla cella #2. Incrementa la cella #2 10 -volte, torna alla cella #1, e decrementa quest'ultima. -Il ciclo si ripete 6 volte (la cella #1 viene decrementata 6 volte prima di -raggiungere lo 0, quindi prosegue oltre la corrispondente ]). - -A questo punto, siamo sulla cella #1, che ha valore 0, mentre la cella #2 ha -valore 60. Ci spostiamo sulla cella #2, la incrementiamo per 5 volte, ottenendo -il valore 65, quindi stampiamo il valore della cella #2. -Il valore 65 equivale ad 'A' in ASCII, per cui viene stampato 'A' nel terminale. - - -, [ > + < - ] > . - -Questo programma legge un carattere come input dall'utente, quindi salva il -carattere nella cella #1. Dopodichè entra in un ciclo. Si sposta alla cella #2, -incrementa quest'ultima, torna alla cella #1, e decrementa quest'ultima. -Il ciclo continua fino a quando la cella #1 diventa 0, e quindi la cella #2 -avrà il valore iniziale della cella #1. Infine, visto che ci troviamo sulla -cella #1 alla fine del ciclo, si sposta sulla cella #2 e stampa il valore in -ASCII. - -Gli spazi nel codice sovrastante sono presenti solo a scopo di ottenere -una maggiore leggibilità. Lo stesso programma poteva essere scritto senza spazi: - -,[>+<-]>. - -Proviamo, adesso, a capire cosa fa invece questo programma: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Il programma legge 2 numeri come input dall'utente, e li moltiplica. - -Innanzitutto, legge in input i due numeri. Poi entra nel ciclo più esterno -basandosi sulla cella #1. Quindi si sposta sulla cella #2, e inizia il ciclo -più interno basandosi sul valore della cella #2, incrementando la cella #3. -Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno -la cella #2 avrà valore 0. Ciò impedirà di eseguire nuovamente il ciclo interno. -Per ovviare a questo problema, incrementiamo anche la cella #4, e copiamo il -valore di quest'ultima nella cella #2. -Il risultato sarà infine contenuto nella cella #3. -``` - -E questo è brainfuck. Non è così difficile, eh? Se vuoi, ora puoi scrivere per -divertimento altri programmi in brainfuck, oppure scrivere un interprete -brainfuck in un altro linguaggio. L'interprete è abbastanza semplice da -implementare, ma se sei veramente masochista, prova ad implementare un interprete brainfuck... in brainfuck. diff --git a/ko-kr/bf-kr.html.markdown b/ko-kr/bf-kr.html.markdown new file mode 100644 index 00000000..3d366d7c --- /dev/null +++ b/ko-kr/bf-kr.html.markdown @@ -0,0 +1,84 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["JongChan Choi", "http://0xABCDEF.com/"] + - ["Peter Lee", "http://peterjlee.com/"] +lang: ko-kr +--- + +Brainfuck(문장을 시작하는 단어가 아닌이상 첫글자는 대문자를 사용하지 않습니다)은 +여덟가지 명령어만으로 튜링-완전한 최소주의 프로그래밍 언어입니다. + +``` +"><+-.,[]" 이외의 문자들은 무시됩니다. (쌍따옴표는 제외) + +브레인퍽은 30,000 칸 짜리의 0으로 초기화된 배열과, +현재 칸을 가르키는 포인터로 표현됩니다. + +여덟가지의 명령어는 다음과 같습니다: ++ : 포인터가 가르키는 현재 칸의 값을 1 증가시킵니다. +- : 포인터가 가르키는 현재 칸의 값을 1 감소시킵니다. +> : 포인터가 다음 칸(오른쪽 칸)을 가르키도록 이동시킵니다. +< : 포인터가 이전 칸(왼쪽 칸)을 가르키도록 이동시킵니다. +. : 현재 칸의 값을 ASCII 문자로 출력합니다. (즉, 65 = 'A') +, : 하나의 문자를 입력받고 그 값을 현재 칸에 대입합니다. +[ : 현재 칸의 값이 0이면 짝이 맞는 ] 명령으로 넘어갑니다. + 0이 아니면 다음 명령어로 넘어갑니다. +] : 현재 칸의 값이 0이면 다음 명령어로 넘어갑니다. + 0이 아니면 짝이 맞는 [ 명령으로 다시 돌아갑니다. + +[이랑 ]은 while 루프를 만들어냅니다. 무조건, 짝이 맞아야 합니다. + +몇가지 간단한 브레인퍽 프로그램을 보겠습니다. + +++++++ [ > ++++++++++ < - ] > +++++ . + +이 프로그램은 문자 'A'를 출력합니다. 처음에는, 반복할 횟수를 정하기 위한 값을 +만들기 위해 첫번째 칸의 값을 6으로 증가시킵니다. 그리고 루프로 들어가서([) +두번째 칸으로 넘어갑니다. 루프 안에서는 두번째 칸의 값을 10 증가시키고, +다시 첫번째 칸으로 넘어가서 값을 1 감소시킵니다. 이 루프는 여섯번 돕니다. +(첫번째 칸의 값을 6번 감소시켜서 0이 될 때 까지는 ] 명령을 만날 때마다 +루프의 시작 지점으로 돌아갑니다) + +이 시점에서, 두번째 칸의 값은 60이고, 포인터는 값이 0인 첫번째 칸에 위치합니다. +여기서 두번째 칸으로 넘어간 다음 값을 5 증가시키면 두번째 칸의 값이 65가 되고, +65는 문자 'A'에 대응하는 아스키 코드이기 때문에, 두번째 칸의 값을 출력하면 +터미널에 'A'가 출력됩니다. + +, [ > + < - ] > . + +이 프로그램은 사용자로부터 문자 하나를 입력받아 첫번째 칸에 집어넣습니다. +그리고 루프에 들어가서, 두번째 칸으로 넘어가 값을 한 번 증가시킨 다음, +다시 첫번째 칸으로 넘어가서 값을 한 번 감소시킵니다. +이는 첫번째 칸의 값이 0이 될 때까지 지속되며, +두번째 칸은 첫번째 칸이 갖고있던 값을 가지게 됩니다. +루프가 종료되면 포인터는 첫번째 칸을 가르키기 때문에 두번째 칸으로 넘어가고, +해당 아스키 코드에 대응하는 문자를 출력합니다. + +또한 공백문자는 순전히 가독성을 위해서 작성되었다는 것을 기억하세요. +다음과 같이 작성해도 똑같이 돌아갑니다: + +,[>+<-]>. + +한 번 돌려보고 아래의 프로그램이 실제로 무슨 일을 하는지 맞춰보세요: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +이 프로그램은 두 개의 숫자를 입력받은 뒤, 그 둘을 곱합니다. + +위 코드는 일단 두 번의 입력을 받고, 첫번째 칸의 값만큼 바깥 루프를 돕니다. +그리고 루프 안에서 다시 두번째 칸의 값만큼 안쪽의 루프를 돕니다. +그리고 그 루프에서는 세번째 칸의 값을 증가시키는데, 문제가 하나 있습니다: +내부 루프가 한 번 끝나게 되면 두번째 칸의 값은 0이 됩니다. +그럼 다시 바깥 루프를 돌 때에 안쪽의 루프를 돌지 않게 되는데, 이를 해결하려면 +네번째 칸의 값도 같이 증가시킨 다음, 그 값을 두번째 칸으로 옮기면 됩니다. +그러면 세번째 칸에 곱셈의 결과가 남습니다. +``` + +여기까지 브레인퍽이었습니다. 참 쉽죠? +재미삼아 브레인퍽 프로그램이나 다른 언어로 브레인퍽 인터프리터를 작성해보세요. +인터프리터 구현은 간단한 편인데, +사서 고생하는 것을 즐기는 편이라면 한 번 작성해보세요… 브레인퍽으로. diff --git a/ko-kr/brainfuck-kr.html.markdown b/ko-kr/brainfuck-kr.html.markdown deleted file mode 100644 index c2e4341f..00000000 --- a/ko-kr/brainfuck-kr.html.markdown +++ /dev/null @@ -1,84 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["JongChan Choi", "http://0xABCDEF.com/"] - - ["Peter Lee", "http://peterjlee.com/"] -lang: ko-kr ---- - -Brainfuck(문장을 시작하는 단어가 아닌이상 첫글자는 대문자를 사용하지 않습니다)은 -여덟가지 명령어만으로 튜링-완전한 최소주의 프로그래밍 언어입니다. - -``` -"><+-.,[]" 이외의 문자들은 무시됩니다. (쌍따옴표는 제외) - -브레인퍽은 30,000 칸 짜리의 0으로 초기화된 배열과, -현재 칸을 가르키는 포인터로 표현됩니다. - -여덟가지의 명령어는 다음과 같습니다: -+ : 포인터가 가르키는 현재 칸의 값을 1 증가시킵니다. -- : 포인터가 가르키는 현재 칸의 값을 1 감소시킵니다. -> : 포인터가 다음 칸(오른쪽 칸)을 가르키도록 이동시킵니다. -< : 포인터가 이전 칸(왼쪽 칸)을 가르키도록 이동시킵니다. -. : 현재 칸의 값을 ASCII 문자로 출력합니다. (즉, 65 = 'A') -, : 하나의 문자를 입력받고 그 값을 현재 칸에 대입합니다. -[ : 현재 칸의 값이 0이면 짝이 맞는 ] 명령으로 넘어갑니다. - 0이 아니면 다음 명령어로 넘어갑니다. -] : 현재 칸의 값이 0이면 다음 명령어로 넘어갑니다. - 0이 아니면 짝이 맞는 [ 명령으로 다시 돌아갑니다. - -[이랑 ]은 while 루프를 만들어냅니다. 무조건, 짝이 맞아야 합니다. - -몇가지 간단한 브레인퍽 프로그램을 보겠습니다. - -++++++ [ > ++++++++++ < - ] > +++++ . - -이 프로그램은 문자 'A'를 출력합니다. 처음에는, 반복할 횟수를 정하기 위한 값을 -만들기 위해 첫번째 칸의 값을 6으로 증가시킵니다. 그리고 루프로 들어가서([) -두번째 칸으로 넘어갑니다. 루프 안에서는 두번째 칸의 값을 10 증가시키고, -다시 첫번째 칸으로 넘어가서 값을 1 감소시킵니다. 이 루프는 여섯번 돕니다. -(첫번째 칸의 값을 6번 감소시켜서 0이 될 때 까지는 ] 명령을 만날 때마다 -루프의 시작 지점으로 돌아갑니다) - -이 시점에서, 두번째 칸의 값은 60이고, 포인터는 값이 0인 첫번째 칸에 위치합니다. -여기서 두번째 칸으로 넘어간 다음 값을 5 증가시키면 두번째 칸의 값이 65가 되고, -65는 문자 'A'에 대응하는 아스키 코드이기 때문에, 두번째 칸의 값을 출력하면 -터미널에 'A'가 출력됩니다. - -, [ > + < - ] > . - -이 프로그램은 사용자로부터 문자 하나를 입력받아 첫번째 칸에 집어넣습니다. -그리고 루프에 들어가서, 두번째 칸으로 넘어가 값을 한 번 증가시킨 다음, -다시 첫번째 칸으로 넘어가서 값을 한 번 감소시킵니다. -이는 첫번째 칸의 값이 0이 될 때까지 지속되며, -두번째 칸은 첫번째 칸이 갖고있던 값을 가지게 됩니다. -루프가 종료되면 포인터는 첫번째 칸을 가르키기 때문에 두번째 칸으로 넘어가고, -해당 아스키 코드에 대응하는 문자를 출력합니다. - -또한 공백문자는 순전히 가독성을 위해서 작성되었다는 것을 기억하세요. -다음과 같이 작성해도 똑같이 돌아갑니다: - -,[>+<-]>. - -한 번 돌려보고 아래의 프로그램이 실제로 무슨 일을 하는지 맞춰보세요: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -이 프로그램은 두 개의 숫자를 입력받은 뒤, 그 둘을 곱합니다. - -위 코드는 일단 두 번의 입력을 받고, 첫번째 칸의 값만큼 바깥 루프를 돕니다. -그리고 루프 안에서 다시 두번째 칸의 값만큼 안쪽의 루프를 돕니다. -그리고 그 루프에서는 세번째 칸의 값을 증가시키는데, 문제가 하나 있습니다: -내부 루프가 한 번 끝나게 되면 두번째 칸의 값은 0이 됩니다. -그럼 다시 바깥 루프를 돌 때에 안쪽의 루프를 돌지 않게 되는데, 이를 해결하려면 -네번째 칸의 값도 같이 증가시킨 다음, 그 값을 두번째 칸으로 옮기면 됩니다. -그러면 세번째 칸에 곱셈의 결과가 남습니다. -``` - -여기까지 브레인퍽이었습니다. 참 쉽죠? -재미삼아 브레인퍽 프로그램이나 다른 언어로 브레인퍽 인터프리터를 작성해보세요. -인터프리터 구현은 간단한 편인데, -사서 고생하는 것을 즐기는 편이라면 한 번 작성해보세요… 브레인퍽으로. diff --git a/nl-nl/bf.html.markdown b/nl-nl/bf.html.markdown new file mode 100644 index 00000000..016e2ba2 --- /dev/null +++ b/nl-nl/bf.html.markdown @@ -0,0 +1,86 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Jelle Besseling", "https://github.com/Jell-E"] +lang: nl-nl +--- + +Brainfuck (schrijf je niet met een hoofdletter behalve aan het begin van een +zin) is een extreem +minimalistische Turing-complete programmeertaal met maar acht commando's. + +``` +Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd. + +Brainfuck wordt gerepresenteerd door een array met 30.000 cellen die initieel +gevuld is met nullen en een pointer die wijst naar de huidige cel. + +Dit zijn de acht commando's: ++ : Verhoog de huidige cell met 1. +- : Verminder de huidige cell met 1. +> : Beweeg de pointer naar de volgende cell (één naar rechts). +< : Beweeg de pointer naar de vorige cell (één naar links). +. : Print de huidige cell als een ASCII karakter(d.w.z. 65 = 'A'). +, : Lees een karakter in de huidige cell. +[ : Als de huidige cell nul is ga dan naar de bijbehorende ] . + Als het geen nul is, ga dan gewoon verder. +] : Als de huidige cell nul is ga dan gewoon verder. + Als het geen nul is, ga dan terug naar de bijbehorende [ . + +[ en ] maken een while loop. Ze moeten uiteraard wel gebalanceerd zijn + +Laten we een kijkje nemen naar een paar brainfuck programma's. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Dit programma print het karakter 'A'. Eerst verhoogt het cell #1 tot 6. +Cell #1 wordt gebruikt om te loopen. Dan begint het de loop ([) en gaat +naar cell #2. Het verhoogt cell #2 tien keer, gaat terug naar cell #1, en +verlaagt cell #1. Deze loop gebeurt zes keer (na zes keer staat cell #1 +weer op nul, waarna het doorgaat naar het einde van de loop (]) en +verder gaat). + +De pointer staat nu weer op cell #1, deze heeft een waarde van 0, en cell #2 +heeft een waarde van 60. > beweegt de pointer naar cell #2, daarna verhoogt +het de cell vijf keer, waardoor het een waarde van 65 bevat, en print dan +de waarde van cell #2. 65 is 'A' in ASCII, dus 'A' wordt geprint in de terminal. + + +, [ > + < - ] > . + +Dit programma leest een karakter van de gebruiker in put en kopieert dat +karakter in cel #1. Dan start de loop. Ga naar cel #2, verhoog de waarde in +cel #2, ga terug naar cel #1, en verklein de waarde in cel #1. Dit gaat door +totdat cel #1 nul is en cel #2 de oude waarde heeft van cell #1. Omdat we +op cel #1 staan verplaatst > de pointer één naar rechts en . print het +karakter in cel #2. + +Houd wel in gedachten dat de spaties alleen zijn voor leesbaarheid, je kan het +bovenstaande programma net zo goed schrijven als: + +,[>+<-]>. + +Probeer maar eens te bedenken wat het volgende programma doet: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Dit programma neemt twee getallen als input, en vermenigvuldigt ze. + +In het begin leest het twee karakters in cel #1 en #2. Dan start het de +buitenste loop, met als teller cel #1. Het beweegt naar cel #2, dan start het +de binnenste loop met als teller cel #2, daar verhoogd het cel #3. Maar +dan is er een probleem als cel #2 nul wordt aan het einde van de binnenste loop. +Om dit op te lossen wordt ook cel #4 verhoogd naar het oorspronkelijke getal +uit cel #2 en daarna wordt cel #4 weer gekopieerd naar cell #2. +Het resultaat komt in cel #3 te staan. +``` + +En dat is dan brainfuck. Niet heel moeilijk, toch? Je kan zelf voor de lol +brainfuck programma's gaan schrijven, of je kan een interpreter schrijven +voor brainfuck in een andere taal. Het is namelijk redelijk makkelijk om te +implementeren aangezien brainfuck maar acht commando's heeft. En als je een +masochist bent kan je ook nog proberen om brainfuck te implementeren… in +brainfuck. diff --git a/nl-nl/brainfuck-nl.html.markdown b/nl-nl/brainfuck-nl.html.markdown deleted file mode 100644 index 6062b24c..00000000 --- a/nl-nl/brainfuck-nl.html.markdown +++ /dev/null @@ -1,86 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Jelle Besseling", "https://github.com/Jell-E"] -lang: nl-nl ---- - -Brainfuck (schrijf je niet met een hoofdletter behalve aan het begin van een -zin) is een extreem -minimalistische Turing-complete programmeertaal met maar acht commando's. - -``` -Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd. - -Brainfuck wordt gerepresenteerd door een array met 30.000 cellen die initieel -gevuld is met nullen en een pointer die wijst naar de huidige cel. - -Dit zijn de acht commando's: -+ : Verhoog de huidige cell met 1. -- : Verminder de huidige cell met 1. -> : Beweeg de pointer naar de volgende cell (één naar rechts). -< : Beweeg de pointer naar de vorige cell (één naar links). -. : Print de huidige cell als een ASCII karakter(d.w.z. 65 = 'A'). -, : Lees een karakter in de huidige cell. -[ : Als de huidige cell nul is ga dan naar de bijbehorende ] . - Als het geen nul is, ga dan gewoon verder. -] : Als de huidige cell nul is ga dan gewoon verder. - Als het geen nul is, ga dan terug naar de bijbehorende [ . - -[ en ] maken een while loop. Ze moeten uiteraard wel gebalanceerd zijn - -Laten we een kijkje nemen naar een paar brainfuck programma's. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Dit programma print het karakter 'A'. Eerst verhoogt het cell #1 tot 6. -Cell #1 wordt gebruikt om te loopen. Dan begint het de loop ([) en gaat -naar cell #2. Het verhoogt cell #2 tien keer, gaat terug naar cell #1, en -verlaagt cell #1. Deze loop gebeurt zes keer (na zes keer staat cell #1 -weer op nul, waarna het doorgaat naar het einde van de loop (]) en -verder gaat). - -De pointer staat nu weer op cell #1, deze heeft een waarde van 0, en cell #2 -heeft een waarde van 60. > beweegt de pointer naar cell #2, daarna verhoogt -het de cell vijf keer, waardoor het een waarde van 65 bevat, en print dan -de waarde van cell #2. 65 is 'A' in ASCII, dus 'A' wordt geprint in de terminal. - - -, [ > + < - ] > . - -Dit programma leest een karakter van de gebruiker in put en kopieert dat -karakter in cel #1. Dan start de loop. Ga naar cel #2, verhoog de waarde in -cel #2, ga terug naar cel #1, en verklein de waarde in cel #1. Dit gaat door -totdat cel #1 nul is en cel #2 de oude waarde heeft van cell #1. Omdat we -op cel #1 staan verplaatst > de pointer één naar rechts en . print het -karakter in cel #2. - -Houd wel in gedachten dat de spaties alleen zijn voor leesbaarheid, je kan het -bovenstaande programma net zo goed schrijven als: - -,[>+<-]>. - -Probeer maar eens te bedenken wat het volgende programma doet: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Dit programma neemt twee getallen als input, en vermenigvuldigt ze. - -In het begin leest het twee karakters in cel #1 en #2. Dan start het de -buitenste loop, met als teller cel #1. Het beweegt naar cel #2, dan start het -de binnenste loop met als teller cel #2, daar verhoogd het cel #3. Maar -dan is er een probleem als cel #2 nul wordt aan het einde van de binnenste loop. -Om dit op te lossen wordt ook cel #4 verhoogd naar het oorspronkelijke getal -uit cel #2 en daarna wordt cel #4 weer gekopieerd naar cell #2. -Het resultaat komt in cel #3 te staan. -``` - -En dat is dan brainfuck. Niet heel moeilijk, toch? Je kan zelf voor de lol -brainfuck programma's gaan schrijven, of je kan een interpreter schrijven -voor brainfuck in een andere taal. Het is namelijk redelijk makkelijk om te -implementeren aangezien brainfuck maar acht commando's heeft. En als je een -masochist bent kan je ook nog proberen om brainfuck te implementeren… in -brainfuck. diff --git a/pl-pl/bf-pl.html.markdown b/pl-pl/bf-pl.html.markdown new file mode 100644 index 00000000..801f1a9a --- /dev/null +++ b/pl-pl/bf-pl.html.markdown @@ -0,0 +1,93 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Jakub Młokosiewicz", "https://github.com/hckr"] +lang: pl-pl +--- + +Brainfuck (pisane małymi literami, za wyjątkiem początku zdania) jest bardzo +minimalistycznym, kompletnym w sensie Turinga, językiem programowania. +Zawiera zaledwie 8 poleceń. + +Możesz przetesotwać brainfucka w swojej przeglądarce, korzystając z narzędzia +[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Wszystkie znaki oprócz "><+-.,[]" (wyłączając znaki zapytania) są ignorowane. + +Pamięć w brainfucku jest reprezentowana przez tablicę 30.000 komórek +zainicjalizowanych zerami, ze wskaźnikiem pokazującym na aktualną komórkę. + +Oto osiem poleceń brainfucka: ++ : inkrementuje (zwiększa o jeden) wartość aktualnie wskazywanej komórki +- : dekrementuje (zmniejsza o jeden) wartość aktualnie wskazywanej komórki +> : przesuwa wskaźnik na następną komórkę (w prawo) +< : przesuwa wskaźnik na poprzednią komórkę (w lewo) +. : wyświetla wartość bieżącej komórki (w formie znaku ASCII, np. 65 = 'A') +, : wczytuje (jeden) znak z wejścia do bieżącej komórki + (konkretnie jego numer z tabeli ASCII) +[ : jeśli wartość w bieżącej komórce jest rózna zero, przechodzi do + odpowiadającego ]; w przeciwnym wypdaku przechodzi do następnej instrukcji +] : Jeśli wartość w bieżącej komórce jest rózna od zera, przechodzi do + następnej instrukcji; w przeciwnym wypdaku przechodzi do odpowiadającego [ + +[ i ] oznaczają pętlę while. Oczywiście każda pętla rozpoczęta [ +musi być zakończona ]. + +Zobaczmy kilka prostych programów w brainfucku. + + +++++++ [ > ++++++++++ < - ] > +++++ . + +Ten program wypisuje literę 'A'. Najpierw zwiększa wartość komórki #1 do 6. +Komórka #1 będzie wykorzystana w pętli. Następnie program wchodzi w pętlę ([) +i przechodzi do komórki #2. Pętla wykonuje się sześć razy (komórka #1 jest +dekrementowana sześć razy, nim osiągnie wartość zero, kiedy to program +przechodzi do odpowiadającego ] i wykonuje kolejne instrukcje). + +W tym momencie wskaźnik pokazuje na komórkę #1, mającą wartość 0, podczas gdy +komórka #2 ma wartość 60. Przesuwamy wskaźnik na komórkę #2, inkrementujemy ją +pięć razy, uzyskując wartość 65. Następnie wyświetlamy wartość komórki #2. +65 to 'A' w tabeli ASCII, więc właśnie ten znak jest wypisany na konsolę. + + +, [ > + < - ] > . + +Ten program wczytuje znak z wejścia i umieszcza jego kod ASCII w komórce #1. +Następnie zaczyna się pętla, w której znajdują się następujące instrukcje: +przesunięcie wskaźnika na komórkę #2, inkrementacja wartości komóri #2, +powrót do komórki #1 i dekrementacja wartości komórki #1. Instrukcje pętli +wykonują się aż wartość komórki #1 osiągnie zero, a komórka #2 osiągnie +poprednią wartość komórki #1. Ponieważ na końcu pętli wskaźnik pokazuje na +komórkę #1, po pętli następuje instrukcja przejścia do komórki #2 i wysłanie +jej wartości (w formie znaku ASCII) na wyjście. + +Zauważ, że odstępy służą wyłącznie poprawie czytelności. +Równie dobrze można powyższy program zapisać tak: + +,[>+<-]>. + + +Spróbuj odgadnąć, co robi poniższy program: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Ten program pobiera z wejścia dwie liczby i je mnoży. + +Po wczytaniu dwóch wejść (do komórek #1 i #2) następuje pętla zewnętrzna, +warunkowana wartością komórki #1. Następnie program przechodzi do komórki #2 +i rozpoczyna pętlę wewnętrzną z warunkiem zakończenia w komórce #2, +inkrementującą komórkę #3. Tu jednak pojawia się problem: w chwili zakończenia +wewnętrznej pętli komórka #2 ma wartość zero. W takim razie wewętrzna pętla +nie wywoła się następny raz. Aby rozwiązać ten problem, inkrementujemy także +wartość komórki #4, a następnie kopiujemy jej wartość do komórki #2. +Ostatecznie wynik działania znajduje się w komórce #3. +``` + +I to właśnie jest brainfuck. Nie taki trudny, co? W ramach rozrywki możesz +napisać własne programy w brainfucku. Możesz też napisać interpreter brainfucka +w innym języku. Implementacja interpretera to dość proste zadanie. Jeśli +jesteś masochistą, spróbuj napisać interpreter brainfucka w... brainfucku. diff --git a/pl-pl/brainfuck-pl.html.markdown b/pl-pl/brainfuck-pl.html.markdown deleted file mode 100644 index 69d814c4..00000000 --- a/pl-pl/brainfuck-pl.html.markdown +++ /dev/null @@ -1,93 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Jakub Młokosiewicz", "https://github.com/hckr"] -lang: pl-pl ---- - -Brainfuck (pisane małymi literami, za wyjątkiem początku zdania) jest bardzo -minimalistycznym, kompletnym w sensie Turinga, językiem programowania. -Zawiera zaledwie 8 poleceń. - -Możesz przetesotwać brainfucka w swojej przeglądarce, korzystając z narzędzia -[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - -``` -Wszystkie znaki oprócz "><+-.,[]" (wyłączając znaki zapytania) są ignorowane. - -Pamięć w brainfucku jest reprezentowana przez tablicę 30.000 komórek -zainicjalizowanych zerami, ze wskaźnikiem pokazującym na aktualną komórkę. - -Oto osiem poleceń brainfucka: -+ : inkrementuje (zwiększa o jeden) wartość aktualnie wskazywanej komórki -- : dekrementuje (zmniejsza o jeden) wartość aktualnie wskazywanej komórki -> : przesuwa wskaźnik na następną komórkę (w prawo) -< : przesuwa wskaźnik na poprzednią komórkę (w lewo) -. : wyświetla wartość bieżącej komórki (w formie znaku ASCII, np. 65 = 'A') -, : wczytuje (jeden) znak z wejścia do bieżącej komórki - (konkretnie jego numer z tabeli ASCII) -[ : jeśli wartość w bieżącej komórce jest rózna zero, przechodzi do - odpowiadającego ]; w przeciwnym wypdaku przechodzi do następnej instrukcji -] : Jeśli wartość w bieżącej komórce jest rózna od zera, przechodzi do - następnej instrukcji; w przeciwnym wypdaku przechodzi do odpowiadającego [ - -[ i ] oznaczają pętlę while. Oczywiście każda pętla rozpoczęta [ -musi być zakończona ]. - -Zobaczmy kilka prostych programów w brainfucku. - - -++++++ [ > ++++++++++ < - ] > +++++ . - -Ten program wypisuje literę 'A'. Najpierw zwiększa wartość komórki #1 do 6. -Komórka #1 będzie wykorzystana w pętli. Następnie program wchodzi w pętlę ([) -i przechodzi do komórki #2. Pętla wykonuje się sześć razy (komórka #1 jest -dekrementowana sześć razy, nim osiągnie wartość zero, kiedy to program -przechodzi do odpowiadającego ] i wykonuje kolejne instrukcje). - -W tym momencie wskaźnik pokazuje na komórkę #1, mającą wartość 0, podczas gdy -komórka #2 ma wartość 60. Przesuwamy wskaźnik na komórkę #2, inkrementujemy ją -pięć razy, uzyskując wartość 65. Następnie wyświetlamy wartość komórki #2. -65 to 'A' w tabeli ASCII, więc właśnie ten znak jest wypisany na konsolę. - - -, [ > + < - ] > . - -Ten program wczytuje znak z wejścia i umieszcza jego kod ASCII w komórce #1. -Następnie zaczyna się pętla, w której znajdują się następujące instrukcje: -przesunięcie wskaźnika na komórkę #2, inkrementacja wartości komóri #2, -powrót do komórki #1 i dekrementacja wartości komórki #1. Instrukcje pętli -wykonują się aż wartość komórki #1 osiągnie zero, a komórka #2 osiągnie -poprednią wartość komórki #1. Ponieważ na końcu pętli wskaźnik pokazuje na -komórkę #1, po pętli następuje instrukcja przejścia do komórki #2 i wysłanie -jej wartości (w formie znaku ASCII) na wyjście. - -Zauważ, że odstępy służą wyłącznie poprawie czytelności. -Równie dobrze można powyższy program zapisać tak: - -,[>+<-]>. - - -Spróbuj odgadnąć, co robi poniższy program: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Ten program pobiera z wejścia dwie liczby i je mnoży. - -Po wczytaniu dwóch wejść (do komórek #1 i #2) następuje pętla zewnętrzna, -warunkowana wartością komórki #1. Następnie program przechodzi do komórki #2 -i rozpoczyna pętlę wewnętrzną z warunkiem zakończenia w komórce #2, -inkrementującą komórkę #3. Tu jednak pojawia się problem: w chwili zakończenia -wewnętrznej pętli komórka #2 ma wartość zero. W takim razie wewętrzna pętla -nie wywoła się następny raz. Aby rozwiązać ten problem, inkrementujemy także -wartość komórki #4, a następnie kopiujemy jej wartość do komórki #2. -Ostatecznie wynik działania znajduje się w komórce #3. -``` - -I to właśnie jest brainfuck. Nie taki trudny, co? W ramach rozrywki możesz -napisać własne programy w brainfucku. Możesz też napisać interpreter brainfucka -w innym języku. Implementacja interpretera to dość proste zadanie. Jeśli -jesteś masochistą, spróbuj napisać interpreter brainfucka w... brainfucku. diff --git a/pt-br/bf.html.markdown b/pt-br/bf.html.markdown new file mode 100644 index 00000000..d6d7c6e9 --- /dev/null +++ b/pt-br/bf.html.markdown @@ -0,0 +1,85 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Suzane Sant Ana", "http://github.com/suuuzi"] + - ["Rodrigo Muniz", "http://github.com/muniz95"] +lang: pt-br +--- + +Brainfuck (em letras minúsculas, exceto no início de frases) é uma linguagem de +programação Turing-completa extremamente simples com apenas 8 comandos. + +``` +Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. + +Brainfuck é representado por um vetor com 30 000 células inicializadas em zero +e um ponteiro de dados que aponta para a célula atual. + +Existem 8 comandos: ++ : Incrementa o valor da célula atual em 1. +- : Decrementa o valor da célula atual em 1. +> : Move o ponteiro de dados para a célula seguinte (célula à direita). +< : Move o ponteiro de dados para a célula anterior (célula à esquerda). +. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A'). +, : Lê um único caractere para a célula atual. +[ : Se o valor da célula atual for zero, salta para o ] correspondente. + Caso contrário, passa para a instrução seguinte. +] : Se o valor da célula atual for zero, passa para a instrução seguinte. + Caso contrário, volta para a instrução relativa ao [ correspondente. + +[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. + +Vamos ver alguns exemplos básicos em brainfuck: + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. +A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se +o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10 +vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se +a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para +a célula #1 chegar a 0, momento em que se salta para o ] correspondente, +continuando com a instrução seguinte). + +Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2 +tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 +vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor +65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal. + +, [ > + < - ] > . + +Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é +iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na +célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente +decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser +igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de +dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a +célula #2 e imprimimos o valor em ASCII. + +Os espaços servem apenas para tornar o programa mais legível. Podemos escrever +o mesmo programa da seguinte maneira: + +,[>+<-]>. + +Tente descobrir o que este programa faz: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa lê dois números e os multiplica. + +Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um +ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados +para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula +#2, incrementando o valor da célula #3. Porém existe um problema, no final do +ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da +célula #4 é também incrementado e copiado para a célula #2. +``` + +E isto é brainfuck. Simples, não? Por divertimento você pode escrever os +seus próprios programas em brainfuck, ou então escrever um interpretador de +brainfuck em outra linguagem. O interpretador é relativamente fácil de se +implementar, mas caso você seja masoquista, tente escrever um interpretador de +brainfuck… em brainfuck. diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/brainfuck-pt.html.markdown deleted file mode 100644 index 9e4b458d..00000000 --- a/pt-br/brainfuck-pt.html.markdown +++ /dev/null @@ -1,85 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Suzane Sant Ana", "http://github.com/suuuzi"] - - ["Rodrigo Muniz", "http://github.com/muniz95"] -lang: pt-br ---- - -Brainfuck (em letras minúsculas, exceto no início de frases) é uma linguagem de -programação Turing-completa extremamente simples com apenas 8 comandos. - -``` -Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. - -Brainfuck é representado por um vetor com 30 000 células inicializadas em zero -e um ponteiro de dados que aponta para a célula atual. - -Existem 8 comandos: -+ : Incrementa o valor da célula atual em 1. -- : Decrementa o valor da célula atual em 1. -> : Move o ponteiro de dados para a célula seguinte (célula à direita). -< : Move o ponteiro de dados para a célula anterior (célula à esquerda). -. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A'). -, : Lê um único caractere para a célula atual. -[ : Se o valor da célula atual for zero, salta para o ] correspondente. - Caso contrário, passa para a instrução seguinte. -] : Se o valor da célula atual for zero, passa para a instrução seguinte. - Caso contrário, volta para a instrução relativa ao [ correspondente. - -[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. - -Vamos ver alguns exemplos básicos em brainfuck: - -++++++ [ > ++++++++++ < - ] > +++++ . - -Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. -A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se -o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10 -vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se -a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para -a célula #1 chegar a 0, momento em que se salta para o ] correspondente, -continuando com a instrução seguinte). - -Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2 -tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 -vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor -65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal. - -, [ > + < - ] > . - -Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é -iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na -célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente -decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser -igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de -dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a -célula #2 e imprimimos o valor em ASCII. - -Os espaços servem apenas para tornar o programa mais legível. Podemos escrever -o mesmo programa da seguinte maneira: - -,[>+<-]>. - -Tente descobrir o que este programa faz: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Este programa lê dois números e os multiplica. - -Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um -ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados -para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula -#2, incrementando o valor da célula #3. Porém existe um problema, no final do -ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da -célula #4 é também incrementado e copiado para a célula #2. -``` - -E isto é brainfuck. Simples, não? Por divertimento você pode escrever os -seus próprios programas em brainfuck, ou então escrever um interpretador de -brainfuck em outra linguagem. O interpretador é relativamente fácil de se -implementar, mas caso você seja masoquista, tente escrever um interpretador de -brainfuck… em brainfuck. diff --git a/pt-pt/bf.html.markdown b/pt-pt/bf.html.markdown new file mode 100644 index 00000000..da4c787f --- /dev/null +++ b/pt-pt/bf.html.markdown @@ -0,0 +1,84 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Joao Marques", "http://github.com/mrshankly"] +lang: pt-pt +--- + +Brainfuck (não capitalizado excepto no início de uma frase) é uma linguagem de +programação Turing-completa extremamente simples com apenas 8 comandos. + +``` +Qualquer caractere excepto "><+-.,[]" (não contar com as aspas) é ignorado. + +Brainfuck é representado por um vector com 30 000 células inicializadas a zero +e um ponteiro de dados que aponta para a célula actual. + +Existem 8 comandos: ++ : Incrementa o valor da célula actual em 1. +- : Decrementa o valor da célula actual em 1. +> : Move o ponteiro de dados para a célula seguinte (célula à direita). +< : Move o ponteiro de dados para a célula anterior (célula à esquerda). +. : Imprime o valor ASCII da célula actual. (ex. 65 = 'A'). +, : Lê um único caractere para a célula actual. +[ : Se o valor da célula actual for zero, salta para o ] correspondente. + Caso contrário, passa para a instrução seguinte. +] : Se o valor da célula actual for zero, passa para a instrução seguinte. + Caso contrário, volta para a instrução relativa ao [ correspondente. + +[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. + +Vejamos alguns programas básicos de brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. +A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se +o ponteiro de dados para a célula #2. Incrementa-se o valor da célula #2 10 +vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se +a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para +a célula #1 chegar a 0, momento em que se salta para o ] correspondente, +continuando com a instrução seguinte). + +Nesta altura encontramo-nos na célula #1, cujo valor é 0, enquanto a célula #2 +tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 +vezes para um valor final de 65, é então impresso o valor da célula #2. Ao valor +65 corresponde o caractere 'A' em ASCII, 'A' é então impresso para o terminal. + +, [ > + < - ] > . + +Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é +iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na +célula #2, movemos o ponteiro de dados de volta para a célula #1, finalmente +decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser +igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de +dados está a apontar para a célula #1 no fim do ciclo, movemos o ponteiro para a +célula #2 e imprimimos o valor em ASCII. + +Os espaços servem apenas para tornar o programa mais legível. Podemos escrever +o mesmo programa da seguinte maneira: + +,[>+<-]>. + +Tenta descobrir o que este programa faz: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa lê dois números e multiplica-os. + +Basicamente o programa pede dois caracteres ao utilizador. Depois é iniciado um +ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados +para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula +#2, incrementando o valor da célula #3. Contudo, existe um problema, no final do +ciclo interior a célula #2 tem o valor 0. Para resolver este problema o valor da +célula #4 é também incrementado e copiado para a célula #2. +``` + +Fica então explicado brainfuck. Simples, não? Por divertimento podes escrever os +teus próprios programas em brainfuck, ou então escrever um interpretador de +brainfuck noutra linguagem. O interpretador é relativamente fácil de se +implementar, mas se fores masoquista, tenta escrever um interpretador de +brainfuck… em brainfuck. diff --git a/pt-pt/brainfuck-pt.html.markdown b/pt-pt/brainfuck-pt.html.markdown deleted file mode 100644 index da4c787f..00000000 --- a/pt-pt/brainfuck-pt.html.markdown +++ /dev/null @@ -1,84 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Joao Marques", "http://github.com/mrshankly"] -lang: pt-pt ---- - -Brainfuck (não capitalizado excepto no início de uma frase) é uma linguagem de -programação Turing-completa extremamente simples com apenas 8 comandos. - -``` -Qualquer caractere excepto "><+-.,[]" (não contar com as aspas) é ignorado. - -Brainfuck é representado por um vector com 30 000 células inicializadas a zero -e um ponteiro de dados que aponta para a célula actual. - -Existem 8 comandos: -+ : Incrementa o valor da célula actual em 1. -- : Decrementa o valor da célula actual em 1. -> : Move o ponteiro de dados para a célula seguinte (célula à direita). -< : Move o ponteiro de dados para a célula anterior (célula à esquerda). -. : Imprime o valor ASCII da célula actual. (ex. 65 = 'A'). -, : Lê um único caractere para a célula actual. -[ : Se o valor da célula actual for zero, salta para o ] correspondente. - Caso contrário, passa para a instrução seguinte. -] : Se o valor da célula actual for zero, passa para a instrução seguinte. - Caso contrário, volta para a instrução relativa ao [ correspondente. - -[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. - -Vejamos alguns programas básicos de brainfuck. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. -A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se -o ponteiro de dados para a célula #2. Incrementa-se o valor da célula #2 10 -vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se -a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para -a célula #1 chegar a 0, momento em que se salta para o ] correspondente, -continuando com a instrução seguinte). - -Nesta altura encontramo-nos na célula #1, cujo valor é 0, enquanto a célula #2 -tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 -vezes para um valor final de 65, é então impresso o valor da célula #2. Ao valor -65 corresponde o caractere 'A' em ASCII, 'A' é então impresso para o terminal. - -, [ > + < - ] > . - -Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é -iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na -célula #2, movemos o ponteiro de dados de volta para a célula #1, finalmente -decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser -igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de -dados está a apontar para a célula #1 no fim do ciclo, movemos o ponteiro para a -célula #2 e imprimimos o valor em ASCII. - -Os espaços servem apenas para tornar o programa mais legível. Podemos escrever -o mesmo programa da seguinte maneira: - -,[>+<-]>. - -Tenta descobrir o que este programa faz: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Este programa lê dois números e multiplica-os. - -Basicamente o programa pede dois caracteres ao utilizador. Depois é iniciado um -ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados -para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula -#2, incrementando o valor da célula #3. Contudo, existe um problema, no final do -ciclo interior a célula #2 tem o valor 0. Para resolver este problema o valor da -célula #4 é também incrementado e copiado para a célula #2. -``` - -Fica então explicado brainfuck. Simples, não? Por divertimento podes escrever os -teus próprios programas em brainfuck, ou então escrever um interpretador de -brainfuck noutra linguagem. O interpretador é relativamente fácil de se -implementar, mas se fores masoquista, tenta escrever um interpretador de -brainfuck… em brainfuck. diff --git a/ru-ru/bf.html.markdown b/ru-ru/bf.html.markdown new file mode 100644 index 00000000..20f0fa56 --- /dev/null +++ b/ru-ru/bf.html.markdown @@ -0,0 +1,85 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] +lang: ru-ru +--- + +Brainfuck (пишется маленькими буквами, кроме начала предложения) - это очень +маленький Тьюринг-полный язык программирования лишь с 8 командами. + +Вы можете испытать brainfuck в вашем браузере с помощью [brainfuck-визуализатора](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Любой символ, кроме "><+-.,[]", игнорируется, за исключением кавычек. + +Brainfuck представлен массивом из 30000 ячеек, инициализированных нулями, +и указателем с позицией в текущей ячейке. + +Всего восемь команд: ++ : Увеличивает значение на единицу в текущей ячейке. +- : Уменьшает значение на единицу в текущей ячейке. +> : Смещает указатель данных на следующую ячейку (ячейку справа). +< : Смещает указатель данных на предыдущую ячейку (ячейку слева). +. : Печатает ASCII символ из текущей ячейки (напр. 65 = 'A'). +, : Записывает один входной символ в текущую ячейку. +[ : Если значение в текущей ячейке равно нулю, то пропустить все команды + до соответствующей ] . В противном случае, перейти к следующей инструкции. +] : Если значение в текущей ячейке равно нулю, то перейти к следующей инструкции. + В противном случае, вернуться назад к соответствующей [ . + +[ и ] образуют цикл while. Естественно, они должны быть сбалансированы. + +Давайте рассмотрим некоторые базовые brainfuck-программы. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Эта программа выводит букву 'A'. Сначала программа увеличивает значение +ячейки №1 до 6. Ячейка №1 будет использоваться циклом. Затем программа входит +в цикл ([) и переходит к ячейке №2. Ячейка №2 увеличивается до 10, переходим +назад к ячейке №1 и уменьшаем ячейку №1. Этот цикл проходит 6 раз (ячейка №1 +уменьшается до нуля, и с этого места пропускает инструкции до соответствующей ] +и идет дальше). + +В этот момент мы находимся в ячейке №1, которая имеет значение 0, значение +ячейки №2 пока 60. Мы переходим на ячейку №2, увеличиваем 5 раз, до значения 65, +и затем выводим значение ячейки №2. Код 65 является символом 'A' в кодировке ASCII, +так что 'A' выводится на терминал. + + +, [ > + < - ] > . + +Данная программа считывает символ из пользовательского ввода и копирует символ +в ячейку №1. Затем мы начинаем цикл. Переходим к ячейке №2, увеличиваем значение +ячейки №2, идем назад к ячейке №1 и уменьшаем значение ячейки №1. Это продолжается +до тех пор, пока ячейка №1 не равна 0, а ячейка №2 сохраняет старое значение +ячейки №1. Мы завершаем цикл на ячейке №1, поэтому переходим в ячейку №2 и +затем выводим символ ASCII. + +Также имейте в виду, что пробелы здесь исключительно для читабельности. Вы можете +легко написать и так: + +,[>+<-]>. + +Попытайтесь разгадать, что следующая программа делает: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Программа принимает два числа на вход и умножает их. + +Суть в том, что программа сначала читает два ввода. Затем начинается внешний цикл, +сохраняя ячейку №1. Затем программа перемещается в ячейку №2, и начинается +внутренний цикл с сохранением ячейки №2, увеличивая ячейку №3. Однако появляется +проблема: В конце внутреннего цикла ячейка №2 равна нулю. В этом случае, +внутренний цикл не будет работать уже в следующий раз. Чтобы решить эту проблему, +мы также увеличим ячейку №4, а затем копируем ячейку №4 в ячейку №2. +Итак, ячейка №3 - результат. +``` + +Это и есть brainfuck. Не так уж сложно, правда? Забавы ради, вы можете написать +свою собственную brainfuck-программу или интерпретатор на другом языке. +Интерпретатор достаточно легко реализовать, но если вы мазохист, попробуйте +написать brainfuck-интерпретатор... на языке brainfuck. diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/brainfuck-ru.html.markdown deleted file mode 100644 index fcee185f..00000000 --- a/ru-ru/brainfuck-ru.html.markdown +++ /dev/null @@ -1,85 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Dmitry Bessonov", "https://github.com/TheDmitry"] -lang: ru-ru ---- - -Brainfuck (пишется маленькими буквами, кроме начала предложения) - это очень -маленький Тьюринг-полный язык программирования лишь с 8 командами. - -Вы можете испытать brainfuck в вашем браузере с помощью [brainfuck-визуализатора](http://fatiherikli.github.io/brainfuck-visualizer/). - -``` -Любой символ, кроме "><+-.,[]", игнорируется, за исключением кавычек. - -Brainfuck представлен массивом из 30000 ячеек, инициализированных нулями, -и указателем с позицией в текущей ячейке. - -Всего восемь команд: -+ : Увеличивает значение на единицу в текущей ячейке. -- : Уменьшает значение на единицу в текущей ячейке. -> : Смещает указатель данных на следующую ячейку (ячейку справа). -< : Смещает указатель данных на предыдущую ячейку (ячейку слева). -. : Печатает ASCII символ из текущей ячейки (напр. 65 = 'A'). -, : Записывает один входной символ в текущую ячейку. -[ : Если значение в текущей ячейке равно нулю, то пропустить все команды - до соответствующей ] . В противном случае, перейти к следующей инструкции. -] : Если значение в текущей ячейке равно нулю, то перейти к следующей инструкции. - В противном случае, вернуться назад к соответствующей [ . - -[ и ] образуют цикл while. Естественно, они должны быть сбалансированы. - -Давайте рассмотрим некоторые базовые brainfuck-программы. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Эта программа выводит букву 'A'. Сначала программа увеличивает значение -ячейки №1 до 6. Ячейка №1 будет использоваться циклом. Затем программа входит -в цикл ([) и переходит к ячейке №2. Ячейка №2 увеличивается до 10, переходим -назад к ячейке №1 и уменьшаем ячейку №1. Этот цикл проходит 6 раз (ячейка №1 -уменьшается до нуля, и с этого места пропускает инструкции до соответствующей ] -и идет дальше). - -В этот момент мы находимся в ячейке №1, которая имеет значение 0, значение -ячейки №2 пока 60. Мы переходим на ячейку №2, увеличиваем 5 раз, до значения 65, -и затем выводим значение ячейки №2. Код 65 является символом 'A' в кодировке ASCII, -так что 'A' выводится на терминал. - - -, [ > + < - ] > . - -Данная программа считывает символ из пользовательского ввода и копирует символ -в ячейку №1. Затем мы начинаем цикл. Переходим к ячейке №2, увеличиваем значение -ячейки №2, идем назад к ячейке №1 и уменьшаем значение ячейки №1. Это продолжается -до тех пор, пока ячейка №1 не равна 0, а ячейка №2 сохраняет старое значение -ячейки №1. Мы завершаем цикл на ячейке №1, поэтому переходим в ячейку №2 и -затем выводим символ ASCII. - -Также имейте в виду, что пробелы здесь исключительно для читабельности. Вы можете -легко написать и так: - -,[>+<-]>. - -Попытайтесь разгадать, что следующая программа делает: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Программа принимает два числа на вход и умножает их. - -Суть в том, что программа сначала читает два ввода. Затем начинается внешний цикл, -сохраняя ячейку №1. Затем программа перемещается в ячейку №2, и начинается -внутренний цикл с сохранением ячейки №2, увеличивая ячейку №3. Однако появляется -проблема: В конце внутреннего цикла ячейка №2 равна нулю. В этом случае, -внутренний цикл не будет работать уже в следующий раз. Чтобы решить эту проблему, -мы также увеличим ячейку №4, а затем копируем ячейку №4 в ячейку №2. -Итак, ячейка №3 - результат. -``` - -Это и есть brainfuck. Не так уж сложно, правда? Забавы ради, вы можете написать -свою собственную brainfuck-программу или интерпретатор на другом языке. -Интерпретатор достаточно легко реализовать, но если вы мазохист, попробуйте -написать brainfuck-интерпретатор... на языке brainfuck. diff --git a/tr-tr/bf-tr.html.markdown b/tr-tr/bf-tr.html.markdown new file mode 100644 index 00000000..e7015cd0 --- /dev/null +++ b/tr-tr/bf-tr.html.markdown @@ -0,0 +1,87 @@ +--- +language: bf +filename: brainfuck-tr +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io"] +translators: + - ["Haydar KULEKCI", "http://scanf.info/"] +lang: tr-tr +--- + +Brainfuck (normalde brainfuck olarak bütün harfleri küçük olarak yazılır.) +son derece minimal bir programlama dilidir. (Sadece 8 komut) ve tamamen +Turing'dir. + +``` +"><+-.,[]" (tırnak işaretleri hariç) karakterleri dışındaki her karakter +gözardı edilir. + +Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir +dizidir. İşaretçi ilk hücreyi işaret eder. + +Sekiz komut vardır: ++ : Geçerli hücrenin değerini bir artırır. +- : Geçerli hücrenin değerini bir azaltır. +> : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye). +< : Veri işaretçisini bir önceki hücreye hareket ettirir(soldaki hücreye). +. : Geçerli hücrenin ASCII değerini yazdırır (örn: 65 = 'A'). +, : Bir girdilik karakteri aktif hücre için okur. +[ : Eğer geçerli hücredeki değer sıfır ise, ]ifadesine atlar. + Diğer durumlarda bir sonraki yönergeye geçer. +] : Eğer geçerli hücredeki değer sıfır ise, bir sonraki yönergeye geçer. + Diğer durumlarda, [ ifadesine karşılık gelen yönergelere döner. + +[ ve ] bir while döngüsü oluşturur. Açıkça, dengeli olmalıdırlar. + +Basit bir brainfuck programına göz atalım. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Bu program 'A' karaterini ekrana basar. İlk olarak, #1'inci hücre 6'ya artırılır. +#1'inci hücre döngü için kullanılacaktır. Sonra, ([) döngüsüne girilir ve +#2'inci hücreye hareket edilir. #2'inci hücre 10 kez artırılır, #1'inci hücreye +geri dönülür. #1 hücresini bir azaltır. Bu döngü 6 kez gerçekleşir. (Bu 6 kez +azaltmak demektir, #1 hücresi 0 değerini alır ve bu noktada ] ifadesini atlar). + +Bu noktada, biz #1 hücresindeyiz, değeri şu anda 0 ve #2 hücresinin değeri +60'tır. Biz #2 hücresine hareket diyoruz ve bu hücreyi 5 defa artırıyoruz. +#2'nin şu anki değeri 65 olur. Sonra #2 hücresinin ASCII karşılığını +yazdırıyoruz. 65 değerinin ASCII karşılığı 'A'dır. Ekrana 'A' yazılacaktır. + + +, [ > + < - ] > . + +Bu program kullanıcıdan bir girdi okur, ve karakteri bir diğer hücreye yazdırır, +ve daha sonra aynı karakteri ekrana yazdırır. + +, ifadesi kullanıcıdan karakteri #1 hücresine okur. Sonra bir döngü +başlar. #2 hücresine hareket edilir, #2 hücresinin değeri bir artırılır, #1 +hücresine geri dönülür, ve #1 hücresinin değer bir azaltılır. Bu #1 hücresinin +değeri 0 olana kadar devam eder ve #2 hücresi #1'in eski değerini tutar. Çünkü +biz #1 hücresindeki verileri döngü süresince #2 hücresine taşıyoruz, ve sonunda +#2 hücresinin ASCII değerini yazdırıyoruz. + +Boşluk karakteri sadece okunabilirliği artırmak içindir. Aşağıdaki gibi de +yazabilirsiniz. + +,[>+<-]>. + + +Bu uygulamanın ne yaptığına bakalım: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Bu program 2 sayı alır, ve birbiri ile çarpar. + +Özetle, ilk olarak iki girdi alır. Sonra, #1 hücresinde şarta bağlı harici bir +döngü başlar. Sonra #2 ye hareket edilir, ve içerde #2 hücresine bağlı bir döngü +daha başlar ve #3 hücresinin değerini artırır. Ama, Bir problem vardır: iç +döngünün sonunda #2'inci hücrenin değeri 0 olacaktır. Bunu çözmek için #4 +hücresinin de değerini yükseltiyoruz, ve sonra #4 hücresinin değerini #2'ye +kopyalıyoruz. +``` + +İşte brainfuck. Zor değil değil mi? Eğlenmek için kendi programınızı +yazabilirsiniz, veya farklı bir dilde brainfuck yorumlayıcısı yazabilirsiniz. +Yorumlayıcı oldukça basittir, ama mazoşist iseniz, brainfuck içerisinde bir +brainfuck yorumlayıcısı yazmayı deneyebilirsiniz. diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/brainfuck-tr.html.markdown deleted file mode 100644 index bd842b17..00000000 --- a/tr-tr/brainfuck-tr.html.markdown +++ /dev/null @@ -1,87 +0,0 @@ ---- -language: brainfuck -filename: brainfuck-tr -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io"] -translators: - - ["Haydar KULEKCI", "http://scanf.info/"] -lang: tr-tr ---- - -Brainfuck (normalde brainfuck olarak bütün harfleri küçük olarak yazılır.) -son derece minimal bir programlama dilidir. (Sadece 8 komut) ve tamamen -Turing'dir. - -``` -"><+-.,[]" (tırnak işaretleri hariç) karakterleri dışındaki her karakter -gözardı edilir. - -Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir -dizidir. İşaretçi ilk hücreyi işaret eder. - -Sekiz komut vardır: -+ : Geçerli hücrenin değerini bir artırır. -- : Geçerli hücrenin değerini bir azaltır. -> : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye). -< : Veri işaretçisini bir önceki hücreye hareket ettirir(soldaki hücreye). -. : Geçerli hücrenin ASCII değerini yazdırır (örn: 65 = 'A'). -, : Bir girdilik karakteri aktif hücre için okur. -[ : Eğer geçerli hücredeki değer sıfır ise, ]ifadesine atlar. - Diğer durumlarda bir sonraki yönergeye geçer. -] : Eğer geçerli hücredeki değer sıfır ise, bir sonraki yönergeye geçer. - Diğer durumlarda, [ ifadesine karşılık gelen yönergelere döner. - -[ ve ] bir while döngüsü oluşturur. Açıkça, dengeli olmalıdırlar. - -Basit bir brainfuck programına göz atalım. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Bu program 'A' karaterini ekrana basar. İlk olarak, #1'inci hücre 6'ya artırılır. -#1'inci hücre döngü için kullanılacaktır. Sonra, ([) döngüsüne girilir ve -#2'inci hücreye hareket edilir. #2'inci hücre 10 kez artırılır, #1'inci hücreye -geri dönülür. #1 hücresini bir azaltır. Bu döngü 6 kez gerçekleşir. (Bu 6 kez -azaltmak demektir, #1 hücresi 0 değerini alır ve bu noktada ] ifadesini atlar). - -Bu noktada, biz #1 hücresindeyiz, değeri şu anda 0 ve #2 hücresinin değeri -60'tır. Biz #2 hücresine hareket diyoruz ve bu hücreyi 5 defa artırıyoruz. -#2'nin şu anki değeri 65 olur. Sonra #2 hücresinin ASCII karşılığını -yazdırıyoruz. 65 değerinin ASCII karşılığı 'A'dır. Ekrana 'A' yazılacaktır. - - -, [ > + < - ] > . - -Bu program kullanıcıdan bir girdi okur, ve karakteri bir diğer hücreye yazdırır, -ve daha sonra aynı karakteri ekrana yazdırır. - -, ifadesi kullanıcıdan karakteri #1 hücresine okur. Sonra bir döngü -başlar. #2 hücresine hareket edilir, #2 hücresinin değeri bir artırılır, #1 -hücresine geri dönülür, ve #1 hücresinin değer bir azaltılır. Bu #1 hücresinin -değeri 0 olana kadar devam eder ve #2 hücresi #1'in eski değerini tutar. Çünkü -biz #1 hücresindeki verileri döngü süresince #2 hücresine taşıyoruz, ve sonunda -#2 hücresinin ASCII değerini yazdırıyoruz. - -Boşluk karakteri sadece okunabilirliği artırmak içindir. Aşağıdaki gibi de -yazabilirsiniz. - -,[>+<-]>. - - -Bu uygulamanın ne yaptığına bakalım: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Bu program 2 sayı alır, ve birbiri ile çarpar. - -Özetle, ilk olarak iki girdi alır. Sonra, #1 hücresinde şarta bağlı harici bir -döngü başlar. Sonra #2 ye hareket edilir, ve içerde #2 hücresine bağlı bir döngü -daha başlar ve #3 hücresinin değerini artırır. Ama, Bir problem vardır: iç -döngünün sonunda #2'inci hücrenin değeri 0 olacaktır. Bunu çözmek için #4 -hücresinin de değerini yükseltiyoruz, ve sonra #4 hücresinin değerini #2'ye -kopyalıyoruz. -``` - -İşte brainfuck. Zor değil değil mi? Eğlenmek için kendi programınızı -yazabilirsiniz, veya farklı bir dilde brainfuck yorumlayıcısı yazabilirsiniz. -Yorumlayıcı oldukça basittir, ama mazoşist iseniz, brainfuck içerisinde bir -brainfuck yorumlayıcısı yazmayı deneyebilirsiniz. diff --git a/zh-cn/bf-cn.html.markdown b/zh-cn/bf-cn.html.markdown new file mode 100644 index 00000000..6cea3012 --- /dev/null +++ b/zh-cn/bf-cn.html.markdown @@ -0,0 +1,70 @@ +--- +language: bf +lang: zh-cn +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["lyuehh", "https://github.com/lyuehh"] +--- + +Brainfuck 是一个极小的只有8个指令的图灵完全的编程语言。 + +``` +除"><+-.,[]"之外的的任何字符都会被忽略 (不包含双引号)。 + +Brainfuck 包含一个有30,000个单元为0的数组,和 +一个数据指针指向当前的单元。 + +8个指令如下: ++ : 指针指向的单元的值加1 +- : 指针指向的单元的值减1 +> : 将指针移动到下一个单元(右边的元素) +< : 将指针移动到上一个单元(左边的元素) +. : 打印当前单元的内容的ASCII值 (比如 65 = 'A'). +, : 读取一个字符到当前的单元 +[ : 如果当前单元的值是0,则向后调转到对应的]处 +] : 如果当前单元的值不是0,则向前跳转到对应的[处 + +[ 和 ] 组成了一个while循环。很明显,它们必须配对。 + +让我们看一些基本的brainfuck 程序。 + +++++++ [ > ++++++++++ < - ] > +++++ . + +这个程序打印字母'A'。首先,它把 #1 增加到6,使用它来作为循环条件, +然后,进入循环,将指针移动到 #2 ,将 #2 的值增加到10,然后 +移动回 #1,将单元 #1 的值减1,然后继续。循环共进行了6次。 + +这时,我们在 #1,它的值为0,#2 的值为60,我们移动到 +#2,将 #2 的内容加上5,然后将 #2 的内容打印出来,65在 +ASCII中表示'A', 所以'A'就会被打印出来。 + + +, [ > + < - ] > . + +这个程序从用户的输入中读取一个字符,然后把它复制到 #1。 +然后我们开始一个循环,移动到 #2,将 #2 的值加1,再移动回 #1,将 #1 +的值减1,直到 #1的值为0,这样 #2 里就保存了 #1 的旧值,循环结束时我们 +在 #1,这时我们移动到 #2,然后把字符以ASCII打印出来。 + +而且要记住的一点就是,空格在这里只是为了可读性,你可以将他们写成这样: + +,[>+<-]>. + +试着思考一下这段程序是干什么的: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +这段程序从输入接收2个参数,然后将他们相乘。 + +先读取2个输入,然后开始外层循环,以 #1 作为终止条件,然后将指针移动到 +#2,然后开始 #2 的内层循环,将 #3 加1。但是这里有一个小问题,在内层 +循环结束的时候,#2 的值是0了,那么下次执行外层循环的时候,就有问题了。 +为了解决这个问题,我们可以增加 #4 的值,然后把 #4 的值复制到 #2, +最后结果就保存在 #3 中了。 +``` +好了这就是brainfuck了。也没那么难,是吧?为了好玩,你可以写你自己的 +brainfuck程序,或者用其他语言写一个brainfuck的解释器,解释器非常容易 +实现,但是如果你是一个自虐狂的话,你可以尝试用brainfuck写一个brainfuk的 +解释器。 diff --git a/zh-cn/brainfuck-cn.html.markdown b/zh-cn/brainfuck-cn.html.markdown deleted file mode 100644 index a6f3fa09..00000000 --- a/zh-cn/brainfuck-cn.html.markdown +++ /dev/null @@ -1,70 +0,0 @@ ---- -language: brainfuck -lang: zh-cn -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["lyuehh", "https://github.com/lyuehh"] ---- - -Brainfuck 是一个极小的只有8个指令的图灵完全的编程语言。 - -``` -除"><+-.,[]"之外的的任何字符都会被忽略 (不包含双引号)。 - -Brainfuck 包含一个有30,000个单元为0的数组,和 -一个数据指针指向当前的单元。 - -8个指令如下: -+ : 指针指向的单元的值加1 -- : 指针指向的单元的值减1 -> : 将指针移动到下一个单元(右边的元素) -< : 将指针移动到上一个单元(左边的元素) -. : 打印当前单元的内容的ASCII值 (比如 65 = 'A'). -, : 读取一个字符到当前的单元 -[ : 如果当前单元的值是0,则向后调转到对应的]处 -] : 如果当前单元的值不是0,则向前跳转到对应的[处 - -[ 和 ] 组成了一个while循环。很明显,它们必须配对。 - -让我们看一些基本的brainfuck 程序。 - -++++++ [ > ++++++++++ < - ] > +++++ . - -这个程序打印字母'A'。首先,它把 #1 增加到6,使用它来作为循环条件, -然后,进入循环,将指针移动到 #2 ,将 #2 的值增加到10,然后 -移动回 #1,将单元 #1 的值减1,然后继续。循环共进行了6次。 - -这时,我们在 #1,它的值为0,#2 的值为60,我们移动到 -#2,将 #2 的内容加上5,然后将 #2 的内容打印出来,65在 -ASCII中表示'A', 所以'A'就会被打印出来。 - - -, [ > + < - ] > . - -这个程序从用户的输入中读取一个字符,然后把它复制到 #1。 -然后我们开始一个循环,移动到 #2,将 #2 的值加1,再移动回 #1,将 #1 -的值减1,直到 #1的值为0,这样 #2 里就保存了 #1 的旧值,循环结束时我们 -在 #1,这时我们移动到 #2,然后把字符以ASCII打印出来。 - -而且要记住的一点就是,空格在这里只是为了可读性,你可以将他们写成这样: - -,[>+<-]>. - -试着思考一下这段程序是干什么的: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -这段程序从输入接收2个参数,然后将他们相乘。 - -先读取2个输入,然后开始外层循环,以 #1 作为终止条件,然后将指针移动到 -#2,然后开始 #2 的内层循环,将 #3 加1。但是这里有一个小问题,在内层 -循环结束的时候,#2 的值是0了,那么下次执行外层循环的时候,就有问题了。 -为了解决这个问题,我们可以增加 #4 的值,然后把 #4 的值复制到 #2, -最后结果就保存在 #3 中了。 -``` -好了这就是brainfuck了。也没那么难,是吧?为了好玩,你可以写你自己的 -brainfuck程序,或者用其他语言写一个brainfuck的解释器,解释器非常容易 -实现,但是如果你是一个自虐狂的话,你可以尝试用brainfuck写一个brainfuk的 -解释器。 -- cgit v1.2.3 From f3b10beb01795bf7513ec8d06c9e90ab98df7a83 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 12 Feb 2016 23:04:31 -0800 Subject: Clean up various errors --- edn.html.markdown | 2 +- fr-fr/HTML-fr.html.markdown | 3 +- fr-fr/d.html.markdown | 12 +- fr-fr/make-fr.html.markdown | 4 +- fr-fr/objective-c-fr.html.markdown | 3 +- hu-hu/ruby-hu.html.markdown | 4 +- less.html.markdown | 2 +- nim.html.markdown | 2 +- nl-nl/amd-nl.html.markdown | 235 ------------------------------------- ru-ru/d-ru.html.markdown | 3 +- ta_in/css-ta.html.markdown | 6 +- ta_in/javascript-ta.html.markdown | 4 +- ta_in/xml-ta.html.markdown | 4 +- 13 files changed, 25 insertions(+), 259 deletions(-) delete mode 100644 nl-nl/amd-nl.html.markdown diff --git a/edn.html.markdown b/edn.html.markdown index d0bdddfc..ca04df89 100644 --- a/edn.html.markdown +++ b/edn.html.markdown @@ -14,7 +14,7 @@ Clojure, there are implementations of EDN for many other languages. The main benefit of EDN over JSON and YAML is that it is extensible. We will see how it is extended later on. -```Clojure +```clojure ; Comments start with a semicolon. ; Anything after the semicolon is ignored. diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown index fdde9107..4d2da921 100644 --- a/fr-fr/HTML-fr.html.markdown +++ b/fr-fr/HTML-fr.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] lang: fr-fr --- + HTML signifie HyperText Markup Language. C'est un langage (format de fichiers) qui permet d'écrire des pages internet. C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). @@ -17,7 +18,7 @@ Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parl Cet article porte principalement sur la syntaxe et quelques astuces. -```HTML +```html diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index d9bd9b48..bfb9f2ce 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -8,7 +8,7 @@ translators: lang: fr-fr --- -```d +```c // Commençons par un classique module hello; @@ -30,7 +30,7 @@ D est activement développé par de nombreuses personnes très intelligents, gui [Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). Après cette petite introduction, jetons un coup d'oeil à quelques exemples. -```d +```c import std.stdio; void main() { @@ -75,7 +75,7 @@ On peut définir de nouveaux types avec les mots-clés `struct`, `class`, `union` et `enum`. Ces types sont passés au fonction par valeur (ils sont copiés) De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. -```d +```c // Ici, 'T' est un paramètre de type. Il est similaire au de C++/C#/Java. struct LinkedList(T) { T data = null; @@ -140,7 +140,7 @@ une méthode qui peut se comporter comme une lvalue. On peut donc utiliser la syntaxe des structures classiques (`struct.x = 7`) comme si il s'agissait de méthodes getter ou setter. -```d +```c // Considérons une classe paramétrée avec les types 'T' et 'U' class MyClass(T, U) { T _data; @@ -212,7 +212,7 @@ de premier ordre, les fonctions `pure` et les données immuables. De plus, tout vos algorithmes fonctionelles favoris (map, reduce, filter) sont disponibles dans le module `std.algorithm`. -```d +```c import std.algorithm : map, filter, reduce; import std.range : iota; // construit un intervalle excluant la dernière valeur. @@ -242,7 +242,7 @@ est de type A, comme si c'était une méthode de A. J'aime le parallélisme. Vous aimez les parallélisme ? Bien sur que vous aimez ça Voyons comment on le fait en D ! -```d +```c import std.stdio; import std.parallelism : parallel; import std.math : sqrt; diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 5a1e03e7..48d24549 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -1,9 +1,9 @@ --- language: make contributors: - - ["Robert Steed", "https://github.com/robochat"] + - ["Robert Steed", "https://github.com/robochat"] translators: - - ["altaris", "https://github.com/altaris"] + - ["altaris", "https://github.com/altaris"] filename: Makefile-fr lang: fr-fr --- diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index 4e31c4bf..fbe1741e 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -1,5 +1,4 @@ --- - language: Objective-C contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] @@ -9,7 +8,6 @@ translators: - ["Yannick Loriot", "https://github.com/YannickL"] filename: LearnObjectiveC-fr.m lang: fr-fr - --- L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch. @@ -519,6 +517,7 @@ __unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais la variable n'es // l'objet est supprimé ``` + ## Lectures Complémentaires [La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C) diff --git a/hu-hu/ruby-hu.html.markdown b/hu-hu/ruby-hu.html.markdown index 169f2b8e..f2fe4e5d 100644 --- a/hu-hu/ruby-hu.html.markdown +++ b/hu-hu/ruby-hu.html.markdown @@ -1,7 +1,7 @@ --- language: ruby lang: hu-hu -filenev: learnruby.rb +filename: learnruby-hu.rb contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] @@ -13,7 +13,7 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - translators: +translators: - ["Zsolt Prontvai", "https://github.com/prozsolt"] --- diff --git a/less.html.markdown b/less.html.markdown index 41d66a54..7195271e 100644 --- a/less.html.markdown +++ b/less.html.markdown @@ -8,7 +8,7 @@ contributors: Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more. Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help developers to write maintainable and DRY (Don't Repeat Yourself) code. -```less +```css //Single line comments are removed when Less is compiled to CSS. diff --git a/nim.html.markdown b/nim.html.markdown index 79271732..4901ebfe 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -11,7 +11,7 @@ that gives the programmer power without compromises on runtime efficiency. Nim is efficient, expressive, and elegant. -```nimrod +```javascript var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" diff --git a/nl-nl/amd-nl.html.markdown b/nl-nl/amd-nl.html.markdown deleted file mode 100644 index d5e0022a..00000000 --- a/nl-nl/amd-nl.html.markdown +++ /dev/null @@ -1,235 +0,0 @@ ---- -category: tool -tool: amd -contributors: - - ["Frederik Ring", "https://github.com/m90"] -translators: - - ["Reinoud Kruithof", "https://github.com/reinoudk"] -filename: learnamd-nl.js -lang: nl-nl ---- - -## Aan de slag met AMD - -De **Asynchronous Module Definition** API specificeert een mechanisme om JavaScript - modules the definiren zodat de module en dependencies (afhankelijkheden) asynchroon - geladen kunnen worden. Dit is vooral erg geschikt voor de browseromgeving, waar het - synchroon laden van modules zorgt voor problemen qua prestatie, gebruiksvriendelijkheid, - debugging en cross-domain toegangsproblemen. - -### Basis concept -```javascript -// De basis AMD API bestaat uit niks meer dan twee methodes: `define` en `require` -// and gaat vooral over de definitie en gebruik van modules: -// `define(id?, dependencies?, factory)` definieert een module -// `require(dependencies, callback)` importeert een set van dependencies en -// gebruikt ze in de gegeven callback - -// Laten we starten met het gebruiken van define om een nieuwe module (met naam) -// te creeren, welke geen dependencies heeft. Dit doen we door een naam -// en een zogeheten factory functie door te geven aan define: -define('awesomeAMD', function(){ - var isAMDAwesome = function(){ - return true; - }; - // De return waarde van een module's factory functie is - // wat andere modules of require calls ontvangen wanneer - // ze onze `awesomeAMD` module requiren. - // De gexporteerde waarde kan van alles zijn: (constructor) functies, - // objecten, primitives, zelfs undefined (hoewel dat niet veel nut heeft). - return isAMDAwesome; -}); - - -// We gaan nu een andere module defineren die afhankelijk is van onze -// `awesomeAMD` module. Merk hierbij op dat er nu een extra functieargument -// is die de dependencies van onze module defineert: -define('schreewlelijk', ['awesomeAMD'], function(awesomeAMD){ - // dependencies worden naar de factory's functieargumenten - // gestuurd in de volgorde waarin ze gespecificeert zijn - var vertelIedereen = function(){ - if (awesomeAMD()){ - alert('Dit is zOoOo cool!'); - } else { - alert('Vrij saai, niet?'); - } - }; - return vertelIedereen; -}); - -// Nu we weten hoe we define moeten gebruiken, kunnen we require gebruiken -// om ons programma mee te starten. De vorm van `require` is -// `(arrayVanDependencies, callback)`. -require(['schreeuwlelijk'], function(schreewlelijk){ - schreeuwlelijk(); -}); - -// Om deze tutorial code uit te laten voeren, gaan we hier een vrij basic -// (niet-asynchrone) versie van AMD implementeren: -function define(naam, deps, factory){ - // merk op hoe modules zonder dependencies worden afgehandeld - define[naam] = require(factory ? deps : [], factory || deps); -} - -function require(deps, callback){ - var args = []; - // we halen eerst alle dependecies op die nodig zijn - // om require aan te roepen - for (var i = 0; i < deps.length; i++){ - args[i] = define[deps[i]]; - } - // voldoe aan alle dependencies van de callback - return callback.apply(null, args); -} -// je kan deze code hier in actie zien (Engels): http://jsfiddle.net/qap949pd/ -``` - -### require.js in de echte wereld - -In contrast met het voorbeeld uit de introductie, implementeert `require.js` - (de meest populaire AMD library) de **A** in **AMD**. Dit maakt het mogelijk - om je modules en hun dependencies asynchroon in the laden via XHR: - -```javascript -/* file: app/main.js */ -require(['modules/someClass'], function(SomeClass){ - // de callback word uitgesteld tot de dependency geladen is - var things = new SomeClass(); -}); -console.log('Dus, hier wachten we!'); // dit wordt als eerste uitgevoerd -``` - -De afspraak is dat je over het algemeen n module in n bestand opslaat. -`require.js` kan module-namen achterhalen gebaseerd op de bestandslocatie, -dus je hoeft je module geen naam te geven. Je kan simpelweg aan ze referen - door hun locatie te gebruiken. -In het voorbeeld nemen we aan dat `someClass` aanwezig is in de `modules` map, - relatief ten opzichte van de `baseUrl` uit je configuratie. - -* app/ - * main.js - * modules/ - * someClass.js - * someHelpers.js - * ... - * daos/ - * things.js - * ... - -Dit betekent dat we `someClass` kunnen defineren zonder een module-id te specificeren: - -```javascript -/* file: app/modules/someClass.js */ -define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ - // definitie van de module gebeurt, natuurlijk, ook asynchroon - function SomeClass(){ - this.method = function(){/**/}; - // ... - } - return SomeClass; -}); -``` -Gebruik `requirejs.config(configObj)` om het gedrag van de standaard mapping - aan te passen in je `main.js`: - -```javascript -/* file: main.js */ -requirejs.config({ - baseUrl : 'app', - paths : { - // je kan ook modules uit andere locatie inladen - jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', - coolLibUitBower : '../bower_components/cool-lib/coollib' - } -}); -require(['jquery', 'coolLibUitBower', 'modules/someHelpers'], function($, coolLib, helpers){ - // een `main` bestand moet require minstens eenmaal aanroepen, - // anders zal er geen code uitgevoerd worden - coolLib.doFancyDingenMet(helpers.transform($('#foo'))); -}); -``` -Op `require.js` gebaseerde apps hebben vaak een enkel beginpunt (`main.js`) - welke toegevoegd wordt aan de `require.js` script tag als een data-attribuut. -Deze zal automisch geladen en uitgevoerd worden als de pagina laadt: - -```html - - - - Honder script tags? Nooi meer! - - - - - -``` - -### Een heel project optimaliseren met r.js - -Veel mensen geven er de voorkeur aan om AMD te gebruiken tijdens de - ontwikkelfase om code op een gezonde manier te organiseren maar - willen nog steeds een enkel scriptbestand gebruiken in productie in - plaats van honderderen XHR verzoeken uit te voeren als de pagina laadt. - -`require.js` wordt geleverd met een script genaamd `r.js` (die je waarschijnlijk -uitvoert in node.js, hoewel Rhino ook ondersteund wordt) welke de -dependency book van je project analyseert en een enkel bestand bouwt met daarin -al je module (juist genaamd), geminificeerd en klaar voor productie. - -Instaleren met `npm`: -```shell -$ npm install requirejs -g -``` - -Nu kun je het een configuratiebestand voeden: -```shell -$ r.js -o app.build.js -``` - -Voor ons bovenstaande voorbeeld zou de configuratie er zo uit kunnen zien: -```javascript -/* file : app.build.js */ -({ - name : 'main', // naam van het beginpunt - out : 'main-built.js', // naam van het bestand waar de output naar geschreven wordt - baseUrl : 'app', - paths : { - // `empty:` verteld r.js dat dee nog steeds geladen moet worden van de CDN, - // gebruik makend van de locatie gespecificeert in `main.js` - jquery : 'empty:', - coolLibUitBower : '../bower_components/cool-lib/coollib' - } -}) -``` -Verwissel simpelweg `data-main` om het gebouwde bestand te gebruiken in productie: -```html - -``` - -Een erg gedetaileerd [overzicht van bouwopties](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is -beschikbar in de GitHub repo (Engels). - -Hieronder vind je nog meer informatie over AMD (Engels). - -### Onderwerpen die niet aan bod zijn gekomen -* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html) -* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html) -* [Advanced configuration](http://requirejs.org/docs/api.html#config) -* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim) -* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss) -* [Using almond.js for builds](https://github.com/jrburke/almond) - -### Verder lezen: - -* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD) -* [Why AMD?](http://requirejs.org/docs/whyamd.html) -* [Universal Module Definition](https://github.com/umdjs/umd) - -### Implementaties: - -* [require.js](http://requirejs.org) -* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) -* [cujo.js](http://cujojs.com/) -* [curl.js](https://github.com/cujojs/curl) -* [lsjs](https://github.com/zazl/lsjs) -* [mmd](https://github.com/alexlawrence/mmd) diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index 8f4233fd..162ec4c8 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -7,11 +7,12 @@ contributors: - ["Andre Polykanine", "http://oire.me/"] lang: ru-ru --- + D - современный компилируемый язык общего назначения с Си-подобным синтаксисом, который сочетает удобство, продуманный дизайн и высокую производительность. D - это С++, сделанный правильно. -```d +```c // Welcome to D! Это однострочный комментарий /* многострочный diff --git a/ta_in/css-ta.html.markdown b/ta_in/css-ta.html.markdown index 56f94ed0..cbe88f1e 100644 --- a/ta_in/css-ta.html.markdown +++ b/ta_in/css-ta.html.markdown @@ -7,9 +7,9 @@ contributors: - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] translators: - - ["Rasendran Kirushan", "https://github.com/kirushanr"] -filename: learncss.css -lang:in-ta + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +filename: learncss-ta.css +lang: in-ta --- diff --git a/ta_in/javascript-ta.html.markdown b/ta_in/javascript-ta.html.markdown index f0b0a36a..d3fe5a85 100644 --- a/ta_in/javascript-ta.html.markdown +++ b/ta_in/javascript-ta.html.markdown @@ -5,8 +5,8 @@ contributors: - ['Ariel Krakowski', 'http://www.learneroo.com'] translators: - ["Rasendran Kirushan", "https://github.com/kirushanr"] -filename: javascript.js -lang:in-ta +filename: javascript-ta.js +lang: in-ta --- javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுரிந்த Brendan Eich diff --git a/ta_in/xml-ta.html.markdown b/ta_in/xml-ta.html.markdown index a9bfa9cd..d782399d 100644 --- a/ta_in/xml-ta.html.markdown +++ b/ta_in/xml-ta.html.markdown @@ -1,11 +1,11 @@ --- language: xml -filename: learnxml.xml +filename: learnxml-ta.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Rasendran Kirushan", "https://github.com/kirushanr"] -lang:in-ta +lang: in-ta --- -- cgit v1.2.3 From 00e288cee1a9564e0a482a24bdf9e33170d7cd4e Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sat, 13 Feb 2016 15:37:31 -0700 Subject: corrected spelling --- make.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/make.html.markdown b/make.html.markdown index e8cfd2b5..bf934c58 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -11,7 +11,7 @@ target to the most recent version of the source. Famously written over a weekend by Stuart Feldman in 1976, it is still widely used (particularly on Unix) despite many competitors and criticisms. -There are many varieties of make in existance, this article assumes that +There are many varieties of make in existence, this article assumes that we are using GNU make which is the standard on Linux. ```make -- cgit v1.2.3 From 0c020f4da8563cbc9e509a63a1f03c1f53162c1c Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 14 Feb 2016 22:47:19 -0800 Subject: Fix up asciidoc --- asciidoc.html.markdown | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown index f9ca8e21..7f2a4374 100644 --- a/asciidoc.html.markdown +++ b/asciidoc.html.markdown @@ -13,7 +13,7 @@ Headers are optional and can't contain blank lines. It must be offset from conte Title Only -```asciidoc +``` = Document Title First sentence of document. @@ -21,7 +21,7 @@ First sentence of document. Title and Author -```asciidoc +``` = Document Title First Last @@ -29,7 +29,8 @@ Start of this document. ``` Multiple Authors -```asciidoc + +``` = Document Title John Doe ; Jane Doe; Black Beard @@ -37,16 +38,18 @@ Start of a doc with multiple authors. ``` Revision Line (requires an author line) -```asciidoc + +``` = Doc Title V1 Potato Man v1.0, 2016-01-13 This article about chips is going to be fun. ``` + Paragraphs -```asciidoc +``` You don't need anything special for paragraphs. Add a blank line between paragraphs to seperate them. @@ -57,7 +60,7 @@ and you will recieve a line break! Formatting Text -```asciidoc +``` _underscore creates italics_ *asterisks for bold* *_combine for extra fun_* @@ -67,7 +70,7 @@ _underscore creates italics_ Section Titles -```asciidoc +``` = Level 0 (may only be used in document's header) == Level 1

@@ -87,34 +90,33 @@ Section Titles Lists To create a bulleted list use asterisks. -```asciidoc + +``` * foo * bar * baz ``` To create a numbered list use periods. -```asciidoc + +``` . item 1 . item 2 . item 3 ``` You can nest lists by adding extra asterisks or periods up to five times. -```asciidoc + +``` * foo 1 ** foo 2 *** foo 3 **** foo 4 ***** foo 5 -``` -```asciidoc + . foo 1 .. foo 2 ... foo 3 .... foo 4 ..... foo 5 ``` - - - -- cgit v1.2.3