mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-11-23 06:03:07 +03:00
Merge branch 'master' of github.com:adambard/learnxinyminutes-docs
This commit is contained in:
commit
a6c3a64a4c
@ -235,12 +235,12 @@ sqr ;; => #<procedure (sqr x)>
|
||||
(= 2 1) ;; => #f
|
||||
|
||||
;; 'eq?' returns #t if two arguments refer to the same object in memory
|
||||
;; In other words, it's a simple pointer comparision.
|
||||
;; In other words, it's a simple pointer comparison.
|
||||
(eq? '() '()) ;; => #t ;; there's only one empty list in memory
|
||||
(eq? (list 3) (list 3)) ;; => #f ;; not the same object
|
||||
(eq? 'yes 'yes) ;; => #t
|
||||
(eq? 3 3) ;; => #t ;; don't do this even if it works in this case
|
||||
(eq? 3 3.0) ;; => #f ;; it's better to use '=' for number comparisions
|
||||
(eq? 3 3.0) ;; => #f ;; it's better to use '=' for number comparisons
|
||||
(eq? "Hello" "Hello") ;; => #f
|
||||
|
||||
;; 'eqv?' is same as 'eq?' all datatypes except numbers and characters
|
||||
@ -255,7 +255,7 @@ sqr ;; => #<procedure (sqr x)>
|
||||
(equal? '(1 2 3) '(1 2 3)) ;; => #t
|
||||
(equal? #(a b c) #(a b c)) ;; => #t
|
||||
(equal? 'a 'a) ;; => #t
|
||||
(equal? "abc" "abc") ;; => #f
|
||||
(equal? "abc" "abc") ;; => #t
|
||||
|
||||
;; In Summary:
|
||||
;; eq? tests if objects are identical
|
||||
|
@ -2,8 +2,8 @@
|
||||
language: awk
|
||||
filename: learnawk.awk
|
||||
contributors:
|
||||
- ["Marshall Mason", "http://github.com/marshallmason"]
|
||||
lang: en
|
||||
- ["Marshall Mason", "http://github.com/marshallmason"]
|
||||
|
||||
---
|
||||
|
||||
AWK is a standard tool on every POSIX-compliant UNIX system. It's like a
|
||||
@ -264,7 +264,7 @@ function io_functions( localvar) {
|
||||
# automatically for you.
|
||||
|
||||
# You can probably guess there are other $ variables. Every line is
|
||||
# implicitely split before every action is called, much like the shell
|
||||
# implicitly split before every action is called, much like the shell
|
||||
# does. And, like the shell, each field can be access with a dollar sign
|
||||
|
||||
# This will print the second and fourth fields in the line
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: bf
|
||||
language: "Brainfuck"
|
||||
filename: brainfuck.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -2,7 +2,7 @@
|
||||
name: perl
|
||||
category: language
|
||||
language: perl
|
||||
filename: learnperl.pl
|
||||
filename: learnperl-bg.pl
|
||||
contributors:
|
||||
- ["Korjavin Ivan", "http://github.com/korjavin"]
|
||||
- ["Dan Book", "http://github.com/Grinnz"]
|
||||
|
@ -8,7 +8,7 @@ contributors:
|
||||
- ["Connor Waters", "http://github.com/connorwaters"]
|
||||
- ["Ankush Goyal", "http://github.com/ankushg07"]
|
||||
- ["Jatin Dhankhar", "https://github.com/jatindhankhar"]
|
||||
lang: en
|
||||
|
||||
---
|
||||
|
||||
C++ is a systems programming language that,
|
||||
|
@ -336,10 +336,10 @@ int main (int argc, char** argv)
|
||||
goto error;
|
||||
}
|
||||
error :
|
||||
printf("Error occured at i = %d & j = %d.\n", i, j);
|
||||
printf("Error occurred at i = %d & j = %d.\n", i, j);
|
||||
/*
|
||||
https://ideone.com/GuPhd6
|
||||
this will print out "Error occured at i = 52 & j = 99."
|
||||
this will print out "Error occurred at i = 52 & j = 99."
|
||||
*/
|
||||
|
||||
///////////////////////////////////////
|
||||
|
@ -242,7 +242,7 @@ do {
|
||||
} while (j <= 10000);
|
||||
writeln(jSum);
|
||||
|
||||
// for loops are much like those in python in that they iterate over a
|
||||
// for loops are much like those in Python in that they iterate over a
|
||||
// range. Ranges (like the 1..10 expression below) are a first-class object
|
||||
// in Chapel, and as such can be stored in variables.
|
||||
for i in 1..10 do write(i, ", ");
|
||||
@ -1064,14 +1064,14 @@ proc main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Heres an example using atomics and a sync variable to create a
|
||||
// Here's an example using atomics and a sync variable to create a
|
||||
// count-down mutex (also known as a multiplexer).
|
||||
var count: atomic int; // our counter
|
||||
var lock$: sync bool; // the mutex lock
|
||||
|
||||
count.write(2); // Only let two tasks in at a time.
|
||||
lock$.writeXF(true); // Set lock$ to full (unlocked)
|
||||
// Note: The value doesnt actually matter, just the state
|
||||
// Note: The value doesn't actually matter, just the state
|
||||
// (full:unlocked / empty:locked)
|
||||
// Also, writeXF() fills (F) the sync var regardless of its state (X)
|
||||
|
||||
|
@ -28,8 +28,8 @@ are used in the usual way.
|
||||
# - cmake ..
|
||||
# - make
|
||||
#
|
||||
# With those steps, we will follow the best pratice to compile into a subdir
|
||||
# and the second line will request to CMake to generate a new OS-dependant
|
||||
# With those steps, we will follow the best practice to compile into a subdir
|
||||
# and the second line will request to CMake to generate a new OS-dependent
|
||||
# Makefile. Finally, run the native Make command.
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
@ -215,7 +215,7 @@ Range.new(1, 10).class #=> Range(Int32, Int32)
|
||||
# possibly different types.
|
||||
{1, "hello", 'x'}.class #=> Tuple(Int32, String, Char)
|
||||
|
||||
# Acces tuple's value by its index
|
||||
# Access tuple's value by its index
|
||||
tuple = {:key1, :key2}
|
||||
tuple[1] #=> :key2
|
||||
tuple[2] #=> syntax error : Index out of bound
|
||||
|
@ -1095,6 +1095,28 @@ namespace Learning.More.CSharp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
using System;
|
||||
namespace Csharp7
|
||||
{
|
||||
//New C# 7 Feature
|
||||
//Install Microsoft.Net.Compilers Latest from Nuget
|
||||
//Install System.ValueTuple Latest from Nuget
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
//Type 1 Declaration
|
||||
(string FirstName, string LastName) names1 = ("Peter", "Parker");
|
||||
Console.WriteLine(names1.FirstName);
|
||||
|
||||
//Type 2 Declaration
|
||||
var names2 = (First:"Peter", Last:"Parker");
|
||||
Console.WriteLine(names2.Last);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Topics Not Covered
|
||||
|
@ -20,7 +20,7 @@ Nodes
|
||||
It's an empty *node*, to indicate that there is a *node*, but it's not relevant for the query.
|
||||
|
||||
```(n)```
|
||||
It's a *node* refered by the variable **n**, reusable in the query. It begins with lowercase and uses camelCase.
|
||||
It's a *node* referred by the variable **n**, reusable in the query. It begins with lowercase and uses camelCase.
|
||||
|
||||
```(p:Person)```
|
||||
You can add a *label* to your node, here **Person**. It's like a type / a class / a category. It begins with uppercase and uses camelCase.
|
||||
@ -53,7 +53,7 @@ Relationships (or Edges)
|
||||
It's a *relationship* with the *label* **KNOWS**. It's a *label* as the node's label. It begins with uppercase and use UPPER_SNAKE_CASE.
|
||||
|
||||
```[k:KNOWS]```
|
||||
The same *relationship*, refered by the variable **k**, reusable in the query, but it's not necessary.
|
||||
The same *relationship*, referred by the variable **k**, reusable in the query, but it's not necessary.
|
||||
|
||||
```[k:KNOWS {since:2017}]```
|
||||
The same *relationship*, with *properties* (like *node*), here **since**.
|
||||
@ -244,6 +244,6 @@ Special hints
|
||||
---
|
||||
|
||||
- There is just single-line comments in Cypher, with double-slash : // Comments
|
||||
- You can execute a Cypher script stored in a **.cql** file directly in Neo4j (it's an import). However, you can't have multiple statements in this file (separed by **;**).
|
||||
- You can execute a Cypher script stored in a **.cql** file directly in Neo4j (it's an import). However, you can't have multiple statements in this file (separated by **;**).
|
||||
- Use the Neo4j shell to write Cypher, it's really awesome.
|
||||
- The Cypher will be the standard query language for all graph databases (known as **OpenCypher**).
|
||||
|
@ -3,7 +3,7 @@ language: D
|
||||
filename: learnd.d
|
||||
contributors:
|
||||
- ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
|
||||
lang: en
|
||||
|
||||
---
|
||||
|
||||
```d
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: java
|
||||
filename: LearnJavaDe.java
|
||||
filename: LearnJavaDe-de.java
|
||||
contributors:
|
||||
- ["Jake Prather", "http://github.com/JakeHP"]
|
||||
- ["Jakukyo Friel", "http://weakish.github.io"]
|
||||
|
@ -32,7 +32,7 @@ false
|
||||
"hungarian breakfast"
|
||||
"farmer's cheesy omelette"
|
||||
|
||||
; Characters are preceeded by backslashes
|
||||
; Characters are preceded by backslashes
|
||||
\g \r \a \c \e
|
||||
|
||||
; Keywords start with a colon. They behave like enums. Kind of
|
||||
@ -42,7 +42,7 @@ false
|
||||
:olives
|
||||
|
||||
; Symbols are used to represent identifiers. They start with #.
|
||||
; You can namespace symbols by using /. Whatever preceeds / is
|
||||
; You can namespace symbols by using /. Whatever precedes / is
|
||||
; the namespace of the name.
|
||||
#spoon
|
||||
#kitchen/spoon ; not the same as #spoon
|
||||
|
@ -286,7 +286,7 @@ leftmostElement tree =
|
||||
-- Put this at the top of the file. If omitted, you're in Main.
|
||||
module Name where
|
||||
|
||||
-- By default, everything is exported. You can specify exports explicity.
|
||||
-- By default, everything is exported. You can specify exports explicitly.
|
||||
module Name (MyType, myValue) where
|
||||
|
||||
-- One common pattern is to export a union type but not its tags. This is known
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: bf
|
||||
language: Brainfuck
|
||||
filename: brainfuck-es.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -1,12 +1,13 @@
|
||||
---
|
||||
language: c#
|
||||
language: C#(C Sharp)
|
||||
filename: LearnCSharp-es.cs
|
||||
contributors:
|
||||
- ["Irfan Charania", "https://github.com/irfancharania"]
|
||||
- ["Max Yankov", "https://github.com/golergka"]
|
||||
translators:
|
||||
- ["Olfran Jiménez", "https://twitter.com/neslux"]
|
||||
filename: LearnCSharp-es.cs
|
||||
lang: es-es
|
||||
|
||||
---
|
||||
|
||||
C# es un lenguaje orientado a objetos elegante y de tipado seguro que
|
||||
|
@ -1,11 +1,11 @@
|
||||
---
|
||||
category: tool
|
||||
tool: git
|
||||
filename: LearnGit-es.txt
|
||||
contributors:
|
||||
- ["Jake Prather", "http://github.com/JakeHP"]
|
||||
translator:
|
||||
- ["Raúl Ascencio", "http://rscnt.github.io"]
|
||||
filename: LearnGit.txt
|
||||
lang: es-es
|
||||
|
||||
---
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: sass
|
||||
filename: learnsass.scss
|
||||
filename: learnsass-es.scss
|
||||
contributors:
|
||||
- ["Laura Kyle", "https://github.com/LauraNK"]
|
||||
- ["Sean Corrales", "https://github.com/droidenator"]
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: xml
|
||||
filename: learnxml.xml
|
||||
filename: learnxml-es.xml
|
||||
contributors:
|
||||
- ["João Farias", "https://github.com/JoaoGFarias"]
|
||||
translators:
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: bf
|
||||
filename: bf-fa.bf
|
||||
contributors:
|
||||
- ["Mohammad Valipour", "https://github.com/mvalipour"]
|
||||
lang: fa-ir
|
||||
|
@ -54,7 +54,7 @@ public class LearnJava {
|
||||
///////////////////////////////////////
|
||||
|
||||
/*
|
||||
* Ouput
|
||||
* Output
|
||||
*/
|
||||
|
||||
// Use System.out.println() to print lines.
|
||||
|
@ -6,7 +6,7 @@ filename: learnfortran.f95
|
||||
---
|
||||
|
||||
Fortran is one of the oldest computer languages. It was developed in the 1950s
|
||||
by IBM for numeric calculations (Fortran is an abreviation of "Formula
|
||||
by IBM for numeric calculations (Fortran is an abbreviation of "Formula
|
||||
Translation"). Despite its age, it is still used for high-performance computing
|
||||
such as weather prediction. However, the language has changed considerably over
|
||||
the years, although mostly maintaining backwards compatibility; well known
|
||||
@ -242,7 +242,7 @@ program example !declare a program called example.
|
||||
close(12)
|
||||
|
||||
! There are more features available than discussed here and alternative
|
||||
! variants due to backwards compatability with older Fortran versions.
|
||||
! variants due to backwards compatibility with older Fortran versions.
|
||||
|
||||
|
||||
! Built-in Functions
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: css
|
||||
filename: cascading-fr.css
|
||||
contributors:
|
||||
- ["Mohammad Valipour", "https://github.com/mvalipour"]
|
||||
- ["Marco Scannadinari", "https://github.com/marcoms"]
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: haml
|
||||
filename: learnhaml.haml
|
||||
filename: learnhaml-fr.haml
|
||||
contributors:
|
||||
- ["Simon Neveu", "https://github.com/sneveu"]
|
||||
- ["Thibault", "https://github.com/iTech-"]
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: PHP
|
||||
filename: php-fr.php
|
||||
contributors:
|
||||
- ["Malcolm Fell", "http://emarref.net/"]
|
||||
- ["Trismegiste", "https://github.com/Trismegiste"]
|
||||
|
@ -276,7 +276,7 @@ i // Montre la valeur de i. Notez que while est une boucle au sens classique.
|
||||
i = 0
|
||||
// La boucle do while
|
||||
do {
|
||||
println("x is still less then 10");
|
||||
println("x is still less than 10");
|
||||
i += 1
|
||||
} while (i < 10)
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
---
|
||||
category: tool
|
||||
tool: vim
|
||||
filename: LearnVim.txt
|
||||
filename: LearnVim-fr.txt
|
||||
contributors:
|
||||
- ["RadhikaG", "https://github.com/RadhikaG"]
|
||||
translators:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: yaml
|
||||
filename: learnyaml.yaml
|
||||
filename: learnyaml-fr.yaml
|
||||
contributors:
|
||||
- ["Andrei Curelaru", "http://www.infinidad.fr"]
|
||||
lang: fr-fr
|
||||
|
@ -432,7 +432,7 @@ Stashing takes the dirty state of your working directory and saves it on a
|
||||
stack of unfinished changes that you can reapply at any time.
|
||||
|
||||
Let's say you've been doing some work in your git repo, but you want to pull
|
||||
from the remote. Since you have dirty (uncommited) changes to some files, you
|
||||
from the remote. Since you have dirty (uncommitted) changes to some files, you
|
||||
are not able to run `git pull`. Instead, you can run `git stash` to save your
|
||||
changes onto a stack!
|
||||
|
||||
@ -521,7 +521,7 @@ $ git reset --hard
|
||||
$ git reset 31f2bb1
|
||||
|
||||
# Moves the current branch tip backward to the specified commit
|
||||
# and makes the working dir match (deletes uncommited changes and all commits
|
||||
# and makes the working dir match (deletes uncommitted changes and all commits
|
||||
# after the specified commit).
|
||||
$ git reset --hard 31f2bb1
|
||||
```
|
||||
|
@ -257,7 +257,7 @@ class InvalidFooSubclass extends ConsistentFoo
|
||||
// ...
|
||||
}
|
||||
|
||||
// Using the __Override annotation on a non-overriden method will cause a
|
||||
// Using the __Override annotation on a non-overridden method will cause a
|
||||
// type checker error:
|
||||
//
|
||||
// "InvalidFooSubclass::otherMethod() is marked as override; no non-private
|
||||
@ -299,7 +299,7 @@ $cat instanceof KittenInterface === true; // True
|
||||
## More Information
|
||||
|
||||
Visit the [Hack language reference](http://docs.hhvm.com/manual/en/hacklangref.php)
|
||||
for detailed explainations of the features Hack adds to PHP, or the [official Hack website](http://hacklang.org/)
|
||||
for detailed explanations of the features Hack adds to PHP, or the [official Hack website](http://hacklang.org/)
|
||||
for more general information.
|
||||
|
||||
Visit the [official HHVM website](http://hhvm.com/) for HHVM installation instructions.
|
||||
|
@ -36,7 +36,7 @@ $ haml input_file.haml output_file.html
|
||||
To write a multi line comment, indent your commented code to be
|
||||
wrapped by the forward slash
|
||||
|
||||
-# This is a silent comment, which means it wont be rendered into the doc at all
|
||||
-# This is a silent comment, which means it won't be rendered into the doc at all
|
||||
|
||||
|
||||
/ -------------------------------------------
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: Haskell
|
||||
filename: learnhaskell.hs
|
||||
contributors:
|
||||
- ["Adit Bhargava", "http://adit.io"]
|
||||
---
|
||||
|
@ -466,7 +466,7 @@ class LearnHaxe3{
|
||||
The untyped keyword operates on entire *blocks* of code, skipping
|
||||
any type checks that might be otherwise required. This keyword should
|
||||
be used very sparingly, such as in limited conditionally-compiled
|
||||
situations where type checking is a hinderance.
|
||||
situations where type checking is a hindrance.
|
||||
|
||||
In general, skipping type checks is *not* recommended. Use the
|
||||
enum, inheritance, or structural type models in order to help ensure
|
||||
|
@ -102,7 +102,7 @@ True ; => True
|
||||
(apply something-fancy ["My horse" "amazing"] { "mane" "spectacular" })
|
||||
|
||||
; anonymous functions are created using `fn' or `lambda' constructs
|
||||
; which are similiar to `defn'
|
||||
; which are similar to `defn'
|
||||
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
|
||||
|
||||
;; Sequence operations
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: bf
|
||||
filename: learnbf-it.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: json
|
||||
filename: learnjson-it.json
|
||||
contributors:
|
||||
- ["Anna Harren", "https://github.com/iirelu"]
|
||||
- ["Marco Scannadinari", "https://github.com/marcoms"]
|
||||
|
@ -1,11 +1,11 @@
|
||||
---
|
||||
language: python
|
||||
filename: learnpython-it.py
|
||||
contributors:
|
||||
- ["Louie Dinh", "http://ldinh.ca"]
|
||||
- ["Amin Bandali", "http://aminbandali.com"]
|
||||
- ["Andre Polykanine", "https://github.com/Oire"]
|
||||
- ["evuez", "http://github.com/evuez"]
|
||||
filename: learnpython.py
|
||||
translators:
|
||||
- ["Ale46", "http://github.com/Ale46/"]
|
||||
- ["Tommaso Pifferi", "http://github.com/neslinesli93/"]
|
||||
|
@ -119,7 +119,7 @@ echo 'Multiple', 'Parameters', 'Valid';
|
||||
define("FOO", "something");
|
||||
|
||||
// 定義した名前をそのまま($はつけずに)使用することで、定数にアクセスできます
|
||||
// access to a constant is possible by direct using the choosen name
|
||||
// access to a constant is possible by direct using the chosen name
|
||||
echo 'This outputs '.FOO;
|
||||
|
||||
|
||||
|
@ -57,7 +57,7 @@ public class LearnJava {
|
||||
///////////////////////////////////////
|
||||
|
||||
/*
|
||||
* Ouput
|
||||
* Output
|
||||
*/
|
||||
|
||||
// Use System.out.println() to print lines.
|
||||
|
@ -6,7 +6,7 @@ contributors:
|
||||
filename: learnkdb.q
|
||||
---
|
||||
|
||||
The q langauge and its database component kdb+ were developed by Arthur Whitney
|
||||
The q language and its database component kdb+ were developed by Arthur Whitney
|
||||
and released by Kx systems in 2003. q is a descendant of APL and as such is
|
||||
very terse and a little strange looking for anyone from a "C heritage" language
|
||||
background. Its expressiveness and vector oriented nature make it well suited
|
||||
@ -301,7 +301,7 @@ l:1+til 9 / til is a useful shortcut for generating ranges
|
||||
-5#l / => 5 6 7 8 9
|
||||
/ drop the last 5
|
||||
-5_l / => 1 2 3 4
|
||||
/ find the first occurance of 4
|
||||
/ find the first occurrence of 4
|
||||
l?4 / => 3
|
||||
l[3] / => 4
|
||||
|
||||
@ -316,7 +316,7 @@ key d / => `a`b`c
|
||||
/ and value the second
|
||||
value d / => 1 2 3
|
||||
|
||||
/ Indexing is indentical to lists
|
||||
/ Indexing is identical to lists
|
||||
/ with the first list as a key instead of the position
|
||||
d[`a] / => 1
|
||||
d[`b] / => 2
|
||||
@ -406,7 +406,7 @@ k!t
|
||||
/ We can also use this shortcut for defining keyed tables
|
||||
kt:([id:1 2 3]c1:1 2 3;c2:4 5 6;c3:7 8 9)
|
||||
|
||||
/ Records can then be retreived based on this key
|
||||
/ Records can then be retrieved based on this key
|
||||
kt[1]
|
||||
/ => c1| 1
|
||||
/ => c2| 4
|
||||
@ -428,7 +428,7 @@ kt[`id!1]
|
||||
f:{x+x}
|
||||
f[2] / => 4
|
||||
|
||||
/ Functions can be annonymous and called at point of definition
|
||||
/ Functions can be anonymous and called at point of definition
|
||||
{x+x}[2] / => 4
|
||||
|
||||
/ By default the last expression is returned
|
||||
@ -440,7 +440,7 @@ f[2] / => 4
|
||||
|
||||
/ Function arguments can be specified explicitly (separated by ;)
|
||||
{[arg1;arg2] arg1+arg2}[1;2] / => 3
|
||||
/ or if ommited will default to x, y and z
|
||||
/ or if omitted will default to x, y and z
|
||||
{x+y+z}[1;2;3] / => 6
|
||||
|
||||
/ Built in functions are no different, and can be called the same way (with [])
|
||||
@ -472,7 +472,7 @@ a / => 1
|
||||
/ Functions cannot see nested scopes (only local and global)
|
||||
{local:1;{:local}[]}[] / throws error as local is not defined in inner function
|
||||
|
||||
/ A function can have one or more of it's arguments fixed (projection)
|
||||
/ A function can have one or more of its arguments fixed (projection)
|
||||
f:+[4]
|
||||
f[4] / => 8
|
||||
f[5] / => 9
|
||||
@ -483,7 +483,7 @@ f[6] / => 10
|
||||
////////// q-sql //////////
|
||||
////////////////////////////////////
|
||||
|
||||
/ q has it's own syntax for manipulating tables, similar to standard SQL
|
||||
/ q has its own syntax for manipulating tables, similar to standard SQL
|
||||
/ This contains the usual suspects of select, insert, update etc.
|
||||
/ and some new functionality not typically available
|
||||
/ q-sql has two significant differences (other than syntax) to normal SQL:
|
||||
@ -682,7 +682,7 @@ aj[`time`sym;trades;quotes]
|
||||
/ where possible functionality should be vectorized (i.e. operations on lists)
|
||||
/ adverbs supplement this, modifying the behaviour of functions
|
||||
/ and providing loop type functionality when required
|
||||
/ (in q functions are sometimes refered to as verbs, hence adverbs)
|
||||
/ (in q functions are sometimes referred to as verbs, hence adverbs)
|
||||
/ the "each" adverb modifies a function to treat a list as individual variables
|
||||
first each (1 2 3;4 5 6;7 8 9)
|
||||
/ => 1 4 7
|
||||
@ -762,7 +762,7 @@ select from splayed / (the columns are read from disk on request)
|
||||
/ kdb+ is typically used for data capture and analysis.
|
||||
/ This involves using an architecture with multiple processes
|
||||
/ working together. kdb+ frameworks are available to streamline the setup
|
||||
/ and configuration of this architecuture and add additional functionality
|
||||
/ and configuration of this architecture and add additional functionality
|
||||
/ such as disaster recovery, logging, access, load balancing etc.
|
||||
/ https://github.com/AquaQAnalytics/TorQ
|
||||
```
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: bf
|
||||
filename: learnbf-kr.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -1,12 +1,13 @@
|
||||
---
|
||||
category: tool
|
||||
tool: tmux
|
||||
filename: tmux.json
|
||||
lang: lt-lt
|
||||
filename: tmux-lt.json
|
||||
contributors:
|
||||
- ["mdln", "https://github.com/mdln"]
|
||||
translators:
|
||||
- ["Zygimantus", "https://github.com/zygimantus"]
|
||||
lang: lt-lt
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
@ -353,7 +353,7 @@ double_input(6) % ans = 12
|
||||
% anonymous function. Useful when quickly defining a function to pass to
|
||||
% another function (eg. plot with fplot, evaluate an indefinite integral
|
||||
% with quad, find roots with fzero, or find minimum with fminsearch).
|
||||
% Example that returns the square of it's input, assigned to the handle sqr:
|
||||
% Example that returns the square of its input, assigned to the handle sqr:
|
||||
sqr = @(x) x.^2;
|
||||
sqr(10) % ans = 100
|
||||
doc function_handle % find out more
|
||||
|
@ -76,7 +76,7 @@ let myDrink = drinks[2]
|
||||
# static typing powerful and useful.
|
||||
|
||||
type
|
||||
Name = string # A type alias gives you a new type that is interchangable
|
||||
Name = string # A type alias gives you a new type that is interchangeable
|
||||
Age = int # with the old type but is more descriptive.
|
||||
Person = tuple[name: Name, age: Age] # Define data structures too.
|
||||
AnotherSyntax = tuple
|
||||
@ -109,7 +109,7 @@ when compileBadCode:
|
||||
|
||||
type
|
||||
Color = enum cRed, cBlue, cGreen
|
||||
Direction = enum # Alternative formating
|
||||
Direction = enum # Alternative formatting
|
||||
dNorth
|
||||
dWest
|
||||
dEast
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: bf
|
||||
filename: learnbf-nl.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -786,7 +786,7 @@ MyClass *newVar = [classVar retain]; // If classVar is released, object is still
|
||||
// Automatic Reference Counting (ARC)
|
||||
// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC).
|
||||
// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC,
|
||||
// you must not use retain, relase, or autorelease
|
||||
// you must not use retain, release, or autorelease
|
||||
MyClass *arcMyClass = [[MyClass alloc] init];
|
||||
// ... code using arcMyClass
|
||||
// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC,
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: OCaml
|
||||
filename: learnocaml.ml
|
||||
contributors:
|
||||
- ["Daniil Baturin", "http://baturin.org/"]
|
||||
---
|
||||
|
@ -447,7 +447,7 @@ False ~~ True; # True
|
||||
# http://perlcabal.org/syn/S03.html#Smart_matching
|
||||
|
||||
# You also, of course, have `<`, `<=`, `>`, `>=`.
|
||||
# Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`.
|
||||
# Their string equivalent are also available : `lt`, `le`, `gt`, `ge`.
|
||||
3 > 4;
|
||||
|
||||
## * Range constructors
|
||||
@ -618,7 +618,7 @@ my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }`
|
||||
my @arrayplus3 = map(*+*+3, @array); # Same as `-> $a, $b { $a + $b + 3 }`
|
||||
# also `sub ($a, $b) { $a + $b + 3 }`
|
||||
say (*/2)(4); #=> 2
|
||||
# Immediatly execute the function Whatever created.
|
||||
# Immediately execute the function Whatever created.
|
||||
say ((*+3)/5)(5); #=> 1.6
|
||||
# works even in parens !
|
||||
|
||||
@ -750,7 +750,7 @@ sub call_say_dyn {
|
||||
my $*dyn_scoped_1 = 25; # Defines $*dyn_scoped_1 only for this sub.
|
||||
$*dyn_scoped_2 = 100; # Will change the value of the file scoped variable.
|
||||
say_dyn(); #=> 25 100 $*dyn_scoped 1 and 2 will be looked for in the call.
|
||||
# It uses he value of $*dyn_scoped_1 from inside this sub's lexical
|
||||
# It uses the value of $*dyn_scoped_1 from inside this sub's lexical
|
||||
# scope even though the blocks aren't nested (they're call-nested).
|
||||
}
|
||||
say_dyn(); #=> 1 10
|
||||
@ -816,7 +816,7 @@ $class-obj.other-attrib = 10; # This, however, works, because the public
|
||||
# Perl 6 also has inheritance (along with multiple inheritance)
|
||||
# While `method`'s are inherited, `submethod`'s are not.
|
||||
# Submethods are useful for object construction and destruction tasks,
|
||||
# such as BUILD, or methods that must be overriden by subtypes.
|
||||
# such as BUILD, or methods that must be overridden by subtypes.
|
||||
# We will learn about BUILD later on.
|
||||
|
||||
class Parent {
|
||||
@ -840,7 +840,7 @@ $Richard.talk; #=> "Hi, my name is Richard"
|
||||
# # $Richard is able to access the submethod, he knows how to say his name.
|
||||
|
||||
my Child $Madison .= new(age => 1, name => 'Madison');
|
||||
$Madison.talk; # prints "Goo goo ga ga" due to the overrided method.
|
||||
$Madison.talk; # prints "Goo goo ga ga" due to the overridden method.
|
||||
# $Madison.favorite-color does not work since it is not inherited
|
||||
|
||||
# When you use `my T $var`, `$var` starts off with `T` itself in it,
|
||||
@ -1054,7 +1054,7 @@ say why-not[^5]; #=> 5 15 25 35 45
|
||||
|
||||
## * `state` (happens at run time, but only once)
|
||||
# State variables are only initialized one time
|
||||
# (they exist in other langages such as C as `static`)
|
||||
# (they exist in other languages such as C as `static`)
|
||||
sub fixed-rand {
|
||||
state $val = rand;
|
||||
say $val;
|
||||
@ -1105,7 +1105,7 @@ PRE {
|
||||
say "If this block doesn't return a truthy value,
|
||||
an exception of type X::Phaser::PrePost is thrown.";
|
||||
}
|
||||
# exemple:
|
||||
# example:
|
||||
for 0..2 {
|
||||
PRE { $_ > 1 } # This is going to blow up with "Precondition failed"
|
||||
}
|
||||
@ -1204,7 +1204,7 @@ say (1, 10, (20, 10) ).flat; #> (1 10 20 10) Now the iterable is flat
|
||||
|
||||
# - `lazy` - Defer actual evaluation until value is fetched (forces lazy context)
|
||||
my @lazy-array = (1..100).lazy;
|
||||
say @lazy-array.is-lazy; #> True # Check for lazyness with the `is-lazy` method.
|
||||
say @lazy-array.is-lazy; #> True # Check for laziness with the `is-lazy` method.
|
||||
say @lazy-array; #> [...] List has not been iterated on!
|
||||
my @lazy-array { .print }; # This works and will only do as much work as is
|
||||
# needed.
|
||||
@ -1599,7 +1599,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ...
|
||||
# To decide which part is the "longest", it first splits the regex in two parts:
|
||||
# The "declarative prefix" (the part that can be statically analyzed)
|
||||
# and the procedural parts.
|
||||
# Declarative prefixes include alternations (`|`), conjuctions (`&`),
|
||||
# Declarative prefixes include alternations (`|`), conjunctions (`&`),
|
||||
# sub-rule calls (not yet introduced), literals, characters classes and quantifiers.
|
||||
# The latter include everything else: back-references, code assertions,
|
||||
# and other things that can't traditionnaly be represented by normal regexps.
|
||||
@ -1755,10 +1755,10 @@ If you want to go further, you can:
|
||||
This will give you a dropdown menu of all the pages referencing your search
|
||||
term (Much better than using Google to find Perl 6 documents!)
|
||||
- Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This
|
||||
is a great source of Perl 6 snippets and explainations. If the docs don't
|
||||
is a great source of Perl 6 snippets and explanations. If the docs don't
|
||||
describe something well enough, you may find more detailed information here.
|
||||
This information may be a bit older but there are many great examples and
|
||||
explainations. Posts stopped at the end of 2015 when the language was declared
|
||||
explanations. Posts stopped at the end of 2015 when the language was declared
|
||||
stable and Perl 6.c was released.
|
||||
- Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful.
|
||||
- Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize).
|
||||
|
@ -122,9 +122,9 @@ echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid'
|
||||
// followed by any number of letters, numbers, or underscores.
|
||||
define("FOO", "something");
|
||||
|
||||
// access to a constant is possible by calling the choosen name without a $
|
||||
// access to a constant is possible by calling the chosen name without a $
|
||||
echo FOO; // Returns 'something'
|
||||
echo 'This outputs ' . FOO; // Returns 'This ouputs something'
|
||||
echo 'This outputs ' . FOO; // Returns 'This outputs something'
|
||||
|
||||
|
||||
|
||||
@ -837,7 +837,7 @@ try {
|
||||
// Handle exception
|
||||
}
|
||||
|
||||
// When using try catch blocks in a namespaced enviroment use the following
|
||||
// When using try catch blocks in a namespaced environment use the following
|
||||
|
||||
try {
|
||||
// Do something
|
||||
@ -854,7 +854,7 @@ try {
|
||||
$condition = true;
|
||||
|
||||
if ($condition) {
|
||||
throw new MyException('Something just happend');
|
||||
throw new MyException('Something just happened');
|
||||
}
|
||||
|
||||
} catch (MyException $e) {
|
||||
|
@ -1,13 +1,14 @@
|
||||
---
|
||||
category: language
|
||||
language: bf
|
||||
filename: learnbf-pl.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
translators:
|
||||
- ["Jakub Młokosiewicz", "https://github.com/hckr"]
|
||||
lang: pl-pl
|
||||
filename: bf-pl.html
|
||||
|
||||
---
|
||||
|
||||
Brainfuck (pisane małymi literami, za wyjątkiem początku zdania) jest bardzo
|
||||
|
@ -1,12 +1,13 @@
|
||||
---
|
||||
category: language
|
||||
filename: haskell-pl.hs
|
||||
language: Haskell
|
||||
contributors:
|
||||
- ["Adit Bhargava", "http://adit.io"]
|
||||
translators:
|
||||
- ["Remigiusz Suwalski", "https://github.com/remigiusz-suwalski"]
|
||||
lang: pl-pl
|
||||
filename: haskell-pl.hs
|
||||
|
||||
---
|
||||
|
||||
Haskell został zaprojektowany jako praktyczny, czysto funkcyjny język
|
||||
|
@ -2,13 +2,14 @@
|
||||
name: perl
|
||||
category: language
|
||||
language: perl
|
||||
filename: learnperl-pl.pm
|
||||
contributors:
|
||||
- ["Korjavin Ivan", "http://github.com/korjavin"]
|
||||
- ["Dan Book", "http://github.com/Grinnz"]
|
||||
translators:
|
||||
- ["Michał Kupczyński", "http://github.com/ukoms"]
|
||||
lang: pl-pl
|
||||
filename: learnperl-pl.pl
|
||||
|
||||
---
|
||||
|
||||
Perl 5 jest wysoce użytecznym, bogatym w wiele opcji językiem programowania
|
||||
|
331
prolog.html.markdown
Normal file
331
prolog.html.markdown
Normal file
@ -0,0 +1,331 @@
|
||||
---
|
||||
language: prolog
|
||||
filename: learnprolog.pl
|
||||
contributors:
|
||||
- ["hyphz", "http://github.com/hyphz/"]
|
||||
---
|
||||
|
||||
Prolog is a logic programming language first specified in 1972, and refined into multiple modern implementations.
|
||||
|
||||
```
|
||||
% This is a comment.
|
||||
|
||||
% Prolog treats code entered in interactive mode differently
|
||||
% to code entered in a file and loaded ("consulted").
|
||||
% This code must be loaded from a file to work as intended.
|
||||
% Lines that begin with ?- can be typed in interactive mode.
|
||||
% A bunch of errors and warnings will trigger when you load this file
|
||||
% due to the examples which are supposed to fail - they can be safely
|
||||
% ignored.
|
||||
|
||||
% Output is based on SWI-prolog 7.2.3. Different Prologs may behave
|
||||
% differently.
|
||||
|
||||
% Prolog is based on the ideal of logic programming.
|
||||
% A subprogram (called a predicate) represents a state of the world.
|
||||
% A command (called a goal) tells Prolog to make that state of the world
|
||||
% come true, if possible.
|
||||
|
||||
% As an example, here is a definition of the simplest kind of predicate:
|
||||
% a fact.
|
||||
|
||||
magicNumber(7).
|
||||
magicNumber(9).
|
||||
magicNumber(42).
|
||||
|
||||
% This introduces magicNumber as a predicate and says that it is true
|
||||
% with parameter 7, 9, or 42, but no other parameter. Note that
|
||||
% predicate names must start with lower case letters. We can now use
|
||||
% interactive mode to ask if it is true for different values:
|
||||
|
||||
?- magicNumber(7). % True
|
||||
?- magicNumber(8). % False
|
||||
?- magicNumber(9). % True
|
||||
|
||||
% Some older Prologs may display "Yes" and "No" instead of True and
|
||||
% False.
|
||||
|
||||
% What makes Prolog unusual is that we can also tell Prolog to _make_
|
||||
% magicNumber true, by passing it an undefined variable. Any name
|
||||
% starting with a capital letter is a variable in Prolog.
|
||||
|
||||
?- magicNumber(Presto). % Presto = 7 ;
|
||||
% Presto = 9 ;
|
||||
% Presto = 42.
|
||||
|
||||
% Prolog makes magicNumber true by assigning one of the valid numbers to
|
||||
% the undefined variable Presto. By default it assigns the first one, 7.
|
||||
% By pressing ; in interactive mode you can reject that solution and
|
||||
% force it to assign the next one, 9. Pressing ; again forces it to try
|
||||
% the last one, 42, after which it no longer accepts input because this
|
||||
% is the last solution. You can accept an earlier solution by pressing .
|
||||
% instead of ;.
|
||||
|
||||
% This is Prolog's central operation: unification. Unification is
|
||||
% essentially a combination of assignment and equality! It works as
|
||||
% follows:
|
||||
% If both sides are bound (ie, defined), check equality.
|
||||
% If one side is free (ie, undefined), assign to match the other side.
|
||||
% If both sides are free, abort because this can't be resolved.
|
||||
% The = sign in Prolog represents unification, so:
|
||||
|
||||
?- 2 = 3. % False - equality test
|
||||
?- X = 3. % X = 3 - assignment
|
||||
?- X = 2, X = Y. % X = Y = 2 - two assignments
|
||||
% Note Y is assigned to, even though it is
|
||||
% on the right hand side, because it is free
|
||||
?- X = 3, X = 2. % False
|
||||
% First acts as assignment and binds X=3
|
||||
% Second acts as equality because X is bound
|
||||
% Since 3 does not equal 2, gives False
|
||||
% Thus in Prolog variables are immutable
|
||||
?- X = 3+2. % X = 3+2 - unification can't do arithmetic
|
||||
?- X is 3+2. % X = 5 - "is" does arithmetic.
|
||||
?- 5 = X+2. % This is why = can't do arithmetic -
|
||||
% because Prolog can't solve equations
|
||||
?- 5 is X+2. % Error. Unlike =, the right hand side of IS
|
||||
% must always be bound, thus guaranteeing
|
||||
% no attempt to solve an equation.
|
||||
|
||||
% Any unification, and thus any predicate in Prolog, can either:
|
||||
% Succeed (return True) without changing anything,
|
||||
% because an equality-style unification was true
|
||||
% Succeed (return True) and bind one or more variables in the process,
|
||||
% because an assignment-style unification was made true
|
||||
% or Fail (return False)
|
||||
% because an equality-style unification was false
|
||||
% (Failure can never bind variables)
|
||||
|
||||
% The ideal of being able to give any predicate as a goal and have it
|
||||
% made true is not always possible, but can be worked toward. For
|
||||
% example, Prolog has a built in predicate plus which represents
|
||||
% arithmetic addition but can reverse simple additions.
|
||||
|
||||
?- plus(1, 2, 3). % True
|
||||
?- plus(1, 2, X). % X = 3 because 1+2 = X.
|
||||
?- plus(1, X, 3). % X = 2 because 1+X = 3.
|
||||
?- plus(X, 2, 3). % X = 1 because X+1 = 3.
|
||||
?- plus(X, 5, Y). % Error - although this could be solved,
|
||||
% the number of solutions is infinite,
|
||||
% which most predicates try to avoid.
|
||||
|
||||
% When a predicate such as magicNumber can give several solutions, the
|
||||
% overall compound goal including it may have several solutions too.
|
||||
|
||||
?- magicNumber(X), plus(X,Y,100). % X = 7, Y = 93 ;
|
||||
% X = 9, Y = 91 ;
|
||||
% X = 42, Y = 58 .
|
||||
% Note: on this occasion it works to pass two variables to plus because
|
||||
% only Y is free (X is bound by magicNumber).
|
||||
|
||||
% However, if one of the goals is fully bound and thus acts as a test,
|
||||
% then solutions which fail the test are rejected.
|
||||
?- magicNumber(X), X > 40. % X = 42
|
||||
?- magicNumber(X), X > 100. % False
|
||||
|
||||
% To see how Prolog actually handles this, let's introduce the print
|
||||
% predicate. Print always succeeds, never binds any variables, and
|
||||
% prints out its parameter as a side effect.
|
||||
|
||||
?- print("Hello"). % "Hello" true.
|
||||
?- X = 2, print(X). % 2 true.
|
||||
?- X = 2, print(X), X = 3. % 2 false - print happens immediately when
|
||||
% it is encountered, even though the overall
|
||||
% compound goal fails (because 2 != 3,
|
||||
% see the example above).
|
||||
|
||||
% By using Print we can see what actually happens when we give a
|
||||
% compound goal including a test that sometimes fails.
|
||||
?- magicNumber(X), print(X), X > 40. % 7 9 42 X = 42 .
|
||||
|
||||
% MagicNumber(X) unifies X with its first possibility, 7.
|
||||
% Print(X) prints out 7.
|
||||
% X > 40 tests if 7 > 40. It is not, so it fails.
|
||||
% However, Prolog remembers that magicNumber(X) offered multiple
|
||||
% solutions. So it _backtracks_ to that point in the code to try
|
||||
% the next solution, X = 9.
|
||||
% Having backtracked it must work through the compound goal
|
||||
% again from that point including the Print(X). So Print(X) prints out
|
||||
% 9.
|
||||
% X > 40 tests if 9 > 40 and fails again.
|
||||
% Prolog remembers that magicNumber(X) still has solutions and
|
||||
% backtracks. Now X = 42.
|
||||
% It works through the Print(X) again and prints 42.
|
||||
% X > 40 tests if 42 > 40 and succeeds so the result bound to X
|
||||
% The same backtracking process is used when you reject a result at
|
||||
% the interactive prompt by pressing ;, for example:
|
||||
|
||||
?- magicNumber(X), print(X), X > 8. % 7 9 X = 9 ;
|
||||
% 42 X = 42.
|
||||
|
||||
% As you saw above we can define our own simple predicates as facts.
|
||||
% More complex predicates are defined as rules, like this:
|
||||
|
||||
nearby(X,Y) :- X = Y.
|
||||
nearby(X,Y) :- Y is X+1.
|
||||
nearby(X,Y) :- Y is X-1.
|
||||
|
||||
% nearby(X,Y) is true if Y is X plus or minus 1.
|
||||
% However this predicate could be improved. Here's why:
|
||||
|
||||
?- nearby(2,3). % True ; False.
|
||||
% Because we have three possible definitions, Prolog sees this as 3
|
||||
% possibilities. X = Y fails, so Y is X+1 is then tried and succeeds,
|
||||
% giving the True answer. But Prolog still remembers there are more
|
||||
% possibilities for nearby() (in Prolog terminology, "it has a
|
||||
% choice point") even though "Y is X-1" is doomed to fail, and gives us
|
||||
% the option of rejecting the True answer, which doesn't make a whole
|
||||
% lot of sense.
|
||||
|
||||
?- nearby(4, X). % X = 4 ;
|
||||
% X = 5 ;
|
||||
% X = 3. Great, this works
|
||||
?- nearby(X, 4). % X = 4 ;
|
||||
% error
|
||||
% After rejecting X = 4 prolog backtracks and tries "Y is X+1" which is
|
||||
% "4 is X+1" after substitution of parameters. But as we know from above
|
||||
% "is" requires its argument to be fully instantiated and it is not, so
|
||||
% an error occurs.
|
||||
|
||||
% One way to solve the first problem is to use a construct called the
|
||||
% cut, !, which does nothing but which cannot be backtracked past.
|
||||
|
||||
nearbychk(X,Y) :- X = Y, !.
|
||||
nearbychk(X,Y) :- Y is X+1, !.
|
||||
nearbychk(X,Y) :- Y is X-1.
|
||||
|
||||
% This solves the first problem:
|
||||
?- nearbychk(2,3). % True.
|
||||
|
||||
% But unfortunately it has consequences:
|
||||
?- nearbychk(2,X). % X = 2.
|
||||
% Because Prolog cannot backtrack past the cut after X = Y, it cannot
|
||||
% try the possibilities "Y is X+1" and "Y is X-1", so it only generates
|
||||
% one solution when there should be 3.
|
||||
% However if our only interest is in checking if numbers are nearby,
|
||||
% this may be all we need, thus the name nearbychk.
|
||||
% This structure is used in Prolog itself from time to time (for example
|
||||
% in list membership).
|
||||
|
||||
% To solve the second problem we can use built-in predicates in Prolog
|
||||
% to verify if a parameter is bound or free and adjust our calculations
|
||||
% appropriately.
|
||||
nearby2(X,Y) :- nonvar(X), X = Y.
|
||||
nearby2(X,Y) :- nonvar(X), Y is X+1.
|
||||
nearby2(X,Y) :- nonvar(X), Y is X-1.
|
||||
nearby2(X,Y) :- var(X), nonvar(Y), nearby2(Y,X).
|
||||
|
||||
% We can combine this with a cut in the case where both variables are
|
||||
% bound, to solve both problems.
|
||||
nearby3(X,Y) :- nonvar(X), nonvar(Y), nearby2(X,Y), !.
|
||||
nearby3(X,Y) :- nearby2(X,Y).
|
||||
|
||||
% However when writing a predicate it is not normally necessary to go to
|
||||
% these lengths to perfectly support every possible parameter
|
||||
% combination. It suffices to support parameter combinations we need to
|
||||
% use in the program. It is a good idea to document which combinations
|
||||
% are supported. In regular Prolog this is informally in structured
|
||||
% comments, but in some Prolog variants like Visual Prolog and Mercury
|
||||
% this is mandatory and checked by the compiler.
|
||||
|
||||
% Here is the structured comment declaration for nearby3:
|
||||
|
||||
%% nearby3(+X:Int, +Y:Int) is semidet.
|
||||
%% nearby3(+X:Int, -Y:Int) is multi.
|
||||
%% nearby3(-X:Int, +Y:Int) is multi.
|
||||
|
||||
% For each variable we list a type. The + or - before the variable name
|
||||
% indicates if the parameter is bound (+) or free (-). The word after
|
||||
% "is" describes the behaviour of the predicate:
|
||||
% semidet - can succeed once or fail
|
||||
% ( Two specific numbers are either nearby or not )
|
||||
% multi - can succeed multiple times but cannot fail
|
||||
% ( One number surely has at least 3 nearby numbers )
|
||||
% Other possibilities are:
|
||||
% det - always succeeds exactly once (eg, print)
|
||||
% nondet - can succeed multiple times or fail.
|
||||
% In Prolog these are just structured comments and strictly informal but
|
||||
% extremely useful.
|
||||
|
||||
% An unusual feature of Prolog is its support for atoms. Atoms are
|
||||
% essentially members of an enumerated type that are created on demand
|
||||
% whenever an unquoted non variable value is used. For example:
|
||||
character(batman). % Creates atom value batman
|
||||
character(robin). % Creates atom value robin
|
||||
character(joker). % Creates atom value joker
|
||||
character(darthVader). % Creates atom value darthVader
|
||||
?- batman = batman. % True - Once created value is reused
|
||||
?- batman = batMan. % False - atoms are case sensitive
|
||||
?- batman = darthVader. % False - atoms are distinct
|
||||
|
||||
% Atoms are popular in examples but were created on the assumption that
|
||||
% Prolog would be used interactively by end users - they are less
|
||||
% useful for modern applications and some Prolog variants abolish them
|
||||
% completely. However they can be very useful internally.
|
||||
|
||||
% Loops in Prolog are classically written using recursion.
|
||||
% Note that below, writeln is used instead of print because print is
|
||||
% intended for debugging.
|
||||
|
||||
%% countTo(+X:Int) is det.
|
||||
%% countUpTo(+Value:Int, +Limit:Int) is det.
|
||||
countTo(X) :- countUpTo(1,X).
|
||||
countUpTo(Value, Limit) :- Value = Limit, writeln(Value), !.
|
||||
countUpTo(Value, Limit) :- Value \= Limit, writeln(Value),
|
||||
NextValue is Value+1,
|
||||
countUpTo(NextValue, Limit).
|
||||
|
||||
?- countTo(10). % Outputs 1 to 10
|
||||
|
||||
% Note the use of multiple declarations in countUpTo to create an
|
||||
% IF test. If Value = Limit fails the second declaration is run.
|
||||
% There is also a more elegant syntax.
|
||||
|
||||
%% countUpTo2(+Value:Int, +Limit:Int) is det.
|
||||
countUpTo2(Value, Limit) :- writeln(Value),
|
||||
Value = Limit -> true ; (
|
||||
NextValue is Value+1,
|
||||
countUpTo2(NextValue, Limit)).
|
||||
|
||||
?- countUpTo2(1,10). % Outputs 1 to 10
|
||||
|
||||
% If a predicate returns multiple times it is often useful to loop
|
||||
% through all the values it returns. Older Prologs used a hideous syntax
|
||||
% called a "failure-driven loop" to do this, but newer ones use a higher
|
||||
% order function.
|
||||
|
||||
%% countTo2(+X:Int) is det.
|
||||
countTo2(X) :- forall(between(1,X,Y),writeln(Y)).
|
||||
|
||||
?- countTo2(10). % Outputs 1 to 10
|
||||
|
||||
% Lists are given in square brackets. Use memberchk to check membership.
|
||||
% A group is safe if it doesn't include Joker or does include Batman.
|
||||
%% safe(Group:list(atom)) is det.
|
||||
safe(Group) :- memberchk(joker, Group) -> memberchk(batman, Group) ; true.
|
||||
|
||||
?- safe([robin]). % True
|
||||
?- safe([joker]). % False
|
||||
?- safe([joker, batman]). % True
|
||||
|
||||
% The member predicate works like memberchk if both arguments are bound,
|
||||
% but can accept free variables and thus can be used to loop through
|
||||
% lists.
|
||||
|
||||
?- member(X, [1,2,3]). % X = 1 ; X = 2 ; X = 3 .
|
||||
?- forall(member(X,[1,2,3]),
|
||||
(Y is X+1, writeln(Y))). % 2 3 4
|
||||
|
||||
% The maplist function can be used to generate lists based on other
|
||||
% lists. Note that the output list is a free variable, causing an
|
||||
% undefined value to be passed to plus, which is then bound by
|
||||
% unification. Also notice the use of currying on the plus predicate -
|
||||
% it's a 3 argument predicate, but we specify only the first, because
|
||||
% the second and third are filled in by maplist.
|
||||
|
||||
?- maplist(plus(1), [2,3,4], Output). % Output = [3, 4, 5].
|
||||
```
|
||||
|
||||
##Ready For More?
|
||||
|
||||
* [SWI-Prolog](http://www.swi-prolog.org/)
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: bf
|
||||
filename: learnbf-pt.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: c++
|
||||
filename: learncpp.cpp
|
||||
filename: learncpp-pt.cpp
|
||||
contributors:
|
||||
- ["Steven Basart", "http://github.com/xksteven"]
|
||||
- ["Matt Kline", "https://github.com/mrkline"]
|
||||
|
@ -647,7 +647,7 @@ Se você tem uma pergunta, leia [compl.lang.c Frequently Asked Questions](http:/
|
||||
|
||||
É importante usar espaços e indentação adequadamente e ser consistente com seu estilo de código em geral.
|
||||
Código legível é melhor que código 'esperto' e rápido. Para adotar um estilo de código bom e são, veja
|
||||
[Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle).
|
||||
[Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle).
|
||||
|
||||
Além disso, Google é teu amigo.
|
||||
[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member
|
||||
|
@ -1,7 +1,7 @@
|
||||
---
|
||||
language: Groovy
|
||||
category: language
|
||||
filename: learngroovy.groovy
|
||||
filename: learngroovy-pt.groovy
|
||||
contributors:
|
||||
- ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"]
|
||||
translators:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: hy
|
||||
filename: learnhy.hy
|
||||
filename: learnhy-pt.hy
|
||||
contributors:
|
||||
- ["Abhishek L", "http://twitter.com/abhishekl"]
|
||||
translators:
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: javascript
|
||||
filename: javascript-pt.js
|
||||
contributors:
|
||||
- ["Adam Brenecki", "http://adam.brenecki.id.au"]
|
||||
- ["Ariel Krakowski", "http://www.learneroo.com"]
|
||||
|
384
pt-br/kotlin-pt.html.markdown
Normal file
384
pt-br/kotlin-pt.html.markdown
Normal file
@ -0,0 +1,384 @@
|
||||
---
|
||||
language: kotlin
|
||||
filename: LearnKotlin-pt.kt
|
||||
contributors:
|
||||
- ["S Webber", "https://github.com/s-webber"]
|
||||
translators:
|
||||
- ["Márcio Torres", "https://github.com/marciojrtorres"]
|
||||
lang: pt-br
|
||||
---
|
||||
|
||||
Kotlin é uma linguagem de programação estaticamente tipada para a JVM, Android e navegadores web. Ela é 100% interoperável com Java.
|
||||
[Leia mais aqui.](https://kotlinlang.org/)
|
||||
|
||||
```kotlin
|
||||
// Comentários de uma linha iniciam com //
|
||||
/*
|
||||
Comentários multilinha se parecem com este.
|
||||
*/
|
||||
|
||||
// A palavra-chave "package" funciona do mesmo modo que no Java.
|
||||
package com.learnxinyminutes.kotlin
|
||||
|
||||
/*
|
||||
O ponto de entrada para um programa em Kotlin é uma função chamada "main"
|
||||
Esta função recebe um vetor contendo quaisquer argumentos da linha de comando
|
||||
*/
|
||||
fun main(args: Array<String>) {
|
||||
/*
|
||||
A declaração de valores pode ser feita tanto com "var" como "val"
|
||||
Declarações com "val" não podem ser reatribuídas, enquanto com "var" podem.
|
||||
*/
|
||||
val umVal = 10 // não se poderá reatribuir qualquer coisa a umVal
|
||||
var umVar = 10
|
||||
umVar = 20 // umVar pode ser reatribuída, mas respeitando o tipo
|
||||
|
||||
/*
|
||||
Na maioria dos casos Kotlin pode inferir o tipo, então não é preciso sempre
|
||||
especificar o tipo explicitamente, mas quando o fazemos é assim:
|
||||
*/
|
||||
val umInteiro: Int = 7
|
||||
|
||||
/*
|
||||
Strings podem ser representadas de forma semelhante a Java.
|
||||
A contrabarra realiza o "escape", da mesma forma.
|
||||
*/
|
||||
val umaString = "Minha String está aqui!"
|
||||
val outraString = "Imprimir na outra linha?\nSem problema!"
|
||||
val maisString = "Você quer adicionar um tab?\tSem problema!"
|
||||
println(umaString)
|
||||
println(outraString)
|
||||
println(maisString)
|
||||
|
||||
/*
|
||||
Uma string bruta é delimitada com três aspas (""").
|
||||
Strings brutas podem conter novas linhas e outros caracteres.
|
||||
*/
|
||||
val umaStringBruta = """
|
||||
fun olaMundo(val nome : String) {
|
||||
println("Olá, mundo!")
|
||||
}
|
||||
"""
|
||||
println(umaStringBruta)
|
||||
|
||||
/*
|
||||
As strings podem conter expressões modelo (template).
|
||||
Uma expressão modelo começa com um cifrão ($).
|
||||
É semelhante à interpolação de Strings em Ruby.
|
||||
*/
|
||||
val umaStringModelo = "$umaString tem ${umaString.length} caracteres"
|
||||
println(umaStringModelo)
|
||||
|
||||
/*
|
||||
Para uma variável receber null deve-se explicitamente declara-la
|
||||
como anulável.
|
||||
A declaração de anulável é realizada incluindo uma "?" ao fim do tipo.
|
||||
Pode-se acessar uma variável anulável usando o operador "?."
|
||||
Usa-se o operador "?:" (também conhecido como operador Elvis) para
|
||||
atribuir um valor alternativo para quando uma variável é nula.
|
||||
*/
|
||||
var umaVariavelAnulavel: String? = "abc"
|
||||
println(umaVariavelAnulavel?.length) // => 3
|
||||
println(umaVariavelAnulavel?.length ?: -1) // => 3
|
||||
umaVariavelAnulavel = null
|
||||
println(umaVariavelAnulavel?.length) // => null
|
||||
println(umaVariavelAnulavel?.length ?: -1) // => -1
|
||||
|
||||
/*
|
||||
Funções podem ser declaradas usando a palavra-chave "fun"
|
||||
Os parâmetros da função são declarados entre parênteses logo
|
||||
após o nome da função.
|
||||
Os parâmetros da função podem ter opcionalmente um valor padrão.
|
||||
O tipo de retorno da função, se necessário, é especificado após os argumentos.
|
||||
*/
|
||||
fun ola(nome: String = "mundo"): String {
|
||||
return "Olá, $nome!"
|
||||
}
|
||||
println(ola("você")) // => Olá, você!
|
||||
println(ola(nome = "tu")) // => Olá, tu!
|
||||
println(ola()) // => Olá, mundo!
|
||||
|
||||
/*
|
||||
Um parâmetro pode ser declarado com a palavra-chave "vararg" para
|
||||
permitir que seja passado um número variável de argumentos.
|
||||
*/
|
||||
fun exemploVarArg(vararg numeros: Int) {
|
||||
println("Foram recebidos ${numeros.size} argumentos")
|
||||
}
|
||||
exemploVarArg() // => Passando nenhum argumento (0 argumentos)
|
||||
exemploVarArg(1) // => Passando 1 argumento
|
||||
exemploVarArg(1, 2, 3) // => Passando 3 argumentos
|
||||
|
||||
/*
|
||||
Quando uma função consiste numa única expressão as chaves
|
||||
podem ser omitidas e o corpo declarado após o símbolo de "="
|
||||
*/
|
||||
fun impar(x: Int): Boolean = x % 2 == 1
|
||||
println(impar(6)) // => false
|
||||
println(impar(7)) // => true
|
||||
|
||||
// O tipo de retorno não precisa ser declarado se pode ser inferido.
|
||||
fun impar(x: Int) = x % 2 == 0
|
||||
println(impar(6)) // => true
|
||||
println(impar(7)) // => false
|
||||
|
||||
// Funções podem receber e retornar outras funções
|
||||
fun nao(f: (Int) -> Boolean): (Int) -> Boolean {
|
||||
return {n -> !f.invoke(n)}
|
||||
}
|
||||
// Funções nomeadas podem ser passadas como argumento usando o operador "::"
|
||||
val naoImpar = nao(::impar)
|
||||
val naoPar = nao(::par)
|
||||
// Expressões Lambda podem ser usadas como argumentos
|
||||
val naoZero = nao {n -> n == 0}
|
||||
/*
|
||||
Se uma lambda têm apenas um parâmetro sua declaração pode ser omitida,
|
||||
incluindo o símbolo "->".
|
||||
Neste caso o nome do único parâmetro deve ser "it".
|
||||
*/
|
||||
val naoPositivo = nao {it > 0}
|
||||
for (i in 0..4) {
|
||||
println("${naoImpar(i)} ${naoPar(i)} ${naoZero(i)} ${naoPositivo(i)}")
|
||||
}
|
||||
|
||||
// A palavra-chave "class" é usada para declarar classes
|
||||
class ClasseExemplo(val x: Int) {
|
||||
fun funcaoMembro(y: Int): Int { // ou "método"
|
||||
return x + y
|
||||
}
|
||||
|
||||
infix fun funcaoMembroInfixa(y: Int): Int {
|
||||
return x * y
|
||||
}
|
||||
}
|
||||
/*
|
||||
Para criar uma nova instância chama-se o construtor.
|
||||
Note que Kotlin não tem a palavra-chave "new".
|
||||
*/
|
||||
val umaInstanciaDaClasseExemplo = ClasseExemplo(7)
|
||||
// Funções membro (métodos) podem ser chamados usando a notação ponto "."
|
||||
println(umaInstanciaDaClasseExemplo.funcaoMembro(4)) // => 11
|
||||
/*
|
||||
Se uma função foi declarada com a palavra-chave "infix" então
|
||||
ela pode ser invocada com a notação infixa.
|
||||
*/
|
||||
println(umaInstanciaDaClasseExemplo funcaoMembroInfixa 4) // => 28
|
||||
|
||||
/*
|
||||
Classes de dados são um modo sucinto de criar classes que servem apenas
|
||||
para guardas informações.
|
||||
Os métodos "hashCode", "equals" e "toString" são gerados automaticamente.
|
||||
*/
|
||||
data class ExemploClasseDados (val x: Int, val y: Int, val z: Int)
|
||||
val objetoDados = ExemploClasseDados(1, 2, 4)
|
||||
println(objetoDados) // => ExemploClasseDados(x=1, y=2, z=4)
|
||||
|
||||
// Classes de dados têm uma função "copy"
|
||||
val dadosCopia = objetoDados.copy(y = 100)
|
||||
println(dadosCopia) // => ExemploClasseDados(x=1, y=100, z=4)
|
||||
|
||||
// Objetos podem ser desestruturados em múltiplas variáveis.
|
||||
val (a, b, c) = dadosCopia
|
||||
println("$a $b $c") // => 1 100 4
|
||||
|
||||
// desestruturando em um laço "for"
|
||||
for ((a, b, c) in listOf(objetoDados)) {
|
||||
println("$a $b $c") // => 1 100 4
|
||||
}
|
||||
|
||||
val mapaDados = mapOf("a" to 1, "b" to 2)
|
||||
// Map.Entry também é desestruturável
|
||||
for ((chave, valor) in mapaDados) {
|
||||
println("$chave -> $valor")
|
||||
}
|
||||
|
||||
// A função "with" é semelhante à declaração "with" do JavaScript
|
||||
data class ExemploClasseDadosMutaveis (var x: Int, var y: Int, var z: Int)
|
||||
val objDadosMutaveis = ExemploClasseDadosMutaveis(7, 4, 9)
|
||||
with (objDadosMutaveis) {
|
||||
x -= 2
|
||||
y += 2
|
||||
z--
|
||||
}
|
||||
println(objDadosMutaveis) // => ExemploClasseDadosMutaveis(x=5, y=6, z=8)
|
||||
|
||||
/*
|
||||
Pode-se criar uma lista usando a função "listOf".
|
||||
A lista é imutável, isto é, elementos não podem ser adicionados ou removidos.
|
||||
*/
|
||||
val umaLista = listOf("a", "b", "c")
|
||||
println(umaLista.size) // => 3
|
||||
println(umaLista.first()) // => a
|
||||
println(umaLista.last()) // => c
|
||||
// Elementos de uma lista podem ser acessados pelo índice
|
||||
println(umaLista[1]) // => b
|
||||
|
||||
// Uma lista mutável pode ser criada com a função "mutableListOf".
|
||||
val umaListaMutavel = mutableListOf("a", "b", "c")
|
||||
umaListaMutavel.add("d")
|
||||
println(umaListaMutavel.last()) // => d
|
||||
println(umaListaMutavel.size) // => 4
|
||||
|
||||
// Similarmente, pode-se criar um conjunto com a função "setOf".
|
||||
val umConjunto = setOf("a", "b", "c")
|
||||
println(umConjunto.contains("a")) // => true
|
||||
println(umConjunto.contains("z")) // => false
|
||||
|
||||
// Da mesma forma que um mapa com a função "mapOf".
|
||||
val umMapa = mapOf("a" to 8, "b" to 7, "c" to 9)
|
||||
// Os valores contidos no mapa podem ser acessados pela sua chave.
|
||||
println(umMapa["a"]) // => 8
|
||||
|
||||
/*
|
||||
Sequências representam coleções avaliadas "preguiçosamente" (sob demanda).
|
||||
Pode-se criar uma sequência usando a função "generateSequence".
|
||||
*/
|
||||
val umaSequencia = generateSequence(1, { it + 1 })
|
||||
val x = umaSequencia.take(10).toList()
|
||||
println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
|
||||
// Um exemplo de uma sequência usada para gerar Números de Fibonacci:
|
||||
fun sequenciaFibonacci(): Sequence<Long> {
|
||||
var a = 0L
|
||||
var b = 1L
|
||||
|
||||
fun proximo(): Long {
|
||||
val resultado = a + b
|
||||
a = b
|
||||
b = resultado
|
||||
return a
|
||||
}
|
||||
|
||||
return generateSequence(::proximo)
|
||||
}
|
||||
val y = sequenciaFibonacci().take(10).toList()
|
||||
println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
|
||||
|
||||
// Kotlin oferece funções de alta-ordem para trabalhar com coleções.
|
||||
val z = (1..9).map {it * 3}
|
||||
.filter {it < 20}
|
||||
.groupBy {it % 2 == 0}
|
||||
.mapKeys {if (it.key) "par" else "impar"}
|
||||
println(z) // => {impar=[3, 9, 15], par=[6, 12, 18]}
|
||||
|
||||
// Um "for" pode ser usado com qualquer coisa que ofereça um "iterator"
|
||||
for (c in "salve") {
|
||||
println(c)
|
||||
}
|
||||
|
||||
// O "while" funciona da mesma forma que em outras linguagens.
|
||||
var contador = 0
|
||||
while (contador < 5) {
|
||||
println(contador)
|
||||
contador++
|
||||
}
|
||||
do {
|
||||
println(contador)
|
||||
contador++
|
||||
} while (contador < 10)
|
||||
|
||||
/*
|
||||
"if" pode ser usado como uma expressão que retorna um valor.
|
||||
Por este motivo o operador ternário "? :" não é necessário em Kotlin.
|
||||
*/
|
||||
val numero = 5
|
||||
val mensagem = if (numero % 2 == 0) "par" else "impar"
|
||||
println("$numero é $mensagem") // => 5 é impar
|
||||
|
||||
// "when" pode ser usado como alternativa às correntes de "if-else if".
|
||||
val i = 10
|
||||
when {
|
||||
i < 7 -> println("primeiro block")
|
||||
umaString.startsWith("oi") -> println("segundo block")
|
||||
else -> println("bloco else")
|
||||
}
|
||||
|
||||
// "when" pode ser usado com um argumento.
|
||||
when (i) {
|
||||
0, 21 -> println("0 ou 21")
|
||||
in 1..20 -> println("entre 1 e 20")
|
||||
else -> println("nenhum dos anteriores")
|
||||
}
|
||||
|
||||
// "when" pode ser usada como uma função que retorna um valor.
|
||||
var resultado = when (i) {
|
||||
0, 21 -> "0 ou 21"
|
||||
in 1..20 -> "entre 1 e 20"
|
||||
else -> "nenhum dos anteriores"
|
||||
}
|
||||
println(resultado)
|
||||
|
||||
/*
|
||||
Pode-se verificar se um objeto é de um certo tipo usando o operador "is".
|
||||
Se o objeto passar pela verificação então ele pode ser usado como
|
||||
este tipo, sem a necessidade de uma coerção (cast) explícita (SmartCast).
|
||||
*/
|
||||
fun exemploSmartCast(x: Any) : Boolean {
|
||||
if (x is Boolean) {
|
||||
// x é automaticamente coagido para Boolean
|
||||
return x
|
||||
} else if (x is Int) {
|
||||
// x é automaticamente coagido para Int
|
||||
return x > 0
|
||||
} else if (x is String) {
|
||||
// x é automaticamente coagido para String
|
||||
return x.isNotEmpty()
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
println(exemploSmartCast("Olá, mundo!")) // => true
|
||||
println(exemploSmartCast("")) // => false
|
||||
println(exemploSmartCast(5)) // => true
|
||||
println(exemploSmartCast(0)) // => false
|
||||
println(exemploSmartCast(true)) // => true
|
||||
|
||||
// O Smartcast também funciona com blocos "when"
|
||||
fun exemploSmartCastComWhen(x: Any) = when (x) {
|
||||
is Boolean -> x
|
||||
is Int -> x > 0
|
||||
is String -> x.isNotEmpty()
|
||||
else -> false
|
||||
}
|
||||
|
||||
/*
|
||||
As extensões são uma maneira nova de adicionar funcionalidades a classes.
|
||||
Elas são similares aos "extension methods" da linguagem C#.
|
||||
*/
|
||||
fun String.remove(c: Char): String {
|
||||
return this.filter {it != c}
|
||||
}
|
||||
println("olá, mundo!".remove('o')) // => lá, mund!
|
||||
|
||||
println(ExemploEnum.A) // => A
|
||||
println(ExemploObjeto.ola()) // => olá
|
||||
}
|
||||
|
||||
// Classes Enum são similares aos "enum types" do Java.
|
||||
enum class ExemploEnum {
|
||||
A, B, C
|
||||
}
|
||||
|
||||
/*
|
||||
A palavra-chave "object" pode ser usar para criar Singletons.
|
||||
Eles não são instanciados, mas podem referenciar sua instância única pelo nome.
|
||||
É semelhante aos "singleton objects" da linguagem Scala.
|
||||
*/
|
||||
object ExemploObjeto {
|
||||
fun ola(): String {
|
||||
return "olá"
|
||||
}
|
||||
}
|
||||
|
||||
fun usaObjeto() {
|
||||
ExemploObjeto.ola()
|
||||
val algumaReferencia: Any = ExemploObjeto // usa-se o nome diretamente
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Leitura Adicional
|
||||
|
||||
* [Tutoriais de Kotlin](https://kotlinlang.org/docs/tutorials/)(EN)
|
||||
* [Experimente Kotlin no seu navegador](http://try.kotlinlang.org/)(EN)
|
||||
* [Uma lista de material sobre Kotlin](http://kotlin.link/)(EN)
|
@ -1,12 +1,13 @@
|
||||
---
|
||||
language: swift
|
||||
filename: learnswift-pt.swift
|
||||
contributors:
|
||||
- ["Grant Timmerman", "http://github.com/grant"]
|
||||
- ["Christopher Bess", "http://github.com/cbess"]
|
||||
translators:
|
||||
- ["Mariane Siqueira Machado", "https://twitter.com/mariane_sm"]
|
||||
lang: pt-br
|
||||
filename: learnswift.swift
|
||||
|
||||
---
|
||||
|
||||
Swift é uma linguagem de programação para desenvolvimento de aplicações no iOS e OS X criada pela Apple. Criada para
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: brainfuck
|
||||
filename: brainfuck-pt.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: purescript
|
||||
filename: purescript.purs
|
||||
contributors:
|
||||
- ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"]
|
||||
- ["Thimoteus", "https://github.com/Thimoteus"]
|
||||
|
@ -104,7 +104,7 @@ import matplotlib as mpl
|
||||
import matplotlib.pyplot as plt
|
||||
%matplotlib inline
|
||||
|
||||
# To do data vizualization in Python, use matplotlib
|
||||
# To do data visualization in Python, use matplotlib
|
||||
|
||||
plt.hist(pets.age);
|
||||
|
||||
|
@ -5,7 +5,7 @@ language: c++
|
||||
filename: learnqt.cpp
|
||||
contributors:
|
||||
- ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
|
||||
lang: en
|
||||
|
||||
---
|
||||
|
||||
**Qt** is a widely-known framework for developing cross-platform software that can be run on various software and hardware platforms with little or no change in the code, while having the power and speed of native applications. Though **Qt** was originally written in *C++*, there are its ports to other languages: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc.
|
||||
@ -14,7 +14,7 @@ lang: en
|
||||
|
||||
```c++
|
||||
/*
|
||||
* Let's start clasically
|
||||
* Let's start classically
|
||||
*/
|
||||
|
||||
// all headers from Qt framework start with capital letter 'Q'
|
||||
@ -79,7 +79,7 @@ int main(int argc, char *argv[]) {
|
||||
|
||||
Notice that *QObject::connect* part. This method is used to connect *SIGNALS* of one objects to *SLOTS* of another.
|
||||
|
||||
**Signals** are being emited when certain things happen with objects, like *pressed* signal is emited when user presses on QPushButton object.
|
||||
**Signals** are being emitted when certain things happen with objects, like *pressed* signal is emitted when user presses on QPushButton object.
|
||||
|
||||
**Slots** are *actions* that might be performed in response to received signals.
|
||||
|
||||
|
@ -192,7 +192,7 @@ class(-Inf) # "numeric"
|
||||
2.0 * 2L # 4 # numeric times integer gives numeric
|
||||
3L / 4 # 0.75 # integer over numeric gives numeric
|
||||
3 %% 2 # 1 # the remainder of two numerics is another numeric
|
||||
# Illegal arithmetic yeilds you a "not-a-number":
|
||||
# Illegal arithmetic yields you a "not-a-number":
|
||||
0 / 0 # NaN
|
||||
class(NaN) # "numeric"
|
||||
# You can do arithmetic on two vectors with length greater than 1,
|
||||
@ -662,7 +662,7 @@ require(plyr)
|
||||
#########################
|
||||
|
||||
# "pets.csv" is a file on the internet
|
||||
# (but it could just as easily be be a file on your own computer)
|
||||
# (but it could just as easily be a file on your own computer)
|
||||
pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv")
|
||||
pets
|
||||
head(pets, 2) # first two rows
|
||||
|
@ -51,7 +51,7 @@ comment {
|
||||
; no need to restrict this to a 'main' function.
|
||||
|
||||
; Valid variable names start with a letter and can contain numbers,
|
||||
; variables containing only capital A thru F and numbers and ending with 'h'
|
||||
; variables containing only capital A through F and numbers and ending with 'h'
|
||||
; are forbidden, because that is how hexadecimal numbers are expressed in Red
|
||||
; and Red/System.
|
||||
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: bf
|
||||
filename: learnbf-ru.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -477,7 +477,7 @@ void str_reverse_through_pointer(char *str_in) {
|
||||
|
||||
Очень важно использовать правильные отступы и ставить пробелы в нужных местах.
|
||||
Читаемый код лучше чем красивый или быстрый код.
|
||||
Чтобы научиться писать хороший код, почитайте [Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle).
|
||||
Чтобы научиться писать хороший код, почитайте [Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle).
|
||||
|
||||
Также не забывайте, что [Google](http://google.com) и [Яндекс](http://yandex.ru) – ваши хорошие друзья.
|
||||
|
||||
|
467
ru-ru/elixir-ru.html.markdown
Normal file
467
ru-ru/elixir-ru.html.markdown
Normal file
@ -0,0 +1,467 @@
|
||||
---
|
||||
language: elixir
|
||||
contributors:
|
||||
- ["Joao Marques", "http://github.com/mrshankly"]
|
||||
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
|
||||
- ["Ryan Plant", "https://github.com/ryanplant-au"]
|
||||
translator:
|
||||
- ["Ev Bogdanov", "https://github.com/evbogdanov"]
|
||||
filename: learnelixir-ru.ex
|
||||
lang: ru-ru
|
||||
---
|
||||
|
||||
Elixir — современный функциональный язык программирования, который работает на
|
||||
виртуальной машине Erlang. Elixir полностью совместим с Erlang, но обладает
|
||||
дружелюбным синтаксисом и предлагает больше возможностей.
|
||||
|
||||
```elixir
|
||||
|
||||
# Однострочные комментарии начинаются с символа решётки.
|
||||
|
||||
# Для многострочных комментариев отдельного синтаксиса нет,
|
||||
# поэтому просто используйте несколько однострочных комментариев.
|
||||
|
||||
# Запустить интерактивную Elixir-консоль (аналог `irb` в Ruby) можно
|
||||
# при помощи команды `iex`.
|
||||
# Чтобы скомпилировать модуль, воспользуйтесь командой `elixirc`.
|
||||
|
||||
# Обе команды будут работать из терминала, если вы правильно установили Elixir.
|
||||
|
||||
## ---------------------------
|
||||
## -- Базовые типы
|
||||
## ---------------------------
|
||||
|
||||
# Числа
|
||||
3 # целое число
|
||||
0x1F # целое число
|
||||
3.0 # число с плавающей запятой
|
||||
|
||||
# Атомы, которые являются нечисловыми константами. Они начинаются с символа `:`.
|
||||
:hello # атом
|
||||
|
||||
# Кортежи, которые хранятся в памяти последовательно.
|
||||
{1,2,3} # кортеж
|
||||
|
||||
# Получить доступ к элементу кортежа мы можем с помощью функции `elem`:
|
||||
elem({1, 2, 3}, 0) #=> 1
|
||||
|
||||
# Списки, которые реализованы как связные списки.
|
||||
[1,2,3] # список
|
||||
|
||||
# У каждого непустого списка есть голова (первый элемент списка)
|
||||
# и хвост (все остальные элементы списка):
|
||||
[head | tail] = [1,2,3]
|
||||
head #=> 1
|
||||
tail #=> [2,3]
|
||||
|
||||
# В Elixir, как и в Erlang, знак `=` служит для сопоставления с образцом,
|
||||
# а не для операции присваивания.
|
||||
#
|
||||
# Это означает, что выражение слева от знака `=` (образец) сопоставляется с
|
||||
# выражением справа.
|
||||
#
|
||||
# Сопоставление с образцом позволило нам получить голову и хвост списка
|
||||
# в примере выше.
|
||||
|
||||
# Если выражения слева и справа от знака `=` не удаётся сопоставить, будет
|
||||
# брошена ошибка. Например, если кортежи разных размеров.
|
||||
{a, b, c} = {1, 2} #=> ** (MatchError)
|
||||
|
||||
# Бинарные данные
|
||||
<<1,2,3>>
|
||||
|
||||
# Вы столкнётесь с двумя видами строк:
|
||||
"hello" # Elixir-строка (заключена в двойные кавычки)
|
||||
'hello' # Erlang-строка (заключена в одинарные кавычки)
|
||||
|
||||
# Все строки представлены в кодировке UTF-8:
|
||||
"привет" #=> "привет"
|
||||
|
||||
# Многострочный текст
|
||||
"""
|
||||
Я текст на несколько
|
||||
строк.
|
||||
"""
|
||||
#=> "Я текст на несколько\nстрок.\n"
|
||||
|
||||
# Чем Elixir-строки отличаются от Erlang-строк? Elixir-строки являются бинарными
|
||||
# данными.
|
||||
<<?a, ?b, ?c>> #=> "abc"
|
||||
# Erlang-строка — это на самом деле список.
|
||||
[?a, ?b, ?c] #=> 'abc'
|
||||
|
||||
# Оператор `?` возвращает целое число, соответствующее данному символу.
|
||||
?a #=> 97
|
||||
|
||||
# Для объединения бинарных данных (и Elixir-строк) используйте `<>`
|
||||
<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>>
|
||||
"hello " <> "world" #=> "hello world"
|
||||
|
||||
# Для объединения списков (и Erlang-строк) используйте `++`
|
||||
[1,2,3] ++ [4,5] #=> [1,2,3,4,5]
|
||||
'hello ' ++ 'world' #=> 'hello world'
|
||||
|
||||
# Диапазоны записываются как `начало..конец` (оба включительно)
|
||||
1..10 #=> 1..10
|
||||
|
||||
# Сопоставление с образцом применимо и для диапазонов:
|
||||
lower..upper = 1..10
|
||||
[lower, upper] #=> [1, 10]
|
||||
|
||||
# Карты (известны вам по другим языкам как ассоциативные массивы, словари, хэши)
|
||||
genders = %{"david" => "male", "gillian" => "female"}
|
||||
genders["david"] #=> "male"
|
||||
|
||||
# Для карт, где ключами выступают атомы, доступен специальный синтаксис
|
||||
genders = %{david: "male", gillian: "female"}
|
||||
genders.gillian #=> "female"
|
||||
|
||||
## ---------------------------
|
||||
## -- Операторы
|
||||
## ---------------------------
|
||||
|
||||
# Математические операции
|
||||
1 + 1 #=> 2
|
||||
10 - 5 #=> 5
|
||||
5 * 2 #=> 10
|
||||
10 / 2 #=> 5.0
|
||||
|
||||
# В Elixir оператор `/` всегда возвращает число с плавающей запятой.
|
||||
|
||||
# Для целочисленного деления применяйте `div`
|
||||
div(10, 2) #=> 5
|
||||
|
||||
# Для получения остатка от деления к вашим услугам `rem`
|
||||
rem(10, 3) #=> 1
|
||||
|
||||
# Булевые операторы: `or`, `and`, `not`.
|
||||
# В качестве первого аргумента эти операторы ожидают булевое значение.
|
||||
true and true #=> true
|
||||
false or true #=> true
|
||||
1 and true #=> ** (BadBooleanError)
|
||||
|
||||
# Elixir также предоставляет `||`, `&&` и `!`, которые принимают аргументы
|
||||
# любого типа. Всё, кроме `false` и `nil`, считается `true`.
|
||||
1 || true #=> 1
|
||||
false && 1 #=> false
|
||||
nil && 20 #=> nil
|
||||
!true #=> false
|
||||
|
||||
# Операторы сравнения: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<`, `>`
|
||||
1 == 1 #=> true
|
||||
1 != 1 #=> false
|
||||
1 < 2 #=> true
|
||||
|
||||
# Операторы `===` и `!==` более строгие. Разница заметна, когда мы сравниваем
|
||||
# числа целые и с плавающей запятой:
|
||||
1 == 1.0 #=> true
|
||||
1 === 1.0 #=> false
|
||||
|
||||
# Elixir позволяет сравнивать значения разных типов:
|
||||
1 < :hello #=> true
|
||||
|
||||
# При сравнении разных типов руководствуйтесь следующим правилом:
|
||||
# число < атом < ссылка < функция < порт < процесс < кортеж < список < строка
|
||||
|
||||
## ---------------------------
|
||||
## -- Порядок выполнения
|
||||
## ---------------------------
|
||||
|
||||
# Условный оператор `if`
|
||||
if false do
|
||||
"Вы этого никогда не увидите"
|
||||
else
|
||||
"Вы увидите это"
|
||||
end
|
||||
|
||||
# Противоположный ему условный оператор `unless`
|
||||
unless true do
|
||||
"Вы этого никогда не увидите"
|
||||
else
|
||||
"Вы увидите это"
|
||||
end
|
||||
|
||||
# Помните сопоставление с образцом?
|
||||
# Многие конструкции в Elixir построены вокруг него.
|
||||
|
||||
# `case` позволяет сравнить выражение с несколькими образцами:
|
||||
case {:one, :two} do
|
||||
{:four, :five} ->
|
||||
"Этот образец не совпадёт"
|
||||
{:one, x} ->
|
||||
"Этот образец совпадёт и присвоит переменной `x` значение `:two`"
|
||||
_ ->
|
||||
"Этот образец совпадёт с чем угодно"
|
||||
end
|
||||
|
||||
# Символ `_` называется анонимной переменной. Используйте `_` для значений,
|
||||
# которые в текущем выражении вас не интересуют. Например, вам интересна лишь
|
||||
# голова списка, а хвост вы желаете проигнорировать:
|
||||
[head | _] = [1,2,3]
|
||||
head #=> 1
|
||||
|
||||
# Для лучшей читаемости вы можете написать:
|
||||
[head | _tail] = [:a, :b, :c]
|
||||
head #=> :a
|
||||
|
||||
# `cond` позволяет проверить сразу несколько условий за раз.
|
||||
# Используйте `cond` вместо множественных операторов `if`.
|
||||
cond do
|
||||
1 + 1 == 3 ->
|
||||
"Вы меня никогда не увидите"
|
||||
2 * 5 == 12 ->
|
||||
"И меня"
|
||||
1 + 2 == 3 ->
|
||||
"Вы увидите меня"
|
||||
end
|
||||
|
||||
# Обычно последним условием идёт `true`, которое выполнится, если все предыдущие
|
||||
# условия оказались ложны.
|
||||
cond do
|
||||
1 + 1 == 3 ->
|
||||
"Вы меня никогда не увидите"
|
||||
2 * 5 == 12 ->
|
||||
"И меня"
|
||||
true ->
|
||||
"Вы увидите меня (по сути, это `else`)"
|
||||
end
|
||||
|
||||
# Обработка ошибок происходит в блоках `try/catch`.
|
||||
# Elixir также поддерживает блок `after`, который выполнится в любом случае.
|
||||
try do
|
||||
throw(:hello)
|
||||
catch
|
||||
message -> "Поймана ошибка с сообщением #{message}."
|
||||
after
|
||||
IO.puts("Я выполнюсь всегда")
|
||||
end
|
||||
#=> Я выполнюсь всегда
|
||||
# "Поймана ошибка с сообщением hello."
|
||||
|
||||
## ---------------------------
|
||||
## -- Модули и функции
|
||||
## ---------------------------
|
||||
|
||||
# Анонимные функции (обратите внимание на точку при вызове функции)
|
||||
square = fn(x) -> x * x end
|
||||
square.(5) #=> 25
|
||||
|
||||
# Анонимные функции принимают клозы и гарды.
|
||||
#
|
||||
# Клозы (от англ. clause) — варианты исполнения функции.
|
||||
#
|
||||
# Гарды (от англ. guard) — охранные выражения, уточняющие сопоставление с
|
||||
# образцом в функциях. Гарды следуют после ключевого слова `when`.
|
||||
f = fn
|
||||
x, y when x > 0 -> x + y
|
||||
x, y -> x * y
|
||||
end
|
||||
|
||||
f.(1, 3) #=> 4
|
||||
f.(-1, 3) #=> -3
|
||||
|
||||
# В Elixir много встроенных функций.
|
||||
# Они доступны в текущей области видимости.
|
||||
is_number(10) #=> true
|
||||
is_list("hello") #=> false
|
||||
elem({1,2,3}, 0) #=> 1
|
||||
|
||||
# Вы можете объединить несколько функций в модуль. Внутри модуля используйте `def`,
|
||||
# чтобы определить свои функции.
|
||||
defmodule Math do
|
||||
def sum(a, b) do
|
||||
a + b
|
||||
end
|
||||
|
||||
def square(x) do
|
||||
x * x
|
||||
end
|
||||
end
|
||||
|
||||
Math.sum(1, 2) #=> 3
|
||||
Math.square(3) #=> 9
|
||||
|
||||
# Чтобы скомпилировать модуль Math, сохраните его в файле `math.ex`
|
||||
# и наберите в терминале: `elixirc math.ex`
|
||||
|
||||
defmodule PrivateMath do
|
||||
# Публичные функции начинаются с `def` и доступны из других модулей.
|
||||
def sum(a, b) do
|
||||
do_sum(a, b)
|
||||
end
|
||||
|
||||
# Приватные функции начинаются с `defp` и доступны только внутри своего модуля.
|
||||
defp do_sum(a, b) do
|
||||
a + b
|
||||
end
|
||||
end
|
||||
|
||||
PrivateMath.sum(1, 2) #=> 3
|
||||
PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError)
|
||||
|
||||
# Функции внутри модуля тоже принимают клозы и гарды
|
||||
defmodule Geometry do
|
||||
def area({:rectangle, w, h}) do
|
||||
w * h
|
||||
end
|
||||
|
||||
def area({:circle, r}) when is_number(r) do
|
||||
3.14 * r * r
|
||||
end
|
||||
end
|
||||
|
||||
Geometry.area({:rectangle, 2, 3}) #=> 6
|
||||
Geometry.area({:circle, 3}) #=> 28.25999999999999801048
|
||||
Geometry.area({:circle, "not_a_number"}) #=> ** (FunctionClauseError)
|
||||
|
||||
# Из-за неизменяемых переменных в Elixir важную роль играет рекурсия
|
||||
defmodule Recursion do
|
||||
def sum_list([head | tail], acc) do
|
||||
sum_list(tail, acc + head)
|
||||
end
|
||||
|
||||
def sum_list([], acc) do
|
||||
acc
|
||||
end
|
||||
end
|
||||
|
||||
Recursion.sum_list([1,2,3], 0) #=> 6
|
||||
|
||||
# Модули в Elixir поддерживают атрибуты.
|
||||
# Атрибуты бывают как встроенные, так и ваши собственные.
|
||||
defmodule MyMod do
|
||||
@moduledoc """
|
||||
Это встроенный атрибут
|
||||
"""
|
||||
|
||||
@my_data 100 # А это ваш атрибут
|
||||
IO.inspect(@my_data) #=> 100
|
||||
end
|
||||
|
||||
# Одна из фишек языка — оператор `|>`
|
||||
# Он передаёт выражение слева в качестве первого аргумента функции справа:
|
||||
Range.new(1,10)
|
||||
|> Enum.map(fn x -> x * x end)
|
||||
|> Enum.filter(fn x -> rem(x, 2) == 0 end)
|
||||
#=> [4, 16, 36, 64, 100]
|
||||
|
||||
## ---------------------------
|
||||
## -- Структуры и исключения
|
||||
## ---------------------------
|
||||
|
||||
# Структуры — это расширения поверх карт, привносящие в Elixir значения по
|
||||
# умолчанию, проверки на этапе компиляции и полиморфизм.
|
||||
defmodule Person do
|
||||
defstruct name: nil, age: 0, height: 0
|
||||
end
|
||||
|
||||
joe_info = %Person{ name: "Joe", age: 30, height: 180 }
|
||||
#=> %Person{age: 30, height: 180, name: "Joe"}
|
||||
|
||||
# Доступ к полю структуры
|
||||
joe_info.name #=> "Joe"
|
||||
|
||||
# Обновление поля структуры
|
||||
older_joe_info = %{ joe_info | age: 31 }
|
||||
#=> %Person{age: 31, height: 180, name: "Joe"}
|
||||
|
||||
# Блок `try` с ключевым словом `rescue` используется для обработки исключений
|
||||
try do
|
||||
raise "какая-то ошибка"
|
||||
rescue
|
||||
RuntimeError -> "перехвачена ошибка рантайма"
|
||||
_error -> "перехват любой другой ошибки"
|
||||
end
|
||||
#=> "перехвачена ошибка рантайма"
|
||||
|
||||
# У каждого исключения есть сообщение
|
||||
try do
|
||||
raise "какая-то ошибка"
|
||||
rescue
|
||||
x in [RuntimeError] ->
|
||||
x.message
|
||||
end
|
||||
#=> "какая-то ошибка"
|
||||
|
||||
## ---------------------------
|
||||
## -- Параллелизм
|
||||
## ---------------------------
|
||||
|
||||
# Параллелизм в Elixir построен на модели акторов. Для написания
|
||||
# параллельной программы нам понадобятся три вещи:
|
||||
# 1. Создание процессов
|
||||
# 2. Отправка сообщений
|
||||
# 3. Приём сообщений
|
||||
|
||||
# Новый процесс создаётся функцией `spawn`, которая принимает функцию
|
||||
# в качестве аргумента.
|
||||
f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245>
|
||||
spawn(f) #=> #PID<0.40.0>
|
||||
|
||||
# `spawn` возвращает идентификатор процесса (англ. process identifier, PID).
|
||||
# Вы можете использовать PID для отправки сообщений этому процессу. Сообщения
|
||||
# отправляются через оператор `send`. А для приёма сообщений используется
|
||||
# механизм `receive`:
|
||||
|
||||
# Блок `receive do` ждёт сообщений и обработает их, как только получит. Блок
|
||||
# `receive do` обработает лишь одно полученное сообщение. Чтобы обработать
|
||||
# несколько сообщений, функция, содержащая блок `receive do`, должна рекурсивно
|
||||
# вызывать себя.
|
||||
|
||||
defmodule Geometry do
|
||||
def area_loop do
|
||||
receive do
|
||||
{:rectangle, w, h} ->
|
||||
IO.puts("Площадь = #{w * h}")
|
||||
area_loop()
|
||||
{:circle, r} ->
|
||||
IO.puts("Площадь = #{3.14 * r * r}")
|
||||
area_loop()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Скомпилируйте модуль и создайте процесс
|
||||
pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0>
|
||||
# Альтернативно
|
||||
pid = spawn(Geometry, :area_loop, [])
|
||||
|
||||
# Отправьте сообщение процессу
|
||||
send pid, {:rectangle, 2, 3}
|
||||
#=> Площадь = 6
|
||||
# {:rectangle,2,3}
|
||||
|
||||
send pid, {:circle, 2}
|
||||
#=> Площадь = 12.56
|
||||
# {:circle,2}
|
||||
|
||||
# Кстати, интерактивная консоль — это тоже процесс.
|
||||
# Чтобы узнать текущий PID, воспользуйтесь встроенной функцией `self`
|
||||
self() #=> #PID<0.27.0>
|
||||
|
||||
## ---------------------------
|
||||
## -- Агенты
|
||||
## ---------------------------
|
||||
|
||||
# Агент — это процесс, который следит за некоторым изменяющимся значением.
|
||||
|
||||
# Создайте агента через `Agent.start_link`, передав ему функцию.
|
||||
# Начальным состоянием агента будет значение, которое эта функция возвращает.
|
||||
{ok, my_agent} = Agent.start_link(fn -> ["красный", "зелёный"] end)
|
||||
|
||||
# `Agent.get` принимает имя агента и анонимную функцию `fn`, которой будет
|
||||
# передано текущее состояние агента. В результате вы получите то, что вернёт
|
||||
# анонимная функция.
|
||||
Agent.get(my_agent, fn colors -> colors end) #=> ["красный", "зелёный"]
|
||||
|
||||
# Похожим образом вы можете обновить состояние агента
|
||||
Agent.update(my_agent, fn colors -> ["синий" | colors] end)
|
||||
```
|
||||
|
||||
## Ссылки
|
||||
|
||||
* [Официальный сайт](http://elixir-lang.org)
|
||||
* [Шпаргалка по языку](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
|
||||
* [Книга "Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir)
|
||||
* [Книга "Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/)
|
||||
* [Книга "Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang)
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: Haskell
|
||||
filename: haskell-ru.hs
|
||||
contributors:
|
||||
- ["Adit Bhargava", "http://adit.io"]
|
||||
translators:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: html
|
||||
filename: learnhtml.html
|
||||
filename: learnhtml-ru.html
|
||||
contributors:
|
||||
- ["Christophe THOMAS", "https://github.com/WinChris"]
|
||||
translators:
|
||||
|
@ -1,12 +1,13 @@
|
||||
---
|
||||
language: java
|
||||
filename: LearnJava-ru.java
|
||||
contributors:
|
||||
- ["Jake Prather", "http://github.com/JakeHP"]
|
||||
- ["Madison Dickson", "http://github.com/mix3d"]
|
||||
translators:
|
||||
- ["Sergey Gaykov", "https://github.com/gaykov"]
|
||||
filename: LearnJavaRu.java
|
||||
lang: ru-ru
|
||||
|
||||
---
|
||||
|
||||
Java - это объектно-ориентированный язык программирования общего назначения,
|
||||
|
@ -781,7 +781,7 @@ MyClass *newVar = [classVar retain]; // Если classVar освободится
|
||||
// автоматический подсчет ссылок (ARC).
|
||||
// ARC - это особенность компилятора, который помещает "retain", "release"
|
||||
// и "autorelease" автоматически за вас тогда, когда используется ARC,
|
||||
// вам не нужно больше обращаться к "retain", "relase" или "autorelease"
|
||||
// вам не нужно больше обращаться к "retain", "release" или "autorelease"
|
||||
MyClass *arcMyClass = [[MyClass alloc] init];
|
||||
// ... код, использующий объект arcMyClass
|
||||
// Без ARC, вам нужно было бы вызвать: [arcMyClass release] после того, как вы
|
||||
|
@ -128,7 +128,7 @@ define("FOO", "something");
|
||||
|
||||
// Доступ к константе возможен через прямое указание её имени без знака $
|
||||
echo FOO; // печатает 'something'
|
||||
echo 'This outputs ' . FOO; // печатает 'This ouputs something'
|
||||
echo 'This outputs ' . FOO; // печатает 'This outputs something'
|
||||
|
||||
/********************************
|
||||
* Массивы
|
||||
|
@ -88,7 +88,7 @@ implementation.
|
||||
to have stopped since Microsoft pulled their support.
|
||||
|
||||
Ruby implementations may have their own release version numbers, but they always
|
||||
target a specific version of MRI for compatability. Many implementations have
|
||||
target a specific version of MRI for compatibility. Many implementations have
|
||||
the ability to enter different modes (for example, 1.8 or 1.9 mode) to specify
|
||||
which MRI version to target.
|
||||
|
||||
|
@ -3,8 +3,8 @@ language: rust
|
||||
filename: rust-pt.rs
|
||||
contributors:
|
||||
- ["Paulo Henrique Rodrigues Pinheiro", "https://about.me/paulohrpinheiro"]
|
||||
filename: learnrust.rs
|
||||
lang: pt-br
|
||||
|
||||
---
|
||||
|
||||
Rust é uma linguagem de programação desenvolvida pelo Mozilla Research. Rust
|
||||
|
@ -10,7 +10,7 @@ filename: learnshutit.html
|
||||
|
||||
ShutIt is an shell automation framework designed to be easy to use.
|
||||
|
||||
It is a wrapper around a python-based expect clone (pexpect).
|
||||
It is a wrapper around a Python-based expect clone (pexpect).
|
||||
|
||||
You can look at it as 'expect without the pain'.
|
||||
|
||||
@ -167,8 +167,8 @@ session2.logout()
|
||||
Here you use the 'send\_and\_get\_output' method to retrieve the output of the
|
||||
capacity command (df).
|
||||
|
||||
There are much more elegant ways to do the above (eg have a dictionary of the
|
||||
servers to iterate over), but it's up to you how clever you need the python to
|
||||
There are much more elegant ways to do the above (e.g. have a dictionary of the
|
||||
servers to iterate over), but it's up to you how clever you need the Python to
|
||||
be.
|
||||
|
||||
|
||||
@ -300,7 +300,7 @@ over a minute to complete (using the 'wait' method).
|
||||
|
||||
Again, this is trivial, but imagine you have hundreds of servers to manage like
|
||||
this and you can see the power it can bring in a few lines of code and one
|
||||
python import.
|
||||
Python import.
|
||||
|
||||
|
||||
## Learn More
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: smalltalk
|
||||
filename: smalltalk.st
|
||||
contributors:
|
||||
- ["Jigyasa Grover", "https://github.com/jig08"]
|
||||
---
|
||||
@ -907,7 +908,7 @@ b := String isWords. true if index instan
|
||||
Object withAllSubclasses size. "get total number of class entries"
|
||||
```
|
||||
|
||||
## Debuging:
|
||||
## Debugging:
|
||||
```
|
||||
| a b x |
|
||||
x yourself. "returns receiver"
|
||||
|
@ -37,6 +37,9 @@ features are typically marked, and subject to change. Pull requests welcome.
|
||||
// simple_bank.sol (note .sol extension)
|
||||
/* **** START EXAMPLE **** */
|
||||
|
||||
// Declare the source file compiler version.
|
||||
pragma solidity ^0.4.2;
|
||||
|
||||
// Start with Natspec comment (the three slashes)
|
||||
// used for documentation - and as descriptive data for UI elements/actions
|
||||
|
||||
@ -188,7 +191,7 @@ string n = "hello"; // stored in UTF8, note double quotes, not single
|
||||
// string utility functions to be added in future
|
||||
// prefer bytes32/bytes, as UTF8 uses more storage
|
||||
|
||||
// Type inferrence
|
||||
// Type inference
|
||||
// var does inferred typing based on first assignment,
|
||||
// can't be used in functions parameters
|
||||
var a = true;
|
||||
@ -484,7 +487,7 @@ contract MyContract is abc, def("a custom argument to def") {
|
||||
function z() {
|
||||
if (msg.sender == owner) {
|
||||
def.z(); // call overridden function from def
|
||||
super.z(); // call immediate parent overriden function
|
||||
super.z(); // call immediate parent overridden function
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -804,7 +807,7 @@ someContractAddress.callcode('function_name');
|
||||
// else should be placed on own line
|
||||
|
||||
|
||||
// 14. NATSPEC COMENTS
|
||||
// 14. NATSPEC COMMENTS
|
||||
// used for documentation, commenting, and external UIs
|
||||
|
||||
// Contract natspec - always above contract definition
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: "Standard ML"
|
||||
filename: standardml.sml
|
||||
contributors:
|
||||
- ["Simon Shine", "http://shine.eu.org/"]
|
||||
- ["David Pedersen", "http://lonelyproton.com/"]
|
||||
@ -351,7 +352,10 @@ val _ = print (say(Red) ^ "\n")
|
||||
fun say Red = "You are red!"
|
||||
| say Green = "You are green!"
|
||||
| say Blue = "You are blue!"
|
||||
| say _ = raise Fail "Unknown color"
|
||||
|
||||
(* We did not include the match arm `say _ = raise Fail "Unknown color"`
|
||||
because after specifying all three colors, the pattern is exhaustive
|
||||
and redundancy is not permitted in pattern matching *)
|
||||
|
||||
|
||||
(* Here is a binary tree datatype *)
|
||||
@ -395,7 +399,7 @@ fun failing_function [] = raise Empty (* used for empty lists *)
|
||||
| failing_function xs = raise Fail "This list is too long!"
|
||||
|
||||
(* We can pattern match in 'handle' to make sure
|
||||
a specfic exception was raised, or grab the message *)
|
||||
a specific exception was raised, or grab the message *)
|
||||
val err_msg = failing_function [1,2] handle Fail _ => "Fail was raised"
|
||||
| Domain => "Domain was raised"
|
||||
| Empty => "Empty was raised"
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: brainfuck
|
||||
filename: brainfuck-sv.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -281,7 +281,7 @@ testGuard()
|
||||
|
||||
// Variadic Args
|
||||
func setup(numbers: Int...) {
|
||||
// its an array
|
||||
// it's an array
|
||||
let _ = numbers[0]
|
||||
let _ = numbers.count
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: json
|
||||
filename: learnjson.json
|
||||
filename: learnjson-ta.json
|
||||
contributors:
|
||||
- ["Anna Harren", "https://github.com/iirelu"]
|
||||
- ["Marco Scannadinari", "https://github.com/marcoms"]
|
||||
|
@ -49,7 +49,7 @@ discipline of exposing all programmatic functionality as routines, including
|
||||
things like looping and mathematical operations that are usually baked into the
|
||||
syntax of other languages, allows it to fade into the background of whatever
|
||||
domain-specific functionality a project needs. Its syntax, which is even
|
||||
lighter that that of Lisp, just gets out of the way.
|
||||
lighter than that of Lisp, just gets out of the way.
|
||||
|
||||
|
||||
|
||||
@ -75,7 +75,7 @@ lighter that that of Lisp, just gets out of the way.
|
||||
## 2. Syntax
|
||||
###############################################################################
|
||||
|
||||
# A script is made up of commands delimited by newlines or semiclons. Each
|
||||
# A script is made up of commands delimited by newlines or semicolons. Each
|
||||
# command is a call to a routine. The first word is the name of a routine to
|
||||
# call, and subsequent words are arguments to the routine. Words are delimited
|
||||
# by whitespace. Since each argument is a word in the command it is already a
|
||||
@ -99,13 +99,13 @@ set greeting $part1$part2[set part3]
|
||||
|
||||
|
||||
# An embedded script may be composed of multiple commands, the last of which provides
|
||||
# the result for the substtution:
|
||||
# the result for the substitution:
|
||||
set greeting $greeting[
|
||||
incr i
|
||||
incr i
|
||||
incr i
|
||||
]
|
||||
puts $greeting ;# The output is "Salutations3"
|
||||
puts $greeting ;# The output is "Salutations3"
|
||||
|
||||
# Every word in a command is a string, including the name of the routine, so
|
||||
# substitutions can be used on it as well. Given this variable
|
||||
@ -377,7 +377,7 @@ set amount [lindex $amounts 1]
|
||||
set inventory {"item 1" item\ 2 {item 3}}
|
||||
|
||||
|
||||
# It's generally a better idea to use list routines when modifing lists:
|
||||
# It's generally a better idea to use list routines when modifying lists:
|
||||
lappend inventory {item 1} {item 2} {item 3}
|
||||
|
||||
|
||||
@ -422,8 +422,7 @@ eval {set name Neo}
|
||||
eval [list set greeting "Hello, $name"]
|
||||
|
||||
|
||||
# Therefore, when using "eval", , use "list" to build
|
||||
# up the desired command:
|
||||
# Therefore, when using "eval", use "list" to build up the desired command:
|
||||
set command {set name}
|
||||
lappend command {Archibald Sorbisol}
|
||||
eval $command
|
||||
@ -517,7 +516,7 @@ proc while {condition script} {
|
||||
# and then calls that routine. "yield" suspends evaluation in that stack and
|
||||
# returns control to the calling stack:
|
||||
proc countdown count {
|
||||
# send something back to the creater of the coroutine, effectively pausing
|
||||
# send something back to the creator of the coroutine, effectively pausing
|
||||
# this call stack for the time being.
|
||||
yield [info coroutine]
|
||||
|
||||
|
@ -2,8 +2,8 @@
|
||||
language: tcsh
|
||||
filename: LearnTCSH.csh
|
||||
contributors:
|
||||
- ["Nicholas Christopoulos", "https://github.com/nereusx"]
|
||||
lang: en
|
||||
- ["Nicholas Christopoulos", "https://github.com/nereusx"]
|
||||
|
||||
---
|
||||
tcsh ("tee-see-shell") is a Unix shell based on and compatible with the C shell (csh).
|
||||
It is essentially the C shell with programmable command-line completion, command-line editing,
|
||||
@ -592,7 +592,7 @@ while ( $#lst )
|
||||
shift lst
|
||||
end
|
||||
echo 'options =' $options
|
||||
echo 'paramaters =' $params
|
||||
echo 'parameters =' $params
|
||||
|
||||
#### REPEAT
|
||||
# Syntax: repeat count command
|
||||
|
@ -481,7 +481,7 @@ Diğer bir iyi kaynak ise [Learn C the hard way](http://c.learncodethehardway.or
|
||||
|
||||
It's very important to use proper spacing, indentation and to be consistent with your coding style in general.
|
||||
Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the
|
||||
[Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle).
|
||||
[Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle).
|
||||
|
||||
Diğer taraftan google sizin için bir arkadaş olabilir.
|
||||
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: Dynamic Programming
|
||||
filename: dynamic-tr.txt
|
||||
contributors:
|
||||
- ["Akashdeep Goel", "https://github.com/akashdeepgoel"]
|
||||
translators:
|
||||
@ -27,6 +28,8 @@ En Uzun Artan Subsequence problemi belirli bir dizinin en uzun artan alt dizini
|
||||
En uzun artan alt dizinin uzunluğunu bulmak için sözde kod: Bu algoritmaların karmaşıklığı dizi yerine daha iyi veri yapısı kullanılarak azaltılabilir. Büyük dizin ve dizin gibi selefi dizi ve değişkeni saklama çok zaman kazandıracaktır.
|
||||
|
||||
Yönlendirilmiş asiklik grafiğinde en uzun yolu bulmak için benzer bir kavram uygulanabilir.
|
||||
|
||||
```python
|
||||
for i=0 to n-1
|
||||
LS[i]=1
|
||||
for j=0 to i-1
|
||||
@ -35,6 +38,8 @@ for i=0 to n-1
|
||||
for i=0 to n-1
|
||||
if (largest < LS[i])
|
||||
|
||||
```
|
||||
|
||||
Bazı Ünlü Dinamik Programlama Problemleri
|
||||
-Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs—floyd-warshall-algorithm-with-c-program-source-code
|
||||
-Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming—the-integer-knapsack-problem
|
||||
|
474
tr-tr/kotlin-tr.html.markdown
Normal file
474
tr-tr/kotlin-tr.html.markdown
Normal file
@ -0,0 +1,474 @@
|
||||
---
|
||||
language: kotlin
|
||||
filename: kotlin-tr.kt
|
||||
contributors:
|
||||
- ["Baha Can Aydın", "https://github.com/bahacan19"]
|
||||
lang: tr-tr
|
||||
---
|
||||
Kotlin, JVM, Android ve tarayıcı için statik olarak yazılmış bir programlama dilidir.
|
||||
Java %100 birlikte çalışabilir.
|
||||
[Daha:](https://kotlinlang.org/)
|
||||
|
||||
```kotlin
|
||||
|
||||
// Tek satır yoruma almak için : //
|
||||
/*
|
||||
Birkaç satırı yoruma almak için
|
||||
*/
|
||||
|
||||
// "package" anahtar kelimesi tıpkı Java'da olduğu gibidir.
|
||||
package com.learnxinyminutes.kotlin
|
||||
|
||||
/*
|
||||
Bir Kotlin programının başlama noktası (Java'da olduğu gibi) "com.learnxinyminutes.kotlin.main" metodudur.
|
||||
Bu metoda komut satırından bir 'Array' gönderilebilir.
|
||||
*/
|
||||
fun main(args: Array<String>) {
|
||||
/*
|
||||
Bir değer tanımlamak için "var" ya da "val" anahtar kelimeleri kullanılıyor.
|
||||
"val" tanımlananlar tekrar atanamazken "var" tanımlananlar atanabilir.
|
||||
*/
|
||||
val fooVal = 10 // fooVal değerini daha sonra tekrar atayamıyoruz
|
||||
var fooVar = 10
|
||||
fooVar = 20 // fooVar tekrar atanabilir.
|
||||
|
||||
/*
|
||||
Çoğu zaman, Kotlin bir değişkenin tipini anlayabilir,
|
||||
bu yüzden her zaman belirtmeye gerek yoktur.
|
||||
Bir değişkenin tipini şöyle belirtebiliriz:
|
||||
*/
|
||||
val foo: Int = 7
|
||||
|
||||
/*
|
||||
String değerler Java'da olduğu gibi tanımlanır.
|
||||
*/
|
||||
val fooString = "İşte String bu!"
|
||||
val barString = "Yeni satıra geçiyorum...?\nGeçtim!"
|
||||
val bazString = "Tab mı istedin?\tAl bakalım!"
|
||||
println(fooString)
|
||||
println(barString)
|
||||
println(bazString)
|
||||
|
||||
/*
|
||||
Raw string, üçlü çift-tırnak sınırlandırılan String bloklarıdır.
|
||||
Tıpkı bir text editör gibi String tanımlamaya izin verir.
|
||||
*/
|
||||
val fooRawString = """
|
||||
fun helloWorld(val name : String) {
|
||||
println("Merhaba, dünya!")
|
||||
}
|
||||
"""
|
||||
println(fooRawString)
|
||||
|
||||
/*
|
||||
String değerler, ($) işareti ile birtakım deyimler ve değerler içererbilir
|
||||
*/
|
||||
val fooTemplateString = "$fooString değerinin ${fooString.length} adet karakteri vardır."
|
||||
println(fooTemplateString)
|
||||
|
||||
/*
|
||||
Null atanabilen bir değişken nullable olarak tanımlanmalıdır.
|
||||
Bu, deişken tipinin sonuna ? eklenerek yapılabilir.
|
||||
Erişim ise '?.' operatörü ile yapılır.
|
||||
Bir değişken null ise, yerine kullaılacak alternatif bir değer belirtmek için
|
||||
'?:' operatörünü kullanırız.
|
||||
*/
|
||||
var fooNullable: String? = "abc"
|
||||
println(fooNullable?.length) // => 3
|
||||
println(fooNullable?.length ?: -1) // => 3
|
||||
fooNullable = null
|
||||
println(fooNullable?.length) // => null
|
||||
println(fooNullable?.length ?: -1) // => -1
|
||||
|
||||
/*
|
||||
Metodlar "fun" anahtar kelimesi ile tanımlanır.
|
||||
Metod argümanları, Metod adından sonra parantez içinde belirtilir.
|
||||
Metod argümanlarının opsiyonel olarak default (varsayılan) değerleri olabilir.
|
||||
Metodun dönüş tipi, gerekirse, metod parentezinden sonra ':' operatörü ile belirtilir.
|
||||
*/
|
||||
fun hello(name: String = "dünya"): String {
|
||||
return "Merhaba, $name!"
|
||||
}
|
||||
println(hello("foo")) // => Merhaba, foo!
|
||||
println(hello(name = "bar")) // => Merhaba, bar!
|
||||
println(hello()) // => Merhaba, dünya!
|
||||
|
||||
/*
|
||||
Bir metoda çokca argüman göndermek için 'vararg' anahtar kelimesi
|
||||
kullanılır.
|
||||
*/
|
||||
fun varargExample(vararg names: Int) {
|
||||
println("${names.size} adet arguman paslanmıştır")
|
||||
}
|
||||
varargExample() // => 0 adet arguman paslanmıştır
|
||||
varargExample(1) // => 1 adet arguman paslanmıştır
|
||||
varargExample(1, 2, 3) // => 3 adet arguman paslanmıştır
|
||||
|
||||
/*
|
||||
Bir metod tek bir ifadeden oluşuyorsa
|
||||
süslü parantezler yerine '=' kullanılabilir.
|
||||
*/
|
||||
fun odd(x: Int): Boolean = x % 2 == 1
|
||||
println(odd(6)) // => false
|
||||
println(odd(7)) // => true
|
||||
|
||||
// Eğer dönüş tipi anlaşılabiliyorsa ayrıca belirtmemize gerek yoktur.
|
||||
fun even(x: Int) = x % 2 == 0
|
||||
println(even(6)) // => true
|
||||
println(even(7)) // => false
|
||||
|
||||
// Metodlar, metodları arguman ve dönüş tipi olarak alabilir
|
||||
fun not(f: (Int) -> Boolean): (Int) -> Boolean {
|
||||
return {n -> !f.invoke(n)} // bu satırdaki !f.invoke(n) metodu !f(n) şeklinde sadeleştirilebilir.
|
||||
}
|
||||
|
||||
|
||||
// Bir metodu sadece '::' ön eki ile de arguman olarak çağırabiliriz
|
||||
println(not(::odd)(4)) // ==> true
|
||||
|
||||
// Metodlar değişken gibi atanabilir.
|
||||
val notOdd = not(::odd)
|
||||
val notEven = not(::even)
|
||||
|
||||
// Lambda ifadeleri arguman olarak paslanabilir.
|
||||
val notZero = not {n -> n == 0}
|
||||
/*
|
||||
Eğer bir lambda fonksiyonu sadece bir arguman alıyorsa,
|
||||
'->' ifadesi atlanabilir, 'it' ifadesi ile belirtilebilir.
|
||||
*/
|
||||
val notPositive = not { it > 0} // not(n -> n > 0) ifadesi ile aynı
|
||||
|
||||
for (i in 0..4) {
|
||||
println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}")
|
||||
}
|
||||
|
||||
/*
|
||||
* Diğer for döngüleri
|
||||
* */
|
||||
val myInt = 3
|
||||
for (i in 1..100) { } // kapalı aralık. 100 dahil.
|
||||
for (i in 1 until 100) { } // 100 dahil değil
|
||||
for (x in 2..10 step 2) { } // ikişer adımlı
|
||||
for (x in 10 downTo 1) { } // Ondan geriye doğru. 1 dahil.
|
||||
if (myInt in 1..10) { }
|
||||
|
||||
|
||||
|
||||
/*
|
||||
Bir sınıf tanımlamak için 'class' anahtar kelimesi kullanılır.
|
||||
Kotlin'de bütün sınıflar varsayılan olarak 'final' tanımlanırlar.
|
||||
* */
|
||||
class ExampleClass(val x: Int) {
|
||||
|
||||
fun memberFunction(y: Int): Int {
|
||||
return x + y
|
||||
}
|
||||
|
||||
infix fun yTimes(y: Int): Int {
|
||||
return x * y
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Bir sınıfı türetilebilir yapmak için 'open' anahtar kelimesi kullanılır.
|
||||
* */
|
||||
open class A
|
||||
|
||||
class B : A()
|
||||
|
||||
|
||||
/*
|
||||
Yeni bir instance oluşturmak için doğrudan constructor çağırılır.
|
||||
Kotlinde 'new' anahtar kelimesi yoktur.
|
||||
*/
|
||||
val fooExampleClass = ExampleClass(7)
|
||||
// Bir sınıfa üye metodları . (nokta) ile çağırabiliriz.
|
||||
println(fooExampleClass.memberFunction(4)) // => 11
|
||||
/*
|
||||
'infix' ön eki ile tanımlanan metodlar
|
||||
alışılan metod çağrısını daha kolay bir söz dizimine dönüştürür.
|
||||
*/
|
||||
println(fooExampleClass yTimes 4) // => 28
|
||||
|
||||
/*
|
||||
Data class lar sadece veri tutan sınıflar için uygun bir çözümdür.
|
||||
Bu şekilde tanımlanan sınıfların "hashCode"/"equals" ve "toString" metodları
|
||||
otomatik olarak oluşur.
|
||||
*/
|
||||
data class DataClassExample (val x: Int, val y: Int, val z: Int)
|
||||
val fooData = DataClassExample(1, 2, 4)
|
||||
println(fooData) // => DataClassExample(x=1, y=2, z=4)
|
||||
|
||||
// Data class ların copy metodları olur.
|
||||
val fooCopy = fooData.copy(y = 100)
|
||||
println(fooCopy) // => DataClassExample(x=1, y=100, z=4)
|
||||
|
||||
// Destructuring Declarations, bir objeyi çoklu değişkenler ile ifade etme yöntemidir.
|
||||
val (a, b, c) = fooCopy
|
||||
println("$a $b $c") // => 1 100 4
|
||||
|
||||
// bir 'for' döngüsü içinde 'Destructuring' :
|
||||
for ((a, b, c) in listOf(fooData)) {
|
||||
println("$a $b $c") // => 1 100 4
|
||||
}
|
||||
|
||||
val mapData = mapOf("a" to 1, "b" to 2)
|
||||
// Map.Entry de destructurable gösterilebilir.
|
||||
for ((key, value) in mapData) {
|
||||
println("$key -> $value")
|
||||
}
|
||||
|
||||
// 'with' metodu ile bir objeye bir lamda metodu uygulayabiliriz.
|
||||
data class MutableDataClassExample (var x: Int, var y: Int, var z: Int)
|
||||
val fooMutableData = MutableDataClassExample(7, 4, 9)
|
||||
with (fooMutableData) {
|
||||
x -= 2
|
||||
y += 2
|
||||
z--
|
||||
}
|
||||
|
||||
println(fooMutableData) // => MutableDataClassExample(x=5, y=6, z=8)
|
||||
|
||||
/*
|
||||
'listOf' metodu ile bir liste oluşturulabilir.
|
||||
Oluşan liste immutable olacaktır, yani elaman eklenemez ve çıkarılamaz.
|
||||
*/
|
||||
val fooList = listOf("a", "b", "c")
|
||||
println(fooList.size) // => 3
|
||||
println(fooList.first()) // => a
|
||||
println(fooList.last()) // => c
|
||||
// Elemanlara indexleri ile erişilebilir.
|
||||
println(fooList[1]) // => b
|
||||
|
||||
// Mutable bir liste ise 'mutableListOf' metodu ile oluşturabilir.
|
||||
val fooMutableList = mutableListOf("a", "b", "c")
|
||||
fooMutableList.add("d")
|
||||
println(fooMutableList.last()) // => d
|
||||
println(fooMutableList.size) // => 4
|
||||
|
||||
// Bir 'set' oluşturmak için 'setOf' metodunu kullanabiliriz.
|
||||
val fooSet = setOf("a", "b", "c")
|
||||
println(fooSet.contains("a")) // => true
|
||||
println(fooSet.contains("z")) // => false
|
||||
|
||||
// 'mapOf' metodu ile 'map' oluşturabiliriz.
|
||||
val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9)
|
||||
// Map değerlerine ulaşmak için :
|
||||
println(fooMap["a"]) // => 8
|
||||
|
||||
/*
|
||||
Sequence, Kotlin dilinde lazy-hesaplanan collection ları temsil eder.
|
||||
Bunun için 'generateSequence' metodunu kullanabiliriz. Bu metod bir önceki değerden
|
||||
bir sonraki değeri hesaplamak için gerekli bir lamda metodunu arguman olarak alır.
|
||||
*/
|
||||
val fooSequence = generateSequence(1, { it + 1 })
|
||||
|
||||
val x = fooSequence.take(10).toList()
|
||||
println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
|
||||
// Örneğin fibonacci serisi oluşturabilen bir 'Sequence' oluşturmak için:
|
||||
fun fibonacciSequence(): Sequence<Long> {
|
||||
var a = 0L
|
||||
var b = 1L
|
||||
|
||||
fun next(): Long {
|
||||
val result = a + b
|
||||
a = b
|
||||
b = result
|
||||
return a
|
||||
}
|
||||
|
||||
return generateSequence(::next)
|
||||
}
|
||||
val y = fibonacciSequence().take(10).toList()
|
||||
println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
|
||||
|
||||
|
||||
// Kotlin Collection lar ile çalışmak için higher-order metodlar sağlar.
|
||||
val z = (1..9)
|
||||
.map {it * 3} // her bir elamanı 3 ile çarp
|
||||
.filter {it < 20} // 20 den küçük değerleri ele
|
||||
.groupBy {it % 2 == 0} // ikiye tam bölünen ve bölünmeyen şeklinde grupla (Map)
|
||||
.mapKeys {if (it.key) "even" else "odd"} // oluşan map in boolen 'key' lerini String bir değere dönüştür.
|
||||
println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]}
|
||||
|
||||
// Bir 'for' döngüsü 'itearator' sağlayan her objeye uygulanabilir.
|
||||
for (c in "merhaba") {
|
||||
println(c)
|
||||
}
|
||||
|
||||
// 'while' döngüsü diğer dillere benzer şekilde çalışır.
|
||||
var ctr = 0
|
||||
while (ctr < 5) {
|
||||
println(ctr)
|
||||
ctr++
|
||||
}
|
||||
do {
|
||||
println(ctr)
|
||||
ctr++
|
||||
} while (ctr < 10)
|
||||
|
||||
/*
|
||||
'if' bir dönüş değeri olan deyim gibi de kullanılabilir.
|
||||
Bu sebepten Kotlin, Java'da bulunan '?:' ifadesi içermez.
|
||||
*/
|
||||
val num = 5
|
||||
val message = if (num % 2 == 0) "even" else "odd"
|
||||
println("$num is $message") // => 5 is odd
|
||||
|
||||
// 'if-else if' yapıları için 'when' kullanılabilir.
|
||||
val i = 10
|
||||
when {
|
||||
i < 7 -> println("first block")
|
||||
fooString.startsWith("hello") -> println("second block")
|
||||
else -> println("else block")
|
||||
}
|
||||
|
||||
// 'when' bir parametre ile de kullanılabilir.
|
||||
when (i) {
|
||||
0, 21 -> println("0 or 21")
|
||||
in 1..20 -> println("in the range 1 to 20")
|
||||
else -> println("none of the above")
|
||||
}
|
||||
|
||||
// 'when' dönüş değeri olan bir metod gibi de davranabilir.
|
||||
var result = when (i) {
|
||||
0, 21 -> "0 or 21"
|
||||
in 1..20 -> "in the range 1 to 20"
|
||||
else -> "none of the above"
|
||||
}
|
||||
println(result)
|
||||
|
||||
|
||||
/*
|
||||
Bir objenin tipini 'is' operatörü ile tayin edebiliriz.
|
||||
Eğer obje tip kontrolünü geçerse, cast etmeden doğrudan
|
||||
o tipteymiş gibi kullanılabilir.
|
||||
*/
|
||||
fun smartCastExample(x: Any) : Boolean {
|
||||
if (x is Boolean) {
|
||||
// x otomatik olarak Boolean'a cast edilir.
|
||||
return x
|
||||
} else if (x is Int) {
|
||||
// x otomatik olarak Int tipine cast edilir.
|
||||
return x > 0
|
||||
} else if (x is String) {
|
||||
// x otomatik olarak String tipine cast edilir.
|
||||
return x.isNotEmpty()
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
println(smartCastExample("Merhaba, dünya!")) // => true
|
||||
println(smartCastExample("")) // => false
|
||||
println(smartCastExample(5)) // => true
|
||||
println(smartCastExample(0)) // => false
|
||||
println(smartCastExample(true)) // => true
|
||||
|
||||
// Smartcast 'when' bloğu ile de çalışır.
|
||||
fun smartCastWhenExample(x: Any) = when (x) {
|
||||
is Boolean -> x
|
||||
is Int -> x > 0
|
||||
is String -> x.isNotEmpty()
|
||||
else -> false
|
||||
}
|
||||
|
||||
/*
|
||||
Extension lar, bir sınıfa fonksinolalite eklemenin bir yoludur.
|
||||
*/
|
||||
fun String.remove(c: Char): String {
|
||||
return this.filter {it != c}
|
||||
}
|
||||
println("Merhaba, dünya!".remove('a')) // => Merhb, düny!
|
||||
|
||||
|
||||
|
||||
//Biraz detaylı Kotlin
|
||||
|
||||
|
||||
/*
|
||||
* Delegated Properties, bir değişken tanımlarken kullanılan birkaç standart yöntemler içerir.
|
||||
* https://kotlinlang.org/docs/reference/delegated-properties.html
|
||||
* En bilinen delegate property metodları: lazy(), observable()
|
||||
* */
|
||||
|
||||
/*
|
||||
* Lazy, bir değişkeni ilk erişimde çalıştırılacak olan bir lambda ile tanımlama metodudur.
|
||||
* Sonraki erişimlerde değişkene atanan değer hatırlanır.
|
||||
* Lazy, synchronized bir delegation yöntemidir; değer sadece bir thread içinde hesaplanır,
|
||||
* tüm thread ler aynı değere erişir. Eğer senkronizasyon gerekli değilse, lazy metodu içine
|
||||
* LazyThreadSafetyMode.PUBLICATION paslanabilir.
|
||||
* */
|
||||
|
||||
val lazyValue: String by lazy( {
|
||||
println("bi sn... hesaplıyorum....")
|
||||
"Selam!"
|
||||
})
|
||||
|
||||
println(lazyValue)// bi sn... hesaplıyorum.... Selam!
|
||||
println(lazyValue) // Selam!
|
||||
/*
|
||||
* Observable, bir değişkende olabilecek yeniden atama değişikliklerini dinleme yöntemidir.
|
||||
* İki arguman alır; değişkenin ilk değeri, değiştiğinde çağrılan bir handler metodu. Handler
|
||||
* metodu değişken her değiştiğinde çağırılır.
|
||||
* */
|
||||
var myObservableName: String by Delegates.observable("<isim yok>") {
|
||||
prop, old, new ->
|
||||
println("$old -> $new")
|
||||
}
|
||||
myObservableName = "Baha" //<isim yok> -> Baha
|
||||
myObservableName = "Can" //Baha -> Can
|
||||
|
||||
|
||||
/*
|
||||
* Eğer değişkenin yeniden atanmasını denetlemek isterek vetoable()
|
||||
* metodunu kullanabiliriz.
|
||||
* */
|
||||
|
||||
var myVetoableName : String by Delegates.vetoable("<isim yok>"){
|
||||
property, oldValue, newValue ->
|
||||
if (newValue.length < 2) {
|
||||
println("Tek harfli isim kabul etmiyoruz!")
|
||||
false
|
||||
} else {
|
||||
println("$oldValue -> $newValue")
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
myVetoableName = "Baha" //<isim yok> -> Baha
|
||||
myVetoableName = "C" //Tek harfli isim kabul etmiyoruz!
|
||||
println(myVetoableName) //Baha
|
||||
|
||||
|
||||
//singleton değişkene ulaşmak:
|
||||
println(ObjectExample.hello()) // => Merhaba
|
||||
}
|
||||
|
||||
// Enum class lar Java'daki enum lara benzerdir.
|
||||
enum class EnumExample {
|
||||
A, B, C
|
||||
}
|
||||
|
||||
/*
|
||||
'object' anahtar kelimesi ile singleton nesneler oluşturulabilir.
|
||||
Bu şekilde tanımlanan sınıflardan yeni nesneler oluşturulamaz, sadece adı ile refere edilebilir.
|
||||
*/
|
||||
object ObjectExample {
|
||||
fun hello(): String {
|
||||
return "Merhaba"
|
||||
}
|
||||
}
|
||||
|
||||
fun useObject() {
|
||||
ObjectExample.hello()
|
||||
val someRef: Any = ObjectExample
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### İlerisi için:
|
||||
|
||||
* [Kotlin tutorials](https://kotlinlang.org/docs/tutorials/)
|
||||
* [Try Kotlin in your browser](http://try.kotlinlang.org/)
|
||||
* [A list of Kotlin resources](http://kotlin.link/)
|
||||
* [Kotlin Koans in your IDE](https://kotlinlang.org/docs/tutorials/koans.html/)
|
@ -50,7 +50,7 @@ function bigHorribleAlert(): void {
|
||||
// Functions are first class citizens, support the lambda "fat arrow" syntax and
|
||||
// use type inference
|
||||
|
||||
// The following are equivalent, the same signature will be infered by the
|
||||
// The following are equivalent, the same signature will be inferred by the
|
||||
// compiler, and same JavaScript will be emitted
|
||||
let f1 = function (i: number): number { return i * i; }
|
||||
// Return type inferred
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: java
|
||||
filename: LearnJava-ua.java
|
||||
contributors:
|
||||
- ["Jake Prather", "http://github.com/JakeHP"]
|
||||
- ["Jakukyo Friel", "http://weakish.github.io"]
|
||||
@ -11,8 +12,8 @@ contributors:
|
||||
translators:
|
||||
- ["Oleksandr Tatarchuk", "https://github.com/tatarchuk"]
|
||||
- ["Andre Polykanine", "https://github.com/Oire"]
|
||||
filename: LearnJavaUa.java
|
||||
lang: uk-ua
|
||||
|
||||
---
|
||||
|
||||
Java є об’єктно-орієнтованою мовою програмування загального призначення з підтримкою паралельного програмування, яка базується на класах.
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: html
|
||||
filename: learnhtml.html
|
||||
filename: learnhtml-vi.html
|
||||
contributors:
|
||||
- ["Christophe THOMAS", "https://github.com/WinChris"]
|
||||
translators:
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
language: python3
|
||||
filename: learnpython3-vi.py
|
||||
contributors:
|
||||
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
|
||||
- ["Steven Basart", "http://github.com/xksteven"]
|
||||
@ -8,8 +9,8 @@ contributors:
|
||||
- ["evuez", "http://github.com/evuez"]
|
||||
translators:
|
||||
- ["Xuan (Sean) Luong, https://github.com/xuanluong"]
|
||||
filename: learnpython3.py
|
||||
lang: vi-vn
|
||||
|
||||
---
|
||||
|
||||
Python được tạo ra bởi Guido van Rossum vào đầu những năm 90s. Ngày nay nó là một trong những ngôn ngữ phổ biến
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: ruby
|
||||
filename: learnruby.rb
|
||||
filename: learnruby-vi.rb
|
||||
contributors:
|
||||
- ["David Underwood", "http://theflyingdeveloper.com"]
|
||||
- ["Joel Walden", "http://joelwalden.net"]
|
||||
|
@ -40,9 +40,9 @@ specific points in the file, and for fast editing.
|
||||
|
||||
# Searching in the text
|
||||
|
||||
/word # Highlights all occurences of word after cursor
|
||||
?word # Highlights all occurences of word before cursor
|
||||
n # Moves cursor to next occurence of word after search
|
||||
/word # Highlights all occurrences of word after cursor
|
||||
?word # Highlights all occurrences of word before cursor
|
||||
n # Moves cursor to next occurrence of word after search
|
||||
N # Moves cursor to previous occerence of word
|
||||
|
||||
:%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file
|
||||
|
@ -12,7 +12,7 @@ Module Module1
|
||||
'A Quick Overview of Visual Basic Console Applications before we dive
|
||||
'in to the deep end.
|
||||
'Apostrophe starts comments.
|
||||
'To Navigate this tutorial within the Visual Basic Complier, I've put
|
||||
'To Navigate this tutorial within the Visual Basic Compiler, I've put
|
||||
'together a navigation system.
|
||||
'This navigation system is explained however as we go deeper into this
|
||||
'tutorial, you'll understand what it all means.
|
||||
|
@ -27,7 +27,7 @@ another_key: Another value goes here.
|
||||
a_number_value: 100
|
||||
scientific_notation: 1e+12
|
||||
# The number 1 will be interpreted as a number, not a boolean. if you want
|
||||
# it to be intepreted as a boolean, use true
|
||||
# it to be interpreted as a boolean, use true
|
||||
boolean: true
|
||||
null_value: null
|
||||
key with spaces: value
|
||||
@ -132,7 +132,7 @@ python_complex_number: !!python/complex 1+2j
|
||||
# We can also use yaml complex keys with language specific tags
|
||||
? !!python/tuple [5, 7]
|
||||
: Fifty Seven
|
||||
# Would be {(5, 7): 'Fifty Seven'} in python
|
||||
# Would be {(5, 7): 'Fifty Seven'} in Python
|
||||
|
||||
####################
|
||||
# EXTRA YAML TYPES #
|
||||
|
@ -1,11 +1,13 @@
|
||||
---
|
||||
language: bf
|
||||
lang: zh-cn
|
||||
filename: brainfuck-cn.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
translators:
|
||||
- ["lyuehh", "https://github.com/lyuehh"]
|
||||
lang: zh-cn
|
||||
|
||||
---
|
||||
|
||||
Brainfuck 是一个极小的只有8个指令的图灵完全的编程语言。
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: LiveScript
|
||||
filename: learnLivescript.ls
|
||||
filename: learnLivescript-cn.ls
|
||||
contributors:
|
||||
- ["Christina Whyte", "http://github.com/kurisuwhyte/"]
|
||||
translators:
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user